Credentials and refresh
Cookies need nothing
Cookie-based authentication needs no tscache code: cookies go with the worker's fetches, as with any same-origin request.
Tokens
With tokens, the flow is:
- The page passes the token in the fetcher's
context(createClient({ fetcher: { module, context } })). - The fetcher sends it, and throws
AuthInvalidErrorwhen the backend refuses it. - The worker marks credentials invalid and broadcasts
authInvalidto every tab connected to it, once each time credentials become invalid, with thecontextthe refused fetch carried. With a SharedWorker that is every tab of the origin; in a fallback it is one tab (see below). - While credentials are invalid, no fetch runs:
getdoes not wait, and the affected ranges come back at once as misses with reason'auth-pending'. A tab opened while credentials are invalid gets'auth-pending'too, without anauthInvalid: the event was broadcast before it connected. Whether such a tab should be told is an open design decision. - Any tab refreshes and calls
client.updateAuth(newContext). The fetcher's optionalupdateAuthhook runs, the new context takes effect, and fetching resumes. - Tabs read again; the ranges that were
'auth-pending'are fetched.
const stop = client.on("authInvalid", ({ context }) => {
console.log("refused context", context);
// Refresh the credential, then hand it to the fetcher in every worker.
void client.updateAuth({ token: "fresh-token" });
});
stop(); // on() returns the unsubscribe; off(event, fn) works tooA get never waits for a human: nothing is retried on behalf of a get that already returned.
The detection is by marker, error.code === 'tscache:auth-invalid', never instanceof, so a fetcher bundled with its own copy of the class works. A failure from a fetch that started under credentials since replaced is ignored, so a late refusal of an old token does not undo a refresh.
In a dedicated worker or in-process, auth is per tab
The dedicated-worker hosting runs one worker per tab, and the in-process hosting, which has no worker, gives each client an engine of its own (Workers and fallback). There the credential state belongs to that tab alone: authInvalid reaches only the tab whose fetch was refused, and updateAuth restores only that tab's worker, or in-process that client's engine. The other tabs keep fetching with their own context until the backend refuses it, and each then hears its own authInvalid. The refresh snippet below still converges, one tab at a time: a tab that takes the lock after another tab's refresh finds newer stored tokens and adopts them. client.mode tells which hosting a tab has.
Refreshing once across tabs
With a SharedWorker, every tab hears authInvalid. With a rotating refresh token, each refresh token works once, and many servers revoke the whole session when a spent one comes back; if every tab refreshed, all but the first would present a spent token. The examples' snippet refreshes under a Web Lock, one tab at a time: a tab that gets the lock after another's refresh compares the stored access token with the refused one (the event's context) and adopts the new tokens instead of refreshing again.
// Refresh-token rotation across tabs, driven by tscache's authInvalid event.
//
// tscache tells every open tab when the fetcher reports an expired token,
// and names the fetcher context that was refused. With refresh-token
// rotation each refresh token works once: if every tab refreshed, all but
// the first would present a spent token, and many servers answer that by
// revoking the whole session. Here one tab refreshes while the others wait
// on a Web Lock; a tab that gets the lock afterwards finds the refused token
// already replaced and uses the new tokens instead of refreshing again.
//
// A refresh token is never presented twice: it is cleared from storage
// before it is spent, so if the refresh or the save of the new tokens fails,
// every tab ends the session through onSessionLost instead of retrying with
// it.
//
// It assumes a refresh issues a new access token. A backend that renews an
// access token in place (an opaque token whose expiry the refresh extends)
// returns the refused string again, so every tab that heard the refusal
// finds it still stored and refreshes once in turn. Each refresh presents the
// current refresh token, never a spent one, so the session survives; the
// cost is one redundant refresh per extra tab.
//
// A SharedWorker from a tscache version that did not name the refused
// context yet (kept alive by a tab opened before an upgrade) sends the event
// without one. The refused token is then unknown, so the tab refreshes: tabs
// may rotate once each, always with the current refresh token.
import type { TscacheClient } from "@anishbenji/tscache";
export interface StoredTokens {
access: string;
refresh: string | null;
}
export interface RefreshOptions {
load: () => StoredTokens | Promise<StoredTokens>;
save: (tokens: StoredTokens) => void | Promise<void>;
refresh: (
refreshToken: string,
) => Promise<{ access: string; refresh: string }>;
toContext: (access: string) => unknown;
accessOf: (context: unknown) => string | undefined;
onSessionLost: (error: unknown) => void;
lockName?: string;
}
/**
* @param client the tscache client of this tab
* @param options.load returns the tokens all tabs share, `{ access, refresh }`
* (from localStorage, say); may return a promise
* @param options.save stores tokens where `load` finds them; may return a
* promise, which must reject if they were not stored
* @param options.refresh exchanges a refresh token for new tokens
* @param options.toContext builds the fetcher context for an access token
* @param options.accessOf returns the access token in a fetcher context
* (the inverse of `toContext`)
* @param options.onSessionLost called with the error when the session cannot
* be recovered (send the user to sign in)
* @returns the unsubscribe function
*/
export function refreshOnAuthInvalid(
client: TscacheClient,
{
load,
save,
refresh,
toContext,
accessOf,
onSessionLost,
lockName = "tscache-auth-refresh",
}: RefreshOptions,
): () => void {
return client.on("authInvalid", ({ context }) => {
void navigator.locks
.request(lockName, async () => {
let tokens: StoredTokens;
try {
tokens = await load();
if (tokens.refresh === null) {
throw new Error("the session ended in another tab");
}
// Otherwise another tab already replaced the refused token.
if (context === undefined || tokens.access === accessOf(context)) {
await save({ access: tokens.access, refresh: null });
tokens = await refresh(tokens.refresh);
await save(tokens);
}
} catch (error) {
onSessionLost(error);
return;
}
// Tabs sharing a SharedWorker would recover from one tab's update,
// but tabs on their own workers (after a fallback) each need theirs.
await client.updateAuth(toContext(tokens.access));
})
.catch(reportError);
});
}Its main assumption is that a refresh issues a new access token. A backend that renews an access token in place returns the refused string again, so each tab that heard the refusal refreshes once in turn, always with the current refresh token: the session survives, at the cost of one redundant refresh per extra tab.
The reference clients use the same scheme with a sign-in flow around it (reference/shared/src/auth.ts).
Why broadcast
The architecture compared three designs: tell only the tab whose read failed (other tabs stay silently stale), broadcast to all (simple; the lock prevents a stampede), and a worker-elected handler that fails over when its tab dies (cleanest, but election and failover are complex; on the roadmap). Version 1 broadcasts (§6.2 of the architecture document).