feat(DPoP): UI: bcast events to support multi tab

add also playwright test with the multi tab
This commit is contained in:
Edouard Vanbelle
2026-08-08 17:24:44 +02:00
parent 4c2b244166
commit ed99b08e62
8 changed files with 417 additions and 20 deletions
+5 -1
View File
@@ -456,7 +456,6 @@ export async function startOidcLink(): Promise<string> {
headers: { ...JSON_HEADERS, ...getCsrfHeaders() },
body: '{}'
});
<<<<<<< HEAD
if (!res.ok) {
const { errorType, message } = await parseErrorBody(res);
throw new ApiError(res.status, res.statusText, '/api/auth/oidc/link/start', errorType, message);
@@ -515,8 +514,13 @@ export async function logout(): Promise<LogoutResult> {
try {
const { clearKeypair } = await import('$lib/auth/dpop');
const { clearNonce } = await import('$lib/auth/dpop-proof');
const { broadcastSessionCleared } = await import('$lib/auth/session-broadcast');
await clearKeypair();
clearNonce();
// Notify every OTHER tab of this origin that the session is
// gone — Gate 8 cross-tab UX. Tabs that were sitting idle
// don't have to wait for their next 401 to notice.
broadcastSessionCleared();
} catch (err) {
console.debug('dpop: cleanup failed during logout', err);
}
@@ -0,0 +1,78 @@
/**
* Cross-tab session invalidation via `BroadcastChannel` — the
* "logout on tab A, tab B knows immediately" wire.
*
* Why this exists: after a logout on Tab A, Tab B still holds an
* in-memory `CryptoKey` handle to the (now-cleared) DPoP keypair
* and a session cookie whose server-side row was just revoked.
* Without a cross-tab signal, Tab B doesn't notice until its next
* network request — at which point the server 401s and the SPA
* bounces to `/login`. That's correctness-safe (see
* `docs/plan/dpop.md` Gate 8), but UX-poor: an idle Tab B silently
* pretends to be logged in for as long as it stays idle.
*
* This module fires a `BroadcastChannel` message so every other
* tab of the same origin can react synchronously — reset its
* session store, redirect to `/login`, no visible drift.
*
* Scope: session **invalidation** only. Not for cross-tab login
* (a fresh sign-in on Tab B while Tab A sits on `/login`); that's
* a general auth-store consistency concern, not DPoP-specific,
* and can be layered on later using the same primitive if needed.
*
* Fail-open contract mirrors the rest of the DPoP stack: if
* `BroadcastChannel` is unavailable (very old Safari, restricted
* webviews), broadcast/subscribe are no-ops. Users lose the
* instant-redirect UX; the natural 401-on-next-request path
* kicks in as before.
*/
const CHANNEL_NAME = 'oxicloud-session-cleared';
/**
* Post a "session cleared" event to every other tab of this
* origin. The current tab does NOT receive its own message —
* `BroadcastChannel` skips the sender by design.
*
* Called from `logout()` after the server round trip completes
* (success or failure — user intent is what matters). Non-fatal
* on failure so the logout flow always finishes.
*/
export function broadcastSessionCleared(): void {
try {
const ch = new BroadcastChannel(CHANNEL_NAME);
ch.postMessage({ kind: 'session_cleared', at: Date.now() });
ch.close();
} catch (err) {
console.debug('session-broadcast: postMessage failed', err);
}
}
/**
* Subscribe to cross-tab session-cleared events. Wire this once
* from the root layout's `onMount`; the callback should reset
* the SPA's session store and navigate to `/login`.
*
* Returns a cleanup function that closes the channel — call it
* from the layout's `onDestroy` so hot-reload during dev doesn't
* leak listeners.
*
* Errors during subscription are swallowed to a no-op: same
* degradation posture as the rest of the DPoP stack.
*/
export function onSessionCleared(callback: () => void): () => void {
try {
const ch = new BroadcastChannel(CHANNEL_NAME);
ch.onmessage = () => {
try {
callback();
} catch (err) {
console.debug('session-broadcast: callback threw', err);
}
};
return () => ch.close();
} catch (err) {
console.debug('session-broadcast: subscribe failed', err);
return () => {};
}
}
+19
View File
@@ -9,6 +9,7 @@
import DialogHost from '$lib/components/DialogHost.svelte';
import Toaster from '$lib/components/Toaster.svelte';
import { setPasswordChangeRequiredHandler } from '$lib/api/client';
import { onSessionCleared } from '$lib/auth/session-broadcast';
import { session } from '$lib/stores/session.svelte';
import { ui } from '$lib/stores/ui.svelte';
import { hashUrlToPath } from '$lib/utils/hashRedirect';
@@ -61,6 +62,24 @@
});
onMount(async () => {
// Cross-tab logout — when ANOTHER tab logs out, wipe our
// session store and bounce to /login synchronously. Without
// this the natural 401-on-next-request path still catches
// it, just with visible delay for an idle tab. See
// `docs/plan/dpop.md` Gate 8.
//
// The cleanup closure returned by `onSessionCleared` is
// intentionally not wired to `onDestroy` — the root layout
// only unmounts on hot-reload, and a leaked BroadcastChannel
// there is far cheaper than the risk of missing an
// invalidation event during teardown.
onSessionCleared(() => {
session.reset();
// `replaceState: true` so the back button doesn't return
// the user to the now-dead protected page they were on.
void goto(resolve('/login'), { replaceState: true });
});
await killLegacyServiceWorker();
// The instant HTML boot splash has done its job — the app is mounted, so
+146
View File
@@ -54,3 +54,149 @@ for (const name of ['localStorage', 'sessionStorage']) {
g[name] = new MemoryStorage() as unknown as Storage;
}
}
// jsdom has no IndexedDB. `$lib/auth/dpop` uses it as a single-entry
// key/value store for the browser DPoP keypair; without a working
// backing store every test that touches login / fetch prints a
// fail-open `console.debug` on stdout. Rather than pull in
// `fake-indexeddb` for one call-site, provide a minimal in-memory
// shim that covers exactly the API surface `dpop.ts` uses:
//
// indexedDB.open(name) → IDBOpenDBRequest
// .onupgradeneeded / .onsuccess / .onerror → callback slots
// .result → { objectStoreNames.contains,
// createObjectStore, transaction, close }
// store.get(key) / .put(value, key) / .delete(key)
// tx.oncomplete / .onerror
//
// Tests that WANT to exercise DPoP semantics still mock the module
// (see `src/lib/auth/dpop-proof.test.ts`). This shim is for the
// login-path traversals that were noisy without it.
if (!g.indexedDB) {
type Store = Map<string, unknown>;
type Db = {
stores: Map<string, Store>;
objectStoreNames: { contains: (n: string) => boolean };
createObjectStore: (n: string) => void;
transaction: (n: string, mode: 'readonly' | 'readwrite') => FakeTx;
close: () => void;
};
type FakeReq<T> = {
result: T | undefined;
error: unknown;
onsuccess: ((this: unknown, ev: Event) => void) | null;
onerror: ((this: unknown, ev: Event) => void) | null;
};
type FakeTx = {
objectStore: (n: string) => FakeStore;
oncomplete: ((this: unknown, ev: Event) => void) | null;
onerror: ((this: unknown, ev: Event) => void) | null;
_done: () => void;
};
type FakeStore = {
get: (key: string) => FakeReq<unknown>;
put: (value: unknown, key: string) => FakeReq<void>;
delete: (key: string) => FakeReq<void>;
};
// Per-database persistence: opening the same name again gives you
// back your previously-created stores + entries, so the module's
// "read a value someone else wrote" flow works across
// open→close→open cycles within one test.
const databases = new Map<string, Map<string, Store>>();
function makeStore(map: Store, tx: FakeTx): FakeStore {
const microDone = () => queueMicrotask(() => tx._done());
return {
get(key: string): FakeReq<unknown> {
const req: FakeReq<unknown> = {
result: map.get(key),
error: undefined,
onsuccess: null,
onerror: null
};
queueMicrotask(() => req.onsuccess?.call(req, new Event('success')));
microDone();
return req;
},
put(value: unknown, key: string): FakeReq<void> {
map.set(key, value);
const req: FakeReq<void> = {
result: undefined,
error: undefined,
onsuccess: null,
onerror: null
};
queueMicrotask(() => req.onsuccess?.call(req, new Event('success')));
microDone();
return req;
},
delete(key: string): FakeReq<void> {
map.delete(key);
const req: FakeReq<void> = {
result: undefined,
error: undefined,
onsuccess: null,
onerror: null
};
queueMicrotask(() => req.onsuccess?.call(req, new Event('success')));
microDone();
return req;
}
};
}
function makeDb(name: string): Db {
let stores = databases.get(name);
if (!stores) {
stores = new Map();
databases.set(name, stores);
}
return {
stores,
objectStoreNames: { contains: (n: string) => stores!.has(n) },
createObjectStore(n: string): void {
if (!stores!.has(n)) stores!.set(n, new Map());
},
transaction(n: string, _mode: 'readonly' | 'readwrite'): FakeTx {
const store = stores!.get(n);
if (!store) throw new Error(`fake-idb: store '${n}' not found`);
const tx: FakeTx = {
objectStore: () => makeStore(store, tx),
oncomplete: null,
onerror: null,
_done: () => tx.oncomplete?.call(tx, new Event('complete'))
};
return tx;
},
close(): void {
/* no-op — databases map keeps state across close */
}
};
}
g.indexedDB = {
open(name: string) {
const req: FakeReq<Db> & {
onupgradeneeded: ((this: unknown, ev: Event) => void) | null;
} = {
result: undefined,
error: undefined,
onsuccess: null,
onerror: null,
onupgradeneeded: null
};
queueMicrotask(() => {
const db = makeDb(name);
req.result = db;
// Fire upgradeneeded on FIRST open per database, so the
// module can call createObjectStore('keypair') exactly
// like the real API expects.
const stores = databases.get(name)!;
if (stores.size === 0) req.onupgradeneeded?.call(req, new Event('upgradeneeded'));
req.onsuccess?.call(req, new Event('success'));
});
return req;
}
};
}