diff --git a/web/src/lib/app.test.ts b/web/src/lib/app.test.ts index 7772c2c..1146f45 100644 --- a/web/src/lib/app.test.ts +++ b/web/src/lib/app.test.ts @@ -28,6 +28,7 @@ const mocks = vi.hoisted(() => { vi.mock('$lib/pb', () => ({ pb: { + authStore: { isValid: true }, autoCancellation: () => undefined, filter: (tpl: string, params: Record) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))), collection: (name: string) => ({ diff --git a/web/src/lib/db.svelte.ts b/web/src/lib/db.svelte.ts index 0a0678b..562e613 100644 --- a/web/src/lib/db.svelte.ts +++ b/web/src/lib/db.svelte.ts @@ -154,6 +154,7 @@ const staleBuffer = new Map(); const pushedChanges = new Map>(); /** Set when the server rejected a change of the current round; its message stays until a round succeeds. */ let rejected = false; +let sessionExpired: (() => void) | null = null; /** Collections whose local state the sync is about to touch or is touching, by name and nesting depth. */ const applying = new Map(); @@ -194,6 +195,7 @@ async function pullRecords(name: string, cursor: string | null): Promise, AnyDoc, string> { + /** Errors of the sync calls of the current round as they were thrown, before syncAll() summarized them. */ + readonly failures: unknown[] = []; pending(): number { const changes = this.changes; return inScope() ? changes.find({}).count() : readOnce(changes, {}, (cursor) => cursor.count()); @@ -239,7 +248,12 @@ class WotraSync extends SyncManager, AnyDoc, string> { } override async sync(name: string, options?: { force?: boolean; onlyWithChanges?: boolean }): Promise { const before = pullRuns; - await super.sync(name, options); + try { + await super.sync(name, options); + } catch (e) { + this.failures.push(e); + throw e; + } if (pullRuns !== before) onSynced(name); } } @@ -286,7 +300,9 @@ async function doOpenDb(uid: string): Promise { autostart: false, debounceTime: 300, onError: (_opts, err) => { - if (status.ready) status.error = err.message; + if (!status.ready || syncing) return; + if (!pb.authStore.isValid || unauthorized(err)) sessionExpired?.(); + else status.error = err.message; }, pull: async ({ name }) => { pullRuns += 1; @@ -377,6 +393,11 @@ export function onBeforeSync(fn: () => Promise): void { beforeSync = fn; } +/** Registers what runs when a round found the session gone; the session module ends itself there. */ +export function onSessionExpired(fn: () => void): void { + sessionExpired = fn; +} + function runBeforeSync(): Promise { return beforeSync ? beforeSync() : Promise.resolve(); } @@ -385,11 +406,18 @@ export function syncNow(): Promise { if (syncing) return syncing; const m = sm; if (!m || !status.online) return Promise.resolve(); + if (!pb.authStore.isValid) { + sessionExpired?.(); + return Promise.resolve(); + } rejected = false; + m.failures.length = 0; const run: Promise = runBeforeSync() .then(() => m.syncAll()) .catch((err: Error) => { - if (m === sm) status.error = err.message; + if (m !== sm) return; + if (!pb.authStore.isValid || m.failures.some(unauthorized)) sessionExpired?.(); + else status.error = err.message; }) .finally(() => { if (syncing === run) syncing = null; diff --git a/web/src/lib/db.test.ts b/web/src/lib/db.test.ts index 3641e71..e925197 100644 --- a/web/src/lib/db.test.ts +++ b/web/src/lib/db.test.ts @@ -1,7 +1,7 @@ import { Collection } from '@signaldb/core'; import { tick } from 'svelte'; -import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; -import { all, closeDb, get, openDb, pendingCount, remove, removeLegacyStorage, save, status, syncNow, toRecord, update } from './db.svelte'; +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { all, closeDb, get, onSessionExpired, openDb, pendingCount, remove, removeLegacyStorage, save, status, syncNow, toRecord, update } from './db.svelte'; import { watch } from './testing.svelte'; const mocks = vi.hoisted(() => { @@ -10,30 +10,49 @@ const mocks = vi.hoisted(() => { const batches: number[] = []; const reject = { collection: '', error: '' }; const slow = { name: '' }; + /** HTTP status the mock answers instead of a result; 0 answers normally. */ + const fail = { pull: 0, push: 0 }; + const auth = { valid: true }; let tick = 0; + /** Answers like the SDK does: a 401 also clears the auth store. */ + const refuse = (status: number): never => { + if (status === 401) auth.valid = false; + throw Object.assign(new Error(status === 401 ? 'The request requires valid auth token.' : 'Failed to fetch'), { status }); + }; return { server, pushes, batches, reject, slow, + fail, + auth, + refuse, stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' ') }; }); vi.mock('$lib/pb', () => ({ pb: { + authStore: { + get isValid() { + return mocks.auth.valid; + }, + clear: () => (mocks.auth.valid = false) + }, autoCancellation: () => undefined, filter: (tpl: string, params: Record) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))), collection: (name: string) => ({ getFullList: async () => { if (mocks.slow.name === name) await new Promise((resolve) => setTimeout(resolve, 5)); + if (mocks.fail.pull) mocks.refuse(mocks.fail.pull); return [...(mocks.server.get(name)?.values() ?? [])]; }, subscribe: async () => async () => undefined }), send: async (path: string, options: { method?: string; body?: unknown }) => { if (path !== '/api/sync/push' || options.method !== 'POST') return {}; + if (mocks.fail.push) mocks.refuse(mocks.fail.push); const body = options.body as { changes: (typeof mocks.pushes)[number][] }; mocks.batches.push(body.changes.length); const results = body.changes.map((c) => { @@ -62,6 +81,14 @@ beforeEach(async () => { await openDb(`user-${++n}`); }); +afterEach(() => { + mocks.pushes.length = 0; + mocks.fail.pull = 0; + mocks.fail.push = 0; + mocks.auth.valid = true; + status.error = null; +}); + afterAll(async () => { await closeDb(); }); @@ -292,3 +319,48 @@ describe('sync boundary', () => { } }); }); + +describe('session expiry', () => { + it('a 401 from the push ends the session and the round is not reported as synced', async () => { + status.online = true; + status.lastSync = 0; + const expired = vi.fn(); + onSessionExpired(expired); + mocks.fail.push = 401; + await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 }); + await syncNow(); + expect(expired).toHaveBeenCalledTimes(1); + expect(pendingCount()).toBe(1); + expect(status.error).toBeNull(); + expect(status.lastSync).toBe(0); + expect(localStorage.getItem(`wotra-cursor:user-${n}:balance_adjustments`)).toBeNull(); + }); + + it('a 401 from the pull ends the session and keeps the cursor', async () => { + status.online = true; + status.lastSync = 0; + const expired = vi.fn(); + onSessionExpired(expired); + await save('settings_history', null, settingsRow); + await syncNow(); + const cursor = localStorage.getItem(`wotra-cursor:user-${n}:settings_history`); + expect(cursor).not.toBeNull(); + status.lastSync = 0; + mocks.fail.pull = 401; + await syncNow(); + expect(expired).toHaveBeenCalledTimes(1); + expect(status.error).toBeNull(); + expect(status.lastSync).toBe(0); + expect(localStorage.getItem(`wotra-cursor:user-${n}:settings_history`)).toBe(cursor); + }); + + it('a round while the auth store is cleared ends the session instead of running', async () => { + status.online = true; + const expired = vi.fn(); + onSessionExpired(expired); + mocks.auth.valid = false; + await syncNow(); + expect(expired).toHaveBeenCalledTimes(1); + expect(mocks.pushes).toHaveLength(0); + }); +}); diff --git a/web/src/lib/session.svelte.ts b/web/src/lib/session.svelte.ts index 5e2f9b6..efb3314 100644 --- a/web/src/lib/session.svelte.ts +++ b/web/src/lib/session.svelte.ts @@ -1,4 +1,4 @@ -import { closeDb, currentUserId, openDb, removeLegacyStorage, wipeLocal } from '$lib/db.svelte'; +import { closeDb, currentUserId, onSessionExpired, openDb, removeLegacyStorage, wipeLocal } from '$lib/db.svelte'; import { errorMessage, pb } from '$lib/pb'; export const session = $state({ @@ -9,6 +9,11 @@ export const session = $state({ export type Gate = 'login' | 'app'; +/** Whether the layout must resolve the gate again: nothing is resolved, the login page is up, or the session ended. */ +export function gateStale(gate: Gate | null): boolean { + return gate === null || gate === 'login' || !session.userId || !pb.authStore.isValid; +} + /** First field error PocketBase sent, else the general message of the error. */ function authError(e: unknown): string { const data = (e as { response?: { data?: Record } }).response?.data; @@ -36,6 +41,18 @@ async function activate(): Promise { session.checked = true; } +/** Ends the session unless one refresh of the token saves it. */ +async function expire(): Promise { + await refreshAuth(); + if (pb.authStore.isValid && pb.authStore.record) return; + pb.authStore.clear(); + session.userId = ''; + session.email = ''; + session.checked = true; +} + +onSessionExpired(() => void expire()); + export async function resolveGate(): Promise { await refreshAuth(); if (!pb.authStore.isValid || !pb.authStore.record) { diff --git a/web/src/lib/session.test.ts b/web/src/lib/session.test.ts index c410628..51a983a 100644 --- a/web/src/lib/session.test.ts +++ b/web/src/lib/session.test.ts @@ -1,10 +1,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { closeDb, status } from './db.svelte'; -import { resolveGate, session } from './session.svelte'; +import { closeDb, save, status, syncNow, update } from './db.svelte'; +import { gateStale, resolveGate, session } from './session.svelte'; const mocks = vi.hoisted(() => ({ legacy: vi.fn(), - record: null as null | { id: string; email?: string } + record: null as null | { id: string; email?: string }, + /** HTTP status the mock answers instead of a result; 0 answers normally. */ + fail: { push: 0 }, + /** Like the SDK: a 401 clears the auth store. */ + autoClear: true, + /** How authRefresh answers: saves the token, rejects with 401 or fails like a network error. */ + refresh: 'save' as 'save' | 'reject' | 'network' })); vi.mock('./db.svelte', async (importOriginal) => { @@ -13,24 +19,47 @@ vi.mock('./db.svelte', async (importOriginal) => { }); vi.mock('$lib/pb', () => ({ - errorMessage: (e: unknown) => String(e), + errorMessage: (e: unknown) => String((e as Error).message), pb: { authStore: { get isValid() { return mocks.record !== null; }, + get token() { + return mocks.record ? `token-${mocks.record.id}` : ''; + }, get record() { return mocks.record; }, clear: () => (mocks.record = null) }, - collection: () => ({ authRefresh: async () => undefined }) + filter: (tpl: string, params: Record) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))), + collection: () => ({ + authRefresh: async () => { + if (mocks.refresh === 'reject') throw Object.assign(new Error('The request requires valid auth token.'), { status: 401 }); + if (mocks.refresh === 'network') throw Object.assign(new Error('Failed to fetch'), { status: 0 }); + }, + getFullList: async () => [], + subscribe: async () => async () => undefined + }), + send: async (path: string, options: { method?: string }) => { + if (path === '/api/sync/push' && options.method === 'POST') { + if (mocks.fail.push) { + if (mocks.autoClear && mocks.fail.push === 401) mocks.record = null; + throw Object.assign(new Error('The request requires valid auth token.'), { status: mocks.fail.push }); + } + } + return {}; + } } })); beforeEach(() => { status.online = false; mocks.legacy.mockClear(); + mocks.fail.push = 0; + mocks.autoClear = true; + mocks.refresh = 'save'; }); afterEach(async () => { @@ -53,3 +82,36 @@ describe('resolveGate', () => { expect(mocks.legacy).toHaveBeenCalledTimes(1); }); }); + +describe('session expiry', () => { + it('a 401 while syncing ends the session and the layout resolves the gate again', async () => { + mocks.record = { id: 'expiring-user', email: 'me@example.com' }; + expect(await resolveGate()).toBe('app'); + expect(gateStale('app')).toBe(false); + status.online = true; + mocks.fail.push = 401; + await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 }); + await syncNow(); + expect(session).toMatchObject({ userId: '', email: '' }); + expect(gateStale('app')).toBe(true); + expect(await resolveGate()).toBe('login'); + }); + + it('a token that refreshes keeps the session, one that does not ends it', async () => { + mocks.record = { id: 'refresh-user' }; + mocks.autoClear = false; + await resolveGate(); + status.online = true; + mocks.fail.push = 401; + const id = await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 }); + await syncNow(); + expect(session.userId).toBe('refresh-user'); + expect(gateStale('app')).toBe(false); + + mocks.refresh = 'reject'; + await update('balance_adjustments', id, { delta_ms: 2000 }); + await syncNow(); + expect(session.userId).toBe(''); + expect(gateStale('app')).toBe(true); + }); +}); diff --git a/web/src/lib/sync.test.ts b/web/src/lib/sync.test.ts index 11265e8..fff1e15 100644 --- a/web/src/lib/sync.test.ts +++ b/web/src/lib/sync.test.ts @@ -30,6 +30,7 @@ const mocks = vi.hoisted(() => { vi.mock('$lib/pb', () => ({ pb: { + authStore: { isValid: true }, autoCancellation: () => undefined, filter: (tpl: string, params: Record) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))), collection: (name: string) => ({ diff --git a/web/src/routes/+layout.svelte b/web/src/routes/+layout.svelte index fd383f5..515a0bb 100644 --- a/web/src/routes/+layout.svelte +++ b/web/src/routes/+layout.svelte @@ -3,13 +3,13 @@ import { goto } from '$app/navigation'; import { page } from '$app/state'; import { pendingCount, status, syncNow } from '$lib/db.svelte'; - import { resolveGate, safeNext, session } from '$lib/session.svelte'; + import { gateStale, resolveGate, safeNext, session } from '$lib/session.svelte'; let { children } = $props(); let gate = $state<'login' | 'app' | null>(null); async function route() { - if (!session.userId || gate === 'login') gate = await resolveGate(); + if (gateStale(gate)) gate = await resolveGate(); const path = page.url.pathname; if (gate === 'app') { if (path === '/' || path === '/login') await goto(safeNext(page.url), { replaceState: true });