🐛 Recover the app when the session expires

A 401 mid-session made the PocketBase SDK drop the auth store, while
session.userId and the gate of the layout stayed set: the user remained
in the app, every round failed, /login was bounced back and a token-less
pull was even taken for a successful round.

The sync layer now ends the session through an onSessionExpired hook
when a round fails with 401 or finds the auth store cleared, and reports
no round as synced without a valid auth store. The session module tries
one token refresh before it clears the session, and the layout resolves
the gate again whenever the auth store is no longer valid, so the user
lands on the login page and the next sign-in brings the data back.
This commit is contained in:
2026-12-01 19:04:06 +01:00
parent e630f9fd66
commit d750b8c3c9
7 changed files with 194 additions and 13 deletions
+1
View File
@@ -28,6 +28,7 @@ const mocks = vi.hoisted(() => {
vi.mock('$lib/pb', () => ({
pb: {
authStore: { isValid: true },
autoCancellation: () => undefined,
filter: (tpl: string, params: Record<string, unknown>) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))),
collection: (name: string) => ({
+30 -2
View File
@@ -154,6 +154,7 @@ const staleBuffer = new Map<string, AnyDoc[]>();
const pushedChanges = new Map<string, Set<string>>();
/** 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<string, number>();
@@ -194,6 +195,7 @@ async function pullRecords(name: string, cursor: string | null): Promise<RecordM
}
function onSynced(name: string) {
if (!pb.authStore.isValid) return;
const c = pendingCursor.get(name);
if (c && userId) {
localStorage.setItem(cursorKey(userId, name), c);
@@ -203,7 +205,14 @@ function onSynced(name: string) {
if (!rejected) status.error = null;
}
/** A 401 ends the session; the SDK has usually cleared the auth store already. */
function unauthorized(e: unknown): boolean {
return (e as { status?: unknown } | null)?.status === 401;
}
class WotraSync extends SyncManager<Record<string, unknown>, 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<Record<string, unknown>, AnyDoc, string> {
}
override async sync(name: string, options?: { force?: boolean; onlyWithChanges?: boolean }): Promise<void> {
const before = pullRuns;
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<void> {
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>): 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<void> {
return beforeSync ? beforeSync() : Promise.resolve();
}
@@ -385,11 +406,18 @@ export function syncNow(): Promise<void> {
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<void> = 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;
+74 -2
View File
@@ -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<string, unknown>) => 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);
});
});
+18 -1
View File
@@ -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<string, { message?: string } | null> } }).response?.data;
@@ -36,6 +41,18 @@ async function activate(): Promise<void> {
session.checked = true;
}
/** Ends the session unless one refresh of the token saves it. */
async function expire(): Promise<void> {
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<Gate> {
await refreshAuth();
if (!pb.authStore.isValid || !pb.authStore.record) {
+67 -5
View File
@@ -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<string, unknown>) => 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);
});
});
+1
View File
@@ -30,6 +30,7 @@ const mocks = vi.hoisted(() => {
vi.mock('$lib/pb', () => ({
pb: {
authStore: { isValid: true },
autoCancellation: () => undefined,
filter: (tpl: string, params: Record<string, unknown>) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))),
collection: (name: string) => ({
+2 -2
View File
@@ -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 });