Files

216 lines
10 KiB
Markdown
Raw Permalink Normal View History

# CollabTable Server
The CollabTable backend is a small Go `net/http` service backed by PostgreSQL. It serves the
Svelte dashboard and the Android synchronization API from one container.
## Features
- REST API for lists, fields, items, and item values
- Transactional HTTP synchronization with soft-delete tombstones
- Notification polling for background refreshes
- Multi-user browser sessions (with per-account roles/admin user management) authenticated
through AuthGuard, a centralized identity service shared across projects (optional -- see
`AUTHGUARD_URL` below)
- Long-lived bearer API token for Android and other sync clients (independent of AuthGuard)
- Embedded SvelteKit dashboard
- Idempotent PostgreSQL schema initialization
## Quick start with Docker
```bash
cd ..
docker build -f docker/Dockerfile -t collabtable-server .
docker run -d --name collabtable-server --restart unless-stopped \
-p 8080:8080 \
-e DATABASE_URL=postgres://user:password@host:5432/collabtable \
-e AUTHGUARD_URL=https://auth.example.com \
-e SECRET=<long-random-shared-secret> \
-e COOKIE_SECURE=false \
collabtable-server
```
Open `http://localhost:8080` to create the first account. Generate an API token from
the dashboard's Settings menu and enter it in the Android app.
## Local development
The backend requires Go 1.26+ and PostgreSQL. The dashboard requires Node.js 22+.
```bash
cp .env.example .env
go test ./...
go run .
```
`go test ./...` skips the tests that need a database. To run them, set `TEST_DATABASE_URL` to a
disposable PostgreSQL (a `postgres://` URL, never your real `DATABASE_URL`). Each test creates
its own schema in it and drops the schema afterwards.
To build the dashboard for the embedded production binary:
```bash
cd ../frontend
npm ci
npm run check
npm run build
cd ..
Copy-Item -Recurse -Force frontend/build backend/web
go -C backend build -o collabtable-server .
```
The Dockerfile performs those dashboard and Go build steps automatically.
## One-time legacy user remap
Databases from before the AuthGuard migration key list memberships and API tokens by the old
local user IDs. After the migration each person's identity is their AuthGuard ID, which is
usually different, so they sign in and see none of the lists they owned. Run this once, with the
server stopped and before any AuthGuard account signs in:
```bash
# users.json: the array GET /api/auth/users returns, copied while signed in as an AuthGuard admin
collabtable-server remap-users --authguard-users users.json # dry run: prints the plan
collabtable-server remap-users --authguard-users users.json --apply # writes the remap
```
Legacy users are matched to AuthGuard accounts by email, or by username when the legacy account
has no email. For anything unmatched or ambiguous, pass `--map` with a JSON object from legacy ID to
AuthGuard ID, such as `{"3": 12}`. The tool refuses to write while a legacy user who owns rows is
unmapped, and it refuses a second run. If a legacy ID is also the ID of a different AuthGuard
account, the plan blocks until you pass `--accept-id-overlap`; use that only after confirming the
account has never signed in. `DATABASE_URL` must be set.
## API
All Android synchronization routes are prefixed with `/api/` and require:
```text
Authorization: Bearer <api-token>
```
The Android app also sends `x-device-id`, which is used to avoid showing a device its own
notification events.
### Authentication
- `GET /api/auth/status`
- `POST /api/auth/setup`
- `POST /api/auth/login`
- `POST /api/auth/logout`
- `POST /api/auth/credentials`
- `GET /api/auth/token/status`
- `POST /api/auth/token/regenerate`
Browser authentication proxies to AuthGuard (`AUTHGUARD_URL`), which sets and reads its own
`auth_session` HTTP-only cookie; CollabTable itself mints no session token. Any number of
accounts can exist, with `user`/`admin`/`superadmin` roles managed via `/api/auth/users`.
AuthGuard integration has three states: `AUTHGUARD_URL` set (used immediately); unset with
`AUTH_DISABLED` unset/false (the default -- "pending": auth stays fully enabled/gated, waiting
for ProjectConfigurator's push, failing closed on auth calls until then); or `AUTH_DISABLED=true`
(the browser-session gate is off). List access still requires membership. In this mode requests
use placeholder identity 0, which has no list memberships, so the dashboard data is empty and
sync API tokens for identity 0 are rejected. Use it only for local development of the auth shell,
not for a working data deployment. API tokens are unrelated to AuthGuard (see below), hashed at
rest, and shown only when generated.
### Data
- `GET|POST /api/lists`
- `GET|PUT|DELETE /api/lists/:id`
- `GET /api/fields/list/:listId`
- `POST /api/fields`
- `PUT|DELETE /api/fields/:id`
- `GET /api/items/list/:listId`
- `GET /api/items/:itemId/values`
- `POST /api/items`
- `POST /api/items/values`
- `PUT|DELETE /api/items/:id`
- `POST /api/sync`
- `GET /api/notifications/poll?since=<timestamp-ms>`
The list, field, item and item-value collection GETs accept `limit` (default 200, maximum 500)
and an opaque `cursor`. They return `{ "items": [...], "nextCursor": "...", "hasMore": true }`;
continue with `nextCursor` while `hasMore` is true. The final page has an empty `nextCursor`.
`POST /api/sync` requires `lastSyncToken` (use `0` for the first sync) and returns at most 500
changes with `nextSyncToken` and `hasMore`. Clients must request each page until `hasMore` is
false. Older sync clients without `lastSyncToken` receive HTTP 400 and must be updated with the
server.
### Dashboard and health
- `GET /health` is public.
- `GET /web/data` requires the admin session.
- `GET /web/info` requires the admin session.
- `/`, `/about`, and `/lists/:id` serve the embedded dashboard SPA.
## Environment variables
- `PORT` — HTTP port, default `8080`
- `APP_VERSION` — optional version displayed in the dashboard, default `dev`
- `COOKIE_SECURE` — set to `true` when served over HTTPS. It marks only the cookies CollabTable
clears on logout as `Secure`; the session cookie's attributes are set by AuthGuard.
- `TRUSTED_PROXIES` — comma-separated IP addresses or CIDR ranges of reverse proxies, default
unset (no proxy trusted). `X-Forwarded-For` is read for the client IP, used by the rate limits,
only when the socket peer is in this list; `X-Forwarded-Proto` is honoured the same way.
- `PRODUCTION` — set `true` for a production deployment, default `false`. Plain HTTP requests
get 403 unless they arrive over TLS or through a `TRUSTED_PROXIES` proxy that sends
`X-Forwarded-Proto: https` (`/health` stays open). Requires `TRUSTED_PROXIES`. With it unset,
the server logs a warning that TLS is off.
- `SECRET` — shared secret for the internal endpoints. Required unless `AUTH_DISABLED=true`:
without it the auth status endpoint reports the missing secret and auth-gated routes return 500.
- `ALLOWED_ORIGINS` — comma-separated browser origins allowed to call the API cross-origin with
credentials, default unset (no CORS headers; the dashboard is same-origin).
- `DATABASE_URL` — PostgreSQL connection string, required
- `AUTHGUARD_URL` — optional bootstrap/override base URL of the AuthGuard identity service
CollabTable authenticates against, default unset (pending). Leaving it unset does not disable
authentication -- it leaves the service "pending" until ProjectConfigurator pushes a URL,
failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off.
- `AUTH_DISABLED` — set `true` to disable browser-session gates, default `false`. List access is
still membership-scoped; placeholder identity 0 has no memberships and its sync tokens are
rejected. Use only for local auth-shell development, not a working data deployment.
- `DB_INIT_RETRY_INTERVAL_MS` — startup retry delay, default `5000`
- `DB_INIT_RETRY_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever
- `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0`
- `NOTIF_RETENTION_MS` — notification retention period, default seven days
The Go server initializes the existing CollabTable tables in place, so switching from the
previous server does not require a data export or schema conversion.
## Rate limits
The auth routes are throttled in process, per client IP (see `TRUSTED_PROXIES` for how the IP is
resolved): setup, login, TOTP and token regeneration allow 30 requests per minute, after which
the server answers 429 with `Retry-After`. Failed logins (401) are also counted per account
identifier, and an account is locked for its 15-minute window after 10 failures. Anyone who knows
an account name can therefore lock that account out for the window. Limits are per instance and
reset on restart. AuthGuard applies its own limits; confirm them separately.
The sync API is not throttled per request, because the bearer token is 256 bits and devices
sync often.
## Security headers
Every response carries `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`,
`Referrer-Policy: strict-origin-when-cross-origin` and `Content-Security-Policy: frame-ancestors
'none'`. The dashboard page (`index.html`, including the fallback for deep links) gets a full
Content-Security-Policy instead: scripts only from this origin plus the page's own inline
bootstrap script, whose hash is read from the embedded `index.html` at request time, so it
follows every dashboard build. Styles allow `'unsafe-inline'` because the page shell uses a style
attribute. `Strict-Transport-Security` is not set here; set it at the TLS proxy.
## Access model
List, field, item and value reads and writes are scoped to `list_memberships`. On migration,
every current API-token user is granted access to every existing list because the old schema did
not store owners. Lists created afterward are owned only by their creator. There is currently no
API for owners to add or remove members, so a newly created list is private to its creator's
account and devices. Deleting an item, field or list still removes its values permanently, while
the parent rows remain soft-deleted.
When login is off (`AUTH_DISABLED=true`, or the login-required switch turned off in
ProjectConfigurator), browser-session gates are bypassed. Data remains membership-scoped; the
placeholder identity 0 has no memberships, so `/web/data` contains no lists. A caller without a
session can only mint a token for that placeholder identity, and the sync API refuses it.
## License
MIT