Compare commits

...
2 Commits
Author SHA1 Message Date
Gabriel20xx 937f51b4fb fix: address performance and security findings
Lint / Lint (push) Successful in 26s
Tests / Go backend (push) Failing after 1m14s
Tests / Dashboard checks (push) Successful in 52s
Docker / Docker Build & Push (push) Successful in 3m41s
- Add PostgreSQL-backed backend and frontend tests to CI
- Harden Android API logging and disable app backups
- Update the performance report with resolved findings
2026-10-19 21:16:08 +00:00
Gabriel20xxandClaude Haiku 5.5 a84a36349b Fix critical and high audit findings
Fixed findings from the audit reports (SECURITY, QUALITY, PERFORMANCE):
- P-001 · Dashboard re-downloads the entire dataset every 5 seconds

Re-synced the vendored shared/ snapshot from shared commit 199a5ef.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-10-19 07:48:07 +00:00
63 changed files with 3185 additions and 6353 deletions

No files matched your search

+20
View File
@@ -29,6 +29,21 @@ jobs:
working-directory: backend
permissions:
contents: read
# A throwaway database for the handler and sync tests. They create their own
# schema in it and drop it again, and are skipped when TEST_DATABASE_URL is unset.
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: collabtable_test
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 5s
--health-timeout 5s
--health-retries 10
steps:
- name: Checkout
@@ -43,6 +58,8 @@ jobs:
- name: Test
run: go test ./...
env:
TEST_DATABASE_URL: postgres://postgres:postgres@localhost:5432/collabtable_test?sslmode=disable
frontend:
name: Dashboard checks
@@ -72,3 +89,6 @@ jobs:
- name: Check dashboard
run: npm run check
- name: Unit tests
run: npm test
+1
View File
@@ -40,6 +40,7 @@ android {
}
buildFeatures {
compose = true
buildConfig = true
}
packaging {
resources {
@@ -8,7 +8,7 @@
<application
android:name=".CollabTableApplication"
android:allowBackup="true"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
@@ -3,6 +3,7 @@ package com.collabtable.app.data.api
import android.content.Context
import android.net.Uri
import android.os.Build
import com.collabtable.app.BuildConfig
import com.collabtable.app.data.preferences.PreferencesManager
import com.collabtable.app.utils.Logger
import okhttp3.Interceptor
@@ -17,9 +18,13 @@ object ApiClient {
private var retrofit: Retrofit? = null
private var context: Context? = null
// Bodies and the Authorization header carry the sync token and user data, so
// only debug builds log them, and the header is redacted in every build.
private val loggingInterceptor =
HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
level =
if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
redactHeader("Authorization")
}
private val authInterceptor =
@@ -116,6 +121,18 @@ object ApiClient {
}
}
// Cleartext stays allowed so LAN servers work (see network_security_config.xml). The
// warning makes the trade-off visible: the sync token and data are not encrypted in transit.
private fun warnIfCleartext(url: String) {
if (url.startsWith("http://", ignoreCase = true)) {
Logger.w(
"HTTP",
"API base URL uses plain HTTP: the sync token and data are not encrypted in transit. " +
"Use HTTPS for any server outside your LAN.",
)
}
}
fun initialize(context: Context) {
this.context = context.applicationContext
val prefs = PreferencesManager.getInstance(context)
@@ -124,6 +141,7 @@ object ApiClient {
Logger.i("HTTP", "API base URL initialized to $baseUrl")
} catch (_: Exception) {
}
warnIfCleartext(baseUrl)
retrofit = buildRetrofit()
}
@@ -133,6 +151,7 @@ object ApiClient {
Logger.i("HTTP", "API base URL set to $baseUrl")
} catch (_: Exception) {
}
warnIfCleartext(baseUrl)
retrofit = buildRetrofit()
}
+22 -14
View File
@@ -6,63 +6,71 @@
- **Commit:** 6aec03f on main
- **Working tree:** clean (no uncommitted changes, no untracked files)
- **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, TanStack Query) embedded in the Go binary; Android client (Kotlin, Room, Retrofit) with offline sync; Docker multi-stage image on `scratch`; GitHub Actions.
- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed). A second Medium pass re-checked P-004, which stays open for a pagination contract decision.
- **Scope:** Read all first-party backend code (`backend/*.go`, including tests), `docker/Dockerfile`, `.dockerignore`, `.github/workflows/*`, the frontend data layer, list components, routes and Vite config, the Android API client, preferences and sync repository, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, lock files (read for versions only), build output, and the rest of `shared/` (node, python and java packages, which CollabTable does not use). Tracked SQLite files were inspected read-only from a copy (schema and row counts only). No tests, builds or linters were run; the analysis is static.
## Summary
| Severity | Count |
|---|---:|
| Critical | 0 |
| High | 2 |
| Medium | 5 |
| Low | 3 |
| Info | 1 |
| Severity | Count | Fixed | Not reproduced | Open |
|---|---:|---:|---:|---:|
| Critical | 0 | 0 | 0 | 0 |
| High | 2 | 1 | 0 | 1 |
| Medium | 5 | 4 | 0 | 1 |
| Low | 3 | 0 | 0 | 3 |
| Info | 1 | 0 | 0 | 1 |
Two structural costs dominate: the dashboard re-downloads the full database every 5 seconds, and sync writes row by row with several round trips per value inside one long transaction. Missing indexes and pagination will make both worse as data grows.
## Issues
### P-001 · Dashboard re-downloads the entire dataset every 5 seconds · **High**
### P-001 · Dashboard re-downloads the entire dataset every 5 seconds · **High** · Fixed
- **Location:** `backend/web.go:9-29` (four unpaginated queries), `backend/data.go:68-204` (no LIMIT in any query builder), `backend/web.go:74-76` (`no-store`), `frontend/src/lib/features/lists/listsData.svelte.js:4,10`, `frontend/src/lib/api.js:27-29`
- **Description:** `createOverviewData()` polls `/web/data` with `refetchInterval: 5000`. Each response contains every non-deleted list, every field, every item and every item value, with no pagination, no `since` filter and no HTTP caching (`Cache-Control: no-store`). The server already computes per-list effective update times (`web.go:31-72`), but the client has no way to use them to skip unchanged data. TanStack Query's default is to poll only while the tab is visible, so each open dashboard pays this cost.
- **Impact:** Transfer, JSON encoding and client re-rendering all scale with total data size rather than with the amount of change. With a few thousand items and several viewers this is continuous multi-megabyte traffic and repeated full re-renders.
- **Recommendation:** Serve changes incrementally with a `since` cursor (as sync already does), or add an ETag derived from the maximum `updatedat` and answer `304` when nothing changed, dropping `no-store` for that path. Compress the response (see P-006). Consider a longer interval or server push for the dashboard.
- **Status:** Fixed 2026-10-19 — `/web/data` now sends a weak ETag over the response data (the per-request timestamp is excluded), answers `304` when `If-None-Match` matches, and uses `Cache-Control: private, no-cache` instead of `no-store`, so an unchanged poll sends no body. A `max(updatedat)` validator was rejected because client-supplied timestamps can move backwards and hard deletes leave no trace. Residual: changed data is still sent in full, the server still runs the four queries on every poll, and browsers may now keep a private on-disk copy of the dashboard data, which `no-store` previously prevented. Files: `backend/web.go`, `backend/data.go` (stable tie-break order), `backend/web_test.go`.
### P-002 · Sync issues several statements per row inside one long transaction · **High**
### P-002 · Sync issues several statements per row inside one long transaction · **High** · Open
- **Location:** `backend/sync.go:61-209` (the transaction closure). For item values, `sync.go:172-207`: `listid` lookup (`:175`), `EXISTS` on items (`:185`), optional stub insert (`:193`), upsert (`:198`) and a notification insert (`:206`). Per-row upserts at `sync.go:64-79`, `:104-126`, `:149-164`. Request size is capped at 50 MB by `backend/server.go:253-259`.
- **Description:** Every list, field, item and value in a request is processed one at a time with separate statements. Each item value needs four to five round trips, plus a notification row per change, and the whole batch holds row locks until commit. There is no cap on the number of rows per request.
- **Impact:** An initial sync or a large offline push (potentially thousands of rows) becomes thousands of sequential round trips. The transaction stays open for the whole batch, and the 60-second `WriteTimeout` (`server.go:123`) can cut the request off. The device then retries and repeats the same work, and concurrent devices contend on the same rows.
- **Recommendation:** Batch the writes, using `pgx.Batch` or multi-row `INSERT ... SELECT FROM unnest(...)` upserts per table. Load the field-to-list map once per request instead of once per value. Insert notifications as one multi-row statement per request. Cap rows per request, return `413` above the cap, and have clients chunk their pushes.
- **Status:** Open 2026-10-19 — partly addressed: `backend/sync.go` now resolves each request's fields and items in two statements (`valueReferences`) instead of up to two lookups per value, which removes the per-value reads. Still needed: the list, field, item and value upserts and their notification inserts still run one statement at a time inside one transaction, so this needs `pgx.Batch` or `unnest` bulk upserts; the per-request row cap with `413` is a client-facing change and needs CollabTableAndroid to chunk pushes first. Not measured against PostgreSQL, since none is available in this environment.
### P-003 · No index on `updatedat`, so every delta query scans the table · **Medium**
### P-003 · No index on `updatedat`, so every delta query scans the table · **Medium** · Fixed
- **Location:** `backend/db.go:40-189` (indexes exist only on `fields.listid`, `items.listid`, `item_values.itemid`, `item_values.fieldid`, and notifications `createdat` and `listid`, at `:83-86` and `:97-98`). Queries filtering on `updatedat`: `backend/data.go:75`, `:108`, `:145`, `:178`; sync calls at `backend/sync.go:220-235`.
- **Description:** Sync and `/web/data` filter with `updatedat >= $1`, but `lists`, `fields`, `items` and `item_values` have no index on `updatedat`. Rows are soft-deleted and never physically removed, so the tables only grow.
- **Impact:** Every sync from every device performs four full table scans, and the cost grows with history rather than with recent change volume.
- **Recommendation:** Add `CREATE INDEX IF NOT EXISTS` on `updatedat` for `lists`, `items`, `fields` and `item_values` in `initSchema`. Consider `(isdeleted, updatedat)` if soft-delete filtering is common in the same queries.
- **Status:** Fixed 2026-10-19 — `initSchema` creates indexes on `updatedat` for lists, fields, items and item values, so delta queries stop scanning whole tables. The index builds run at startup and briefly block writes on large tables. Files: backend/db.go.
### P-004 · No pagination on list endpoints or the sync response; the first sync returns everything · **Medium**
### P-004 · No pagination on list endpoints or the sync response; the first sync returns everything · **Medium** · Open
- **Location:** `backend/data.go:68-204` (`queryLists`, `queryFields`, `queryItems`, `queryValues`, none with LIMIT), `backend/data.go:228-235` (`GET /api/lists`), `backend/sync.go:216-248` (`since` is nil when `lastSync == 0`, so the full table is returned).
- **Description:** Collection endpoints return unbounded arrays. The first sync from any device (`lastSync == 0`) returns every list, field, item and value in the database in one response.
- **Impact:** Response size and server memory grow linearly with total data. Large first syncs risk the 60-second write timeout and slow mobile clients.
- **Recommendation:** Add keyset pagination (a `(updatedat, id)` cursor and a `limit` parameter) to the collection endpoints. For sync, return a `hasMore` flag and a cursor, and let the client loop until it is caught up.
- **Status:** Open 2026-10-19 — Re-checked, unchanged: the collection queries have no LIMIT and `lastSync == 0` still returns every row. Decision needed: the pagination contract (`hasMore` plus a cursor, or keyset on `(updatedat, id)`), the default page size, and the rollout order. CollabTableAndroid has to loop until caught up before the server may page, or existing clients would silently get a truncated sync.
### P-005 · Frontend scans full arrays for every row, card and cell on each poll · **Medium**
### P-005 · Frontend scans full arrays for every row, card and cell on each poll · **Medium** · Fixed
- **Location:** `frontend/src/routes/lists/[id]/+page.svelte:94` (`itemValuesFor(overview.values, item.id)` runs once per visible row and scans every value in the database) and `:98` (`valueFor` per cell); `frontend/src/lib/components/lists/ListCard.svelte:7-8` (each card filters all fields and all items); `frontend/src/lib/features/lists/listHelpers.js:1-15` (linear `filter` and `find` with no index).
- **Description:** The helpers are linear scans over the complete data set, and they run for every visible row and card. Because each 5-second poll replaces the arrays, every derived value is recomputed on every poll.
- **Impact:** Cost per render is roughly visible rows times total values. With a large data set this appears as delayed input and scroll jank.
- **Recommendation:** Build lookup maps once per data change in a `$derived` (a `Map` keyed by `listId`, by `itemId`, and by `itemId + fieldId`). Pass pre-grouped slices into the card and row components. Rely on TanStack's structural sharing so unchanged data keeps its references.
- **Status:** Fixed 2026-10-19 — Fields, items and item values are grouped once per data change with `groupByKey`, and each grid card, table row and detail row reads only its own slice. `itemValuesFor` is removed because it had no other callers. Files: frontend/src/lib/features/lists/listHelpers.js, frontend/src/routes/+page.svelte, frontend/src/routes/lists/[id]/+page.svelte, frontend/src/lib/components/lists/ListsGrid.svelte, frontend/src/lib/components/lists/ListsTable.svelte.
### P-006 · No HTTP compression and no cache headers on JSON or static assets · **Medium**
### P-006 · No HTTP compression and no cache headers on JSON or static assets · **Medium** · Fixed
- **Location:** `backend/server.go:118-125` (plain `http.Server`, no compression middleware), `backend/server.go:292-316` (`spaFileServer` sets no `Cache-Control`), `backend/web.go:74-76` (`no-store` on `/web/data`).
- **Description:** JSON responses (`/web/data`, `/api/sync`, `/api/lists`) are sent uncompressed. Static build output, including content-hashed Vite assets, is served with no cache-control, and the embedded filesystem provides no modification times for conditional requests.
- **Impact:** Large JSON bodies transfer several times more bytes than necessary, and browsers refetch the whole app bundle on each visit.
- **Recommendation:** Add gzip or brotli middleware, or enable it at the reverse proxy. Set `Cache-Control: public, max-age=31536000, immutable` for `_app/immutable/*` and `no-cache` for `index.html`. Add ETags for `/web/data` (see P-001).
- **Status:** Fixed 2026-10-19 — Responses are gzip-compressed for clients that accept it, `_app/immutable/` assets are cached for a year as immutable, and `index.html` and other static files are sent with `no-cache`. Files: backend/server.go, backend/server_test.go.
### P-007 · Request bodies up to 50 MB are decoded into memory with no per-route limit · **Medium**
### P-007 · Request bodies up to 50 MB are decoded into memory with no per-route limit · **Medium** · Fixed
- **Location:** `backend/server.go:253-259` (`decodeJSON` uses `io.LimitReader(r.Body, 50*1024*1024)`), used by `backend/sync.go:46` and by the write handlers in `backend/data.go`.
- **Description:** Every write endpoint accepts up to 50 MB of JSON and decodes it fully into Go structs. `io.LimitReader` truncates silently, so an oversized body fails with a confusing decode error instead of `413`. These handlers have no concurrency cap, so each concurrent request can allocate its full decode buffer.
- **Impact:** A few concurrent large requests can exhaust memory. It is also an easy denial-of-service vector (see the rate-limiting note in the Security report).
- **Recommendation:** Use `http.MaxBytesReader` with per-route limits (for example 1 to 5 MB for single-entity writes, and a higher bound for sync), returning `413` when exceeded. Bound concurrent sync transactions with a semaphore sized below `DATABASE_MAX_CONNS`.
- **Status:** Fixed 2026-10-19 — Request bodies are limited with `http.MaxBytesReader` (2 MB for single-entity writes, 50 MB for sync), oversized bodies get 413, and at most four syncs run at once. Single-entity writes above 2 MB now fail with 413; the shared auth proxy already caps bodies at 128 KB. Files: backend/server.go, backend/sync.go, backend/data.go.
### P-008 · One notification row per changed row, on every write path · **Low**
- **Location:** `backend/sync.go:79`, `:126`, `:164`, `:206`; `backend/data.go:256`, `:302`, `:364`, `:418`, `:507`, `:561`, `:605`, `:621`; retention in `backend/db.go:212-230`; polling in `backend/web.go:92-141` (`LIMIT 500` at `:109`).
+20 -13
View File
@@ -5,58 +5,65 @@
- **Analyzed:** 2026-10-16
- **Commit:** 6aec03f on main
- **Working tree:** clean (no uncommitted changes, no untracked files)
- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed); open Medium findings name their blocker in their status lines. A second Medium pass added database-backed backend tests, frontend helper tests and a CI Postgres service (Q-004, still open for Android tests) and re-checked Q-006.
- **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, Tailwind 4, TanStack Query) embedded in the Go binary; Android client (Kotlin, Jetpack Compose, Room, Retrofit/OkHttp); Docker; GitHub Actions.
- **Scope:** Read all first-party backend code (`backend/*.go`, including the five test files), the frontend data layer, routes, list components and Vite config, the Android API client, preferences, sync repository and app Gradle file, `README.md`, `.github/workflows/*`, `docker/Dockerfile`, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper jar, generated build output, lock files (read for versions only), and the rest of `shared/`. The tracked SQLite files were inspected read-only from a copy. No tests, linters or builds were run.
## Summary
| Severity | Count |
|---|---:|
| Critical | 0 |
| High | 0 |
| Medium | 6 |
| Low | 8 |
| Info | 0 |
| Severity | Count | Fixed | Not reproduced | Open |
|---|---:|---:|---:|---:|
| Critical | 0 | 0 | 0 | 0 |
| High | 0 | 0 | 0 | 0 |
| Medium | 6 | 4 | 0 | 2 |
| Low | 8 | 0 | 0 | 8 |
| Info | 0 | 0 | 0 | 0 |
The backend is small and readable, but its transactional and delete logic is duplicated across the REST and sync paths and has drifted apart. A few error-handling assumptions are wrong, and the data layer has essentially no test coverage.
## Issues
### Q-001 · Notification errors inside transactions abort the sync they were meant to tolerate · **Medium**
### Q-001 · Notification errors inside transactions abort the sync they were meant to tolerate · **Medium** · Fixed
- **Location:** `backend/notifications.go:51-57` (`ignoreNotificationError`); called inside transactions at `backend/sync.go:79`, `:126`, `:164`, `:206` and `backend/data.go:453`.
- **Description:** `ignoreNotificationError` says a failed notification "must never roll back the data mutation". When the notification insert runs inside the transaction, PostgreSQL marks the transaction as aborted after any failing statement, so the next statement fails and the commit cannot succeed. The error is only logged, which makes the function look like it tolerates the failure, but the whole sync then returns `500 Sync failed` after rolling back. The comment is wrong for these paths.
- **Impact:** A transient failure of a notification insert turns a successful write into a failed sync, and the client retries the same payload. Maintainers reading the comment will assume the opposite of what happens.
- **Recommendation:** Isolate the notification insert in a savepoint (a nested `tx.Begin` in pgx, or `SAVEPOINT` and `ROLLBACK TO SAVEPOINT`), or write notifications after commit. Update the comment to match the actual behavior.
- **Status:** Fixed 2026-10-19 — Notification inserts inside a transaction now run in a savepoint (`enqueueNotificationInTx`), so a failed insert rolls back only the notification and the data change still commits. Each such notification adds two statements (savepoint and release). Files: backend/notifications.go, backend/sync.go, backend/data.go.
### Q-002 · Delete semantics differ between REST endpoints and sync · **Medium**
### Q-002 · Delete semantics differ between REST endpoints and sync · **Medium** · Fixed
- **Location:** `backend/data.go:309-321` (REST list delete sets only `lists.isdeleted`); `backend/sync.go:81-91` (sync list delete also cascades to fields, items and values); `backend/data.go:420-455` (field delete cascades only when no active fields remain); `backend/data.go:609-621` (item delete updates the item, then deletes its values in a separate statement whose error is discarded at `:620`, and skips the notification at `:618-619` if the re-read fails).
- **Description:** The same logical operations (delete a list, delete an item) leave different state depending on the entry point. A list deleted through REST keeps its fields, items and values active, while the same delete through sync removes the children. `/web/data` filters out deleted lists but still returns the active items and values that belong to them (`backend/web.go:31-72`). Item deletion is not atomic and can leave orphaned values if the second statement fails.
- **Impact:** The dashboard, the Android client and sync can disagree about what exists, and orphaned values are silently accepted.
- **Recommendation:** Implement `deleteList`, `deleteField` and `deleteItem` once, each inside a transaction, and call them from both REST and sync. Check every error.
- **Status:** Fixed 2026-10-19 — REST and sync now share `cascadeDeleteList`, `cascadeDeleteField` and `cascadeDeleteItem`, each delete runs in one transaction, and the value-delete error is no longer discarded. REST list deletes now cascade to fields, items and values as sync already did, which is a client-visible change for REST callers. Files: backend/data.go, backend/sync.go.
### Q-003 · `handleSync` is a 200-line function, and cascade logic is duplicated · **Medium**
### Q-003 · `handleSync` is a 200-line function, and cascade logic is duplicated · **Medium** · Fixed
- **Location:** `backend/sync.go:45-249` (one function; the transaction closure spans `:61-209`). Duplicated cascade logic: `sync.go:128-143` and `backend/data.go:440-452`. Event-type selection repeated at `sync.go:72-78`, `:119-125` and `:157-163`. Default-value handling repeated at `sync.go:96-103` and `backend/data.go:349-354` and `:393-398`.
- **Description:** Upserts, notifications, cascades and response assembly all live in one closure. The business rules for deletion, defaults and event types are implemented twice, once in the sync handler and once in the REST handlers. Q-002 is a direct result of this duplication.
- **Impact:** Hard to test or change safely, and the two code paths have already diverged.
- **Recommendation:** Extract a small repository layer (`upsertList`, `upsertField`, `upsertItem`, `upsertValue`, `deleteList`, `deleteField`, `deleteItem`) shared by the REST handlers and sync, and keep the handlers as thin request and response adapters. Move event-type selection into one helper.
- **Status:** Fixed 2026-10-19 — `handleSync` is now a thin adapter over `applySyncRequest` and the per-table `applyLists`, `applyFields`, `applyItems` and `applyValues` helpers. The cascades (`cascadeDeleteList`, `cascadeDeleteField`, `cascadeDeleteItem`), `fieldDefaults` and `upsertValue` are shared by REST and sync, and sync picks its event type through one helper (`changeEventType`). The REST list, field and item create and update handlers keep their own SQL on purpose, because a plain `INSERT` rejects a duplicate id and switching it to the last-writer-wins upsert would change REST behaviour. Files: backend/sync.go, backend/data.go.
### Q-004 · Core data layer has no tests, and CI never starts a database · **Medium**
### Q-004 · Core data layer has no tests, and CI never starts a database · **Medium** · Open
- **Location:** `backend/routes_test.go:8-11` (registers routes with a nil database and asserts nothing); `backend/auth_test.go`, `env_test.go`, `models_test.go` and `sync_test.go` (cover env parsing, JSON timestamp parsing, timestamp normalization and the auth stub only); `.github/workflows/tests.yml` (Go job runs `go test ./...` with no Postgres service); the frontend has no unit tests (CI runs `npm run check` only); `CollabTableAndroid/app/src` has no test sources.
- **Description:** No test exercises `handleSync`, the list, field, item and value handlers, `/web/data`, the CORS wrapper, the SPA fallback, or the frontend helpers in `listHelpers.js`. The one route test runs without assertions.
- **Impact:** The most complex logic (sync merge, cascades, notification side effects, timestamp handling) is covered only by manual testing, so regressions like Q-001 and Q-002 are invisible.
- **Recommendation:** Add `httptest` integration tests against a real Postgres (as a CI service container), starting with sync round trips and delete cascades. Give `routes_test.go` real assertions on methods and status codes. Add Vitest tests for `listHelpers.js`, and JVM unit tests for the Android sync merge logic.
- **Status:** Open 2026-10-19 — Partly fixed: route and middleware tests assert real behaviour (`backend/routes_test.go`, `backend/server_test.go`). New database-backed tests in `backend/db_test.go` cover sync round trips between devices, the `updatedat >= since` delta, last-writer-wins, stale and newer deletes, delete cascades on the REST and sync paths, the value-cell guard, orphan values, the notification savepoint, `/web/data` ETags and API tokens. They need `TEST_DATABASE_URL` (each test uses its own schema and drops it) and are skipped without it; `tests.yml` now starts a PostgreSQL service container and sets it. A `node --test` suite covers `listHelpers.js` (`npm test`, no new dependency, also run in CI). Run against PostgreSQL 18 here: all pass, and breaking four of the rules made a test fail. Still open: Android JVM unit tests for the sync merge logic. JUnit is declared, but there is no JDK or Gradle here to compile or run them, so none were written. The CI change itself has not run.
### Q-005 · Setup documentation contradicts the configuration · **Medium**
### Q-005 · Setup documentation contradicts the configuration · **Medium** · Fixed
- **Location:** `README.md:52` (`SECRET` marked as optional, default "unset (push endpoint refuses every caller)"); `README.md:70-79` (Quick Start `docker run` sets no `SECRET`); `README.md:55` (`COOKIE_SECURE` described as marking cookies `Secure`); `shared/backend/auth/proxy.go:359-361` and `:838-841`; `backend/auth.go:113-120`; `frontend/vite.config.js:38-41` (dev proxy forwards only `/web` and `/health`).
- **Description:** The auth service is built with `RequireSecret()` (`auth.go:118`). When `SECRET` is unset, `/api/auth/status` and every auth-gated route return `500 SECRET environment variable is not set.`, so the documented Quick Start produces a dashboard that cannot load. The README table also calls `SECRET` optional. The live session cookie's `Secure` and `SameSite` attributes come from AuthGuard (see Security S-013), so `COOKIE_SECURE` does not do what the README says. `npm run dev` proxies only `/web` and `/health`, but the dashboard calls `/api/auth/*` and `/api/tech-stack` (`frontend/src/lib/api.js`), so the dev server cannot reach the API.
- **Impact:** Operators who follow the docs get a deployment that fails or looks secure when it is not, and developers hit a confusing dev setup.
- **Recommendation:** Mark `SECRET` as required when auth is enabled, add it to the Quick Start, correct the `COOKIE_SECURE` description, and add `/api` to the Vite proxy.
- **Status:** Fixed 2026-10-19 — README and backend README now mark `SECRET` as required unless `AUTH_DISABLED=true`, add it to the Quick Start, correct the `COOKIE_SECURE` description, and document `ALLOWED_ORIGINS`; the Vite dev proxy now forwards `/api`. Files: README.md, backend/README.md, frontend/vite.config.js.
### Q-006 · Client-supplied timestamps drive the change cursor and overwrite unconditionally · **Medium**
### Q-006 · Client-supplied timestamps drive the change cursor and overwrite unconditionally · **Medium** · Open
- **Location:** `backend/sync.go:20-43` (client timestamps accepted as sent, clamped only if in the future); upserts that overwrite regardless of the stored `updatedat`: `sync.go:64-69`, `:104-116`, `:149-156`, `:198-203`; the delta cursor filters on the stored value at `backend/data.go:75`, `:108`, `:145`, `:178`. Android: local edits stamped with device time (`CollabTableAndroid/app/src/main/java/com/collabtable/app/ui/screens/ListDetailViewModel.kt:148`), and the cursor is the server's `serverTimestamp` (`CollabTableAndroid/app/src/main/java/com/collabtable/app/data/repository/SyncRepository.kt:49-60`, `:283`).
- **Description:** Two related problems. (1) A device that edits offline stamps the change with an old local time. If another device has already advanced its cursor past that time, the `updatedat >= since` filter never returns the change to it. (2) Upserts overwrite the stored row whatever its `updatedat`, so an older change that arrives later replaces a newer one. The Android client mitigates (1) by forcing a full down-sync at app start (`SyncRepository.kt:122`), so the devices affected are those that stay open for a long time.
- **Impact:** Silent divergence between devices, and lost updates when two devices edit the same row offline. Dashboard users see stale data until a device restarts.
- **Recommendation:** Assign server-side change tokens (a monotonically increasing sequence, or the server receive time) to every write and use that as the cursor, keeping client `updatedat` for display only. Alternatively, make each upsert conditional on `EXCLUDED.updatedat` being newer than the stored value, and document the last-writer-wins rule.
- **Status:** Open 2026-10-19 — Re-checked, unchanged. Conditional upserts are in place and now covered by `backend/db_test.go` (`TestSyncLastWriterWinsByTimestamp`, `TestStaleDeleteDoesNotCascadeButNewerDeleteDoes`; an equal timestamp still applies). Still open: a change stamped with an old device clock can miss the `updatedat >= since` cursor. The fix needs a server-side change token on every row (a new column with a backfill, so a stored-data-format change) and a rollout plan. Decision needed: the token design (server receive time or a sequence) and whether the Android cursor changes with it.
### Q-007 · Validation and error mapping return misleading status codes and contract drift · **Low**
- **Location:** `backend/data.go:248-255` (duplicate list id returns `500 Failed to create list` rather than `409`); `backend/data.go:549-558` (an item value for a missing item or field fails on a foreign key and returns `500`); `backend/data.go:589-607` (`PUT /api/items/{id}` accepts a body but only bumps `updatedat`, ignoring the body); `backend/server.go:292-316` (unknown `/api/...` paths return `index.html` with `200`).
+11 -3
View File
@@ -49,10 +49,13 @@ The device-sync API token (generated from the dashboard's Settings page, used by
| `AUTHGUARD_URL` | No | unset (pending) | Optional bootstrap/override base URL of the AuthGuard identity service. 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` | No | `false` | Set `true` to disable authentication entirely (no login screen, nothing gated, every request treated as authenticated) — for local development or a standalone deployment with no AuthGuard integration at all. |
| `CARRIERNODE_URL` | No | unset | Base URL of a CarrierNode instance. Bootstrap fallback only — see below; not used by any feature here yet. |
| `SECRET` | No | unset (push endpoint refuses every caller) | Shared secret, the same value CarrierNode/ProjectConfigurator were configured with, checked against `X-Internal-Auth` on `PUT /api/core-services/internal`. |
| `SECRET` | Yes, unless `AUTH_DISABLED=true` | unset | Shared secret, the same value CarrierNode/ProjectConfigurator were configured with, checked against `X-Internal-Auth` on `PUT /api/core-services/internal` and `PUT /api/auth/access/internal`. Without it, `GET /api/auth/status` reports `SECRET environment variable is not set.` and every auth-gated route returns 500, and the internal endpoints refuse every caller. |
| `ALLOWED_ORIGINS` | No | unset | Comma-separated browser origins that may call the API cross-origin with credentials. Leave unset: the dashboard is same-origin and needs no CORS. |
| `PORT` | No | `8080` | HTTP listen port |
| `APP_VERSION` | No | `dev` | Version label shown on the dashboard's About page |
| `COOKIE_SECURE` | No | `false` | Set `true` once served over HTTPS, to mark cookies `Secure` |
| `COOKIE_SECURE` | No | `false` | Set `true` once served over HTTPS. It marks only the cookies CollabTable clears on logout as `Secure`; the session cookie's `Secure`, `SameSite` and `Domain` attributes are set by AuthGuard. |
| `TRUSTED_PROXIES` | No | unset | Comma-separated IPs or CIDR ranges of reverse proxies. `X-Forwarded-For` (client IP for rate limits) and `X-Forwarded-Proto` are read only from these peers. |
| `PRODUCTION` | No | `false` | Set `true` to refuse plain HTTP: requests must arrive over TLS or through a `TRUSTED_PROXIES` proxy sending `X-Forwarded-Proto: https`. Requires `TRUSTED_PROXIES`. With `false`, the server logs a warning that TLS is off. |
| `DB_INIT_RETRY_INTERVAL_MS` | No | `5000` | Delay between database-connection retry attempts at startup |
| `DB_INIT_RETRY_MAX_ATTEMPTS` | No | `0` (retry forever) | Max database-connection retry attempts at startup |
| `SYNC_MAX_FUTURE_SKEW_MS` | No | `0` | Client clock skew tolerated in sync timestamps, to avoid re-sending future-dated rows in hot loops |
@@ -73,6 +76,7 @@ docker run -d \
-p 8080:8080 \
-e DATABASE_URL="postgresql://user:password@host:5432/collabtable" \
-e AUTHGUARD_URL="https://auth.example.com" \
-e SECRET="<long-random-shared-secret>" \
collabtable:local
```
@@ -120,8 +124,12 @@ Open `CollabTableAndroid` in Android Studio, let Gradle sync, and run on an emul
```bash
cd backend
go test ./...
# The handler and sync tests need a disposable PostgreSQL and are skipped without one.
# Never point this at your real DATABASE_URL: each test creates and drops its own schema.
TEST_DATABASE_URL='postgres://postgres:postgres@localhost:5432/collabtable_test?sslmode=disable' go test ./...
cd ../frontend
npm test
npm run check
npm run lint
```
@@ -136,7 +144,7 @@ Every push runs three GitHub Actions workflows against the backend and frontend
- **`docker.yml`** — builds a multi-arch image (`linux/amd64` + `linux/arm64` on `main`, `linux/amd64` otherwise) from `docker/Dockerfile` and pushes `${DOCKERHUB_USERNAME}/collabtableserver` to Docker Hub on pushes to `main`, tagged by branch name, `sha-<short-sha>`, and `latest`.
- **`lint.yml`** — runs `npm run lint` (ESLint) against `frontend`.
- **`tests.yml`** — runs `go test ./...` against `backend` and `npm run check` against `frontend`.
- **`tests.yml`** — runs `go test ./...` against `backend` (with a PostgreSQL service container, so the database-backed tests run) and `npm test` and `npm run check` against `frontend`.
**Required secrets / variables in your GitHub repository settings:**
+28 -17
View File
@@ -5,82 +5,93 @@
- **Analyzed:** 2026-10-16
- **Commit:** 6aec03f on main
- **Working tree:** clean (no uncommitted changes, no untracked files)
- **Updated:** 2026-10-19 — Critical, High and Medium findings handled in the working tree (not committed). S-006 and S-009 follow owner decisions 5 (trusted-proxy client IP) and 11 (LAN HTTP with a warning). A second Medium pass re-checked the open items: S-007 is fixed (full dashboard CSP), S-002 does not reproduce, and S-003 and S-005 stay open for owner or shared decisions.
- **Stack:** Go 1.26 (net/http, pgx v5) API server with PostgreSQL; identity delegated to a separate AuthGuard service via `shared/backend/auth`; SvelteKit 2 / Svelte 5 static dashboard embedded in the Go binary; Android client (Kotlin, Retrofit/OkHttp, Room, SharedPreferences); Docker multi-stage image on `scratch`; GitHub Actions.
- **Scope:** Read all first-party backend code (`backend/*.go`), the Docker and CI configuration, the frontend API client, routes and query layer, the Vite config, the Android API client, preferences, manifest, network security config and app Gradle file, and the shared auth, authclient, authproxy, coreconfig and postgres code that CollabTable calls. Git history was searched for credential-shaped strings and `.env` files. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, generated build output, lock files (read for versions only), and the rest of `shared/`. Tracked SQLite files were inspected read-only from a copy, schema and row counts only. No tests, audits, builds or network calls were made; the analysis is static.
## Summary
| Severity | Count |
|---|---:|
| Critical | 0 |
| High | 0 |
| Medium | 10 |
| Low | 7 |
| Info | 2 |
| Severity | Count | Fixed | Not reproduced | Open |
|---|---:|---:|---:|---:|
| Critical | 0 | 0 | 0 | 0 |
| High | 0 | 0 | 0 | 0 |
| Medium | 10 | 7 | 1 | 2 |
| Low | 7 | 0 | 0 | 7 |
| Info | 2 | 0 | 0 | 2 |
No critical or high-severity issues were confirmed. Authentication is delegated to AuthGuard and fails closed when it is not configured, and sync tokens are generated with 256 bits of randomness and stored hashed. The main concerns are a reflective CORS policy with credentials, a login-disabled mode that hands out sync tokens to anyone, the absence of object-level authorization on data (possibly intended, but unscoped), missing rate limiting and security headers, and several Android client exposures (the token written to logcat, cleartext traffic permitted, and the token stored in plain preferences).
## Issues
### S-001 · Reflective CORS with credentials on every route · **Medium**
### S-001 · Reflective CORS with credentials on every route · **Medium** · Fixed
- **Location:** `backend/server.go:274-290` (`withCORS`), in particular `:276-281`.
- **Description:** The middleware echoes any request `Origin` into `Access-Control-Allow-Origin` and sets `Access-Control-Allow-Credentials: true` on all responses, including session-protected routes (`/web/data`, `/api/auth/users`, `/api/auth/token/regenerate`). If the browser sends the user's cookies, any origin can read those responses. The preflight `Allow-Methods` list also omits `PATCH`, which `server.go:181` accepts.
- **Impact:** Exploitability depends on the AuthGuard cookie attributes, which are not in this repository. With `SameSite=Lax`, a cross-site page will not receive the cookie, but a same-site origin will (another subdomain of the same site, or a sibling app on a shared cookie domain, which the authclient docs describe as a cross-project SSO option). Such an origin could read `/web/data` or call `POST /api/auth/token/regenerate` and read the new sync token. Rated Medium here; it would be High if the cookie is scoped to a parent domain. Needs verification against the deployed AuthGuard cookie.
- **Recommendation:** Replace the reflection with an explicit allow-list from configuration (for example `ALLOWED_ORIGINS`) and set credentials headers only for those origins. The dashboard is same-origin and needs no CORS headers at all, so the default should be none. Keep `Vary: Origin` and add `PATCH` to the allowed methods if it is needed.
- **Status:** Fixed 2026-10-19 — `withCORS` now reflects only origins listed in `ALLOWED_ORIGINS` (empty by default), sends credentials headers only for them, and allows `PATCH` in preflight. Browser clients on other origins lose cross-origin access, which the same-origin dashboard does not need. Files: backend/server.go, backend/server_test.go, backend/README.md, README.md.
### S-002 · Login-disabled mode lets anyone obtain a write-capable sync token · **Medium**
### S-002 · Login-disabled mode lets anyone obtain a write-capable sync token · **Medium** · Not reproduced
- **Location:** `backend/server.go:186-188` (`POST /api/auth/token/regenerate` behind `RequireIfLoginRequired`); `shared/backend/auth/proxy.go:504-519` (`CurrentUser` returns the superadmin placeholder whenever login is not required); `backend/auth.go:194-210` (`handleTokenRegenerate` mints a token for the placeholder identity).
- **Description:** When login is not required (`AUTH_DISABLED=true`, or the login-required override pushed by ProjectConfigurator set to false), `RequireIfLoginRequired` lets any caller reach token regeneration without credentials. The endpoint mints a write-capable sync token for identity 0, and the bearer-token check on the sync API then passes for that caller.
- **Impact:** The sync API's token requirement protects nothing in that mode, and any network client can obtain full read, write and delete access. The README describes `AUTH_DISABLED` as "nothing gated", so this matches the documented intent. The override path can be set centrally in a shared deployment, however, and nobody may notice that the token API has become open.
- **Recommendation:** Keep token minting behind a real credential even when login is off (for example, always require a session for token regeneration), or document the consequence prominently and log a warning when the override is set to false.
- **Status:** Not reproduced 2026-10-19 — The last step of the chain fails. With login off, callers resolve to the placeholder identity 0, and `requireAPIToken` (`backend/auth.go`) never accepts identity 0, so the token minted without a session gets 401 on `/api/sync` and `/api/lists`. Test `TestTokenMintedWithoutASessionDoesNotOpenTheSyncAPI` (`backend/db_test.go`, run against PostgreSQL) pins this. Write and delete access through the token API is not reachable. What login-off mode does open is the dashboard (`/web/data`, user management), as `AUTH_DISABLED` documents; `backend/README.md` now says so. Side effect: with login off, devices cannot get a working sync token; accepting identity 0 would fix that and open the sync API, so it is an owner decision. The `auth.go` comment that called such a token functional is corrected.
### S-003 · No object-level ownership or roles on list, field, item or value data · **Medium**
### S-003 · No object-level ownership or roles on list, field, item or value data · **Medium** · Open
- **Location:** `backend/auth.go:129-149` (`requireAPIToken` only checks that a token exists); `backend/server.go:195-219` (all data routes); `backend/data.go` (all handlers); `backend/sync.go:61-209`; `backend/db.go:40-189` (no owner or tenant columns); `backend/sync.go:198-203` and `backend/data.go:549-558` (item values upserted by `id` alone).
- **Description:** Any valid sync token (one per account) and any logged-in account can read, overwrite, soft-delete and move every list, field, item and value. The item-value conflict clause updates only `value` and `updatedat`, so a write that names a different `itemId` or `fieldId` than the stored row is silently applied to the stored row. The schema has no owner column, and `api_tokens.user_id` is used only for token regeneration. Item values are hard-deleted when their item or list is deleted (`sync.go:88`, `:129`, `:140`, `:166`), so those deletions cannot be undone by a later sync, even though lists and items are soft-deleted.
- **Impact:** For a collaborative tool this may be intended, in which case every account is effectively an administrator of the data. If it is not intended, it is an authorization gap. Either way, one compromised device token can wipe or rewrite the database, and some of that loss is permanent.
- **Recommendation:** Confirm the intended model and document it. If the data is shared, make item-value upserts reject writes whose `itemid` or `fieldid` do not match the stored row. If per-list access is needed, add a membership table and check it in every handler.
- **Status:** Open 2026-10-19 — Partly addressed: item values apply only to a stored row with the same `itemId` and `fieldId` (sync and REST; tests in `backend/db_test.go`), stale writes are ignored (see Q-006), and the current access model is written down in `backend/README.md` ("Access model"). Still needed: an owner decision on the model (shared data, or per-list membership, which needs a membership table checked in every handler), and whether item values should be soft-deleted instead of removed for good (a schema change).
### S-004 · Managed-user routes require a login only, leaving the role check to AuthGuard · **Medium**
### S-004 · Managed-user routes require a login only, leaving the role check to AuthGuard · **Medium** · Fixed
- **Location:** `backend/server.go:178-182` (list, create, update and delete users, behind `RequireIfLoginRequired`); `shared/backend/auth/proxy.go:897-1013` (handlers forward the caller's session to AuthGuard without a local role check); `shared/backend/auth/proxy.go:618` (`RequireUserManager` exists but CollabTable does not use it).
- **Description:** The handlers document that AuthGuard enforces authorization, which holds only if AuthGuard rejects non-admin sessions. CollabTable does not check the role before proxying. If AuthGuard does not reject it, `GET /api/auth/users` returns every account's username, email and role to any logged-in account.
- **Impact:** No defense in depth. A bug or policy change in AuthGuard would expose administrative functions here. Needs verification against the deployed AuthGuard version.
- **Recommendation:** Gate these routes with `RequireUserManager` (or `RequireAdminIfLoginRequired`), which the shared package already provides, so the policy is visible in this repository.
- **Status:** Fixed 2026-10-19 — Managed-user routes now pass the shared `RequireUserManager` gate, so the role check happens in this repository as well as in AuthGuard; accounts without user-management rights get 403 locally. Files: backend/server.go, backend/routes_test.go.
### S-005 · Password change does not require the current password, and existing sessions stay valid · **Medium**
### S-005 · Password change does not require the current password, and existing sessions stay valid · **Medium** · Open
- **Location:** `shared/backend/auth/proxy.go:664-705` (`UpdateMe` accepts only `email`, `username` and `password`); `backend/auth.go:39-43` (documented behavior: a credentials change "simply returns the updated account and leaves the current session valid").
- **Description:** Anyone holding a session cookie can change the account password without knowing the current one. Sessions on other devices also remain valid, and there is no re-authentication step.
- **Impact:** A stolen or unattended session can lock the owner out. The usual defenses (re-authentication, and revoking other sessions on password change) are absent.
- **Recommendation:** Require `currentPassword` (and the TOTP code when enabled) on `POST /api/auth/credentials` whenever the password changes, and have AuthGuard revoke other sessions on a password change.
- **Status:** Open 2026-10-19 — Re-checked, shared-dependent. `UpdateMe` in the vendored `shared/backend/auth/proxy.go` accepts no `currentPassword`, and the shared medium pass left this open pending a decision on the request shape. Needed: that decision, then the change in Web/shared (and AuthGuard revoking other sessions), re-synced here. CollabTable cannot add the check alone without changing the `POST /api/auth/credentials` request.
### S-006 · No rate limiting or request budgets on login, token use, writes or body size · **Medium**
### S-006 · No rate limiting or request budgets on login, token use, writes or body size · **Medium** · Fixed
- **Location:** `shared/backend/auth/proxy.go:1093-1142` (`Login` forwards every attempt to AuthGuard with no local throttling); `backend/auth.go:129-149` (sync-token check, no throttling); `backend/server.go:188` (token regeneration); `backend/server.go:253-259` (up to 50 MB per request, see P-007).
- **Description:** A search of CollabTable and the shared auth packages finds no rate limiter, lockout or request throttle. Brute-force protection for passwords and TOTP codes depends entirely on AuthGuard. Sync tokens carry 256 bits of entropy, so guessing them is not a practical concern; the issue is request volume and availability.
- **Impact:** Credential stuffing against the login proxy, load from unthrottled token checks, and memory exhaustion from large bodies.
- **Recommendation:** Add per-IP and per-account limits on `/api/auth/login`, `/api/auth/totp/*` and `/api/auth/setup`, either in-process or at the proxy. Confirm AuthGuard's own limits. Enforce body size per route (see P-007).
- **Status:** Fixed 2026-10-19 — In-process budgets (owner decision 5) on setup, login, the TOTP routes and token regeneration: 30 requests per minute per client IP, and 10 failed logins per account identifier per 15 minutes, answered with 429 and `Retry-After`. The client IP is read from `X-Forwarded-For` only when the socket peer is in the new `TRUSTED_PROXIES` list, and is the socket address otherwise. Not throttled per request: the sync API and writes, because the bearer token is 256 bits and devices sync often; body size and concurrent syncs bound their cost (P-007). Still to confirm: AuthGuard's own login limits on the deployed instance. Verified by Go unit and route tests only, not against a running instance. Files: backend/clientip.go, backend/ratelimit.go, backend/server.go, backend/clientip_test.go, backend/ratelimit_test.go, backend/.env.example, backend/README.md, README.md.
### S-007 · No security headers on the dashboard or API · **Medium**
### S-007 · No security headers on the dashboard or API · **Medium** · Fixed
- **Location:** `backend/server.go:118-125` (no header middleware); `backend/server.go:292-316` (`spaFileServer` writes `index.html` with only `Content-Type`); `backend/web.go:74-76` (cache headers only).
- **Description:** Responses carry no `Content-Security-Policy`, no `X-Frame-Options` or `frame-ancestors`, no `X-Content-Type-Options` and no `Referrer-Policy`. The app can be framed, which allows clickjacking of user-management and token-regeneration actions. Without a CSP, an injected script would have no restrictions. No unsafe HTML rendering was found in first-party code, which limits the immediate risk.
- **Impact:** Clickjacking of logged-in actions and a weaker defense against future XSS. HSTS belongs at the TLS terminator and is not set here.
- **Recommendation:** Add middleware that sets `X-Frame-Options: DENY` (or `frame-ancestors 'none'`), `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, and a CSP such as `default-src 'self'` with hashes or nonces for SvelteKit's inline bootstrap script. Set HSTS at the proxy.
- **Status:** Fixed 2026-10-19 — The dashboard page (`index.html` and the deep-link fallback) now sends a full Content-Security-Policy (`backend/csp.go`, set in `spaFileServer`): `default-src 'self'`, `script-src 'self'` plus the SHA-256 of the page's inline bootstrap script (read from the embedded `index.html` at request time, so it follows each build), `style-src 'self' 'unsafe-inline'` (the page shell uses a style attribute), `connect-src 'self'`, `object-src 'none'`, `base-uri`, `form-action` and `frame-ancestors 'none'`. Other responses keep `frame-ancestors 'none'`. HSTS stays with the TLS proxy, as recommended, and `backend/README.md` says so. Checked on a real build: the Go hash equals an independent computation, and the bundle has no eval, workers, external URLs or CSS `url()`. Not loaded in a browser (none available here), so open the dashboard once after deploying.
### S-008 · Android app logs full HTTP traffic, including the bearer token, in every build · **Medium**
### S-008 · Android app logs full HTTP traffic, including the bearer token, in every build · **Medium** · Fixed
- **Location:** `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt:20-23` (`HttpLoggingInterceptor` at `Level.BODY`), and `:55-64` (the interceptor is added to the client unconditionally; `authInterceptor` at `:58` sets the `Authorization` header first).
- **Description:** The logging interceptor is not gated on the debug build type, and it does not redact headers. Its output includes the `Authorization: Bearer <token>` header and the full request and response bodies, which carry all list and item data, in release builds.
- **Impact:** The long-lived sync token and user data end up in logcat and in any log capture or bug report. Exploiting this requires access to device logs (ADB, a debugging tool, or a bug report), not a remote attack.
- **Recommendation:** Use `Level.NONE` for release builds (for example `if (BuildConfig.DEBUG)`), call `redactHeader("Authorization")`, and do not log bodies in production.
- **Status:** Fixed 2026-10-19 — HTTP logging now uses `Level.NONE` unless `BuildConfig.DEBUG`, and the `Authorization` header is redacted in every build; `buildConfig` is enabled because AGP 8.8 does not generate `BuildConfig` by default. The Kotlin compile could not run in this environment (the JVM hit the process limit), so it is unverified. Files: CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt, CollabTableAndroid/app/build.gradle.
### S-009 · Cleartext HTTP is allowed for all domains and is the default server URL · **Medium**
### S-009 · Cleartext HTTP is allowed for all domains and is the default server URL · **Medium** · Fixed
- **Location:** `CollabTableAndroid/app/src/main/res/xml/network_security_config.xml:3-4` (`cleartextTrafficPermitted="true"` in `base-config`); `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt:298` (default `http://10.0.2.2:8080/api/`); `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt:25-44` (the bearer token is attached to every request).
- **Description:** The release app accepts `http://` server URLs for any host, and the bearer token is sent with every request. Traffic is unencrypted and can be read or altered on the network path.
- **Impact:** Token and data exposure on untrusted networks whenever an operator configures an HTTP URL. Cleartext is needed only for the emulator default.
- **Recommendation:** Keep cleartext only for debug builds (a debug resource overlay) or for `10.0.2.2` and `localhost`. Require HTTPS for remote hosts and reject `http://` in the settings UI otherwise.
- **Status:** Fixed 2026-10-19 — Handled by owner decision 11 (LAN HTTP allowed, with a warning). Cleartext stays permitted, so the network security config and the default emulator URL are unchanged. `ApiClient` logs a warning whenever the server URL is `http://`. The backend logs a warning at startup while TLS is off. `PRODUCTION=true` refuses plain HTTP requests unless they arrive over TLS or through a `TRUSTED_PROXIES` proxy that sends `X-Forwarded-Proto: https` (`/health` stays open). The Android app has no production profile, so release builds keep cleartext. The settings screen does not reject `http://` for remote hosts, which the decision replaces. Files: CollabTableAndroid/app/src/main/java/com/collabtable/app/data/api/ApiClient.kt, backend/server.go, backend/.env.example, backend/README.md, README.md. The Kotlin change is not compiled: the Android build cannot run on this Alpine (musl) host, because the SDK's aapt2 needs glibc.
### S-010 · Long-lived sync token stored in plain SharedPreferences, with app backup enabled · **Medium**
### S-010 · Long-lived sync token stored in plain SharedPreferences, with app backup enabled · **Medium** · Fixed
- **Location:** `CollabTableAndroid/app/src/main/java/com/collabtable/app/data/preferences/PreferencesManager.kt:73-80` and `:283` (token written to `collab_table_prefs` with `MODE_PRIVATE`, unencrypted); `CollabTableAndroid/app/src/main/AndroidManifest.xml:11` (`android:allowBackup="true"`).
- **Description:** The API token is written to ordinary SharedPreferences. With `allowBackup="true"` the file is included in device backups, and on a rooted device or with ADB backup access it can be read directly.
- **Impact:** The token grants full sync access (see S-003) and can be recovered from a backup or a compromised device.
- **Recommendation:** Store the token with `EncryptedSharedPreferences` or the Android Keystore, exclude it from backups with `dataExtractionRules` and `fullBackupContent`, or set `allowBackup="false"`.
- **Status:** Fixed 2026-10-19 — `android:allowBackup` is now `false`, so the sync token is kept out of device backups and transfers. Users must re-enter the token on a new device, and the token remains plain text on the device, which a rooted device can still read. Files: CollabTableAndroid/app/src/main/AndroidManifest.xml.
### S-011 · Sync token has no expiry, scope or per-device identity · **Low**
- **Location:** `backend/db.go:181-188` (`api_tokens` has no expiry column); `backend/auth.go:159-170` (32 random bytes, stored as an unsalted SHA-256 hash); `backend/auth.go:194-210` (regeneration replaces the account's single token).
+10
View File
@@ -7,6 +7,16 @@ APP_VERSION=dev
# Set to "true" once served over HTTPS - marks the admin session cookie Secure.
COOKIE_SECURE=false
# Comma-separated IPs or CIDR ranges of reverse proxies whose X-Forwarded-For and
# X-Forwarded-Proto headers are believed. Empty (default) trusts no proxy, so the
# socket address is used for rate limits. Example: 10.0.0.1,172.18.0.0/16
TRUSTED_PROXIES=
# Set to "true" in production. Plain HTTP requests are refused unless they arrive
# over TLS or through a TRUSTED_PROXIES proxy that sends X-Forwarded-Proto: https.
# Requires TRUSTED_PROXIES. Default false: plain HTTP is allowed and logs a warning.
PRODUCTION=false
#################################################################
# Authentication (AuthGuard)
#################################################################
+53 -1
View File
@@ -24,6 +24,7 @@ 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
```
@@ -41,6 +42,10 @@ 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
@@ -112,7 +117,19 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
- `PORT` — HTTP port, default `8080`
- `APP_VERSION` — optional version displayed in the dashboard, default `dev`
- `COOKIE_SECURE` — set to `true` when served over HTTPS
- `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
@@ -129,6 +146,41 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
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
There is one shared data set. Lists, fields, items and values have no owner and no per-list
roles: any valid sync token can read, change and delete all of them, and any signed-in dashboard
user can see all of them. Tokens are per account only so that each can be regenerated on its own.
Deleting an item, field or list removes its values for good, while the rows themselves are soft
deleted. Per-list access would need a membership table checked in every handler; that has not
been decided.
When login is off (`AUTH_DISABLED=true`, or the login-required switch turned off in
ProjectConfigurator), the dashboard data and user management need no session. Sync tokens are a
separate matter: a caller without a session can only mint a token for the placeholder identity,
and the sync API refuses that identity.
## License
MIT
+7 -4
View File
@@ -139,6 +139,9 @@ func requireAPIToken(db *DB) func(http.Handler) http.Handler {
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
return
}
// getAPITokenUserID answers 0 for an unknown token. 0 is also the
// placeholder identity used when login is off, so tokens minted without
// a session are refused here as well (see handleTokenRegenerate).
if userID == 0 {
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
return
@@ -173,10 +176,10 @@ func hashToken(token string) string {
// view/regenerate the bearer token its own devices use against the sync API.
// The caller's identity is resolved via sharedauth.UserFromContext, populated
// by the s.auth.Require wrapper server.go mounts these routes behind -- in
// auth-disabled mode that middleware always resolves to sharedauth's fixed
// placeholder identity (ID 0), so a token minted in that mode is real and
// functional, just scoped to that one shared identity rather than a
// per-account AuthGuard identity, matching the pre-migration behavior.
// auth-disabled mode, or while login is switched off, that middleware always
// resolves to sharedauth's fixed placeholder identity (ID 0). A token minted
// for it is stored, but requireAPIToken never accepts identity 0, so a caller
// without a session cannot turn it into access to the sync API.
func (s *Server) handleTokenStatus(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
if user == nil {
+95
View File
@@ -0,0 +1,95 @@
package main
import (
"fmt"
"net"
"net/http"
"strings"
)
// parseTrustedProxies reads TRUSTED_PROXIES, a comma-separated list of IP
// addresses and CIDR ranges for reverse proxies whose forwarding headers may be
// believed. An empty value trusts no proxy.
func parseTrustedProxies(value string) ([]*net.IPNet, error) {
var networks []*net.IPNet
for _, entry := range strings.Split(value, ",") {
entry = strings.TrimSpace(entry)
if entry == "" {
continue
}
if ip := net.ParseIP(entry); ip != nil {
if v4 := ip.To4(); v4 != nil {
ip = v4
}
networks = append(networks, &net.IPNet{IP: ip, Mask: net.CIDRMask(8*len(ip), 8*len(ip))})
continue
}
_, network, err := net.ParseCIDR(entry)
if err != nil {
return nil, fmt.Errorf("TRUSTED_PROXIES entry %q is neither an IP address nor a CIDR range", entry)
}
networks = append(networks, network)
}
return networks, nil
}
// clientIP returns the address a request is attributed to, for rate limits and
// logs. The socket peer is used unless it is a trusted proxy. Only then is
// X-Forwarded-For read, walking from the nearest hop outwards and stopping at
// the first address that is not itself a trusted proxy. A malformed chain falls
// back to the peer, so an unknown caller cannot choose the address it appears as.
func clientIP(r *http.Request, trusted []*net.IPNet) string {
peer := remoteHost(r.RemoteAddr)
peerIP := net.ParseIP(peer)
if peerIP == nil || !inNetworks(peerIP, trusted) {
return peer
}
hops := strings.Split(r.Header.Get("X-Forwarded-For"), ",")
var leftmost net.IP
for i := len(hops) - 1; i >= 0; i-- {
hop := net.ParseIP(strings.TrimSpace(hops[i]))
if hop == nil {
return peer
}
if !inNetworks(hop, trusted) {
return hop.String()
}
leftmost = hop
}
if leftmost != nil {
return leftmost.String()
}
return peer
}
// requestIsHTTPS reports whether the client's connection was encrypted: either
// TLS terminated in this process, or a trusted proxy reported https through
// X-Forwarded-Proto. The header is ignored from any other peer.
func requestIsHTTPS(r *http.Request, trusted []*net.IPNet) bool {
if r.TLS != nil {
return true
}
peerIP := net.ParseIP(remoteHost(r.RemoteAddr))
if peerIP == nil || !inNetworks(peerIP, trusted) {
return false
}
protos := strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")
return strings.EqualFold(strings.TrimSpace(protos[len(protos)-1]), "https")
}
func remoteHost(remoteAddr string) string {
host, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
return remoteAddr
}
return host
}
func inNetworks(ip net.IP, networks []*net.IPNet) bool {
for _, network := range networks {
if network.Contains(ip) {
return true
}
}
return false
}
+121
View File
@@ -0,0 +1,121 @@
package main
import (
"crypto/tls"
"net"
"net/http"
"net/http/httptest"
"testing"
)
func mustTrusted(t *testing.T, value string) []*net.IPNet {
t.Helper()
networks, err := parseTrustedProxies(value)
if err != nil {
t.Fatalf("parseTrustedProxies(%q) error = %v", value, err)
}
return networks
}
func TestParseTrustedProxiesAcceptsAddressesAndRanges(t *testing.T) {
networks := mustTrusted(t, " 10.0.0.5, 192.168.2.0/24 ,, fd00::1 ")
if len(networks) != 3 {
t.Fatalf("parsed %d networks, want 3", len(networks))
}
for _, ip := range []string{"10.0.0.5", "192.168.2.77", "fd00::1"} {
if !inNetworks(net.ParseIP(ip), networks) {
t.Fatalf("%s should be trusted", ip)
}
}
for _, ip := range []string{"10.0.0.6", "192.168.3.1", "fd00::2"} {
if inNetworks(net.ParseIP(ip), networks) {
t.Fatalf("%s should not be trusted", ip)
}
}
}
func TestParseTrustedProxiesEmptyTrustsNothing(t *testing.T) {
networks := mustTrusted(t, "")
if len(networks) != 0 {
t.Fatalf("empty TRUSTED_PROXIES parsed %d networks, want none", len(networks))
}
}
func TestParseTrustedProxiesRejectsGarbage(t *testing.T) {
for _, value := range []string{"proxy.local", "10.0.0.0/33", "10.0.0.1/", "999.1.1.1"} {
if _, err := parseTrustedProxies(value); err == nil {
t.Fatalf("parseTrustedProxies(%q) returned no error", value)
}
}
}
func TestClientIPUsesSocketPeerUnlessPeerIsTrusted(t *testing.T) {
trusted := mustTrusted(t, "10.0.0.1")
cases := []struct {
name string
remoteAddr string
forwarded string
trusted []*net.IPNet
want string
}{
{name: "untrusted peer ignores forwarded header", remoteAddr: "192.0.2.9:4000", forwarded: "203.0.113.7", trusted: trusted, want: "192.0.2.9"},
{name: "no trusted proxies at all", remoteAddr: "10.0.0.1:4000", forwarded: "203.0.113.7", trusted: nil, want: "10.0.0.1"},
{name: "trusted peer uses forwarded client", remoteAddr: "10.0.0.1:4000", forwarded: "203.0.113.7", trusted: trusted, want: "203.0.113.7"},
{name: "trusted peer without header uses peer", remoteAddr: "10.0.0.1:4000", forwarded: "", trusted: trusted, want: "10.0.0.1"},
{name: "chain skips trusted hops", remoteAddr: "10.0.0.1:4000", forwarded: "198.51.100.4, 203.0.113.7, 10.0.0.1", trusted: trusted, want: "203.0.113.7"},
{name: "spoofed leftmost entry is not used", remoteAddr: "10.0.0.1:4000", forwarded: "1.2.3.4, 203.0.113.7", trusted: trusted, want: "203.0.113.7"},
{name: "malformed entry falls back to peer", remoteAddr: "10.0.0.1:4000", forwarded: "203.0.113.7, not-an-ip", trusted: trusted, want: "10.0.0.1"},
{name: "all hops trusted returns leftmost", remoteAddr: "10.0.0.1:4000", forwarded: "10.0.0.1, 10.0.0.1", trusted: trusted, want: "10.0.0.1"},
{name: "IPv6 forwarded client is normalised", remoteAddr: "10.0.0.1:4000", forwarded: "2001:DB8::7", trusted: trusted, want: "2001:db8::7"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "/api/auth/login", nil)
request.RemoteAddr = tc.remoteAddr
if tc.forwarded != "" {
request.Header.Set("X-Forwarded-For", tc.forwarded)
}
if got := clientIP(request, tc.trusted); got != tc.want {
t.Fatalf("clientIP() = %q, want %q", got, tc.want)
}
})
}
}
func TestRequestIsHTTPSHonoursTLSOrTrustedProxyOnly(t *testing.T) {
trusted := mustTrusted(t, "10.0.0.1")
direct := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
direct.TLS = &tls.ConnectionState{}
cases := []struct {
name string
remoteAddr string
proto string
tlsConn bool
want bool
}{
{name: "plain request", remoteAddr: "192.0.2.9:4000", want: false},
{name: "terminated here", remoteAddr: "192.0.2.9:4000", tlsConn: true, want: true},
{name: "trusted proxy reports https", remoteAddr: "10.0.0.1:4000", proto: "https", want: true},
{name: "trusted proxy reports http", remoteAddr: "10.0.0.1:4000", proto: "http", want: false},
{name: "untrusted peer claims https", remoteAddr: "192.0.2.9:4000", proto: "https", want: false},
{name: "last proto hop decides", remoteAddr: "10.0.0.1:4000", proto: "https, http", want: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
request.RemoteAddr = tc.remoteAddr
if tc.proto != "" {
request.Header.Set("X-Forwarded-Proto", tc.proto)
}
if tc.tlsConn {
request.TLS = direct.TLS
}
if got := requestIsHTTPS(request, trusted); got != tc.want {
t.Fatalf("requestIsHTTPS() = %v, want %v", got, tc.want)
}
})
}
}
+51
View File
@@ -0,0 +1,51 @@
package main
import (
"crypto/sha256"
"encoding/base64"
"regexp"
"strings"
)
var (
scriptElement = regexp.MustCompile(`(?is)<script\b([^>]*)>(.*?)</script\s*>`)
scriptSrcAttribute = regexp.MustCompile(`(?i)\bsrc\s*=`)
// A browser reads a CR or CRLF in the HTML source as LF, and hashes that.
htmlNewlines = strings.NewReplacer("\r\n", "\n", "\r", "\n")
)
// inlineScriptHashes returns a CSP hash source for every inline <script> in the
// page. SvelteKit's static build puts one bootstrap script in index.html, and its
// text changes with every build, so the hash is read from the page being served
// instead of being configured.
func inlineScriptHashes(page []byte) []string {
var hashes []string
for _, match := range scriptElement.FindAllSubmatch(page, -1) {
if scriptSrcAttribute.Match(match[1]) || len(match[2]) == 0 {
continue
}
sum := sha256.Sum256([]byte(htmlNewlines.Replace(string(match[2]))))
hashes = append(hashes, "'sha256-"+base64.StdEncoding.EncodeToString(sum[:])+"'")
}
return hashes
}
// dashboardCSP is the Content-Security-Policy for the dashboard page. Scripts may
// only come from this origin or be the page's own inline bootstrap script, so an
// injected script does not run. Styles keep 'unsafe-inline' because the page
// shell uses a style attribute; the bundle has no eval, workers or external URLs.
func dashboardCSP(page []byte) string {
scriptSrc := append([]string{"script-src 'self'"}, inlineScriptHashes(page)...)
return strings.Join([]string{
"default-src 'self'",
strings.Join(scriptSrc, " "),
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data:",
"font-src 'self' data:",
"connect-src 'self'",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
}, "; ")
}
+95
View File
@@ -0,0 +1,95 @@
package main
import (
"crypto/sha256"
"encoding/base64"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
)
func scriptHash(text string) string {
sum := sha256.Sum256([]byte(text))
return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
}
func TestInlineScriptHashesCoversOnlyInlineScripts(t *testing.T) {
const bootstrap = "\n\t{\n\t\tconst element = document.currentScript.parentElement;\n\t}\n"
page := `<html><head><script src="/_app/start.js"></script>
<script type="module" crossorigin src="/_app/other.js"></script><script></script></head>
<body><script>` + bootstrap + `</script></body></html>`
got := inlineScriptHashes([]byte(page))
if len(got) != 1 || got[0] != scriptHash(bootstrap) {
t.Fatalf("inlineScriptHashes() = %v, want only %s", got, scriptHash(bootstrap))
}
}
func TestInlineScriptHashesNormalizesNewlinesLikeABrowser(t *testing.T) {
got := inlineScriptHashes([]byte("<script>a();\r\nb();\rc();</script>"))
if len(got) != 1 || got[0] != scriptHash("a();\nb();\nc();") {
t.Fatalf("inlineScriptHashes() = %v, want the hash of the LF-normalized text", got)
}
}
func TestDashboardCSPAllowsOnlyOwnAndHashedScripts(t *testing.T) {
const bootstrap = "start();"
policy := dashboardCSP([]byte("<body><script>" + bootstrap + "</script></body>"))
directives := map[string]string{}
for _, part := range strings.Split(policy, "; ") {
name, value, _ := strings.Cut(part, " ")
directives[name] = value
}
if want := "'self' " + scriptHash(bootstrap); directives["script-src"] != want {
t.Fatalf("script-src = %q, want %q", directives["script-src"], want)
}
for name, want := range map[string]string{
"default-src": "'self'",
"object-src": "'none'",
"base-uri": "'self'",
"frame-ancestors": "'none'",
} {
if directives[name] != want {
t.Fatalf("%s = %q, want %q", name, directives[name], want)
}
}
if strings.Contains(directives["script-src"], "unsafe") {
t.Fatalf("script-src = %q, must not allow unsafe-inline or unsafe-eval", directives["script-src"])
}
}
func TestDashboardCSPWithoutInlineScriptAllowsOnlyOwnOrigin(t *testing.T) {
policy := dashboardCSP([]byte("<html></html>"))
if !strings.Contains(policy, "script-src 'self';") {
t.Fatalf("policy = %q, want script-src limited to 'self'", policy)
}
}
func TestSPAFileServerSendsDashboardCSPOnThePageOnly(t *testing.T) {
const bootstrap = "start();"
root := fstest.MapFS{
"index.html": {Data: []byte("<html><body><script>" + bootstrap + "</script></body></html>")},
"_app/immutable/app.abc.js": {Data: []byte("console.log(1)")},
}
// Behind withSecurityHeaders, as in main: the page's policy replaces the
// frame-ancestors-only default instead of being added to it.
handler := withSecurityHeaders(spaFileServer(root))
for _, path := range []string{"/", "/index.html", "/lists/123"} {
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, path, nil))
values := recorder.Header().Values("Content-Security-Policy")
if len(values) != 1 || !strings.Contains(values[0], scriptHash(bootstrap)) || !strings.Contains(values[0], "frame-ancestors 'none'") {
t.Fatalf("GET %s Content-Security-Policy = %q, want one full policy with the bootstrap hash", path, values)
}
}
asset := httptest.NewRecorder()
handler.ServeHTTP(asset, httptest.NewRequest(http.MethodGet, "/_app/immutable/app.abc.js", nil))
if got := asset.Header().Get("Content-Security-Policy"); got != "frame-ancestors 'none'" {
t.Fatalf("asset Content-Security-Policy = %q, want the frame-ancestors default", got)
}
}
+190 -64
View File
@@ -79,7 +79,7 @@ func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64)
if len(conditions) > 0 {
query += " WHERE " + strings.Join(conditions, " AND ")
}
query += " ORDER BY updatedat DESC"
query += " ORDER BY updatedat DESC, id"
rows, err := d.pool.Query(ctx, query, args...)
if err != nil {
@@ -116,7 +116,7 @@ func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64,
if len(conditions) > 0 {
query += " WHERE " + strings.Join(conditions, " AND ")
}
query += ` ORDER BY "order" ASC`
query += ` ORDER BY "order" ASC, id`
rows, err := d.pool.Query(ctx, query, args...)
if err != nil {
@@ -152,7 +152,7 @@ func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64,
if len(conditions) > 0 {
query += " WHERE " + strings.Join(conditions, " AND ")
}
query += " ORDER BY updatedat DESC"
query += " ORDER BY updatedat DESC, id"
rows, err := d.pool.Query(ctx, query, args...)
if err != nil {
@@ -185,7 +185,7 @@ func (d *DB) queryValues(ctx context.Context, since *int64, itemID string) ([]It
if len(conditions) > 0 {
query += " WHERE " + strings.Join(conditions, " AND ")
}
query += " ORDER BY updatedat ASC"
query += " ORDER BY updatedat ASC, id"
rows, err := d.pool.Query(ctx, query, args...)
if err != nil {
@@ -220,6 +220,132 @@ func boolInt(value bool) int {
return 0
}
// fieldDefaults fills in the field type and alignment that clients may leave out.
func fieldDefaults(fieldType, alignment string) (string, string) {
if fieldType == "" {
fieldType = "TEXT"
}
if alignment == "" {
alignment = "start"
}
return fieldType, alignment
}
// The upsert helpers below write one row each and report whether the write was
// applied. A write older than the stored row loses (last writer wins by client
// timestamp) and changes nothing, so callers skip the cascade and notification
// for it.
func upsertList(ctx context.Context, executor queryExecutor, list List, createdAt, updatedAt int64) (bool, error) {
result, err := executor.Exec(ctx, `
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name, updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
WHERE EXCLUDED.updatedat >= lists.updatedat
`, list.ID, list.Name, createdAt, updatedAt, boolInt(list.IsDeleted))
if err != nil {
return false, err
}
return result.RowsAffected() > 0, nil
}
func upsertField(ctx context.Context, executor queryExecutor, field Field, createdAt, updatedAt int64) (bool, error) {
fieldType, alignment := fieldDefaults(field.FieldType, field.Alignment)
result, err := executor.Exec(ctx, `
INSERT INTO fields
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name,
fieldtype = EXCLUDED.fieldtype,
fieldoptions = EXCLUDED.fieldoptions,
alignment = EXCLUDED.alignment,
"order" = EXCLUDED."order",
updatedat = EXCLUDED.updatedat,
isdeleted = EXCLUDED.isdeleted
WHERE EXCLUDED.updatedat >= fields.updatedat
`, field.ID, field.Name, fieldType, field.FieldOptions, alignment, field.ListID, field.Order, createdAt, updatedAt, boolInt(field.IsDeleted))
if err != nil {
return false, err
}
return result.RowsAffected() > 0, nil
}
func upsertItem(ctx context.Context, executor queryExecutor, item Item, createdAt, updatedAt int64) (bool, error) {
result, err := executor.Exec(ctx, `
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE
SET updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
WHERE EXCLUDED.updatedat >= items.updatedat
`, item.ID, item.ListID, createdAt, updatedAt, boolInt(item.IsDeleted))
if err != nil {
return false, err
}
return result.RowsAffected() > 0, nil
}
// upsertValue also ignores a value that names a different item or field than the
// stored row, so a write cannot move a value onto another cell.
func upsertValue(ctx context.Context, executor queryExecutor, value ItemValue, updatedAt int64) (bool, error) {
result, err := executor.Exec(ctx, `
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
WHERE EXCLUDED.updatedat >= item_values.updatedat
AND item_values.itemid = EXCLUDED.itemid
AND item_values.fieldid = EXCLUDED.fieldid
`, value.ID, value.ItemID, value.FieldID, value.Value, updatedAt)
if err != nil {
return false, err
}
return result.RowsAffected() > 0, nil
}
// cascadeDeleteList removes the children of a deleted list: its fields and items
// are soft-deleted and their values are hard-deleted. The REST and sync delete
// paths both call it, so they leave the same state behind.
func cascadeDeleteList(ctx context.Context, tx pgx.Tx, listID string, updatedAt int64) error {
if _, err := tx.Exec(ctx, `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, listID); err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, listID); err != nil {
return err
}
_, err := tx.Exec(ctx, `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, listID)
return err
}
// cascadeDeleteField removes the values of a deleted field. When no active field
// remains in the list, the list's items are deleted too, and the returned flag
// reports that.
func cascadeDeleteField(ctx context.Context, tx pgx.Tx, fieldID, listID string, updatedAt int64) (bool, error) {
if _, err := tx.Exec(ctx, `DELETE FROM item_values WHERE fieldid = $1`, fieldID); err != nil {
return false, err
}
var remaining int
if err := tx.QueryRow(ctx, `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, listID).Scan(&remaining); err != nil {
return false, err
}
if remaining > 0 {
return false, nil
}
if _, err := tx.Exec(ctx, `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, listID); err != nil {
return false, err
}
if _, err := tx.Exec(ctx, `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, listID); err != nil {
return false, err
}
return true, nil
}
// cascadeDeleteItem removes the values of a deleted item.
func cascadeDeleteItem(ctx context.Context, tx pgx.Tx, itemID string) error {
_, err := tx.Exec(ctx, `DELETE FROM item_values WHERE itemid = $1`, itemID)
return err
}
type listMutation struct {
List
DeviceID string `json:"deviceId,omitempty"`
@@ -237,8 +363,8 @@ func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
}
var request listMutation
if err := decodeJSON(r, &request); err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
if err := decodeJSON(w, r, &request); err != nil {
writeDecodeError(w, err, "Invalid JSON body")
return
}
if request.ID == "" || request.Name == "" {
@@ -285,8 +411,8 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
Name string `json:"name"`
DeviceID string `json:"deviceId,omitempty"`
}
if err := decodeJSON(r, &request); err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
if err := decodeJSON(w, r, &request); err != nil {
writeDecodeError(w, err, "Invalid JSON body")
return
}
updatedAt := time.Now().UnixMilli()
@@ -308,16 +434,28 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, list)
case http.MethodDelete:
updatedAt := time.Now().UnixMilli()
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
result, err := tx.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
if err != nil {
return err
}
if result.RowsAffected() == 0 {
return pgx.ErrNoRows
}
if err := cascadeDeleteList(r.Context(), tx, id, updatedAt); err != nil {
return err
}
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
return nil
})
if errors.Is(err, pgx.ErrNoRows) {
writeJSONError(w, http.StatusNotFound, "List not found")
return
}
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to delete list")
return
}
if result.RowsAffected() == 0 {
writeJSONError(w, http.StatusNotFound, "List not found")
return
}
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
writeJSON(w, http.StatusOK, map[string]string{"message": "List deleted successfully"})
}
}
@@ -338,20 +476,15 @@ func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleFieldCollection(w http.ResponseWriter, r *http.Request) {
var request fieldMutation
if err := decodeJSON(r, &request); err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
if err := decodeJSON(w, r, &request); err != nil {
writeDecodeError(w, err, "Invalid JSON body")
return
}
if request.ID == "" || request.ListID == "" || request.Name == "" {
writeJSONError(w, http.StatusBadRequest, "Field id, listId, and name are required")
return
}
if request.Alignment == "" {
request.Alignment = "start"
}
if request.FieldType == "" {
request.FieldType = "TEXT"
}
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
_, err := s.db.pool.Exec(r.Context(), `
INSERT INTO fields
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
@@ -386,16 +519,11 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
Order int `json:"order"`
DeviceID string `json:"deviceId,omitempty"`
}
if err := decodeJSON(r, &request); err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
if err := decodeJSON(w, r, &request); err != nil {
writeDecodeError(w, err, "Invalid JSON body")
return
}
if request.Alignment == "" {
request.Alignment = "start"
}
if request.FieldType == "" {
request.FieldType = "TEXT"
}
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
updatedAt := time.Now().UnixMilli()
result, err := s.db.pool.Exec(r.Context(), `
UPDATE fields
@@ -421,7 +549,7 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
var request struct {
DeviceID string `json:"deviceId,omitempty"`
}
_ = decodeJSON(r, &request) // DELETE bodies are optional.
_ = decodeJSON(w, r, &request) // DELETE bodies are optional.
updatedAt := time.Now().UnixMilli()
var field Field
cascade := false
@@ -434,23 +562,11 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil {
return err
}
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, id); err != nil {
cascade, err = cascadeDeleteField(r.Context(), tx, id, field.ListID, updatedAt)
if err != nil {
return err
}
var remaining int
if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil {
return err
}
if remaining == 0 {
cascade = true
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil {
return err
}
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil {
return err
}
}
ignoreNotificationError(enqueueNotification(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
return nil
})
if errors.Is(err, pgx.ErrNoRows) {
@@ -488,8 +604,8 @@ func (s *Server) handleItemsForList(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleItemCollection(w http.ResponseWriter, r *http.Request) {
var request itemMutation
if err := decodeJSON(r, &request); err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
if err := decodeJSON(w, r, &request); err != nil {
writeDecodeError(w, err, "Invalid JSON body")
return
}
if request.ID == "" || request.ListID == "" {
@@ -538,28 +654,26 @@ func (s *Server) handleItemValueCollection(w http.ResponseWriter, r *http.Reques
ItemValue
DeviceID string `json:"deviceId,omitempty"`
}
if err := decodeJSON(r, &request); err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
if err := decodeJSON(w, r, &request); err != nil {
writeDecodeError(w, err, "Invalid JSON body")
return
}
if request.ID == "" || request.ItemID == "" || request.FieldID == "" {
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
return
}
_, err := s.db.pool.Exec(r.Context(), `
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
`, request.ID, request.ItemID, request.FieldID, request.Value, int64(request.UpdatedAt))
applied, err := upsertValue(r.Context(), s.db.pool, request.ItemValue, int64(request.UpdatedAt))
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
return
}
// An older write than the stored value changes nothing, so it notifies no one.
var listID string
if applied {
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err == nil {
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
}
}
var value ItemValue
err = s.db.pool.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID).Scan(
&value.ID,
@@ -584,7 +698,7 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
DeviceID string `json:"deviceId,omitempty"`
}
if r.Method == http.MethodPut || r.Method == http.MethodDelete {
_ = decodeJSON(r, &request)
_ = decodeJSON(w, r, &request)
}
updatedAt := time.Now().UnixMilli()
if r.Method == http.MethodPut {
@@ -606,19 +720,31 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, item)
return
}
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
result, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to delete item")
return
return err
}
if result.RowsAffected() == 0 {
return pgx.ErrNoRows
}
item, err := scanItem(tx.QueryRow(r.Context(), `SELECT `+itemColumns+` FROM items WHERE id = $1`, id))
if err != nil {
return err
}
if err := cascadeDeleteItem(r.Context(), tx, id); err != nil {
return err
}
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
return nil
})
if errors.Is(err, pgx.ErrNoRows) {
writeJSONError(w, http.StatusNotFound, "Item not found")
return
}
item, itemErr := s.getItem(r.Context(), id)
if itemErr == nil {
_, _ = s.db.pool.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, id)
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to delete item")
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "Item deleted successfully"})
}
+14
View File
@@ -0,0 +1,14 @@
package main
import "testing"
func TestFieldDefaultsFillMissingValues(t *testing.T) {
fieldType, alignment := fieldDefaults("", "")
if fieldType != "TEXT" || alignment != "start" {
t.Fatalf("fieldDefaults(empty) = (%q, %q), want (TEXT, start)", fieldType, alignment)
}
fieldType, alignment = fieldDefaults("NUMBER", "end")
if fieldType != "NUMBER" || alignment != "end" {
t.Fatalf("fieldDefaults(set) = (%q, %q), want (NUMBER, end)", fieldType, alignment)
}
}
+4
View File
@@ -84,6 +84,10 @@ func (d *DB) initSchema(ctx context.Context) error {
CREATE INDEX IF NOT EXISTS idx_items_listid ON items(listid);
CREATE INDEX IF NOT EXISTS idx_item_values_itemid ON item_values(itemid);
CREATE INDEX IF NOT EXISTS idx_item_values_fieldid ON item_values(fieldid);
CREATE INDEX IF NOT EXISTS idx_lists_updatedat ON lists(updatedat);
CREATE INDEX IF NOT EXISTS idx_fields_updatedat ON fields(updatedat);
CREATE INDEX IF NOT EXISTS idx_items_updatedat ON items(updatedat);
CREATE INDEX IF NOT EXISTS idx_item_values_updatedat ON item_values(updatedat);
CREATE TABLE IF NOT EXISTS notifications (
id TEXT PRIMARY KEY,
+581
View File
@@ -0,0 +1,581 @@
package main
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
)
// These tests run the handlers against a real PostgreSQL. Set TEST_DATABASE_URL
// to a postgres:// URL of a database the tests may write to; without it they are
// skipped. Each test works in its own schema, which it drops afterwards, so the
// database can be shared. TEST_DATABASE_URL must not be the service's own
// DATABASE_URL.
const (
testBearer = "test-device-token"
// Realistic millisecond timestamps in the past, so normalizeTimestamp leaves
// them alone. Later writes use t0 plus an offset.
t0 = int64(1_700_000_000_000)
)
// testDB returns a DB on a fresh schema of TEST_DATABASE_URL, with the tables
// created by initSchema.
func testDB(t *testing.T) *DB {
t.Helper()
base := strings.TrimSpace(os.Getenv("TEST_DATABASE_URL"))
if base == "" {
t.Skip("TEST_DATABASE_URL is not set; database-backed tests need a PostgreSQL they may write to")
}
if base == strings.TrimSpace(os.Getenv("DATABASE_URL")) {
t.Fatal("TEST_DATABASE_URL must not be the same database as DATABASE_URL")
}
parsed, err := url.Parse(base)
if err != nil {
t.Fatalf("TEST_DATABASE_URL is not a URL: %v", err)
}
suffix := make([]byte, 6)
if _, err := rand.Read(suffix); err != nil {
t.Fatal(err)
}
schema := "collabtable_test_" + hex.EncodeToString(suffix)
ctx := context.Background()
admin, err := pgx.Connect(ctx, base)
if err != nil {
t.Fatalf("connect to TEST_DATABASE_URL: %v", err)
}
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
_ = admin.Close(ctx)
t.Fatalf("create schema: %v", err)
}
query := parsed.Query()
query.Set("search_path", schema)
parsed.RawQuery = query.Encode()
db, err := connectDB(ctx, parsed.String())
if err != nil {
t.Fatalf("connectDB: %v", err)
}
t.Cleanup(func() {
db.close()
_, _ = admin.Exec(ctx, "DROP SCHEMA "+schema+" CASCADE")
_ = admin.Close(ctx)
})
if err := db.initSchema(ctx); err != nil {
t.Fatalf("initSchema: %v", err)
}
return db
}
// testUserID owns testBearer. It is not 0: identity 0 is the placeholder used
// when login is off, and the sync API never accepts it.
const testUserID = 1
// testAPI serves the real routes over a test database. Auth is disabled, and the
// sync API accepts testBearer.
type testAPI struct {
t *testing.T
db *DB
mux *http.ServeMux
}
func newTestAPI(t *testing.T) *testAPI {
t.Helper()
db := testDB(t)
server := &Server{
db: db,
auth: newAuthService(db, "", false, true),
syncSlots: make(chan struct{}, maxConcurrentSyncs),
}
mux := http.NewServeMux()
server.registerRoutes(mux, webFS)
if err := db.regenerateAPIToken(context.Background(), testUserID, hashToken(testBearer)); err != nil {
t.Fatalf("seed API token: %v", err)
}
return &testAPI{t: t, db: db, mux: mux}
}
func (a *testAPI) do(method, path, device string, body any) *httptest.ResponseRecorder {
a.t.Helper()
var reader *bytes.Reader
if body == nil {
reader = bytes.NewReader(nil)
} else {
encoded, err := json.Marshal(body)
if err != nil {
a.t.Fatalf("encode request: %v", err)
}
reader = bytes.NewReader(encoded)
}
request := httptest.NewRequest(method, path, reader)
request.Header.Set("Authorization", "Bearer "+testBearer)
if device != "" {
request.Header.Set("X-Device-Id", device)
}
recorder := httptest.NewRecorder()
a.mux.ServeHTTP(recorder, request)
return recorder
}
func (a *testAPI) mustDo(method, path, device string, body any, wantStatus int) *httptest.ResponseRecorder {
a.t.Helper()
recorder := a.do(method, path, device, body)
if recorder.Code != wantStatus {
a.t.Fatalf("%s %s status = %d, want %d; body %s", method, path, recorder.Code, wantStatus, recorder.Body.String())
}
return recorder
}
func decodeBody[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
t.Helper()
var value T
if err := json.Unmarshal(recorder.Body.Bytes(), &value); err != nil {
t.Fatalf("decode %q: %v", recorder.Body.String(), err)
}
return value
}
func (a *testAPI) sync(device string, request SyncRequest) SyncResponse {
a.t.Helper()
request.DeviceID = device
return decodeBody[SyncResponse](a.t, a.mustDo(http.MethodPost, "/api/sync", device, request, http.StatusOK))
}
func (a *testAPI) count(query string, args ...any) int {
a.t.Helper()
var n int
if err := a.db.pool.QueryRow(context.Background(), query, args...).Scan(&n); err != nil {
a.t.Fatalf("%s: %v", query, err)
}
return n
}
func (a *testAPI) notifications(eventType, entityType, entityID string) int {
a.t.Helper()
return a.count(`SELECT count(*) FROM notifications WHERE eventtype = $1 AND entitytype = $2 AND entityid = $3`, eventType, entityType, entityID)
}
// cascadeState summarizes a list and its children, so two delete paths can be
// compared: the list's isdeleted flag, deleted/total fields and items, and the
// number of values left on the list's items.
func (a *testAPI) cascadeState(listID string) string {
a.t.Helper()
return fmt.Sprintf("list=%d fields=%d/%d items=%d/%d values=%d",
a.count(`SELECT isdeleted FROM lists WHERE id = $1`, listID),
a.count(`SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 1`, listID),
a.count(`SELECT count(*) FROM fields WHERE listid = $1`, listID),
a.count(`SELECT count(*) FROM items WHERE listid = $1 AND isdeleted = 1`, listID),
a.count(`SELECT count(*) FROM items WHERE listid = $1`, listID),
a.count(`SELECT count(*) FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, listID),
)
}
func testList(id, name string, updatedAt int64, deleted bool) List {
return List{ID: id, Name: name, CreatedAt: Timestamp(t0), UpdatedAt: Timestamp(updatedAt), IsDeleted: deleted}
}
func testField(id, listID, name string, updatedAt int64, deleted bool) Field {
return Field{ID: id, ListID: listID, Name: name, FieldType: "TEXT", Alignment: "start", CreatedAt: Timestamp(t0), UpdatedAt: Timestamp(updatedAt), IsDeleted: deleted}
}
func testItem(id, listID string, updatedAt int64, deleted bool) Item {
return Item{ID: id, ListID: listID, CreatedAt: Timestamp(t0), UpdatedAt: Timestamp(updatedAt), IsDeleted: deleted}
}
func testValue(id, itemID, fieldID, value string, updatedAt int64) ItemValue {
return ItemValue{ID: id, ItemID: itemID, FieldID: fieldID, Value: value, UpdatedAt: Timestamp(updatedAt)}
}
// seedList pushes a list with two fields, one item and a value in each field, all
// stamped t0+10, as one device's first sync. Its IDs are prefix-list, prefix-f1,
// prefix-f2, prefix-item, prefix-v1 and prefix-v2.
func (a *testAPI) seedList(device, prefix string) {
a.t.Helper()
at := t0 + 10
a.sync(device, SyncRequest{
Lists: []List{testList(prefix+"-list", "Groceries", at, false)},
Fields: []Field{testField(prefix+"-f1", prefix+"-list", "Name", at, false), testField(prefix+"-f2", prefix+"-list", "Qty", at, false)},
Items: []Item{testItem(prefix+"-item", prefix+"-list", at, false)},
ItemValues: []ItemValue{
testValue(prefix+"-v1", prefix+"-item", prefix+"-f1", "milk", at),
testValue(prefix+"-v2", prefix+"-item", prefix+"-f2", "2", at),
},
})
}
func TestInitSchemaCanRunAgainstAnExistingDatabase(t *testing.T) {
db := testDB(t)
if err := db.initSchema(context.Background()); err != nil {
t.Fatalf("second initSchema() error = %v", err)
}
}
func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
api := newTestAPI(t)
api.seedList("phone", "g")
// A device that has never synced gets everything.
full := api.sync("tablet", SyncRequest{})
if len(full.Lists) != 1 || len(full.Fields) != 2 || len(full.Items) != 1 || len(full.ItemValues) != 2 {
t.Fatalf("first sync returned lists=%d fields=%d items=%d values=%d, want 1/2/1/2", len(full.Lists), len(full.Fields), len(full.Items), len(full.ItemValues))
}
if full.ServerTimestamp <= 0 {
t.Fatalf("serverTimestamp = %d, want a positive time", full.ServerTimestamp)
}
if len(full.OrphanItemValues) != 0 {
t.Fatalf("orphanItemValues = %v, want none", full.OrphanItemValues)
}
// The delta filter is "updated at or after the cursor".
if got := api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 11)}); len(got.Lists)+len(got.Fields)+len(got.Items)+len(got.ItemValues) != 0 {
t.Fatalf("sync after the last change returned %+v, want nothing", got)
}
if got := api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 10)}); len(got.Lists) != 1 || len(got.ItemValues) != 2 {
t.Fatalf("sync at the change time returned lists=%d values=%d, want 1 and 2", len(got.Lists), len(got.ItemValues))
}
// The REST reads see the same data.
lists := decodeBody[[]List](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
if len(lists) != 1 || lists[0].Name != "Groceries" {
t.Fatalf("GET /api/lists = %+v, want the pushed list", lists)
}
values := decodeBody[[]ItemValue](t, api.mustDo(http.MethodGet, "/api/items/g-item/values", "", nil, http.StatusOK))
if len(values) != 2 {
t.Fatalf("GET item values = %+v, want 2", values)
}
// The first push is announced to the other device, and not back to its sender.
toTablet := decodeBody[PollResponse](t, api.mustDo(http.MethodGet, "/api/notifications/poll?since=0", "tablet", nil, http.StatusOK))
if len(toTablet.Notifications) == 0 {
t.Fatal("tablet got no notifications for the phone's push")
}
for _, event := range toTablet.Notifications {
if event.DeviceIDOrigin != "phone" {
t.Fatalf("notification origin = %q, want phone", event.DeviceIDOrigin)
}
}
toPhone := decodeBody[PollResponse](t, api.mustDo(http.MethodGet, "/api/notifications/poll?since=0", "phone", nil, http.StatusOK))
if len(toPhone.Notifications) != 0 {
t.Fatalf("phone got its own notifications back: %+v", toPhone.Notifications)
}
}
func TestSyncLastWriterWinsByTimestamp(t *testing.T) {
api := newTestAPI(t)
push := func(name string, updatedAt int64) {
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("l1", name, updatedAt, false)}})
}
name := func() string {
return decodeBody[List](t, api.mustDo(http.MethodGet, "/api/lists/l1", "", nil, http.StatusOK)).Name
}
push("v2", t0+2000)
events := api.notifications("updated", "list", "l1")
push("v1", t0+1000)
if got := name(); got != "v2" {
t.Fatalf("name after an older write = %q, want v2", got)
}
if got := api.notifications("updated", "list", "l1"); got != events {
t.Fatalf("an ignored write added %d notification(s)", got-events)
}
push("v3", t0+3000)
if got := name(); got != "v3" {
t.Fatalf("name after a newer write = %q, want v3", got)
}
push("v3b", t0+3000)
if got := name(); got != "v3b" {
t.Fatalf("name after a write with the same timestamp = %q, want v3b", got)
}
}
func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
api := newTestAPI(t)
api.seedList("phone", "g")
const kept = "list=0 fields=0/2 items=0/1 values=2"
api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("g-list", "Groceries", t0+5, true)}})
if got := api.cascadeState("g-list"); got != kept {
t.Fatalf("state after a stale delete = %s, want %s", got, kept)
}
if got := api.notifications("deleted", "list", "g-list"); got != 0 {
t.Fatalf("a stale delete produced %d deleted notification(s)", got)
}
api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("g-list", "Groceries", t0+20, true)}})
if got, want := api.cascadeState("g-list"), "list=1 fields=2/2 items=1/1 values=0"; got != want {
t.Fatalf("state after a newer delete = %s, want %s (fields and items soft-deleted, values removed)", got, want)
}
if got := api.notifications("deleted", "list", "g-list"); got != 1 {
t.Fatalf("deleted notifications = %d, want 1", got)
}
// The tombstone travels to other devices, but the REST list read hides it.
delta := api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 15)})
if len(delta.Lists) != 1 || !delta.Lists[0].IsDeleted {
t.Fatalf("delta after the delete = %+v, want the tombstone", delta.Lists)
}
if lists := decodeBody[[]List](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)); len(lists) != 0 {
t.Fatalf("GET /api/lists = %+v, want the deleted list hidden", lists)
}
}
func TestDeletingTheLastFieldDeletesTheItems(t *testing.T) {
api := newTestAPI(t)
api.seedList("phone", "g")
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Fields: []Field{testField("g-f1", "g-list", "Name", t0+20, true)}})
if got, want := api.cascadeState("g-list"), "list=0 fields=1/2 items=0/1 values=1"; got != want {
t.Fatalf("state after deleting one of two fields = %s, want %s", got, want)
}
// Through REST this time. The response says the items went with it.
answer := decodeBody[map[string]any](t, api.mustDo(http.MethodDelete, "/api/fields/g-f2", "phone", nil, http.StatusOK))
if answer["cascadeItemsDeleted"] != true {
t.Fatalf("DELETE last field answer = %v, want cascadeItemsDeleted true", answer)
}
if got, want := api.cascadeState("g-list"), "list=0 fields=2/2 items=1/1 values=0"; got != want {
t.Fatalf("state after deleting the last field = %s, want %s", got, want)
}
}
func TestRESTAndSyncDeletesLeaveTheSameState(t *testing.T) {
api := newTestAPI(t)
api.seedList("phone", "rest")
api.seedList("phone", "sync")
api.mustDo(http.MethodDelete, "/api/lists/rest-list", "phone", nil, http.StatusOK)
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("sync-list", "Groceries", time.Now().UnixMilli(), true)}})
const want = "list=1 fields=2/2 items=1/1 values=0"
if got := api.cascadeState("rest-list"); got != want {
t.Fatalf("REST delete left %s, want %s", got, want)
}
if got := api.cascadeState("sync-list"); got != want {
t.Fatalf("sync delete left %s, want %s", got, want)
}
// Item deletes agree as well.
api.seedList("phone", "ri")
api.seedList("phone", "si")
api.mustDo(http.MethodDelete, "/api/items/ri-item", "phone", nil, http.StatusOK)
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Items: []Item{testItem("si-item", "si-list", time.Now().UnixMilli(), true)}})
const wantItem = "list=0 fields=0/2 items=1/1 values=0"
if got := api.cascadeState("ri-list"); got != wantItem {
t.Fatalf("REST item delete left %s, want %s", got, wantItem)
}
if got := api.cascadeState("si-list"); got != wantItem {
t.Fatalf("sync item delete left %s, want %s", got, wantItem)
}
}
func TestSyncCannotMoveAValueOntoAnotherCell(t *testing.T) {
api := newTestAPI(t)
api.seedList("phone", "g")
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), Items: []Item{testItem("g-item2", "g-list", t0+10, false)}})
// Same value id, newer timestamp, but naming another item and another field.
api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), ItemValues: []ItemValue{testValue("g-v1", "g-item2", "g-f2", "hijacked", t0+50)}})
var itemID, fieldID, value string
if err := api.db.pool.QueryRow(context.Background(), `SELECT itemid, fieldid, value FROM item_values WHERE id = 'g-v1'`).Scan(&itemID, &fieldID, &value); err != nil {
t.Fatal(err)
}
if itemID != "g-item" || fieldID != "g-f1" || value != "milk" {
t.Fatalf("stored value = (%s, %s, %q), want it unchanged at (g-item, g-f1, milk)", itemID, fieldID, value)
}
if got := api.notifications("listContentUpdated", "value", "g-v1"); got != 1 {
t.Fatalf("notifications for the value = %d, want only the original push", got)
}
}
func TestSyncReportsValuesItCannotPlaceAndStubsMissingItems(t *testing.T) {
api := newTestAPI(t)
api.seedList("phone", "g")
answer := api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), ItemValues: []ItemValue{
testValue("lost", "g-item", "no-such-field", "x", t0+20),
testValue("late", "item-not-pushed-yet", "g-f1", "y", t0+20),
}})
if len(answer.OrphanItemValues) != 1 || answer.OrphanItemValues[0].ID != "lost" || answer.OrphanItemValues[0].Reason != "missingField" {
t.Fatalf("orphanItemValues = %+v, want only lost with reason missingField", answer.OrphanItemValues)
}
if got := api.count(`SELECT count(*) FROM item_values WHERE id = 'lost'`); got != 0 {
t.Fatal("a value for a missing field was stored")
}
// A value for an item the server has not seen yet creates the item in the
// field's list, so the value is kept.
if got := api.count(`SELECT count(*) FROM items WHERE id = 'item-not-pushed-yet' AND listid = 'g-list' AND isdeleted = 0`); got != 1 {
t.Fatalf("stub item rows = %d, want 1", got)
}
if got := api.count(`SELECT count(*) FROM item_values WHERE id = 'late'`); got != 1 {
t.Fatalf("value rows for the stubbed item = %d, want 1", got)
}
}
func TestFailedNotificationDoesNotAbortTheMutation(t *testing.T) {
api := newTestAPI(t)
if _, err := api.db.pool.Exec(context.Background(), `DROP TABLE notifications`); err != nil {
t.Fatal(err)
}
// Every notification insert now fails. The sync still commits its data.
api.sync("phone", SyncRequest{Lists: []List{testList("l1", "Kept", t0+10, false)}})
if got := api.count(`SELECT count(*) FROM lists WHERE id = 'l1'`); got != 1 {
t.Fatal("the list was rolled back because its notification failed")
}
// So does a REST delete, which runs in a transaction.
api.mustDo(http.MethodDelete, "/api/lists/l1", "phone", nil, http.StatusOK)
if got := api.count(`SELECT isdeleted FROM lists WHERE id = 'l1'`); got != 1 {
t.Fatal("the REST delete was rolled back because its notification failed")
}
}
func TestRESTValueWriteIgnoresAnOlderTimestamp(t *testing.T) {
api := newTestAPI(t)
api.seedList("phone", "g")
write := func(value string, updatedAt int64) ItemValue {
return decodeBody[ItemValue](t, api.mustDo(http.MethodPost, "/api/items/values", "phone",
testValue("g-v1", "g-item", "g-f1", value, updatedAt), http.StatusOK))
}
if got := write("oat milk", t0+30); got.Value != "oat milk" {
t.Fatalf("newer write answered %q, want oat milk", got.Value)
}
if got := write("stale", t0+20); got.Value != "oat milk" || int64(got.UpdatedAt) != t0+30 {
t.Fatalf("older write answered %+v, want the stored oat milk at t0+30", got)
}
}
func TestWebDataSupportsConditionalRequests(t *testing.T) {
api := newTestAPI(t)
api.seedList("phone", "g")
get := func(etag string) *httptest.ResponseRecorder {
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
if etag != "" {
request.Header.Set("If-None-Match", etag)
}
recorder := httptest.NewRecorder()
api.mux.ServeHTTP(recorder, request)
return recorder
}
first := get("")
if first.Code != http.StatusOK {
t.Fatalf("GET /web/data status = %d, want 200; body %s", first.Code, first.Body.String())
}
var payload struct {
Lists []struct {
ID string `json:"id"`
EffectiveUpdatedAt int64 `json:"effectiveUpdatedAt"`
} `json:"lists"`
Stats map[string]int `json:"stats"`
}
if err := json.Unmarshal(first.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.Lists) != 1 || payload.Lists[0].EffectiveUpdatedAt != t0+10 || payload.Stats["values"] != 2 {
t.Fatalf("payload = %+v, want one list effective at t0+10 and two values", payload)
}
etag := first.Header().Get("ETag")
if etag == "" {
t.Fatal("GET /web/data sent no ETag")
}
if again := get(etag); again.Code != http.StatusNotModified {
t.Fatalf("unchanged data status = %d, want 304", again.Code)
}
api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0), ItemValues: []ItemValue{testValue("g-v1", "g-item", "g-f1", "oat milk", t0+40)}})
if changed := get(etag); changed.Code != http.StatusOK {
t.Fatalf("changed data status = %d, want 200", changed.Code)
}
}
func TestRegeneratingAnAccountsTokenReplacesTheOldOne(t *testing.T) {
api := newTestAPI(t)
const fresh = "replacement-device-token"
if err := api.db.regenerateAPIToken(context.Background(), testUserID, hashToken(fresh)); err != nil {
t.Fatal(err)
}
if old := api.do(http.MethodGet, "/api/lists", "", nil); old.Code != http.StatusUnauthorized {
t.Fatalf("old token status = %d, want 401", old.Code)
}
request := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
request.Header.Set("Authorization", "Bearer "+fresh)
recorder := httptest.NewRecorder()
api.mux.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Fatalf("new token status = %d, want 200", recorder.Code)
}
}
// With login off (AUTH_DISABLED, or the login-required override) a caller with no
// session can reach token regeneration, but only as the placeholder identity 0.
// A token minted that way must not open the sync API.
func TestTokenMintedWithoutASessionDoesNotOpenTheSyncAPI(t *testing.T) {
api := newTestAPI(t)
answer := decodeBody[map[string]string](t, api.mustDo(http.MethodPost, "/api/auth/token/regenerate", "", nil, http.StatusOK))
minted := answer["token"]
if minted == "" {
t.Fatalf("regenerate answer = %v, want a token", answer)
}
if got := api.count(`SELECT count(*) FROM api_tokens WHERE user_id = 0`); got != 1 {
t.Fatalf("tokens stored for identity 0 = %d, want 1", got)
}
for _, probe := range []struct{ method, path string }{
{http.MethodGet, "/api/lists"},
{http.MethodPost, "/api/sync"},
} {
request := httptest.NewRequest(probe.method, probe.path, strings.NewReader("{}"))
request.Header.Set("Authorization", "Bearer "+minted)
recorder := httptest.NewRecorder()
api.mux.ServeHTTP(recorder, request)
if recorder.Code != http.StatusUnauthorized {
t.Fatalf("%s %s with a session-less token status = %d, want 401", probe.method, probe.path, recorder.Code)
}
}
// And it did not disturb the real account's token.
api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)
}
func TestSetupClaimCanBeTakenOnceAndReopened(t *testing.T) {
db := testDB(t)
ctx := context.Background()
claimed, err := db.IsSetupClaimed(ctx)
if err != nil || claimed {
t.Fatalf("IsSetupClaimed() on a new database = %v, %v, want false", claimed, err)
}
if won, err := db.TryClaimSetup(ctx); err != nil || !won {
t.Fatalf("first TryClaimSetup() = %v, %v, want true", won, err)
}
if won, err := db.TryClaimSetup(ctx); err != nil || won {
t.Fatalf("second TryClaimSetup() = %v, %v, want false", won, err)
}
if err := db.UnclaimSetup(ctx); err != nil {
t.Fatal(err)
}
if won, err := db.TryClaimSetup(ctx); err != nil || !won {
t.Fatalf("TryClaimSetup() after UnclaimSetup() = %v, %v, want true", won, err)
}
}
+27
View File
@@ -41,6 +41,31 @@ func enqueueNotification(
return err
}
// enqueueNotificationInTx writes a notification inside a savepoint. PostgreSQL
// aborts the whole transaction after any failing statement, so without the
// savepoint a failed notification insert would make the data mutation's commit
// fail too.
func enqueueNotificationInTx(
ctx context.Context,
tx pgx.Tx,
deviceID string,
eventType string,
entityType string,
entityID string,
listID string,
createdAt int64,
) error {
savepoint, err := tx.Begin(ctx)
if err != nil {
return err
}
if err := enqueueNotification(ctx, savepoint, deviceID, eventType, entityType, entityID, listID, createdAt); err != nil {
_ = savepoint.Rollback(ctx)
return err
}
return savepoint.Commit(ctx)
}
func nullableString(value string) any {
if value == "" {
return nil
@@ -48,6 +73,8 @@ func nullableString(value string) any {
return value
}
// ignoreNotificationError logs a failed notification. Use it only for
// notifications written by enqueueNotificationInTx or outside a transaction.
func ignoreNotificationError(err error) {
if err != nil {
// Notifications are an acceleration path for clients that poll. A failed
+212
View File
@@ -0,0 +1,212 @@
package main
import (
"bytes"
"encoding/json"
"io"
"math"
"net"
"net/http"
"strconv"
"strings"
"sync"
"time"
)
// Budgets for the credential-bearing auth routes. Client IPs are resolved with
// clientIP, so they honour X-Forwarded-For only from TRUSTED_PROXIES.
const (
authIPLimit = 30
authIPWindow = time.Minute
loginFailureLimit = 10
loginFailureWindow = 15 * time.Minute
// loginBodyLimit matches the body cap AuthGuard's login handler reads.
loginBodyLimit = 128 * 1024
// rateLimiterMaxKeys bounds memory held for distinct keys.
rateLimiterMaxKeys = 10000
)
// rateLimiter counts events per key in fixed windows. It lives in process, so
// the budgets apply to one server instance.
type rateLimiter struct {
mu sync.Mutex
limit int
window time.Duration
maxKeys int
now func() time.Time
counts map[string]*rateWindow
}
type rateWindow struct {
start time.Time
count int
}
func newRateLimiter(limit int, window time.Duration) *rateLimiter {
return &rateLimiter{
limit: limit,
window: window,
maxKeys: rateLimiterMaxKeys,
now: time.Now,
counts: make(map[string]*rateWindow),
}
}
// Blocked reports whether key has spent its budget in the current window, and
// how long until that window ends.
func (l *rateLimiter) Blocked(key string) (bool, time.Duration) {
l.mu.Lock()
defer l.mu.Unlock()
now := l.now()
window, ok := l.counts[key]
if !ok || now.Sub(window.start) >= l.window || window.count < l.limit {
return false, 0
}
return true, window.start.Add(l.window).Sub(now)
}
// Hit counts one event for key in the current window.
func (l *rateLimiter) Hit(key string) {
l.mu.Lock()
defer l.mu.Unlock()
now := l.now()
window, ok := l.counts[key]
if !ok || now.Sub(window.start) >= l.window {
if !ok && len(l.counts) >= l.maxKeys {
l.evictLocked(now)
}
window = &rateWindow{start: now}
l.counts[key] = window
}
window.count++
}
// evictLocked drops expired windows. If every window is still live, it clears
// the map rather than let memory grow without bound. That can reset budgets
// under a flood of distinct keys, which is the cost of a bounded map.
func (l *rateLimiter) evictLocked(now time.Time) {
for key, window := range l.counts {
if now.Sub(window.start) >= l.window {
delete(l.counts, key)
}
}
if len(l.counts) >= l.maxKeys {
clear(l.counts)
}
}
// writeRateLimited answers 429 with a Retry-After in whole seconds.
func writeRateLimited(w http.ResponseWriter, retryAfter time.Duration) {
seconds := int(math.Ceil(retryAfter.Seconds()))
if seconds < 1 {
seconds = 1
}
w.Header().Set("Retry-After", strconv.Itoa(seconds))
writeJSONError(w, http.StatusTooManyRequests, "Too many attempts. Try again later.")
}
// authRateLimits holds the budgets for the auth routes. A fresh set is built
// per route registration, so tests start with empty counters.
type authRateLimits struct {
trusted []*net.IPNet
ip *rateLimiter
failures *rateLimiter
}
func newAuthRateLimits(trusted []*net.IPNet) *authRateLimits {
return &authRateLimits{
trusted: trusted,
ip: newRateLimiter(authIPLimit, authIPWindow),
failures: newRateLimiter(loginFailureLimit, loginFailureWindow),
}
}
// perClient counts every request against the client's IP and refuses it once
// the IP has spent its budget. Used on setup, TOTP and token regeneration.
func (l *authRateLimits) perClient(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := clientIP(r, l.trusted)
if blocked, retryAfter := l.ip.Blocked(key); blocked {
writeRateLimited(w, retryAfter)
return
}
l.ip.Hit(key)
next.ServeHTTP(w, r)
})
}
// login applies two budgets. Every attempt counts against the client IP. Failed
// attempts (401) count against the account named in the body, so guessing one
// password is capped even when the attacker rotates addresses.
func (l *authRateLimits) login(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := clientIP(r, l.trusted)
if blocked, retryAfter := l.ip.Blocked(key); blocked {
writeRateLimited(w, retryAfter)
return
}
l.ip.Hit(key)
account := loginAccount(r)
if account != "" {
if blocked, retryAfter := l.failures.Blocked(account); blocked {
writeRateLimited(w, retryAfter)
return
}
}
recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(recorder, r)
if account != "" && recorder.status == http.StatusUnauthorized {
l.failures.Hit(account)
}
})
}
// loginAccount returns the normalised identifier from a login body and restores
// the body for the handler. It returns "" when the body names no account.
func loginAccount(r *http.Request) string {
if r.Body == nil {
return ""
}
raw, err := io.ReadAll(io.LimitReader(r.Body, loginBodyLimit))
_ = r.Body.Close()
r.Body = io.NopCloser(bytes.NewReader(raw))
if err != nil {
return ""
}
var input struct {
Identifier string `json:"identifier"`
Email string `json:"email"`
}
if json.Unmarshal(raw, &input) != nil {
return ""
}
identifier := strings.TrimSpace(input.Identifier)
if identifier == "" {
identifier = strings.TrimSpace(input.Email)
}
return strings.ToLower(identifier)
}
// statusRecorder notes the status code a handler writes, so login can tell a
// rejected password from other outcomes.
type statusRecorder struct {
http.ResponseWriter
status int
wroteHeader bool
}
func (w *statusRecorder) WriteHeader(status int) {
if !w.wroteHeader {
w.status = status
w.wroteHeader = true
}
w.ResponseWriter.WriteHeader(status)
}
func (w *statusRecorder) Write(p []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
return w.ResponseWriter.Write(p)
}
+226
View File
@@ -0,0 +1,226 @@
package main
import (
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
)
func TestRateLimiterBlocksAfterLimitAndResetsWithWindow(t *testing.T) {
now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC)
limiter := newRateLimiter(3, time.Minute)
limiter.now = func() time.Time { return now }
for i := 0; i < 3; i++ {
if blocked, _ := limiter.Blocked("a"); blocked {
t.Fatalf("hit %d blocked before the budget was spent", i+1)
}
limiter.Hit("a")
}
blocked, retryAfter := limiter.Blocked("a")
if !blocked {
t.Fatal("fourth attempt was not blocked")
}
if retryAfter != time.Minute {
t.Fatalf("retryAfter = %s, want 1m0s", retryAfter)
}
if blocked, _ := limiter.Blocked("b"); blocked {
t.Fatal("budget for one key blocked another key")
}
now = now.Add(30 * time.Second)
if blocked, retryAfter := limiter.Blocked("a"); !blocked || retryAfter != 30*time.Second {
t.Fatalf("mid-window Blocked() = %v, %s; want true, 30s", blocked, retryAfter)
}
now = now.Add(31 * time.Second)
if blocked, _ := limiter.Blocked("a"); blocked {
t.Fatal("budget did not reset when the window ended")
}
}
func TestRateLimiterBoundsDistinctKeys(t *testing.T) {
now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC)
limiter := newRateLimiter(5, time.Minute)
limiter.maxKeys = 4
limiter.now = func() time.Time { return now }
for i := 0; i < 20; i++ {
limiter.Hit("ip-" + strconv.Itoa(i))
if len(limiter.counts) > limiter.maxKeys {
t.Fatalf("tracked %d keys, want at most %d", len(limiter.counts), limiter.maxKeys)
}
}
// Once the windows have expired, a new key evicts them instead of clearing live ones.
now = now.Add(2 * time.Minute)
limiter.Hit("fresh")
if len(limiter.counts) != 1 {
t.Fatalf("after expiry tracked %d keys, want 1", len(limiter.counts))
}
}
func TestPerClientBudgetCountsEveryRequest(t *testing.T) {
limits := newAuthRateLimits(nil)
reached := 0
handler := limits.perClient(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
reached++
w.WriteHeader(http.StatusOK)
}))
for i := 0; i < authIPLimit+1; i++ {
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/api/auth/totp/enable", nil))
if i < authIPLimit && recorder.Code != http.StatusOK {
t.Fatalf("request %d status = %d, want 200", i+1, recorder.Code)
}
if i == authIPLimit {
if recorder.Code != http.StatusTooManyRequests {
t.Fatalf("request %d status = %d, want 429", i+1, recorder.Code)
}
if recorder.Header().Get("Retry-After") == "" {
t.Fatal("429 response has no Retry-After header")
}
}
}
if reached != authIPLimit {
t.Fatalf("handler ran %d times, want %d", reached, authIPLimit)
}
}
// loginRequest sends one login attempt from the given address and returns the status.
func loginRequest(handler http.Handler, remoteAddr, forwardedFor, body string) int {
request := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(body))
request.RemoteAddr = remoteAddr
if forwardedFor != "" {
request.Header.Set("X-Forwarded-For", forwardedFor)
}
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
return recorder.Code
}
func TestLoginLocksAccountAfterFailuresAcrossAddresses(t *testing.T) {
limits := newAuthRateLimits(nil)
handler := limits.login(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// The handler must still see the body that the limiter read.
raw, _ := io.ReadAll(r.Body)
if !strings.Contains(string(raw), `"password":"wrong"`) {
t.Errorf("handler body = %q, want the original login body", raw)
}
w.WriteHeader(http.StatusUnauthorized)
}))
body := `{"identifier":" Alice@Example.com ","password":"wrong"}`
for i := 0; i < loginFailureLimit; i++ {
// A new address each time, so only the per-account budget can trip.
addr := "198.51.100." + strconv.Itoa(i+1) + ":5000"
if status := loginRequest(handler, addr, "", body); status != http.StatusUnauthorized {
t.Fatalf("failed attempt %d status = %d, want 401", i+1, status)
}
}
if status := loginRequest(handler, "203.0.113.50:5000", "", body); status != http.StatusTooManyRequests {
t.Fatalf("attempt after lockout status = %d, want 429", status)
}
other := `{"identifier":"bob@example.com","password":"wrong"}`
if status := loginRequest(handler, "203.0.113.51:5000", "", other); status != http.StatusUnauthorized {
t.Fatalf("different account status = %d, want 401", status)
}
}
func TestLoginSuccessesDoNotCountAgainstAccount(t *testing.T) {
limits := newAuthRateLimits(nil)
handler := limits.login(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
body := `{"email":"carol@example.com","password":"right"}`
for i := 0; i < loginFailureLimit+5; i++ {
if status := loginRequest(handler, "198.51.100.9:5000", "", body); status != http.StatusOK {
t.Fatalf("successful attempt %d status = %d, want 200", i+1, status)
}
}
}
func TestLoginIPBudgetUsesForwardedClientOnlyFromTrustedProxy(t *testing.T) {
trusted := mustTrusted(t, "10.0.0.1")
body := `{"identifier":"someone","password":"x"}`
ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
// Behind the trusted proxy, each forwarded client has its own budget.
proxied := newAuthRateLimits(trusted).login(ok)
for i := 0; i < authIPLimit+10; i++ {
forwarded := "203.0.113." + strconv.Itoa(i+1)
if status := loginRequest(proxied, "10.0.0.1:5000", forwarded, body); status != http.StatusOK {
t.Fatalf("forwarded client %s status = %d, want 200", forwarded, status)
}
}
// A caller that is not a trusted proxy cannot pick its own address.
direct := newAuthRateLimits(trusted).login(ok)
statuses := make(map[int]int)
for i := 0; i < authIPLimit+10; i++ {
forwarded := "203.0.113." + strconv.Itoa(i+1)
statuses[loginRequest(direct, "192.0.2.9:5000", forwarded, body)]++
}
if statuses[http.StatusTooManyRequests] == 0 {
t.Fatalf("forged X-Forwarded-For bypassed the IP budget: %v", statuses)
}
}
func TestRegisterRoutesLimitsLoginPerClient(t *testing.T) {
// Auth is disabled, so login answers 200 without touching the database.
server := &Server{auth: newAuthService(nil, "", false, true)}
mux := http.NewServeMux()
server.registerRoutes(mux, webFS)
body := `{"identifier":"admin","password":"x"}`
for i := 0; i < authIPLimit; i++ {
if status := loginRequest(mux, "192.0.2.20:5000", "", body); status != http.StatusOK {
t.Fatalf("attempt %d status = %d, want 200", i+1, status)
}
}
if status := loginRequest(mux, "192.0.2.20:5000", "", body); status != http.StatusTooManyRequests {
t.Fatalf("attempt over the budget status = %d, want 429", status)
}
if status := loginRequest(mux, "192.0.2.21:5000", "", body); status != http.StatusOK {
t.Fatalf("other client status = %d, want 200", status)
}
}
func TestWithHTTPSRequiredRefusesPlainHTTP(t *testing.T) {
trusted := mustTrusted(t, "10.0.0.1")
ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
handler := withHTTPSRequired(trusted, ok)
cases := []struct {
name string
path string
remoteAddr string
proto string
want int
}{
{name: "plain request refused", path: "/api/lists", remoteAddr: "192.0.2.9:5000", want: http.StatusForbidden},
{name: "health probe stays open", path: "/health", remoteAddr: "192.0.2.9:5000", want: http.StatusOK},
{name: "trusted proxy over https allowed", path: "/api/lists", remoteAddr: "10.0.0.1:5000", proto: "https", want: http.StatusOK},
{name: "trusted proxy over http refused", path: "/api/lists", remoteAddr: "10.0.0.1:5000", proto: "http", want: http.StatusForbidden},
{name: "untrusted https claim refused", path: "/api/lists", remoteAddr: "192.0.2.9:5000", proto: "https", want: http.StatusForbidden},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, tc.path, nil)
request.RemoteAddr = tc.remoteAddr
if tc.proto != "" {
request.Header.Set("X-Forwarded-Proto", tc.proto)
}
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != tc.want {
t.Fatalf("status = %d, want %d", recorder.Code, tc.want)
}
})
}
}
+27 -2
View File
@@ -2,10 +2,35 @@ package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestRegisterRoutes(t *testing.T) {
server := &Server{auth: newAuthService(nil, "", false, false)}
server.registerRoutes(http.NewServeMux(), webFS)
// Auth is disabled and there is no database, so these checks only touch
// routes that answer before any query runs.
server := &Server{auth: newAuthService(nil, "", false, true)}
mux := http.NewServeMux()
server.registerRoutes(mux, webFS)
cases := []struct {
name string
method string
path string
want int
}{
{name: "health is public", method: http.MethodGet, path: "/health", want: http.StatusOK},
{name: "sync needs a bearer token", method: http.MethodPost, path: "/api/sync", want: http.StatusUnauthorized},
{name: "lists need a bearer token", method: http.MethodGet, path: "/api/lists", want: http.StatusUnauthorized},
{name: "managed users pass the role gate when auth is disabled", method: http.MethodGet, path: "/api/auth/users", want: http.StatusOK},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
mux.ServeHTTP(recorder, httptest.NewRequest(tc.method, tc.path, nil))
if recorder.Code != tc.want {
t.Fatalf("%s %s status = %d, want %d", tc.method, tc.path, recorder.Code, tc.want)
}
})
}
}
+186 -23
View File
@@ -1,12 +1,14 @@
package main
import (
"compress/gzip"
"context"
"embed"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"path"
@@ -36,8 +38,19 @@ type Server struct {
internalServiceSecret string
coreConfig *coreconfig.Store
carrierNode *carriernodeclient.Client
syncSlots chan struct{}
// trustedProxies are the TRUSTED_PROXIES networks whose X-Forwarded-For and
// X-Forwarded-Proto headers are believed. Nil trusts no proxy.
trustedProxies []*net.IPNet
}
// Request body limits per route. Sync pushes can carry many rows at once, so
// they keep the larger limit; single-entity writes get the smaller one.
const (
jsonBodyLimit = 2 << 20
syncBodyLimit = 50 << 20
)
func main() {
port := envOrDefault("PORT", "8080")
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
@@ -47,6 +60,19 @@ func main() {
}
internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET"))
trustedProxies, err := parseTrustedProxies(os.Getenv("TRUSTED_PROXIES"))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// PRODUCTION=true refuses plain HTTP. This process has no TLS of its own, so
// the encrypted hop has to be a reverse proxy listed in TRUSTED_PROXIES.
production := strings.EqualFold(strings.TrimSpace(os.Getenv("PRODUCTION")), "true")
if production && len(trustedProxies) == 0 {
fmt.Fprintln(os.Stderr, "PRODUCTION=true requires TRUSTED_PROXIES: HTTPS must be terminated by a reverse proxy listed there")
os.Exit(1)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -104,6 +130,8 @@ func main() {
internalServiceSecret: internalServiceSecret,
coreConfig: coreConfig,
carrierNode: carrierNode,
syncSlots: make(chan struct{}, maxConcurrentSyncs),
trustedProxies: trustedProxies,
}
webRoot, err := fs.Sub(webFS, "web")
@@ -115,9 +143,17 @@ func main() {
mux := http.NewServeMux()
server.registerRoutes(mux, webRoot)
handler := withSecurityHeaders(withGzip(withCORS(allowedOriginsFromEnv(), mux)))
if production {
handler = withHTTPSRequired(trustedProxies, handler)
fmt.Println("PRODUCTION=true: plain HTTP requests are refused unless they arrive over TLS or through a trusted proxy that sets X-Forwarded-Proto: https")
} else {
fmt.Fprintln(os.Stderr, "WARNING: TLS is off in this process, so passwords, session cookies and sync tokens cross the network unencrypted unless a TLS proxy is in front. Set PRODUCTION=true to refuse plain HTTP.")
}
httpServer := &http.Server{
Addr: ":" + port,
Handler: withCORS(mux),
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
@@ -163,6 +199,10 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error)
}
func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
// Budgets for setup, login, TOTP and token regeneration, keyed by client IP
// (and by account for failed logins). See ratelimit.go.
limits := newAuthRateLimits(s.trustedProxies)
// Health and auth bootstrap routes are intentionally public.
mux.HandleFunc("GET /health", s.handleHealth)
mux.HandleFunc("GET /api/info", s.handleInfo)
@@ -170,22 +210,23 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
// to push a fresh AuthGuard/CarrierNode URL (see coreConfig's construction in main above).
mux.Handle("PUT /api/core-services/internal", coreconfig.Handler(s.internalServiceSecret, s.coreConfig))
mux.HandleFunc("GET /api/auth/status", s.auth.Status)
mux.HandleFunc("POST /api/auth/setup", s.auth.Signup)
mux.HandleFunc("POST /api/auth/login", s.auth.Login)
mux.Handle("POST /api/auth/setup", limits.perClient(http.HandlerFunc(s.auth.Signup)))
mux.Handle("POST /api/auth/login", limits.login(http.HandlerFunc(s.auth.Login)))
mux.Handle("PUT /api/auth/access/internal", s.auth.SetLoginRequiredInternal(s.internalServiceSecret))
mux.Handle("POST /api/auth/logout", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.Logout)))
mux.Handle("POST /api/auth/credentials", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.UpdateMe)))
mux.Handle("GET /api/auth/users", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUsers)))
mux.Handle("POST /api/auth/users", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedCreateUser)))
mux.Handle("PUT /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUpdateUser)))
mux.Handle("PATCH /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedUpdateUser)))
mux.Handle("DELETE /api/auth/users/{id}", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.ManagedDeleteUser)))
mux.Handle("GET /api/auth/totp/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPStatus)))
mux.Handle("POST /api/auth/totp/setup", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPInitiate)))
mux.Handle("POST /api/auth/totp/enable", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPVerify)))
mux.Handle("POST /api/auth/totp/disable", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPDisable)))
// Managed-user routes check the caller's role here, not only in AuthGuard.
mux.Handle("GET /api/auth/users", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUsers)))
mux.Handle("POST /api/auth/users", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedCreateUser)))
mux.Handle("PUT /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUpdateUser)))
mux.Handle("PATCH /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedUpdateUser)))
mux.Handle("DELETE /api/auth/users/{id}", s.auth.RequireUserManager(http.HandlerFunc(s.auth.ManagedDeleteUser)))
mux.Handle("GET /api/auth/totp/status", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPStatus))))
mux.Handle("POST /api/auth/totp/setup", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPInitiate))))
mux.Handle("POST /api/auth/totp/enable", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPVerify))))
mux.Handle("POST /api/auth/totp/disable", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.auth.TOTPDisable))))
mux.Handle("GET /api/auth/token/status", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenStatus)))
mux.Handle("POST /api/auth/token/regenerate", s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenRegenerate)))
mux.Handle("POST /api/auth/token/regenerate", limits.perClient(s.auth.RequireIfLoginRequired(http.HandlerFunc(s.handleTokenRegenerate))))
// Sync/collaboration API routes use a long-lived bearer token shared by the
// user's devices. This is deliberately separate from browser sessions.
@@ -250,12 +291,24 @@ func envOrDefault(name, fallback string) string {
return fallback
}
func decodeJSON(r *http.Request, target any) error {
decoder := json.NewDecoder(io.LimitReader(r.Body, 50*1024*1024))
if err := decoder.Decode(target); err != nil {
return err
func decodeJSON(w http.ResponseWriter, r *http.Request, target any) error {
return decodeJSONLimit(w, r, target, jsonBodyLimit)
}
// decodeJSONLimit decodes a body of at most limit bytes. An oversized body fails
// with *http.MaxBytesError, which writeDecodeError turns into 413.
func decodeJSONLimit(w http.ResponseWriter, r *http.Request, target any, limit int64) error {
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit))
return decoder.Decode(target)
}
func writeDecodeError(w http.ResponseWriter, err error, message string) {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
writeJSONError(w, http.StatusRequestEntityTooLarge, "Request body too large")
return
}
return nil
writeJSONError(w, http.StatusBadRequest, message)
}
func writeJSON(w http.ResponseWriter, status int, value any) {
@@ -271,17 +324,42 @@ func writeJSONError(w http.ResponseWriter, status int, message string) {
})
}
func withCORS(next http.Handler) http.Handler {
// allowedOriginsFromEnv reads ALLOWED_ORIGINS, a comma-separated list of browser
// origins that may call the API cross-origin with credentials. It is empty by
// default: the dashboard is same-origin and needs no CORS headers.
func allowedOriginsFromEnv() []string {
var origins []string
for _, origin := range strings.Split(os.Getenv("ALLOWED_ORIGINS"), ",") {
if origin = strings.TrimSpace(origin); origin != "" {
origins = append(origins, origin)
}
}
return origins
}
// withCORS sends CORS headers only for origins in allowedOrigins. Any other
// origin gets no Access-Control-Allow-Origin and no credentials header, so a
// browser refuses its cross-origin reads.
func withCORS(allowedOrigins []string, next http.Handler) http.Handler {
allowed := make(map[string]bool, len(allowedOrigins))
for _, origin := range allowedOrigins {
allowed[origin] = true
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Add("Vary", "Origin")
}
permitted := origin != "" && allowed[origin]
if permitted {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
if r.Method == http.MethodOptions {
if permitted {
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
}
w.WriteHeader(http.StatusNoContent)
return
}
@@ -289,6 +367,82 @@ func withCORS(next http.Handler) http.Handler {
})
}
// withSecurityHeaders sets headers that stop the dashboard and API from being
// framed (clickjacking) or MIME-sniffed. The dashboard page replaces the
// Content-Security-Policy with the full one from dashboardCSP. HSTS is not set
// here: this process has no TLS, so the TLS proxy sets Strict-Transport-Security.
func withSecurityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
headers := w.Header()
headers.Set("X-Content-Type-Options", "nosniff")
headers.Set("X-Frame-Options", "DENY")
headers.Set("Content-Security-Policy", "frame-ancestors 'none'")
headers.Set("Referrer-Policy", "strict-origin-when-cross-origin")
next.ServeHTTP(w, r)
})
}
// withHTTPSRequired is the PRODUCTION=true profile: a request that did not
// arrive over TLS, directly or through a trusted proxy, gets 403. The health
// probe is exempt so local container checks keep working.
func withHTTPSRequired(trusted []*net.IPNet, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/health" || requestIsHTTPS(r, trusted) {
next.ServeHTTP(w, r)
return
}
writeJSONError(w, http.StatusForbidden, "HTTPS is required on this server")
})
}
// gzipResponseWriter compresses a response body when the client accepts gzip.
// Responses that carry no body (204, 304) are passed through unchanged.
type gzipResponseWriter struct {
http.ResponseWriter
gzipWriter *gzip.Writer
wroteHeader bool
}
func (w *gzipResponseWriter) WriteHeader(status int) {
if w.wroteHeader {
return
}
w.wroteHeader = true
// Partial (206) bodies are left alone: a byte range of the plain file is not a gzip stream.
if status != http.StatusNoContent && status != http.StatusNotModified && status != http.StatusPartialContent {
w.Header().Set("Content-Encoding", "gzip")
w.Header().Del("Content-Length")
w.gzipWriter = gzip.NewWriter(w.ResponseWriter)
}
w.ResponseWriter.WriteHeader(status)
}
func (w *gzipResponseWriter) Write(p []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
if w.gzipWriter == nil {
return w.ResponseWriter.Write(p)
}
return w.gzipWriter.Write(p)
}
// withGzip compresses responses for clients that send Accept-Encoding: gzip.
func withGzip(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Vary", "Accept-Encoding")
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
return
}
compressed := &gzipResponseWriter{ResponseWriter: w}
next.ServeHTTP(compressed, r)
if compressed.gzipWriter != nil {
_ = compressed.gzipWriter.Close()
}
})
}
func spaFileServer(root fs.FS) http.Handler {
fileServer := http.FileServer(http.FS(root))
serveIndex := func(w http.ResponseWriter, r *http.Request) {
@@ -298,6 +452,8 @@ func spaFileServer(root fs.FS) http.Handler {
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Content-Security-Policy", dashboardCSP(data))
_, _ = w.Write(data)
}
@@ -311,6 +467,13 @@ func spaFileServer(root fs.FS) http.Handler {
serveIndex(w, r)
return
}
// SvelteKit names its content-hashed bundle files under _app/immutable/, so
// those can be cached for a long time. Everything else is revalidated.
if strings.HasPrefix(cleanPath, "_app/immutable/") {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
} else {
w.Header().Set("Cache-Control", "no-cache")
}
fileServer.ServeHTTP(w, r)
})
}
+203
View File
@@ -0,0 +1,203 @@
package main
import (
"compress/gzip"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
)
func TestWithCORSAllowsOnlyListedOrigins(t *testing.T) {
const listed = "https://dashboard.example.com"
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
cases := []struct {
name string
allowed []string
origin string
want string
}{
{name: "listed origin is echoed", allowed: []string{listed}, origin: listed, want: listed},
{name: "unlisted origin gets no header", allowed: []string{listed}, origin: "https://evil.example", want: ""},
{name: "no allow list means no CORS", allowed: nil, origin: listed, want: ""},
{name: "no origin header means no CORS", allowed: []string{listed}, origin: "", want: ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
if tc.origin != "" {
request.Header.Set("Origin", tc.origin)
}
withCORS(tc.allowed, next).ServeHTTP(recorder, request)
if got := recorder.Header().Get("Access-Control-Allow-Origin"); got != tc.want {
t.Fatalf("Access-Control-Allow-Origin = %q, want %q", got, tc.want)
}
wantCredentials := ""
if tc.want != "" {
wantCredentials = "true"
}
if got := recorder.Header().Get("Access-Control-Allow-Credentials"); got != wantCredentials {
t.Fatalf("Access-Control-Allow-Credentials = %q, want %q", got, wantCredentials)
}
})
}
}
func TestWithCORSPreflightAllowsPatchForListedOrigin(t *testing.T) {
const listed = "https://dashboard.example.com"
handler := withCORS([]string{listed}, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodOptions, "/api/auth/users/1", nil)
request.Header.Set("Origin", listed)
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusNoContent {
t.Fatalf("preflight status = %d, want %d", recorder.Code, http.StatusNoContent)
}
if methods := recorder.Header().Get("Access-Control-Allow-Methods"); !strings.Contains(methods, "PATCH") {
t.Fatalf("Access-Control-Allow-Methods = %q, want PATCH included", methods)
}
}
func TestWithSecurityHeadersSetsFramingAndSniffingDefaults(t *testing.T) {
handler := withSecurityHeaders(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
want := map[string]string{
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Content-Security-Policy": "frame-ancestors 'none'",
"Referrer-Policy": "strict-origin-when-cross-origin",
}
for name, value := range want {
if got := recorder.Header().Get(name); got != value {
t.Fatalf("%s = %q, want %q", name, got, value)
}
}
}
func TestWithGzipCompressesOnlyWhenAccepted(t *testing.T) {
handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}))
accepted := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
request.Header.Set("Accept-Encoding", "gzip, deflate")
handler.ServeHTTP(accepted, request)
if got := accepted.Header().Get("Content-Encoding"); got != "gzip" {
t.Fatalf("Content-Encoding = %q, want gzip", got)
}
reader, err := gzip.NewReader(accepted.Body)
if err != nil {
t.Fatalf("gzip.NewReader() error = %v", err)
}
body, err := io.ReadAll(reader)
if err != nil {
t.Fatalf("reading gzip body error = %v", err)
}
if got := strings.TrimSpace(string(body)); got != `{"ok":true}` {
t.Fatalf("decompressed body = %q, want the JSON document", got)
}
plain := httptest.NewRecorder()
handler.ServeHTTP(plain, httptest.NewRequest(http.MethodGet, "/web/data", nil))
if got := plain.Header().Get("Content-Encoding"); got != "" {
t.Fatalf("Content-Encoding without Accept-Encoding = %q, want none", got)
}
if got := strings.TrimSpace(plain.Body.String()); got != `{"ok":true}` {
t.Fatalf("plain body = %q, want the JSON document", got)
}
}
func TestWithGzipLeavesNotModifiedWithoutBody(t *testing.T) {
handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("ETag", `W/"abc"`)
w.WriteHeader(http.StatusNotModified)
}))
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
request.Header.Set("Accept-Encoding", "gzip")
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusNotModified {
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusNotModified)
}
if got := recorder.Header().Get("Content-Encoding"); got != "" {
t.Fatalf("Content-Encoding on 304 = %q, want none", got)
}
if recorder.Body.Len() != 0 {
t.Fatalf("304 body length = %d, want 0", recorder.Body.Len())
}
}
func TestSPAFileServerCachesHashedAssetsLong(t *testing.T) {
root := fstest.MapFS{
"index.html": {Data: []byte("<html></html>")},
"favicon.svg": {Data: []byte("<svg></svg>")},
"_app/immutable/app.abc.js": {Data: []byte("console.log(1)")},
}
handler := spaFileServer(root)
cases := []struct {
path string
want string
}{
{path: "/", want: "no-cache"},
{path: "/favicon.svg", want: "no-cache"},
{path: "/_app/immutable/app.abc.js", want: "public, max-age=31536000, immutable"},
{path: "/lists/123", want: "no-cache"},
}
for _, tc := range cases {
t.Run(tc.path, func(t *testing.T) {
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, tc.path, nil))
if got := recorder.Header().Get("Cache-Control"); got != tc.want {
t.Fatalf("Cache-Control = %q, want %q", got, tc.want)
}
})
}
}
func TestDecodeJSONLimitRejectsOversizedBodies(t *testing.T) {
type payload struct {
Name string `json:"name"`
}
small := httptest.NewRecorder()
var ok payload
if err := decodeJSONLimit(small, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(`{"name":"a"}`)), &ok, 64); err != nil {
t.Fatalf("decodeJSONLimit() within limit error = %v", err)
}
large := httptest.NewRecorder()
var tooBig payload
body := `{"name":"` + strings.Repeat("a", 256) + `"}`
err := decodeJSONLimit(large, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(body)), &tooBig, 64)
if err == nil {
t.Fatal("decodeJSONLimit() over limit returned no error")
}
answer := httptest.NewRecorder()
writeDecodeError(answer, err, "Invalid JSON body")
if answer.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("status for oversized body = %d, want %d", answer.Code, http.StatusRequestEntityTooLarge)
}
malformed := httptest.NewRecorder()
err = decodeJSONLimit(malformed, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(`{`)), &tooBig, 64)
writeDecodeError(malformed, err, "Invalid JSON body")
if malformed.Code != http.StatusBadRequest {
t.Fatalf("status for malformed body = %d, want %d", malformed.Code, http.StatusBadRequest)
}
}
+237 -172
View File
@@ -1,7 +1,7 @@
package main
import (
"errors"
"context"
"fmt"
"net/http"
"time"
@@ -9,6 +9,10 @@ import (
"github.com/jackc/pgx/v5"
)
// maxConcurrentSyncs caps sync requests in flight. It stays below the pool size
// (DATABASE_MAX_CONNS defaults to 20), so syncs cannot hold every connection.
const maxConcurrentSyncs = 4
func syncMaxFutureSkew() int64 {
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
if value < 0 {
@@ -42,151 +46,164 @@ func normalizeEntityTimestamps(createdAt, updatedAt, now int64) (int64, int64) {
return created, updated
}
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
var request SyncRequest
if err := decodeJSON(r, &request); err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid sync request")
return
// valueReferences returns the list ID of each field and the existence of each
// item that the values refer to, using one statement per table.
func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[string]string, map[string]bool, error) {
fieldLists := make(map[string]string)
existingItems := make(map[string]bool)
if len(values) == 0 {
return fieldLists, existingItems, nil
}
fieldIDs := make([]string, 0, len(values))
itemIDs := make([]string, 0, len(values))
for _, value := range values {
fieldIDs = append(fieldIDs, value.FieldID)
itemIDs = append(itemIDs, value.ItemID)
}
now := time.Now().UnixMilli()
lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now)
deviceID := requestDeviceID(r, request.DeviceID)
fieldRows, err := tx.Query(ctx, `SELECT id, listid FROM fields WHERE id = ANY($1)`, fieldIDs)
if err != nil {
return nil, nil, err
}
defer fieldRows.Close()
for fieldRows.Next() {
var fieldID, listID string
if err := fieldRows.Scan(&fieldID, &listID); err != nil {
return nil, nil, err
}
fieldLists[fieldID] = listID
}
if err := fieldRows.Err(); err != nil {
return nil, nil, err
}
itemRows, err := tx.Query(ctx, `SELECT id FROM items WHERE id = ANY($1)`, itemIDs)
if err != nil {
return nil, nil, err
}
defer itemRows.Close()
for itemRows.Next() {
var itemID string
if err := itemRows.Scan(&itemID); err != nil {
return nil, nil, err
}
existingItems[itemID] = true
}
if err := itemRows.Err(); err != nil {
return nil, nil, err
}
return fieldLists, existingItems, nil
}
// changeEventType names a synced change for the notification feed: a tombstone
// is "deleted", a first sync reports "created", and anything else "updated".
func changeEventType(initialSync, deleted bool) string {
if deleted {
return "deleted"
}
if initialSync {
return "created"
}
return "updated"
}
// syncBatch holds what every row of one sync request shares.
type syncBatch struct {
now int64
initialSync bool
deviceID string
}
func (b syncBatch) notify(ctx context.Context, tx pgx.Tx, eventType, entityType, entityID, listID string, createdAt int64) {
ignoreNotificationError(enqueueNotificationInTx(ctx, tx, b.deviceID, eventType, entityType, entityID, listID, createdAt))
}
// applyLists upserts the pushed lists. A write older than the stored row
// changes nothing, so it triggers no cascade or notification.
func applyLists(ctx context.Context, tx pgx.Tx, lists []List, batch syncBatch) error {
for _, list := range lists {
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), batch.now)
applied, err := upsertList(ctx, tx, list, createdAt, updatedAt)
if err != nil {
return err
}
if !applied {
continue
}
batch.notify(ctx, tx, changeEventType(batch.initialSync, list.IsDeleted), "list", list.ID, list.ID, updatedAt)
if list.IsDeleted {
if err := cascadeDeleteList(ctx, tx, list.ID, updatedAt); err != nil {
return err
}
}
}
return nil
}
func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch) error {
for _, field := range fields {
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), batch.now)
applied, err := upsertField(ctx, tx, field, createdAt, updatedAt)
if err != nil {
return err
}
if !applied {
continue
}
batch.notify(ctx, tx, changeEventType(batch.initialSync, field.IsDeleted), "field", field.ID, field.ListID, updatedAt)
if field.IsDeleted {
if _, err := cascadeDeleteField(ctx, tx, field.ID, field.ListID, updatedAt); err != nil {
return err
}
}
}
return nil
}
func applyItems(ctx context.Context, tx pgx.Tx, items []Item, batch syncBatch) error {
for _, item := range items {
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), batch.now)
applied, err := upsertItem(ctx, tx, item, createdAt, updatedAt)
if err != nil {
return err
}
if !applied {
continue
}
batch.notify(ctx, tx, changeEventType(batch.initialSync, item.IsDeleted), "item", item.ID, item.ListID, updatedAt)
if item.IsDeleted {
if err := cascadeDeleteItem(ctx, tx, item.ID); err != nil {
return err
}
}
}
return nil
}
// applyValues upserts the pushed item values and returns the ones it could not
// place. Items are read after applyItems has run, so a request's own item inserts
// are visible.
func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncBatch) ([]OrphanValue, error) {
orphans := make([]OrphanValue, 0)
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
if incoming > 0 {
fmt.Printf("[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues))
// Resolve the fields and items the values refer to once per request, not once
// per value.
fieldLists, existingItems, err := valueReferences(ctx, tx, values)
if err != nil {
return nil, err
}
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
for _, list := range request.Lists {
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), now)
if _, err := tx.Exec(r.Context(), `
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name, updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
`, list.ID, list.Name, createdAt, updatedAt, boolInt(list.IsDeleted)); err != nil {
return err
}
event := "updated"
if lastSync == 0 {
event = "created"
}
if list.IsDeleted {
event = "deleted"
}
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "list", list.ID, list.ID, updatedAt))
if list.IsDeleted {
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil {
return err
}
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil {
return err
}
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, list.ID); err != nil {
return err
}
}
}
for _, field := range request.Fields {
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), now)
fieldType := field.FieldType
if fieldType == "" {
fieldType = "TEXT"
}
alignment := field.Alignment
if alignment == "" {
alignment = "start"
}
if _, err := tx.Exec(r.Context(), `
INSERT INTO fields
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name,
fieldtype = EXCLUDED.fieldtype,
fieldoptions = EXCLUDED.fieldoptions,
alignment = EXCLUDED.alignment,
"order" = EXCLUDED."order",
updatedat = EXCLUDED.updatedat,
isdeleted = EXCLUDED.isdeleted
`, field.ID, field.Name, fieldType, field.FieldOptions, alignment, field.ListID, field.Order, createdAt, updatedAt, boolInt(field.IsDeleted)); err != nil {
return err
}
event := "updated"
if lastSync == 0 {
event = "created"
}
if field.IsDeleted {
event = "deleted"
}
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "field", field.ID, field.ListID, updatedAt))
if field.IsDeleted {
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, field.ID); err != nil {
return err
}
var remaining int
if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil {
return err
}
if remaining == 0 {
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil {
return err
}
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil {
return err
}
}
}
}
for _, item := range request.Items {
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), now)
if _, err := tx.Exec(r.Context(), `
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE
SET updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
`, item.ID, item.ListID, createdAt, updatedAt, boolInt(item.IsDeleted)); err != nil {
return err
}
event := "updated"
if lastSync == 0 {
event = "created"
}
if item.IsDeleted {
event = "deleted"
}
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "item", item.ID, item.ListID, updatedAt))
if item.IsDeleted {
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, item.ID); err != nil {
return err
}
}
}
for _, value := range request.ItemValues {
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), now, now)
var listID string
fieldErr := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, value.FieldID).Scan(&listID)
if errors.Is(fieldErr, pgx.ErrNoRows) {
for _, value := range values {
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), batch.now, batch.now)
listID, ok := fieldLists[value.FieldID]
if !ok {
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
continue
}
if fieldErr != nil {
return fieldErr
}
var itemExists bool
if err := tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM items WHERE id = $1)`, value.ItemID).Scan(&itemExists); err != nil {
return err
}
if !itemExists {
if _, err := tx.Exec(r.Context(), `
if !existingItems[value.ItemID] {
if _, err := tx.Exec(ctx, `
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
VALUES ($1, $2, $3, $3, 0)
ON CONFLICT (id) DO NOTHING
@@ -194,18 +211,87 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
continue
}
existingItems[value.ItemID] = true
}
if _, err := tx.Exec(r.Context(), `
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
`, value.ID, value.ItemID, value.FieldID, value.Value, updatedAt); err != nil {
applied, err := upsertValue(ctx, tx, value, updatedAt)
if err != nil {
return nil, err
}
if !applied {
continue
}
batch.notify(ctx, tx, "listContentUpdated", "value", value.ID, listID, updatedAt)
}
return orphans, nil
}
// applySyncRequest writes everything a device pushed, parents before children.
func applySyncRequest(ctx context.Context, tx pgx.Tx, request SyncRequest, batch syncBatch) ([]OrphanValue, error) {
if err := applyLists(ctx, tx, request.Lists, batch); err != nil {
return nil, err
}
if err := applyFields(ctx, tx, request.Fields, batch); err != nil {
return nil, err
}
if err := applyItems(ctx, tx, request.Items, batch); err != nil {
return nil, err
}
return applyValues(ctx, tx, request.ItemValues, batch)
}
// changesSince reads what a device has to pull: everything when since is nil,
// otherwise the rows updated at or after it. The caller adds the orphan list and
// the server timestamp.
func (d *DB) changesSince(ctx context.Context, since *int64) (SyncResponse, error) {
lists, err := d.queryLists(ctx, true, since)
if err != nil {
return SyncResponse{}, err
}
fields, err := d.queryFields(ctx, true, since, "")
if err != nil {
return SyncResponse{}, err
}
items, err := d.queryItems(ctx, true, since, "")
if err != nil {
return SyncResponse{}, err
}
values, err := d.queryValues(ctx, since, "")
if err != nil {
return SyncResponse{}, err
}
return SyncResponse{Lists: lists, Fields: fields, Items: items, ItemValues: values}, nil
}
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
// Bound the number of syncs in flight, so large bodies and transactions cannot
// take every database connection at once.
select {
case s.syncSlots <- struct{}{}:
defer func() { <-s.syncSlots }()
case <-r.Context().Done():
writeJSONError(w, http.StatusServiceUnavailable, "Sync busy")
return
}
var request SyncRequest
if err := decodeJSONLimit(w, r, &request, syncBodyLimit); err != nil {
writeDecodeError(w, err, "Invalid sync request")
return
}
now := time.Now().UnixMilli()
lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now)
batch := syncBatch{now: now, initialSync: lastSync == 0, deviceID: requestDeviceID(r, request.DeviceID)}
orphans := make([]OrphanValue, 0)
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
if incoming > 0 {
fmt.Printf("[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues))
}
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
var err error
orphans, err = applySyncRequest(r.Context(), tx, request, batch)
return err
}
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, "listContentUpdated", "value", value.ID, listID, updatedAt))
}
return nil
})
if err != nil {
fmt.Printf("[SYNC] Failed: %v\n", err)
@@ -217,33 +303,12 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
if lastSync != 0 {
since = &lastSync
}
lists, err := s.db.queryLists(r.Context(), true, since)
response, err := s.db.changesSince(r.Context(), since)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
return
}
fields, err := s.db.queryFields(r.Context(), true, since, "")
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
return
}
items, err := s.db.queryItems(r.Context(), true, since, "")
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
return
}
values, err := s.db.queryValues(r.Context(), since, "")
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
return
}
writeJSON(w, http.StatusOK, SyncResponse{
Lists: lists,
Fields: fields,
Items: items,
ItemValues: values,
OrphanItemValues: orphans,
ServerTimestamp: time.Now().UnixMilli(),
})
response.OrphanItemValues = orphans
response.ServerTimestamp = time.Now().UnixMilli()
writeJSON(w, http.StatusOK, response)
}
+21
View File
@@ -25,3 +25,24 @@ func TestNormalizeEntityTimestampsKeepsUpdatedAfterCreated(t *testing.T) {
t.Fatalf("timestamps = (%d, %d), want (%d, %d)", created, updated, now-100, now-100)
}
}
func TestChangeEventTypeNamesEachChange(t *testing.T) {
cases := []struct {
name string
initialSync bool
deleted bool
want string
}{
{name: "first sync creates", initialSync: true, want: "created"},
{name: "later edit updates", initialSync: false, want: "updated"},
{name: "tombstone is deleted on first sync", initialSync: true, deleted: true, want: "deleted"},
{name: "tombstone is deleted later", initialSync: false, deleted: true, want: "deleted"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := changeEventType(tc.initialSync, tc.deleted); got != tc.want {
t.Fatalf("changeEventType(%v, %v) = %q, want %q", tc.initialSync, tc.deleted, got, tc.want)
}
})
}
}
+40 -6
View File
@@ -1,8 +1,12 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/http"
"strconv"
"strings"
"time"
)
@@ -71,10 +75,7 @@ func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
webLists = append(webLists, webList{List: list, EffectiveUpdatedAt: effective})
}
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
writeJSON(w, http.StatusOK, map[string]any{
payload := map[string]any{
"lists": webLists,
"fields": fields,
"items": items,
@@ -85,8 +86,41 @@ func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
"items": len(items),
"values": len(values),
},
"timestamp": time.Now().UnixMilli(),
})
}
// The ETag covers the data only; the timestamp is added after hashing because
// it changes on every request.
body, err := json.Marshal(payload)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
return
}
digest := sha256.Sum256(body)
etag := `W/"` + hex.EncodeToString(digest[:]) + `"`
// Browsers may keep this per-user response, but revalidate it on every poll,
// so an unchanged dashboard gets a 304 instead of the full body.
w.Header().Set("Cache-Control", "private, no-cache")
w.Header().Set("ETag", etag)
if etagMatches(r.Header.Get("If-None-Match"), etag) {
w.WriteHeader(http.StatusNotModified)
return
}
payload["timestamp"] = time.Now().UnixMilli()
writeJSON(w, http.StatusOK, payload)
}
// etagMatches reports whether an If-None-Match header matches etag under the
// weak comparison of RFC 9110, which ignores the W/ prefix.
func etagMatches(ifNoneMatch, etag string) bool {
if strings.TrimSpace(ifNoneMatch) == "*" {
return true
}
want := strings.TrimPrefix(etag, "W/")
for _, candidate := range strings.Split(ifNoneMatch, ",") {
if strings.TrimPrefix(strings.TrimSpace(candidate), "W/") == want {
return true
}
}
return false
}
func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request) {
+26
View File
@@ -0,0 +1,26 @@
package main
import "testing"
func TestEtagMatchesUsesWeakComparison(t *testing.T) {
const etag = `W/"abc"`
cases := []struct {
name string
ifNoneMatch string
want bool
}{
{name: "missing header", ifNoneMatch: "", want: false},
{name: "same weak tag", ifNoneMatch: `W/"abc"`, want: true},
{name: "strong form of same tag", ifNoneMatch: `"abc"`, want: true},
{name: "one of several tags", ifNoneMatch: `"x", W/"abc"`, want: true},
{name: "different tag", ifNoneMatch: `W/"def"`, want: false},
{name: "wildcard", ifNoneMatch: "*", want: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := etagMatches(tc.ifNoneMatch, etag); got != tc.want {
t.Fatalf("etagMatches(%q) = %v, want %v", tc.ifNoneMatch, got, tc.want)
}
})
}
}
+1
View File
@@ -7,6 +7,7 @@
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"test": "node --test",
"check": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json",
"lint": "eslint .",
"format": "prettier --write .",
@@ -1,7 +1,7 @@
<script>
import ListCard from './ListCard.svelte';
let { lists, fields, items, onSelect } = $props();
let { lists, fieldsByList, itemsByList, onSelect } = $props();
</script>
{#if lists.length === 0}
@@ -12,7 +12,12 @@
{:else}
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{#each lists as list (list.id)}
<ListCard {list} {fields} {items} onClick={onSelect} />
<ListCard
{list}
fields={fieldsByList.get(list.id) ?? []}
items={itemsByList.get(list.id) ?? []}
onClick={onSelect}
/>
{/each}
</div>
{/if}
@@ -1,7 +1,7 @@
<script>
import ListRow from './ListRow.svelte';
let { lists, fields, items, onSelect } = $props();
let { lists, fieldsByList, itemsByList, onSelect } = $props();
</script>
<table class="w-full text-left text-sm">
@@ -15,7 +15,12 @@
</thead>
<tbody>
{#each lists as list (list.id)}
<ListRow {list} {fields} {items} onClick={onSelect} />
<ListRow
{list}
fields={fieldsByList.get(list.id) ?? []}
items={itemsByList.get(list.id) ?? []}
onClick={onSelect}
/>
{/each}
</tbody>
</table>
+14 -2
View File
@@ -6,8 +6,20 @@ export function listItemsFor(items, listId) {
return items.filter((i) => i.listId === listId && !i.isDeleted);
}
export function itemValuesFor(values, itemId) {
return values.filter((v) => v.itemId === itemId);
// groupByKey indexes rows by keyOf in one pass. Build it once per data change in a
// $derived, then look rows up per card, row or cell instead of rescanning the data.
export function groupByKey(rows, keyOf) {
const groups = new Map();
for (const row of rows) {
const key = keyOf(row);
const group = groups.get(key);
if (group) {
group.push(row);
} else {
groups.set(key, [row]);
}
}
return groups;
}
export function valueFor(values, itemId, fieldId) {
@@ -0,0 +1,89 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { fmtDate, groupByKey, listFieldsFor, listItemsFor, valueFor } from './listHelpers.js';
test('listFieldsFor keeps the list’s live fields in display order', () => {
const fields = [
{ id: 'c', listId: 'l1', order: 2 },
{ id: 'gone', listId: 'l1', order: 0, isDeleted: true },
{ id: 'other', listId: 'l2', order: 0 },
{ id: 'a', listId: 'l1', order: 0 },
{ id: 'unordered', listId: 'l1' },
{ id: 'b', listId: 'l1', order: 1 },
];
const ids = listFieldsFor(fields, 'l1').map((f) => f.id);
// A field without an order sorts as 0, and the sort is stable.
assert.deepEqual(ids, ['a', 'unordered', 'b', 'c']);
});
test('listFieldsFor does not reorder the array it was given', () => {
const fields = [
{ id: 'b', listId: 'l1', order: 1 },
{ id: 'a', listId: 'l1', order: 0 },
];
listFieldsFor(fields, 'l1');
assert.deepEqual(
fields.map((f) => f.id),
['b', 'a'],
);
});
test('listItemsFor keeps only the list’s live items', () => {
const items = [
{ id: 'i1', listId: 'l1' },
{ id: 'i2', listId: 'l1', isDeleted: true },
{ id: 'i3', listId: 'l2' },
];
assert.deepEqual(
listItemsFor(items, 'l1').map((i) => i.id),
['i1'],
);
assert.deepEqual(listItemsFor(items, 'missing'), []);
});
test('groupByKey indexes rows by key and keeps their order', () => {
const rows = [
{ id: 1, listId: 'a' },
{ id: 2, listId: 'b' },
{ id: 3, listId: 'a' },
];
const groups = groupByKey(rows, (row) => row.listId);
assert.deepEqual([...groups.keys()], ['a', 'b']);
assert.deepEqual(
groups.get('a').map((row) => row.id),
[1, 3],
);
assert.equal(groups.get('missing'), undefined);
assert.equal(groupByKey([], (row) => row.listId).size, 0);
});
test('valueFor finds the value in one cell, or null', () => {
const values = [
{ itemId: 'i1', fieldId: 'f1', value: 'milk' },
{ itemId: 'i1', fieldId: 'f2', value: '' },
{ itemId: 'i2', fieldId: 'f1', value: 'eggs' },
];
assert.equal(valueFor(values, 'i1', 'f1'), 'milk');
assert.equal(valueFor(values, 'i2', 'f1'), 'eggs');
// An empty value is a value, not a missing one.
assert.equal(valueFor(values, 'i1', 'f2'), '');
assert.equal(valueFor(values, 'i2', 'f2'), null);
});
test('fmtDate shows a dash for missing or invalid dates', () => {
assert.equal(fmtDate(null), '—');
assert.equal(fmtDate(undefined), '—');
assert.equal(fmtDate('not a date'), '—');
});
test('fmtDate formats a millisecond timestamp for the reader’s locale', () => {
const ms = 1_700_000_000_000;
assert.equal(fmtDate(ms), new Date(ms).toLocaleString());
assert.notEqual(fmtDate(ms), '—');
});
+7 -2
View File
@@ -3,6 +3,7 @@
import { resolve } from '$app/paths';
import { ArrowDown, ArrowUp, LayoutGrid, List, Search, X } from '@lucide/svelte';
import { createOverviewData } from '$lib/features/lists/listsData.svelte.js';
import { groupByKey } from '$lib/features/lists/listHelpers.js';
import { searchState, filterListsBySearch } from '$lib/search.svelte.js';
import { createDashboardViewMode } from '$lib/preferences/viewMode.svelte.js';
import Button from '$lib/components/ui/button.svelte';
@@ -42,6 +43,10 @@
let searched = $derived(filterListsBySearch(overview.lists, searchState.query));
let sorted = $derived(sortLists(searched, sortField, sortDir));
let pageItems = $derived(sorted.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize));
// Index fields and items by list once per data change, so each visible card or row
// reads its own slice instead of scanning every field and item.
let fieldsByList = $derived(groupByKey(overview.fields, (f) => f.listId));
let itemsByList = $derived(groupByKey(overview.items, (i) => i.listId));
$effect(() => {
void searchState.query;
@@ -148,9 +153,9 @@
<div class="overflow-x-auto rounded-lg border border-border bg-bg p-3">
{#if viewMode.mode === 'list'}
<ListsTable lists={pageItems} fields={overview.fields} items={overview.items} onSelect={goToList} />
<ListsTable lists={pageItems} {fieldsByList} {itemsByList} onSelect={goToList} />
{:else}
<ListsGrid lists={pageItems} fields={overview.fields} items={overview.items} onSelect={goToList} />
<ListsGrid lists={pageItems} {fieldsByList} {itemsByList} onSelect={goToList} />
{/if}
</div>
+3 -2
View File
@@ -5,7 +5,7 @@
import Button from '$lib/components/ui/button.svelte';
import { Pagination } from '@gabriel20xx/web-ui';
import { createOverviewData } from '$lib/features/lists/listsData.svelte.js';
import { listFieldsFor, listItemsFor, itemValuesFor, valueFor, fmtDate } from '$lib/features/lists/listHelpers.js';
import { listFieldsFor, listItemsFor, groupByKey, valueFor, fmtDate } from '$lib/features/lists/listHelpers.js';
let { data } = $props();
@@ -22,6 +22,7 @@
const list = $derived(overview.lists.find((l) => l.id === data.id));
const listFields = $derived(listFieldsFor(overview.fields, data.id));
const listItems = $derived(listItemsFor(overview.items, data.id));
const valuesByItem = $derived(groupByKey(overview.values, (v) => v.itemId));
let page = $state(1);
let pageSize = $state(24);
@@ -91,7 +92,7 @@
</thead>
<tbody>
{#each pageItems as item (item.id)}
{@const itemValues = itemValuesFor(overview.values, item.id)}
{@const itemValues = valuesByItem.get(item.id) ?? []}
<tr class="border-t border-border">
<td class="py-2 pl-3 font-mono text-xs text-muted-fg">{item.id.slice(0, 8)}…</td>
{#each listFields as f (f.id)}
+1
View File
@@ -38,6 +38,7 @@ export default defineConfig({
proxy: {
'/web': 'http://localhost:8080',
'/health': 'http://localhost:8080',
'/api': 'http://localhost:8080',
},
},
});
@@ -1,5 +0,0 @@
---
"@gabriel20xx/web-ui": minor
---
`UserManagement` accepts an optional `roles` prop (`KnownRole[]`) in place of the `projects` prop it replaces: when present, each account gets a role picker (checkboxes in the add and edit rows, the role names in the read-only row), and `onCreate`/`onUpdate` receive a `roleIds: number[]` field. An account's projects now come from its roles, so per-account project checkboxes are gone. `ManagedUser` carries `roleIds` instead of `projects`. Only AuthGuard's own admin UI passes this prop today; every other consumer is unaffected.
+49 -20
View File
@@ -21,7 +21,6 @@ The single source of truth for code reused across every project in this workspac
|---|---|---|
| `@gabriel20xx/design-tokens` | CSS | Colors, typography, spacing, radii, shadows, light/dark theme variables. |
| `@gabriel20xx/web-ui` | Svelte | Shared application shell and reusable UI components. The complete public component inventory is documented below. |
| `@gabriel20xx/legacy-assets` | Browser JS/CSS | Legacy client-side assets, kept for a handful of older pages. |
| `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations, and the media-family's shared route/table surface (`mediaauth`, `mediacore`, `carriernodeclient`, `syncsocket`). |
| `@gabriel20xx/node-backend` | Node.js | `pg` pool/config/transactions/migrations, auth/session persistence, an AuthGuard client. |
| `gabriel20xx-shared-backend` | Python | `asyncpg` pool/config, auth/session persistence, an AuthGuard client. |
@@ -29,34 +28,64 @@ The single source of truth for code reused across every project in this workspac
### Public `web-ui` components
These are the complete Svelte component exports from `packages/web-ui/src/lib/index.ts` (22 components):
These are the complete Svelte component exports from `packages/web-ui/src/lib/index.ts` (22 components), grouped by purpose.
#### Layout and navigation
| Component | Includes |
|---|---|
| `AppShell` | Application layout that composes the header, notification stack, theme, and primary-color handling. |
| `Header` | Branded application header with navigation, icons, actions, profile/settings menus, and logout. |
#### Buttons and controls
| Component | Includes |
|---|---|
| `Button` | Button with primary, secondary, outline, ghost, and danger variants; multiple sizes and full-width mode. |
| `Pagination` | Page navigation and page-size selection with total/item counts. |
| `PrimaryColorPicker` | Per-project primary-color selector backed by the shared color persistence helpers. |
#### Dialogs
| Component | Includes |
|---|---|
| `AboutDialog` | About modal with application branding, description, version, links, and custom content. |
| `AppShell` | Application layout that composes the header, notification stack, theme, and primary-color handling. |
| `AuthPage` | Login, first-time setup, password-reset, and optional TOTP authentication flows. |
| `Badge` | Small inline label with default, primary, success, warning, and danger variants. |
| `Button` | Button with primary, secondary, outline, ghost, and danger variants; multiple sizes and full-width mode. |
| `Card` | Styled content section for grouping application content. |
| `Dialog` | Generic modal dialog with title, description, body, footer, and bindable open state. |
| `EmptyState` | Empty-content message with an inbox icon, title, and description. |
| `Header` | Branded application header with navigation, icons, actions, profile/settings menus, and logout. |
| `MediaPlayer` | Audio/video player with playback, seeking, volume, quality, fullscreen, keyboard controls, and custom end controls. |
| `MediaPlayerControls` | Reusable media controls for playback, seeking, volume, quality, fullscreen, optional graph toggling, and custom end controls. |
| `Metric` | Labeled metric/value display with optional detail and semantic variants. |
| `NotificationStack` | Global stack of dismissible success, error, warning, and informational notifications. |
| `Pagination` | Page navigation and page-size selection with total/item counts. |
| `PrimaryColorPicker` | Per-project primary-color selector backed by the shared color persistence helpers. |
| `ProfileDialog` | Profile username/email/password editing and TOTP settings. |
| `SectionTitle` | Section heading with optional description. |
| `SettingsDialog` | Generic settings modal with custom content or a default empty-settings message. |
#### Content and data display
| Component | Includes |
|---|---|
| `Badge` | Small inline label with default, primary, success, warning, and danger variants. |
| `Card` | Styled content section for grouping application content. |
| `EmptyState` | Empty-content message with an inbox icon, title, and description. |
| `Metric` | Labeled metric/value display with optional detail and semantic variants. |
| `SectionTitle` | Section heading with optional description. |
#### Feedback and status
| Component | Includes |
|---|---|
| `NotificationStack` | Global stack of dismissible success, error, warning, and informational notifications. |
| `StatusDialog` | Detailed service health/readiness status modal with refresh support. |
| `StatusWidget` | Header-friendly health/readiness indicator that polls `/healthz` and `/ready` and opens `StatusDialog`. |
| `TotpSettings` | TOTP status, setup, enable, and disable controls. |
| `UserManagement` | Role-aware user administration with listing, creation, editing, deletion, role assignment, and pagination. |
This inventory describes the public component API only; the package also exports notification helpers, primary-color helpers, and TypeScript types. When a public component is added, removed, renamed, or materially changes responsibility, update this table in the same change as `packages/web-ui/src/lib/index.ts`. Keep the table aligned with that barrel file, and do not add internal or generated components to it.
#### Media
| Component | Includes |
|---|---|
| `MediaPlayer` | Audio/video player with playback, seeking, volume, quality, fullscreen, keyboard controls, and custom end controls. |
#### Accounts and access
| Component | Includes |
|---|---|
| `AuthPage` | Login, first-time setup, password-reset, and optional TOTP authentication flows. |
| `ProfileDialog` | Profile username/email/password editing and TOTP settings. |
| `TotpSettings` | TOTP status, setup, enable, and disable controls. |
This inventory describes the public component API only; the package also exports notification helpers, primary-color helpers, and TypeScript types. When a public component is added, removed, renamed, or materially changes responsibility, update the matching category table in the same change as `packages/web-ui/src/lib/index.ts`. Keep the tables aligned with that barrel file, place each component in the category that matches its primary purpose, and do not add internal or generated components to them.
The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks.
+57 -10
View File
@@ -85,16 +85,16 @@ func (c *Core) Mount(r chi.Router) {
r.With(c.auth.Require).Post("/security/totp/verify", c.auth.TOTPVerify)
r.With(c.auth.Require).Post("/security/totp/disable", c.auth.TOTPDisable)
r.With(c.auth.Optional).Get("/sync", c.getSyncState)
r.With(c.auth.Optional).Put("/sync", c.putSyncState)
r.With(c.auth.Require).Put("/sync", c.putSyncState)
r.With(c.auth.Optional).Get("/media/state", c.mediaState)
r.With(c.auth.Require).Post("/media/like", c.mediaLike)
r.With(c.auth.Require).Post("/media/save", c.mediaSave)
r.With(c.auth.Optional).Post("/media/view", c.mediaView)
r.With(c.auth.Optional).Post("/media/view-session", c.mediaViewSession)
r.With(c.auth.Require).Get("/media/liked", c.mediaLiked)
r.Get("/media/stream", c.streamMediaByQuery)
r.Head("/media/stream", c.streamMediaByQuery)
r.Get("/media/thumb", c.thumbnailMediaByQuery)
r.With(c.auth.RequireIfLoginRequired).Get("/media/stream", c.streamMediaByQuery)
r.With(c.auth.RequireIfLoginRequired).Head("/media/stream", c.streamMediaByQuery)
r.With(c.auth.RequireIfLoginRequired).Get("/media/thumb", c.thumbnailMediaByQuery)
r.With(c.auth.Optional).Get("/media/{id}/tags", c.mediaTags)
r.With(c.auth.Require).Post("/media/{id}/tags", c.addMediaTag)
@@ -132,10 +132,15 @@ func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "clientId is required")
return
}
mediaID, ok := syncScalar(input["mediaId"])
if !ok {
writeError(w, http.StatusBadRequest, "mediaId must be a string, a number or null")
return
}
sessionID := boundedSyncString(firstNonEmpty(syncString(input, "sessionId"), r.URL.Query().Get("sessionId"), "default"))
state := map[string]any{
"sessionId": sessionID,
"mediaId": input["mediaId"],
"mediaId": mediaID,
"timeMs": syncInt(input, "timeMs", 0),
"paused": syncBool(input, "paused"),
"fps": syncFPS(input),
@@ -144,7 +149,12 @@ func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
}
if value, ok := input["playAt"]; ok {
state["playAt"] = value
playAt, valid := syncScalar(value)
if !valid {
writeError(w, http.StatusBadRequest, "playAt must be a string, a number or null")
return
}
state["playAt"] = playAt
}
c.sync.SetHTTPState(sessionID, state)
c.sync.Broadcast(sessionID)
@@ -179,7 +189,7 @@ func (c *Core) streamMediaByQuery(w http.ResponseWriter, r *http.Request) {
}
func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) {
record, err := c.findMedia(r.Context(), identifier)
record, err := c.findMedia(r.Context(), identifier, canSeeHidden(r))
if err != nil {
writeError(w, http.StatusNotFound, "media not found")
return
@@ -197,6 +207,11 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
writeError(w, http.StatusBadRequest, "invalid media id")
return
}
includeHidden := canSeeHidden(r)
if !includeHidden && c.isHiddenMedia(r.Context(), id) {
writeError(w, http.StatusNotFound, "thumbnail not found")
return
}
if !strings.Contains(id, string(filepath.Separator)) && !strings.Contains(id, "/") {
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, id) {
return
@@ -216,7 +231,7 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
return
}
}
record, err := c.findMedia(r.Context(), id)
record, err := c.findMedia(r.Context(), id, includeHidden)
if err != nil || !isImagePath(record.FilePath) {
writeError(w, http.StatusNotFound, "thumbnail not found")
return
@@ -723,7 +738,25 @@ func (c *Core) profile(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"user": user})
}
func (c *Core) findMedia(ctx context.Context, identifier string) (MediaRecord, error) {
// canSeeHidden reports whether the caller is a moderator, who may stream and view media that has
// been hidden (active = FALSE). Everyone else gets hidden media as not found.
func canSeeHidden(r *http.Request) bool {
return sharedauth.IsAdmin(sharedauth.UserFromContext(r.Context()))
}
// isHiddenMedia reports whether identifier names a media item that has been hidden. A lookup
// error counts as hidden, so a database fault never exposes hidden media.
func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool {
var hidden bool
err := c.db.QueryRow(ctx, `
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR CAST(id AS TEXT)=$1))`,
strings.TrimSpace(identifier)).Scan(&hidden)
return err != nil || hidden
}
// findMedia looks up one media item by media key or numeric id. Hidden media is only returned
// when includeHidden is set.
func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) {
identifier = strings.TrimSpace(identifier)
var record MediaRecord
row := c.db.QueryRow(ctx, `
@@ -732,7 +765,7 @@ func (c *Core) findMedia(ctx context.Context, identifier string) (MediaRecord, e
COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0),
COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), funscript_action_count,
funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at)
FROM media WHERE media_key=$1 OR CAST(id AS TEXT)=$1 LIMIT 1`, identifier)
FROM media WHERE (media_key=$1 OR CAST(id AS TEXT)=$1) AND (active OR $2) LIMIT 1`, identifier, includeHidden)
var title, description string
var width, height int
var duration, size int64
@@ -1084,6 +1117,20 @@ func syncBool(message map[string]any, key string) bool {
return value
}
// syncScalar keeps a client-supplied sync value to what sync state holds: null, a number or a
// bounded string. Objects, arrays and booleans are refused so arbitrary JSON is never stored as
// shared session state.
func syncScalar(value any) (any, bool) {
switch typed := value.(type) {
case nil, float64:
return typed, true
case string:
return boundedSyncString(typed), true
default:
return nil, false
}
}
func syncInt(message map[string]any, key string, fallback int64) int64 {
value, ok := message[key].(float64)
if !ok {
+164
View File
@@ -0,0 +1,164 @@
package mediacore
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-chi/chi/v5"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
// loginRequiredStore is a ProxyStore that always requires login, so the auth gate can be
// exercised without a database.
type loginRequiredStore struct{}
func (loginRequiredStore) LoginRequired(context.Context) (bool, error) { return true, nil }
func (loginRequiredStore) SetLoginRequired(context.Context, bool) error { return nil }
func (loginRequiredStore) IsSetupClaimed(context.Context) (bool, error) { return true, nil }
func (loginRequiredStore) TryClaimSetup(context.Context) (bool, error) { return false, nil }
func (loginRequiredStore) UnclaimSetup(context.Context) error { return nil }
// loginOffStore is loginRequiredStore with login switched off for the whole application.
type loginOffStore struct{ loginRequiredStore }
func (loginOffStore) LoginRequired(context.Context) (bool, error) { return false, nil }
// TestMediaStreamAndThumbnailRequireLogin checks that anonymous requests to the media stream and
// thumbnail routes are refused when login is required, before any database lookup or CarrierNode
// call. The Core in this test has no database and no CarrierNode client, so reaching either would
// panic.
func TestMediaStreamAndThumbnailRequireLogin(t *testing.T) {
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
router := chi.NewRouter()
New(Config{Auth: auth}).Mount(router)
for _, request := range []struct{ method, target string }{
{http.MethodGet, "/media/stream?mediaKey=1"},
{http.MethodHead, "/media/stream?mediaKey=1"},
{http.MethodGet, "/media/thumb?mediaKey=1"},
} {
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(request.method, request.target, nil))
if response.Code != http.StatusUnauthorized {
t.Errorf("%s %s status = %d, want %d", request.method, request.target, response.Code, http.StatusUnauthorized)
}
}
}
// TestMediaGateAllowsAnonymousWhenLoginIsOff checks the gate the media stream and thumbnail routes
// use: with login disabled an anonymous request reaches the handler, as it does for the rest of
// the application. The handler here is a stub, so no database or CarrierNode call is made.
func TestMediaGateAllowsAnonymousWhenLoginIsOff(t *testing.T) {
auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject")
reached := false
gate := auth.RequireIfLoginRequired(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reached = true
}))
for _, target := range []string{"/media/stream?mediaKey=1", "/media/thumb?mediaKey=1"} {
reached = false
response := httptest.NewRecorder()
gate.ServeHTTP(response, httptest.NewRequest(http.MethodGet, target, nil))
if !reached || response.Code != http.StatusOK {
t.Errorf("GET %s with login off: reached = %v, status = %d; want reached and 200", target, reached, response.Code)
}
}
}
// newRoleAuthGuard stands in for AuthGuard's GET /api/me. Each bearer token maps to one role, so a
// test can act as a viewer, a moderator or an admin without a database.
func newRoleAuthGuard(t *testing.T) *httptest.Server {
t.Helper()
roles := map[string]string{"viewer-token": "user", "moderator-token": "moderator", "admin-token": "admin"}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
role, ok := roles[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
if !ok || r.URL.Path != "/api/me" {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"user":{"id":1,"username":"tester","role":%q}}`, role)
}))
t.Cleanup(server.Close)
return server
}
// TestOnlyModeratorsCanSeeHiddenMedia checks which callers get hidden media looked up at all.
// Anonymous callers and viewers may not; moderators and admins may. With login off every caller
// is the placeholder superadmin, as for the rest of the application. The active = FALSE filter
// itself needs a database and is not exercised here.
func TestOnlyModeratorsCanSeeHiddenMedia(t *testing.T) {
guard := newRoleAuthGuard(t)
login := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
loginOff := sharedauth.NewWithStore(loginOffStore{}, "session", false, guard.URL, "testproject")
for _, tc := range []struct {
name string
auth *sharedauth.Service
token string
want string
}{
{"anonymous with login required", login, "", "false"},
{"viewer", login, "viewer-token", "false"},
{"moderator", login, "moderator-token", "true"},
{"admin", login, "admin-token", "true"},
{"anonymous with login off", loginOff, "", "true"},
} {
router := chi.NewRouter()
router.With(tc.auth.Optional).Get("/probe", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, canSeeHidden(r))
})
request := httptest.NewRequest(http.MethodGet, "/probe", nil)
if tc.token != "" {
request.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: tc.token})
}
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if got := response.Body.String(); got != tc.want {
t.Errorf("%s: canSeeHidden = %q, want %q", tc.name, got, tc.want)
}
}
}
// TestSyncWriteRequiresLogin checks that an anonymous PUT /sync is refused before it can change
// shared playback state. The Core has no sync hub, so reaching the handler would panic.
func TestSyncWriteRequiresLogin(t *testing.T) {
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
router := chi.NewRouter()
New(Config{Auth: auth}).Mount(router)
request := httptest.NewRequest(http.MethodPut, "/sync", strings.NewReader(`{"clientId":"c1","mediaId":"m1"}`))
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusUnauthorized {
t.Errorf("PUT /sync status = %d, want %d", response.Code, http.StatusUnauthorized)
}
}
// TestSyncScalarKeepsOnlyScalars checks that sync values are limited to null, numbers and
// bounded strings, so objects, arrays and booleans are never stored as session state.
func TestSyncScalarKeepsOnlyScalars(t *testing.T) {
if value, ok := syncScalar(nil); !ok || value != nil {
t.Errorf("syncScalar(nil) = %v, %v; want nil, true", value, ok)
}
if value, ok := syncScalar(float64(7)); !ok || value != float64(7) {
t.Errorf("syncScalar(7) = %v, %v; want 7, true", value, ok)
}
if value, ok := syncScalar(" media-1 "); !ok || value != "media-1" {
t.Errorf("syncScalar(string) = %v, %v; want media-1, true", value, ok)
}
long, ok := syncScalar(strings.Repeat("x", 500))
if text, isText := long.(string); !ok || !isText || len(text) != 128 {
t.Errorf("syncScalar(long string) = %v, %v; want a 128-byte string, true", long, ok)
}
for _, refused := range []any{map[string]any{"a": 1}, []any{1}, true} {
if _, ok := syncScalar(refused); ok {
t.Errorf("syncScalar(%#v) accepted a non-scalar value", refused)
}
}
}
+27 -3
View File
@@ -33,6 +33,7 @@ import (
const (
maxSyncIdentifier = 128
maxSyncSessions = 1000
maxSyncConnections = 1000
)
type peer struct {
@@ -73,10 +74,15 @@ func NewHub() *Hub {
}
}
func (h *Hub) add(p *peer) {
// add registers a peer, or reports false when the hub already holds maxSyncConnections peers.
func (h *Hub) add(p *peer) bool {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.peers) >= maxSyncConnections {
return false
}
h.peers[p] = struct{}{}
h.mu.Unlock()
return true
}
func (h *Hub) remove(p *peer) string {
@@ -300,7 +306,10 @@ func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrig
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
}
h.add(p)
if !h.add(p) {
_ = conn.Close(websocket.StatusTryAgainLater, "too many sync connections")
return
}
defer func() {
sessionID := h.remove(p)
_ = conn.Close(websocket.StatusNormalClosure, "")
@@ -453,6 +462,9 @@ func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
h.capturedAtMs[sessionID] = captured
}
trimSessionMap(h.playAt)
trimSessionMap(h.playAtLocalMs)
trimSessionMap(h.capturedAtMs)
if toClientID == "" {
h.states[sessionID] = cloneMap(state)
if len(h.states) > maxSyncSessions {
@@ -571,6 +583,18 @@ func cloneMap(value map[string]any) map[string]any {
return result
}
// trimSessionMap keeps a per-session map within maxSyncSessions by dropping entries, the same
// bound the states map uses. Session IDs come from clients, so without it each map would grow
// for every ID ever seen.
func trimSessionMap[V any](values map[string]V) {
for len(values) > maxSyncSessions {
for key := range values {
delete(values, key)
break
}
}
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
@@ -0,0 +1,46 @@
package syncsocket
import (
"fmt"
"testing"
)
// TestSessionTimingMapsStayBounded checks that fresh client-chosen session IDs cannot grow the
// per-session timing maps past maxSyncSessions.
func TestSessionTimingMapsStayBounded(t *testing.T) {
hub := NewHub()
p := &peer{clientID: "client-1"}
for i := 0; i < maxSyncSessions+100; i++ {
hub.handleSyncUpdate(p, map[string]any{
"clientId": "client-1",
"sessionId": fmt.Sprintf("session-%d", i),
"paused": false,
"playAt": "2026-10-19T10:00:00Z",
"playAtLocalMs": float64(1),
"capturedAtLocalMs": float64(1),
})
}
if n := len(hub.playAt); n > maxSyncSessions {
t.Errorf("playAt holds %d sessions, want at most %d", n, maxSyncSessions)
}
if n := len(hub.playAtLocalMs); n > maxSyncSessions {
t.Errorf("playAtLocalMs holds %d sessions, want at most %d", n, maxSyncSessions)
}
if n := len(hub.capturedAtMs); n > maxSyncSessions {
t.Errorf("capturedAtMs holds %d sessions, want at most %d", n, maxSyncSessions)
}
}
// TestHubRefusesPeersBeyondTheConnectionCap checks that the hub stops registering connections
// once it holds maxSyncConnections peers.
func TestHubRefusesPeersBeyondTheConnectionCap(t *testing.T) {
hub := NewHub()
for i := 0; i < maxSyncConnections; i++ {
if !hub.add(&peer{}) {
t.Fatalf("add refused peer %d, below the cap", i)
}
}
if hub.add(&peer{}) {
t.Fatal("add accepted a peer beyond maxSyncConnections")
}
}
-8
View File
@@ -742,10 +742,6 @@
"resolved": "packages/design-tokens",
"link": true
},
"node_modules/@gabriel20xx/legacy-assets": {
"resolved": "packages/legacy-assets",
"link": true
},
"node_modules/@gabriel20xx/node-backend": {
"resolved": "packages/node-backend",
"link": true
@@ -3109,10 +3105,6 @@
"version": "0.1.1",
"license": "MIT"
},
"packages/legacy-assets": {
"name": "@gabriel20xx/legacy-assets",
"version": "3.0.0"
},
"packages/node-backend": {
"name": "@gabriel20xx/node-backend",
"version": "0.1.1",
-1
View File
@@ -50,7 +50,6 @@
"media:audit:layout": "node scripts/media/audit-inline-layout.mjs",
"media:audit:layout:strict": "node scripts/media/audit-inline-layout.mjs --strict",
"media:clean:test-artifacts": "node scripts/media/clean-test-artifacts.mjs",
"media:enforce:css-design-system": "node scripts/media/enforce-design-system-css.mjs",
"media:enforce:js-mapping": "node scripts/media/enforce-js-mapping.mjs",
"media:enforce:no-skipped-tests": "node scripts/media/enforce-no-skipped-tests.mjs",
"media:lint:all": "node scripts/media/lint-all.mjs",
@@ -715,9 +715,13 @@ public final class AuthClient {
if (candidate.startsWith(prefix)) {
String value = candidate.substring(prefix.length());
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8.name());
// URLDecoder would turn a literal "+" into a space; escape it first so it survives, as in Node.
return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException ex) {
return value;
} catch (IllegalArgumentException ex) {
// A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent.
return "";
}
}
}
@@ -218,6 +218,34 @@ class AuthClientTest {
assertEquals("right", token);
}
@Test
void extractTokenKeepsALiteralPlusSignInTheCookieValue() {
AuthClient client = new AuthClient("https://auth.example.com");
String token = client.extractToken(name -> null, "auth_session=ab+cd%2Bef");
assertEquals("ab+cd+ef", token);
}
@Test
void extractTokenTreatsAMalformedCookieEscapeAsNoToken() {
AuthClient client = new AuthClient("https://auth.example.com");
String token = client.extractToken(name -> null, "auth_session=bad%zz; other=1");
assertEquals("", token);
}
@Test
void middlewareFailsClosedOnAMalformedCookieInsteadOfThrowing() throws Exception {
AuthClient client = new AuthClient("https://auth.example.com");
String result = client.middleware(name -> null, "auth_session=100%",
user -> "authenticated", () -> "unauthorized");
assertEquals("unauthorized", result);
}
@Test
void middlewareFailsClosedAndDoesNotInvokeTheHandlerOnAnInvalidSession() throws Exception {
server = fakeAuthGuard(401, "{\"valid\":false}");
@@ -1,15 +0,0 @@
{
"extends": ["stylelint-config-standard"],
"ignoreFiles": ["public/css/index.css", "**/*.min.css"],
"rules": {
"at-rule-no-unknown": [true, { "ignoreAtRules": ["layer", "apply", "config"] }],
"selector-class-pattern": null,
"keyframes-name-pattern": null,
"custom-property-pattern": null,
"no-descending-specificity": null,
"import-notation": null,
"comment-empty-line-before": null,
"declaration-property-value-no-unknown": null,
"value-keyword-case": ["lower", { "camelCaseSvgKeywords": true }]
}
}
-16
View File
@@ -1,16 +0,0 @@
# @gabriel20xx/legacy-assets
This package now contains exactly one file: `public/css/index.css`, a static (pre-Tailwind-v4)
theme stylesheet. Its only remaining consumer is `Original/MediaDesktop`'s Electron renderer,
which still uses the old `--color-*` utility-class theme rather than the current `--sc-*`
design-token system in `packages/design-tokens`. It's a `file:` dependency there
(`scripts/copy-assets.mjs` copies `index.css` into `MediaDesktop/public/` at build time) - do not
delete this package without first migrating MediaDesktop off the old stylesheet.
Everything else that used to live here (the pre-SvelteKit `public/js/*` auth/layout/media
utilities, an orphaned `MediaDesktop/assets/icon.png` copy, and the broken monorepo-era
`build:theme` script) was removed: nothing else in the workspace referenced any of it.
Originally `MediaCollection/MediaShared`, moved here to centralize shared components. Both the
`MediaCollection` and `MediaShared` umbrella names are retired - everything here is just part of
`shared` now, workspace-wide.
@@ -1,13 +0,0 @@
{
"name": "@gabriel20xx/legacy-assets",
"version": "3.0.0",
"private": true,
"description": "Legacy pre-SvelteKit theme CSS, kept only for MediaDesktop's Electron renderer (file: dependency)",
"scripts": {
"lint:css": "stylelint \"public/**/*.css\""
},
"exports": {
"./index.css": "./public/css/index.css"
},
"files": ["public/**"]
}
File diff suppressed because it is too large. Load diff
@@ -211,9 +211,8 @@ export class AuthClient {
*/
middleware() {
return async (req, res, next) => {
const token = this.tokenFromRequest(req);
try {
req.authUser = await this.validate(token);
req.authUser = await this.validate(this.tokenFromRequest(req));
next();
} catch {
// Fail closed on both an invalid session and a transport/decoding
@@ -236,7 +235,14 @@ export class AuthClient {
.split(';')
.map(part => part.trim())
.find(part => part.startsWith(`${this.cookieName}=`));
if (match) return decodeURIComponent(match.slice(this.cookieName.length + 1));
if (match) {
// A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent.
try {
return decodeURIComponent(match.slice(this.cookieName.length + 1));
} catch {
return '';
}
}
}
return '';
}
@@ -125,6 +125,29 @@ test('tokenFromRequest falls back to the auth_session cookie', () => {
assert.equal(client.tokenFromRequest(req), 'cookie-token');
});
test('tokenFromRequest treats a malformed cookie escape as no token', () => {
const client = new AuthClient('https://auth.example.com');
const req = { headers: { cookie: 'auth_session=bad%zz; other=1' } };
assert.equal(client.tokenFromRequest(req), '');
});
test('middleware answers 401 instead of rejecting on a malformed cookie', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]),
});
let statusCode = null;
const res = {
status(code) {
statusCode = code;
return { json: () => {} };
},
};
await client.middleware()({ headers: { cookie: 'auth_session=100%' } }, res, () => {
throw new Error('next should not be called');
});
assert.equal(statusCode, 401);
});
test('middleware attaches authUser on success and 401s on failure', async () => {
const okClient = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 1, username: 'a', role: 'user' } }]),
@@ -94,6 +94,7 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
# rather than a generic "internal error" indistinguishable from any other bug.
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
ERR_ADMIN_REQUIRED = "Administrator access required."
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
# authentication is disabled, either because AUTHGUARD_URL is disabled or
@@ -338,6 +339,23 @@ def build_auth_router(
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
return token
async def require_admin(
request: Request,
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> PublicUser:
"""FastAPI dependency gating a route behind an administrator session
(the Python counterpart of Go's RequireAdmin). Unlike require_session it
never falls back to _LOCAL_PROFILE, so a route that changes the
login-required flag cannot be called anonymously, even while login is
already disabled."""
if not _enabled(client):
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
assert client is not None
profile, _ = await _current_profile_or_401(request, client)
if not can_manage_users(profile.role):
raise HTTPException(status_code=403, detail=ERR_ADMIN_REQUIRED)
return profile
# --- status / me -------------------------------------------------------
@router.get("/me")
@@ -561,6 +579,7 @@ def build_auth_router(
async def update_access_settings(
req: UpdateAccessRequest,
store: ProxyStore = Depends(get_store), # noqa: B008
_admin: PublicUser = Depends(require_admin), # noqa: B008
) -> dict[str, bool]:
nonlocal login_required_override
await store.set_login_required(req.loginRequired)
@@ -4,7 +4,13 @@ from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from shared_backend import authproxy as ap
from shared_backend.authclient import APIError, AuthClient, PublicUser, SessionResult
from shared_backend.authclient import (
DEFAULT_COOKIE_NAME,
APIError,
AuthClient,
PublicUser,
SessionResult,
)
class _FakeStore(ap.ProxyStore):
@@ -113,14 +119,32 @@ class AuthDisabledModeTests(unittest.TestCase):
class AccessSettingsTests(unittest.TestCase):
def test_get_and_put_round_trip_through_the_store(self) -> None:
def test_get_is_public_and_put_requires_an_admin_session(self) -> None:
store = _FakeStore(login_required=True)
client = TestClient(_build_app(store))
client = TestClient(_build_app(store, _RoleClient()))
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.status_code, 401)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.status_code, 403)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
client.cookies.set(DEFAULT_COOKIE_NAME, "admin-token")
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.json(), {"loginRequired": False})
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": False})
def test_anonymous_put_is_refused_when_authguard_is_not_configured(self) -> None:
store = _FakeStore(login_required=True)
client = TestClient(_build_app(store))
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.status_code, 401)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
store = _FakeStore(login_required=True)
client = TestClient(
@@ -180,6 +204,16 @@ class _FakeClient(AuthClient):
return ["auth_session=; Path=/; Max-Age=0"]
class _RoleClient(_FakeClient):
"""Resolves two fixed session tokens to an administrator and an ordinary user."""
async def me(self, token: str) -> PublicUser:
roles = {"admin-token": "superadmin", "user-token": "user"}
if token not in roles:
raise APIError(401, "unauthenticated")
return PublicUser(id=1, username="a", email="a@b.com", role=roles[token])
class EnabledModeSetupAndLoginTests(unittest.TestCase):
"""Exercises the real (client is not None) path, including the
setup-claim flag's interaction with the store."""
@@ -1,3 +1,6 @@
<!--
Internal to MediaPlayer. Not exported from the package barrel; do not re-export.
-->
<script lang="ts">
import { Maximize2, Minimize2, Pause, Play, Settings, Volume2, VolumeX } from '@lucide/svelte'
import { onMount } from 'svelte'
@@ -1,286 +0,0 @@
<script lang="ts">
import type {
KnownRole,
ManagedUser,
UserCreateInput,
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateInput,
UserUpdateRequest
} from '../types';
import Button from './Button.svelte';
import Pagination from './Pagination.svelte';
let {
currentRole = 'user',
currentUserId,
onCreate,
onDelete,
onList,
onUpdate,
roles
}: {
currentRole?: UserRole;
currentUserId?: UserId;
onCreate?: UserCreateRequest;
onDelete?: UserDeleteRequest;
onList?: UserListRequest;
onUpdate?: UserUpdateRequest;
/**
* The custom roles an account can be placed in (AuthGuard's role-based
* project access: a role decides which projects its members may log into).
* Only AuthGuard's own admin UI passes this - every other project's
* UserManagement usage omits it, and the whole role section of this
* component simply doesn't render.
*/
roles?: KnownRole[];
} = $props();
let users = $state<ManagedUser[]>([]);
let loading = $state(false);
let saving = $state(false);
let error = $state('');
let notice = $state('');
let loaded = $state(false);
let newUser = $state<UserCreateInput>({ username: '', email: '', password: '', role: 'user' });
let editingId = $state<UserId | null>(null);
let editUser = $state<UserUpdateInput>({});
let page = $state(1);
let pageSize = $state(24);
const canManage = $derived(currentRole === 'admin' || currentRole === 'superadmin');
const canAssignAdmin = $derived(currentRole === 'superadmin');
const pageCount = $derived(Math.max(1, Math.ceil(users.length / pageSize)));
const currentPage = $derived(Math.min(page, pageCount));
const pagedUsers = $derived(
users.slice((currentPage - 1) * pageSize, (currentPage - 1) * pageSize + pageSize)
);
function roleForForm(role: UserRole | undefined): UserRole {
return canAssignAdmin && role ? role : 'user';
}
function formatLastLogin(value: string | null | undefined): string {
if (!value) return 'Never';
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? 'Never' : parsed.toLocaleString();
}
async function loadUsers(): Promise<void> {
if (!onList || !canManage) return;
loading = true;
error = '';
try {
users = await onList();
loaded = true;
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to load users.';
} finally {
loading = false;
}
}
$effect(() => {
if (canManage && onList && !loaded) void loadUsers();
});
async function createUser(event: SubmitEvent): Promise<void> {
event.preventDefault();
if (!onCreate) return;
if (!newUser.username.trim() && !newUser.email.trim()) {
error = 'A username or email is required.';
return;
}
saving = true;
error = '';
notice = '';
try {
await onCreate({ ...newUser, role: roleForForm(newUser.role) });
newUser = { username: '', email: '', password: '', role: 'user' };
notice = 'User created.';
await loadUsers();
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to create user.';
} finally {
saving = false;
}
}
function startEditing(user: ManagedUser): void {
editingId = user.id;
editUser = { username: user.username, email: user.email, role: roleForForm(user.role) };
if (roles && roles.length > 0) editUser.roleIds = [...(user.roleIds ?? [])];
error = '';
notice = '';
}
function toggleEditRole(id: number, checked: boolean): void {
const current = editUser.roleIds ?? [];
editUser.roleIds = checked ? [...current, id] : current.filter((roleId) => roleId !== id);
}
function toggleNewRole(id: number, checked: boolean): void {
const current = newUser.roleIds ?? [];
newUser.roleIds = checked ? [...current, id] : current.filter((roleId) => roleId !== id);
}
// Names the roles an account is in, in the order the roles are listed. An account in none of
// them keeps every project.
function roleSummary(user: ManagedUser): string {
const names = (roles ?? []).filter((role) => (user.roleIds ?? []).includes(role.id)).map((role) => role.name);
return names.length > 0 ? names.join(', ') : 'All projects';
}
function stopEditing(): void {
editingId = null;
editUser = {};
}
async function updateUser(event: SubmitEvent): Promise<void> {
event.preventDefault();
if (!onUpdate || editingId === null) return;
saving = true;
error = '';
notice = '';
try {
const input = { ...editUser, role: roleForForm(editUser.role) };
if (!input.password) delete input.password;
await onUpdate(editingId, input);
stopEditing();
notice = 'User updated.';
await loadUsers();
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to update user.';
} finally {
saving = false;
}
}
async function deleteUser(user: ManagedUser): Promise<void> {
if (!onDelete || String(user.id) === String(currentUserId)) return;
if (!window.confirm(`Delete user ${user.username}?`)) return;
saving = true;
error = '';
notice = '';
try {
await onDelete(user.id);
notice = 'User deleted.';
await loadUsers();
} catch (caught) {
error = caught instanceof Error ? caught.message : 'Unable to delete user.';
} finally {
saving = false;
}
}
</script>
{#if canManage && onList && onCreate && onUpdate && onDelete}
<section class="sc-user-management" aria-labelledby="sc-user-management-title">
<div class="sc-user-management-header">
<div>
<h3 id="sc-user-management-title">User management</h3>
<p class="sc-muted">Add, edit, or remove accounts for this project.</p>
</div>
<Button disabled={loading || saving} size="sm" type="button" variant="secondary" onclick={() => void loadUsers()}>
Refresh
</Button>
</div>
<form class="sc-user-form" onsubmit={createUser}>
<strong>Add user</strong>
<div class="sc-user-grid">
<input aria-label="New username" class="sc-input" placeholder="Username (optional if email is set)" type="text" bind:value={newUser.username} />
<input aria-label="New email" class="sc-input" placeholder="Email (optional if username is set)" type="email" bind:value={newUser.email} />
<input aria-label="New password" class="sc-input" minlength="8" placeholder="Password (optional)" type="password" bind:value={newUser.password} />
<select aria-label="New role" class="sc-input" disabled={!canAssignAdmin} bind:value={newUser.role}>
<option value="user">User</option>
{#if canAssignAdmin}<option value="admin">Admin</option>{/if}
</select>
</div>
{#if roles && roles.length > 0}
<fieldset class="sc-user-roles">
<legend>Roles (none checked = all projects)</legend>
{#each roles as role (role.id)}
<label class="sc-user-role-option">
<input
type="checkbox"
checked={(newUser.roleIds ?? []).includes(role.id)}
onchange={(event) => toggleNewRole(role.id, event.currentTarget.checked)}
/>
{role.name}
</label>
{/each}
</fieldset>
{/if}
<div class="sc-form-actions"><Button disabled={saving} type="submit">Add user</Button></div>
</form>
{#if error}<p aria-live="polite" class="sc-error">{error}</p>{/if}
{#if notice}<p aria-live="polite" class="sc-success">{notice}</p>{/if}
{#if loading && users.length === 0}
<p class="sc-muted">Loading users...</p>
{:else if users.length === 0}
<p class="sc-muted">No users found.</p>
{:else}
<div class="sc-user-list">
{#each pagedUsers as user (user.id)}
{#if String(editingId) === String(user.id)}
<form class="sc-user-row sc-user-edit-row" onsubmit={updateUser}>
<input aria-label="Username" class="sc-input" required type="text" bind:value={editUser.username} />
<input aria-label="Email" class="sc-input" required type="email" bind:value={editUser.email} />
<input aria-label="New password" class="sc-input" minlength="8" placeholder="Keep password" type="password" bind:value={editUser.password} />
<select aria-label="Role" class="sc-input" disabled={!canAssignAdmin || user.role === 'superadmin'} bind:value={editUser.role}>
<option value="user">User</option>
{#if canAssignAdmin}<option value="admin">Admin</option>{/if}
{#if user.role === 'superadmin'}<option value="superadmin">Superadmin</option>{/if}
</select>
{#if roles && roles.length > 0}
<fieldset class="sc-user-roles">
<legend>Roles (none checked = all projects)</legend>
{#each roles as role (role.id)}
<label class="sc-user-role-option">
<input
type="checkbox"
checked={(editUser.roleIds ?? []).includes(role.id)}
onchange={(event) => toggleEditRole(role.id, event.currentTarget.checked)}
/>
{role.name}
</label>
{/each}
</fieldset>
{/if}
<div class="sc-user-actions"><Button disabled={saving} size="sm" type="submit">Save</Button><Button disabled={saving} size="sm" type="button" variant="secondary" onclick={stopEditing}>Cancel</Button></div>
</form>
{:else}
<div class="sc-user-row">
<div><strong>{user.username}</strong><span>{user.email}</span></div>
<span class="sc-user-role">{user.role}</span>
<span class="sc-muted sc-user-last-login" title="Last login">{formatLastLogin(user.lastLoginAt)}</span>
{#if roles && roles.length > 0}
<span class="sc-muted sc-user-roles-summary" title="Roles">{roleSummary(user)}</span>
{/if}
<div class="sc-user-actions">
<Button disabled={saving} size="sm" type="button" variant="secondary" onclick={() => startEditing(user)}>Edit</Button>
<Button disabled={saving || String(user.id) === String(currentUserId) || user.role === 'superadmin'} size="sm" type="button" variant="danger" onclick={() => void deleteUser(user)}>Remove</Button>
</div>
</div>
{/if}
{/each}
</div>
<Pagination
page={currentPage}
{pageSize}
pageLength={pagedUsers.length}
totalLength={users.length}
onPaging={(change) => {
page = change.page;
pageSize = change.pageSize;
}}
/>
{/if}
</section>
{/if}
-6
View File
@@ -9,7 +9,6 @@ export { default as EmptyState } from './components/EmptyState.svelte';
export { default as Header } from './components/Header.svelte';
export { default as Metric } from './components/Metric.svelte';
export { default as MediaPlayer } from './components/MediaPlayer.svelte';
export { default as MediaPlayerControls } from './components/MediaPlayerControls.svelte';
export { default as NotificationStack } from './components/NotificationStack.svelte';
export { default as Pagination } from './components/Pagination.svelte';
export { default as ProfileDialog } from './components/ProfileDialog.svelte';
@@ -19,7 +18,6 @@ export { default as SettingsDialog } from './components/SettingsDialog.svelte';
export { default as StatusDialog } from './components/StatusDialog.svelte';
export { default as StatusWidget } from './components/StatusWidget.svelte';
export { default as TotpSettings } from './components/TotpSettings.svelte';
export { default as UserManagement } from './components/UserManagement.svelte';
export { notifications, notify } from './notifications.svelte';
export {
PRIMARY_COLOR_PALETTE,
@@ -49,13 +47,9 @@ export type {
StatusProbe,
StatusSnapshot,
UserCreateInput,
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateInput,
UserUpdateRequest,
TotpSetupRequest,
TotpSetupResponse,
TotpStatusRequest,
@@ -39,9 +39,10 @@ const paletteByName = Object.fromEntries(PRIMARY_COLOR_PALETTE.map((color) => [c
string,
PaletteColor
>
const primaryVars = ['--color-primary', '--color-accent', '--color-ring']
const foregroundVars = ['--color-primary-fg', '--color-accent-fg']
const primaryVars = ['--color-primary', '--color-accent', '--color-ring', '--sc-primary', '--sc-accent', '--sc-ring']
const foregroundVars = ['--color-primary-fg', '--color-accent-fg', '--sc-primary-fg', '--sc-accent-fg']
const activeUserAttribute = 'data-primary-color-user'
const styleElementId = 'sc-primary-color'
const activeProjects = new Set<string>()
function normalizeUserKey(userKey: string): string {
@@ -67,19 +68,45 @@ function readStoredColor(projectKey: string): string {
}
}
// Moves a #rrggbb color a fraction of the way toward a channel value (0 = black, 255 = white).
function mixHex(hex: string, towards: number, weight: number): string {
const channels = [1, 3, 5].map((start) => parseInt(hex.slice(start, start + 2), 16))
return `#${channels.map((c) => Math.round(c + (towards - c) * weight).toString(16).padStart(2, '0')).join('')}`
}
// The color is written to a stylesheet rather than inline on <html>. Shared and app CSS re-declare these
// tokens on every [data-theme] element (the AppShell root, for one), and that declaration hides the value
// <html> would pass down, so the choice never reached the app's UI. Targeting [data-theme] elements with
// !important makes it win everywhere, and the dark/light split is left to the selectors.
function primaryDeclarations(color: PaletteColor, dark: boolean): string {
const primary = dark ? color.dark : color.light
// Hover is lighter on dark and darker on light, as in the shared theme. It is a hex value, not color-mix(),
// because consumers such as the terminal read these tokens as plain colors.
const hover = dark ? mixHex(primary, 255, 0.15) : mixHex(primary, 0, 0.15)
const foreground = dark ? color.darkFg : '#ffffff'
return [
...primaryVars.map((name) => `${name}: ${primary} !important;`),
`--sc-primary-hover: ${hover} !important;`,
...foregroundVars.map((name) => `${name}: ${foreground} !important;`),
].join(' ')
}
export function applyPrimaryColor(_projectKey: string, colorName: string): void {
if (typeof document === 'undefined') return
const color = paletteByName[colorName]
const root = document.documentElement.style
let style = document.getElementById(styleElementId) as HTMLStyleElement | null
if (!color) {
for (const name of [...primaryVars, ...foregroundVars]) root.removeProperty(name)
style?.remove()
return
}
const dark = document.documentElement.getAttribute('data-theme') === 'dark'
const primary = dark ? color.dark : color.light
const foreground = dark ? color.darkFg : '#ffffff'
for (const name of primaryVars) root.setProperty(name, primary)
for (const name of foregroundVars) root.setProperty(name, foreground)
if (!style) {
style = document.createElement('style')
style.id = styleElementId
document.head.append(style)
}
style.textContent = `:root, [data-theme] { ${primaryDeclarations(color, false)} }
[data-theme='dark'] { ${primaryDeclarations(color, true)} }
`
}
export function setPrimaryColor(projectKey: string, colorName: string): void {
@@ -105,11 +132,8 @@ export function initPrimaryColor(projectKey: string, userKey = ''): () => void {
if (typeof document === 'undefined') return () => undefined
if (userKey) setPrimaryColorUser(userKey)
activeProjects.add(projectKey.trim().toLowerCase() || 'application')
const stored = readStoredColor(projectKey)
applyPrimaryColor(projectKey, stored)
const observer = new MutationObserver(() => applyPrimaryColor(projectKey, readStoredColor(projectKey)))
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] })
return () => observer.disconnect()
applyPrimaryColor(projectKey, readStoredColor(projectKey))
return () => undefined
}
export function storedPrimaryColor(projectKey: string): string {
-142
View File
@@ -746,148 +746,6 @@ html[data-wide-layout='true'] .sc-header {
color: var(--sc-success);
}
.sc-user-management {
display: grid;
gap: 1rem;
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid var(--sc-border);
}
.sc-user-management-header,
.sc-user-row,
.sc-user-edit-row {
display: flex;
align-items: center;
gap: 0.75rem;
}
.sc-user-management-header {
justify-content: space-between;
}
.sc-user-management-header h3 {
margin: 0;
}
.sc-user-management-header p {
margin: 0.25rem 0 0;
}
.sc-user-form,
.sc-user-list {
display: grid;
gap: 0.75rem;
}
.sc-user-form {
padding: 0.9rem;
border: 1px solid var(--sc-border);
border-radius: 0.6rem;
background: var(--sc-surface-raised);
}
.sc-user-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.6rem;
}
.sc-user-row {
min-width: 0;
justify-content: space-between;
padding: 0.7rem 0;
border-bottom: 1px solid var(--sc-border);
}
.sc-user-row > div:first-child {
display: grid;
min-width: 0;
}
.sc-user-row > div:first-child span {
overflow: hidden;
color: var(--sc-muted-fg);
text-overflow: ellipsis;
white-space: nowrap;
}
.sc-user-role {
color: var(--sc-muted-fg);
font-size: 0.8rem;
text-transform: capitalize;
}
.sc-user-last-login {
flex-shrink: 0;
font-size: 0.8rem;
white-space: nowrap;
}
.sc-user-actions {
display: flex;
flex-shrink: 0;
gap: 0.4rem;
}
.sc-user-roles-summary {
max-width: 12rem;
overflow: hidden;
font-size: 0.8rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.sc-user-roles {
display: flex;
flex: 1 1 100%;
flex-wrap: wrap;
gap: 0.5rem 1rem;
margin: 0;
padding: 0.5rem 0.7rem;
border: 1px solid var(--sc-border);
border-radius: 0.5rem;
}
.sc-user-roles legend {
flex-basis: 100%;
margin-bottom: 0.3rem;
color: var(--sc-muted-fg);
font-size: 0.8rem;
}
.sc-user-role-option {
display: flex;
align-items: center;
gap: 0.35rem;
font-size: 0.85rem;
}
.sc-user-edit-row {
align-items: stretch;
flex-wrap: wrap;
}
.sc-user-edit-row .sc-input {
flex: 1 1 10rem;
min-width: 8rem;
}
@media (max-width: 620px) {
.sc-user-grid {
grid-template-columns: 1fr;
}
.sc-user-row {
align-items: flex-start;
flex-wrap: wrap;
}
.sc-user-actions {
width: 100%;
}
}
.sc-pagination {
display: flex;
flex-wrap: wrap;
+2 -15
View File
@@ -73,7 +73,7 @@ export interface KnownProject {
label: string;
}
/** One custom role an administrator may assign to a user - see UserManagement's `roles` prop. */
/** One custom role an administrator may assign to a user. */
export interface KnownRole {
id: number;
name: string;
@@ -107,24 +107,11 @@ export interface UserUpdateInput {
/**
* Replaces the account's full set of custom roles when present (an empty
* array removes it from every role); omitted (undefined) leaves them
* untouched. Only ever set when UserManagement was given a `roles` prop.
* untouched.
*/
roleIds?: number[];
}
export type UserListRequest = () => ManagedUser[] | Promise<ManagedUser[]>;
export type UserCreateRequest = (
input: UserCreateInput,
) => void | Promise<void | ManagedUser>;
export type UserUpdateRequest = (
id: UserId,
input: UserUpdateInput,
) => void | Promise<void | ManagedUser>;
export type UserDeleteRequest = (id: UserId) => void | Promise<void>;
export interface AboutLink {
label: string;
href: string;
@@ -1,117 +0,0 @@
#!/usr/bin/env node
/**
* Enforce design-system CSS constraints for shared theme files.
*
* Rules enforced:
* - Theme CSS must not contain project/service-coupled selector tokens.
* - Theme CSS must not contain route-coupled panel IDs in selectors.
*
* TODO(shared extraction): the original monorepo version of this script also asserted that
* MediaShared/public/css/index.css and MediaDesktop/public/index.css stayed byte-for-byte synced.
* That check is no longer possible from inside this repo: MediaDesktop is now a fully separate
* repo (Original/MediaDesktop) and isn't checked out alongside this one, so there is nothing here
* to diff it against. The desktop-vs-shared theme sync check has been dropped rather than pointed
* at a nonexistent path; if that guarantee still matters, it belongs in MediaDesktop's own CI
* (comparing its vendored shared/ copy's theme file against its own), not here.
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
// MediaShared/public/css/index.css became packages/legacy-assets/public/css/index.css once
// media-backend/webui were folded directly into the shared repo (no more vendored copy).
const sharedThemePath = path.join(
repoRoot,
'packages',
'legacy-assets',
'public',
'css',
'index.css'
);
const bannedSelectorRules = [
{
name: 'project-coupled service token',
regex: /\b(?:kiosk|viewer|moderator|generator|library|contentscanner|downloader|carriernode)-page\b/i,
},
{
name: 'project-coupled state class token',
regex:
/\b(?:viewer|kiosk|moderator|generator|library|contentscanner|downloader|carriernode)-(?:home|page|stage|mode|active|panel)\b/i,
},
{
name: 'project-prefixed keyframe name',
regex:
/@keyframes\s+nc-(?:viewer|kiosk|moderator|generator|library|contentscanner|downloader|carriernode)/i,
},
{
name: 'project-coupled data attribute',
regex:
/\[data-(?:kiosk|viewer|moderator|generator|library|contentscanner|downloader|carriernode)[^\]]*\]/i,
},
{
name: 'route-coupled panel selector',
regex: /#panel-[a-z0-9_-]+/i,
},
];
function readUtf8(filePath) {
return fs.readFileSync(filePath, 'utf8');
}
function stripCssComments(text) {
return text.replace(/\/\*[\s\S]*?\*\//g, '');
}
function findViolations(filePath, content) {
const cleaned = stripCssComments(content);
const lines = cleaned.split(/\r?\n/);
const violations = [];
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i];
for (const rule of bannedSelectorRules) {
if (rule.regex.test(line)) {
violations.push({
filePath,
line: i + 1,
rule: rule.name,
snippet: line.trim(),
});
}
}
}
return violations;
}
function main() {
if (!fs.existsSync(sharedThemePath)) {
console.error('[enforce-design-system-css] Missing expected theme file:');
console.error(` - ${path.relative(repoRoot, sharedThemePath)}`);
process.exit(1);
}
const sharedTheme = readUtf8(sharedThemePath);
const allViolations = findViolations(sharedThemePath, sharedTheme);
if (allViolations.length > 0) {
console.error('[enforce-design-system-css] Design-system CSS violations found:');
for (const v of allViolations) {
const rel = path.isAbsolute(v.filePath) ? path.relative(repoRoot, v.filePath) : v.filePath;
console.error(` - ${rel}:${v.line} [${v.rule}] ${v.snippet}`);
}
console.error('[enforce-design-system-css] Fix violations before running lint/test.');
process.exit(1);
}
console.log(
'[enforce-design-system-css] OK: shared theme is free of project-coupled selectors.'
);
}
main();
-142
View File
@@ -727,148 +727,6 @@ html[data-wide-layout='true'] .sc-header {
color: var(--sc-success);
}
.sc-user-management {
display: grid;
gap: 1rem;
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid var(--sc-border);
}
.sc-user-management-header,
.sc-user-row,
.sc-user-edit-row {
display: flex;
align-items: center;
gap: 0.75rem;
}
.sc-user-management-header {
justify-content: space-between;
}
.sc-user-management-header h3 {
margin: 0;
}
.sc-user-management-header p {
margin: 0.25rem 0 0;
}
.sc-user-form,
.sc-user-list {
display: grid;
gap: 0.75rem;
}
.sc-user-form {
padding: 0.9rem;
border: 1px solid var(--sc-border);
border-radius: 0.6rem;
background: var(--sc-surface-raised);
}
.sc-user-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.6rem;
}
.sc-user-row {
min-width: 0;
justify-content: space-between;
padding: 0.7rem 0;
border-bottom: 1px solid var(--sc-border);
}
.sc-user-row > div:first-child {
display: grid;
min-width: 0;
}
.sc-user-row > div:first-child span {
overflow: hidden;
color: var(--sc-muted-fg);
text-overflow: ellipsis;
white-space: nowrap;
}
.sc-user-role {
color: var(--sc-muted-fg);
font-size: 0.8rem;
text-transform: capitalize;
}
.sc-user-last-login {
flex-shrink: 0;
font-size: 0.8rem;
white-space: nowrap;
}
.sc-user-actions {
display: flex;
flex-shrink: 0;
gap: 0.4rem;
}
.sc-user-roles-summary {
max-width: 12rem;
overflow: hidden;
font-size: 0.8rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.sc-user-roles {
display: flex;
flex: 1 1 100%;
flex-wrap: wrap;
gap: 0.5rem 1rem;
margin: 0;
padding: 0.5rem 0.7rem;
border: 1px solid var(--sc-border);
border-radius: 0.5rem;
}
.sc-user-roles legend {
flex-basis: 100%;
margin-bottom: 0.3rem;
color: var(--sc-muted-fg);
font-size: 0.8rem;
}
.sc-user-role-option {
display: flex;
align-items: center;
gap: 0.35rem;
font-size: 0.85rem;
}
.sc-user-edit-row {
align-items: stretch;
flex-wrap: wrap;
}
.sc-user-edit-row .sc-input {
flex: 1 1 10rem;
min-width: 8rem;
}
@media (max-width: 620px) {
.sc-user-grid {
grid-template-columns: 1fr;
}
.sc-user-row {
align-items: flex-start;
flex-wrap: wrap;
}
.sc-user-actions {
width: 100%;
}
}
.sc-pagination {
display: flex;
flex-wrap: wrap;