🐛 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
+31 -3
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;
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<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;