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:
@@ -1774,6 +1774,114 @@ describe('endpoint functions (representative coverage)', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('apiFetch — 401 refresh-and-retry (S1)', () => {
|
||||
let fetchMock: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock = vi.fn()
|
||||
globalThis.fetch = fetchMock as typeof fetch
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
api.setAccessToken(null)
|
||||
api.setUnauthorizedHandler(null)
|
||||
})
|
||||
|
||||
function unauthorizedResponse(detail = 'Unauthorized') {
|
||||
return { ok: false, status: 401, statusText: 'Unauthorized', json: async () => ({ detail }) }
|
||||
}
|
||||
|
||||
function tokenResponse(access_token: string) {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ access_token, token_type: 'bearer', expires_in: 3600 }),
|
||||
}
|
||||
}
|
||||
|
||||
it('refreshes the token once and retries the original request after a 401', async () => {
|
||||
api.setAccessToken('old-token')
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(unauthorizedResponse())
|
||||
.mockResolvedValueOnce(tokenResponse('new-token'))
|
||||
.mockResolvedValueOnce({ ok: true, status: 200, json: async () => [] })
|
||||
|
||||
const result = await api.getTips('ws1')
|
||||
|
||||
expect(result).toEqual([])
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
expect(fetchMock.mock.calls[1]![0]).toBe('/api/auth/refresh')
|
||||
const [retryUrl, retryOptions] = fetchMock.mock.calls[2] as [string, RequestInit]
|
||||
expect(retryUrl).toBe('/api/tips/ws1')
|
||||
expect((retryOptions.headers as Record<string, string>)['Authorization']).toBe('Bearer new-token')
|
||||
})
|
||||
|
||||
it('dedupes concurrent 401s from parallel requests into a single refresh call', async () => {
|
||||
api.setAccessToken('old-token')
|
||||
fetchMock.mockImplementation(async (url: string, options?: RequestInit) => {
|
||||
if (url === '/api/auth/refresh') {
|
||||
return tokenResponse('new-token')
|
||||
}
|
||||
const headers = options?.headers as Record<string, string> | undefined
|
||||
if (headers?.['Authorization'] === 'Bearer new-token') {
|
||||
return { ok: true, status: 200, json: async () => [] }
|
||||
}
|
||||
return unauthorizedResponse()
|
||||
})
|
||||
|
||||
const [r1, r2] = await Promise.all([api.getTips('ws1'), api.getTips('ws1')])
|
||||
|
||||
expect(r1).toEqual([])
|
||||
expect(r2).toEqual([])
|
||||
const refreshCalls = fetchMock.mock.calls.filter(([url]) => url === '/api/auth/refresh')
|
||||
expect(refreshCalls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('clears the token, notifies the unauthorized handler, and surfaces the original 401 when refresh fails', async () => {
|
||||
api.setAccessToken('old-token')
|
||||
const onUnauthorized = vi.fn()
|
||||
api.setUnauthorizedHandler(onUnauthorized)
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(unauthorizedResponse('session expired'))
|
||||
.mockResolvedValueOnce(unauthorizedResponse('refresh token expired'))
|
||||
|
||||
await expect(api.getTips('ws1')).rejects.toMatchObject({
|
||||
status: 401,
|
||||
error: { message: 'session expired' },
|
||||
})
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
expect(onUnauthorized).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does not loop when the retried request also 401s', async () => {
|
||||
api.setAccessToken('old-token')
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(unauthorizedResponse())
|
||||
.mockResolvedValueOnce(tokenResponse('new-token'))
|
||||
.mockResolvedValueOnce(unauthorizedResponse('still unauthorized'))
|
||||
|
||||
await expect(api.getTips('ws1')).rejects.toMatchObject({
|
||||
status: 401,
|
||||
error: { message: 'still unauthorized' },
|
||||
})
|
||||
|
||||
// Original + refresh + one retry — no second refresh attempt.
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('does not attempt a refresh-and-retry for the auth endpoints themselves', async () => {
|
||||
fetchMock.mockResolvedValue(unauthorizedResponse())
|
||||
|
||||
await expect(api.login({ email: 'a@b.com', password: 'x' })).rejects.toMatchObject({ status: 401 })
|
||||
await expect(api.refreshToken()).rejects.toMatchObject({ status: 401 })
|
||||
await expect(api.logout()).rejects.toMatchObject({ status: 401 })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('apiFetch — structured {message_key, data} errors', () => {
|
||||
let fetchMock: ReturnType<typeof vi.fn>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user