Harden the API and the data layer after a security and performance audit

Security
- Every route now requires a login and refuses ids outside the caller's
  workspace with 404: plan, leave-wishes, day-overrides and vacation-days
  were fully anonymous; every other router trusted client-supplied
  workspace/child/parent ids. Scraper sessions are bound to their owner.
- Invitations can no longer be created for a foreign workspace, and a
  redeemer who is already a member (or a full workspace) is refused.
- Production refuses the default JWT secret; API docs are hidden in
  production; a failed migration aborts startup instead of serving.
- Login and register no longer reveal whether an email exists; inactive
  accounts are rejected; /auth/refresh is rate limited.
- The FK scraper writes debug artefacts only when explicitly enabled,
  logs no scraped values or page text, clears the BankID QR as soon as it
  is scanned and purges finished sessions after five minutes.
- Real FK page captures are removed from the tree (history rewrite
  follows); the parser tests use a synthetic fixture.

Performance and correctness
- Plan apply/sync run inside one locked transaction with batched writes
  instead of one commit per row, so a failure mid-batch leaves nothing
  half-applied and concurrent syncs no longer corrupt each other.
- SQLite runs in WAL mode with a busy timeout; 14 indexes cover the
  filters that were full scans; argon2 hashing runs off the event loop;
  responses are gzipped.
- Frontend: a 401 now refreshes the token once and retries, so sessions
  no longer die silently after 15 minutes; every data hook discards
  stale responses; logout clears state even when the server call fails.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CsXCCcDfmV4Sps4ZQSvNEY
This commit is contained in:
2026-09-18 07:54:21 +02:00
parent ae16d71970
commit 02db5430eb
81 changed files with 3616 additions and 600 deletions
+46
View File
@@ -520,9 +520,30 @@ export function setAccessToken(token: string | null): void {
_accessToken = token
}
// Endpoints that must never trigger a refresh-and-retry on 401 — retrying
// them would either be nonsensical (the refresh call retrying itself) or
// mask the real "not logged in" outcome (login/logout).
const AUTH_NO_RETRY_PATHS = new Set(['/auth/login', '/auth/refresh', '/auth/logout'])
// Dedupe concurrent 401s (e.g. Dashboard's ~7 parallel requests all
// expiring at once) into a single in-flight refresh call, shared across
// every apiFetch caller.
let refreshPromise: Promise<TokenResponse> | null = null
// AuthContext registers this so a refresh-and-retry failure can log the
// user out immediately, instead of leaving `isAuthenticated: true` while
// every subsequent request 401s. Kept out of this module so api.ts stays
// framework-agnostic.
let onUnauthorized: (() => void) | null = null
export function setUnauthorizedHandler(handler: (() => void) | null): void {
onUnauthorized = handler
}
async function apiFetch<T>(
path: string,
options: RequestInit = {},
isRetry = false,
): Promise<T> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
@@ -532,6 +553,31 @@ async function apiFetch<T>(
headers['Authorization'] = `Bearer ${_accessToken}`
}
const response = await fetch(`${BASE}${path}`, { ...options, headers })
if (response.status === 401 && !isRetry && !AUTH_NO_RETRY_PATHS.has(path)) {
let refreshed: TokenResponse | null = null
try {
refreshPromise ??= refreshToken().finally(() => {
refreshPromise = null
})
refreshed = await refreshPromise
} catch {
// Refresh itself failed (expired/invalid refresh cookie, or a
// network error) — clear the token and let the caller's original
// 401 surface below so AuthContext can log the user out.
setAccessToken(null)
onUnauthorized?.()
}
if (refreshed) {
setAccessToken(refreshed.access_token)
// Retry exactly once, outside the try/catch above — `isRetry: true`
// means a 401 on this attempt is final and must propagate as-is
// rather than being caught here and re-reported as the original
// (now stale) 401.
return await apiFetch<T>(path, options, true)
}
}
if (!response.ok) {
let error: { code: string; message: string; details?: Record<string, unknown> } = {
code: String(response.status),