tempest-react-sdk 0.82.0 → 0.83.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/bin/lib/openapi/generate.hostile.test.mjs +91 -0
- package/bin/lib/openapi/generate.mjs +42 -3
- package/dist/auth/create-tempest-auth.cjs +1 -1
- package/dist/auth/create-tempest-auth.cjs.map +1 -1
- package/dist/auth/create-tempest-auth.js +135 -132
- package/dist/auth/create-tempest-auth.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +124 -75
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/upload-with-progress.cjs +1 -1
- package/dist/http/upload-with-progress.cjs.map +1 -1
- package/dist/http/upload-with-progress.js +100 -44
- package/dist/http/upload-with-progress.js.map +1 -1
- package/dist/query/offline-persistence.cjs +1 -1
- package/dist/query/offline-persistence.cjs.map +1 -1
- package/dist/query/offline-persistence.js +57 -44
- package/dist/query/offline-persistence.js.map +1 -1
- package/dist/sw/cache.cjs +1 -1
- package/dist/sw/cache.cjs.map +1 -1
- package/dist/sw/cache.js +82 -32
- package/dist/sw/cache.js.map +1 -1
- package/dist/sw.d.ts +21 -1
- package/dist/tempest-react-sdk.d.ts +90 -6
- package/dist/vite/base-url.cjs +1 -1
- package/dist/vite/base-url.cjs.map +1 -1
- package/dist/vite/base-url.js +5 -1
- package/dist/vite/base-url.js.map +1 -1
- package/dist/vite/tempest-pwa-dev-sw.cjs +1 -1
- package/dist/vite/tempest-pwa-dev-sw.cjs.map +1 -1
- package/dist/vite/tempest-pwa-dev-sw.js +96 -31
- package/dist/vite/tempest-pwa-dev-sw.js.map +1 -1
- package/dist/vite/tempest-pwa-manifest.cjs +2 -2
- package/dist/vite/tempest-pwa-manifest.cjs.map +1 -1
- package/dist/vite/tempest-pwa-manifest.js +32 -16
- package/dist/vite/tempest-pwa-manifest.js.map +1 -1
- package/dist/vite.cjs +1 -1
- package/dist/vite.d.ts +63 -12
- package/dist/vite.js +4 -4
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-tempest-auth.cjs","names":["isDevBuild","createAuthStore","SessionSupersededError","createApiClient","createRefreshQueue","require_dev_mode","require_errors","require_api_client","require_session_identity","require_create_auth_store","require_refresh_queue","LOGOUT_REVOCATION_WAIT_MS","REFRESH_LOCK_WAIT_MS","settleWithin","pending","timer","resolve","ms","newLineage","host","UNLINEAGED_SESSION_KEY","warnedCookieWithoutLogout","warnCookieWithoutLogout","storeName","defaultParseTokens","d","data","createTempestAuth","rt","options","withCredentials","logoutPath","useAuthStore","refreshKey","storageImpl","storage","readRefreshToken","heldRefreshToken","writeRefreshToken","token","s","lineageKey","refreshLockName","heldLineage","writeLineage","lineage","state","getToken","fetchUser","mePath","started","epoch","user","api","error","followSharedSession","ending","hooksRunning","loginsInFlight","revocations","credentialRequests","rotatingEpochs","trackCredentialRequest","settled","request","reportLogoutError","onLogoutError","trackRevocation","tracked","build","revokeDiscarded","refreshToken","endedSessionApi","refreshBody","nextEpoch","rotate","before","underRefreshLock","redeem","locks","run","controller","acquired","held","followed","refreshPath","parseTokens","queue","staleWithinSession","current","context","signedOut","awaitLogins","refreshFor","onUnauthorized","endSession","login","signIn","credentials","loginPath","finish","mine","done","embedded","parseUser","live","reason","runSessionEnd","onSessionEnd","sessionApi","ended","readSharedSession","raw","parsed","shared","sameUser","sameSession","continues","revoke","path","inFlight","logout","revocation","redirectTo","refresh","sessionKey","identity","listener","onStorage","event"],"sources":["../../src/auth/create-tempest-auth.ts"],"sourcesContent":["import { createApiClient, SessionSupersededError } from \"../http\";\nimport { bindSessionIdentity, type SessionIdentity } from \"./session-identity\";\nimport { isDevBuild } from \"../utils/dev-mode\";\nimport type { ApiClient, CsrfOptions, RequestAuthContext, RetryOptions } from \"../http\";\nimport { createAuthStore } from \"./create-auth-store\";\nimport type { AuthState } from \"./create-auth-store\";\nimport { createRefreshQueue } from \"./refresh-queue\";\n\n/** The token envelope returned by a Tempest FastAPI SDK login/refresh route. */\nexport interface TempestTokenResponse {\n /** The bearer access token. */\n access_token: string;\n /** Token type — always `\"bearer\"` for the SDK. */\n token_type?: string;\n /** Optional refresh token (when the API returns it in the body, not a cookie). */\n refresh_token?: string;\n}\n\n/**\n * What {@link CreateTempestAuthOptions.onSessionEnd} receives about the session\n * that just ended.\n */\nexport interface TempestSessionEnd<TUser> {\n /**\n * Why it ended: `\"logout\"` for an explicit `logout()`, `\"expired\"` when the\n * client ended it on its own — the refresh failed, or the request replayed\n * after a refresh still came back `401` — and `\"switch\"` when `login()`\n * succeeded for another set of credentials while this session was live.\n */\n reason: \"logout\" | \"expired\" | \"switch\";\n /** The user of the ended session, as the store held it. */\n user: TUser | null;\n /** The access token of the ended session, or `null` when it had none. */\n token: string | null;\n /**\n * A client that sends the ended session's access token — the store has\n * already been cleared, so `auth.api` no longer does.\n *\n * Use it for the server-side half of the teardown, such as deleting this\n * browser's push subscription. It never refreshes and never ends a session:\n * a `401` here just rejects. On `\"logout\"` the token is usually still\n * valid; on `\"expired\"` the server has already refused it, so expect the\n * call to fail and keep the local half of the teardown independent of it.\n */\n api: ApiClient;\n /**\n * Whether another tab of the origin ended or replaced the session, and this\n * tab is only catching up (#524). With `storage: \"local\"` the session's\n * keys are shared by every tab, so a `logout()` or a `login()` in one tab\n * ends the session in all of them: `reason` is `\"logout\"` when the other\n * tab left no session behind and `\"switch\"` when it installed another\n * account.\n *\n * The other tab already ran this hook for the same session. Teardown that\n * lives in this tab's memory (an in-memory cache, an open socket) still has\n * to run here; teardown of state the origin shares (IndexedDB, Cache\n * Storage, a push subscription) was done there, and on `\"switch\"` redoing\n * it here would wipe what the new account already wrote — skip it when\n * this is `true`.\n */\n elsewhere: boolean;\n}\n\nexport interface CreateTempestAuthOptions<TUser> {\n /** Base URL of the API. Required. */\n baseURL: string;\n /**\n * Path segment the API is mounted under, such as `\"/api\"`, forwarded to\n * every client this preset builds — see the `prefix` option of\n * `createApiClient`.\n *\n * Safe to combine with the default paths below: the prefix is applied at\n * most once, so `\"/api/auth/login\"` under a `\"/api\"` prefix stays\n * `\"/api/auth/login\"`.\n */\n prefix?: string;\n /** Login route (`POST`). Default: `\"/api/auth/login\"`. */\n loginPath?: string;\n /** Refresh route (`POST`). Default: `\"/api/auth/refresh\"`. */\n refreshPath?: string;\n /**\n * Server-side logout route (`POST`), called by an explicit `logout()` to\n * revoke the ending session. Off by default.\n *\n * `logout()` alone only clears client state, and an HttpOnly refresh\n * cookie is out of its reach: with `withCredentials`, the cookie stays\n * redeemable until the backend revokes it. The tempest-fastapi-sdk mounts\n * `POST /auth/logout` (`204`, idempotent) when it stores refresh tokens in\n * the database — at `/auth/cookie/logout` when it delivers tokens both in\n * the body and in cookies — and stateless refresh tokens cannot be\n * revoked, so the route is absent there.\n *\n * The request goes out through the ended session's client (the same one\n * `onSessionEnd` receives, carrying its access token), with the body that\n * `refreshBody` builds from the refresh token stored before the clear:\n * `{ refresh_token }` in body mode, no body in cookie mode, which is what\n * that route reads. The local clear does not wait on it — `isAuthenticated`\n * is still `false` when `logout()` returns — but the promise `logout()`\n * returns does, so a navigation after `await auth.logout()` does not abort\n * it. A failure (network, `4xx`, `5xx`) is swallowed: revocation is\n * best-effort and never keeps the user signed in. A `login()` started\n * while it is in flight waits for it, because the logout response clears\n * the auth cookies and would otherwise clear the new account's.\n *\n * An explicit `logout()` revokes, and so does a `\"switch\"` in body mode:\n * the replaced session's refresh token is still in the client's hands, and\n * the tempest-fastapi-sdk revokes by rotation family, so the session the\n * new login opened is untouched even for the same user. Before 0.82.0 a\n * switch revoked nothing and the replaced token stayed redeemable until it\n * expired. A `\"switch\"` in cookie mode does not revoke — the cookie jar\n * already holds the new account's cookie — and on `\"expired\"` the server\n * has already refused the session.\n *\n * Overlapping sign-outs each send their own revocation, and `login()` waits\n * for all of them — at most 10 seconds, so one that\n * never answers delays the sign-in instead of blocking it. In cookie mode,\n * a revocation also waits (within the same bound) for the login and\n * refresh responses that were in flight when `logout()` ran: the server\n * sets the ended session's cookie when that response arrives, and a\n * revocation sent earlier would leave it behind. In body mode, the refresh\n * token such a superseded response brings back is revoked on its own.\n */\n logoutPath?: string;\n /**\n * Called with the error when a `logoutPath` revocation fails — network\n * failure, `4xx` or `5xx`. `logout()` still resolves, since the local\n * sign-out already happened; this is where the app logs or retries. A dev\n * build also warns in the console. Errors it throws are swallowed.\n */\n onLogoutError?: (error: unknown) => void;\n /** Optional current-user route (`GET`) called after login/refresh. */\n mePath?: string;\n /** Persist key for the store. Default: `\"tempest-auth\"`. */\n storeName?: string;\n /** Storage backend. Default: `\"local\"`. */\n storage?: \"local\" | \"session\";\n /** Send cookies (needed when the refresh token lives in an httpOnly cookie). */\n withCredentials?: boolean;\n /**\n * CSRF token for every write, forwarded to `createApiClient`'s `csrf`. Off\n * by default; `true` echoes the `csrf_token` cookie as `X-CSRF-Token`.\n *\n * The pair to `withCredentials`: once the refresh token lives in a cookie,\n * the browser attaches it to a `POST /auth/refresh` that another site\n * triggers. Login and refresh carry the header too — they go out with\n * `skipAuth`, and the CSRF header does not follow auth.\n */\n csrf?: boolean | CsrfOptions;\n /** Custom fetch implementation (testing / SSR). Defaults to `globalThis.fetch`. */\n fetcher?: typeof fetch;\n /**\n * Extract tokens from a login/refresh response. Default reads\n * `access_token` + `refresh_token`.\n */\n parseTokens?: (data: unknown) => { token: string; refreshToken?: string };\n /** Pull the user out of the login response, when the API embeds it. */\n parseUser?: (data: unknown) => TUser | null;\n /**\n * Build the refresh request body. Default sends `{ refresh_token }` when a\n * refresh token is stored, else `undefined` (cookie-based refresh).\n */\n refreshBody?: (refreshToken: string | null) => unknown;\n /**\n * Retry policy for `api`, forwarded to {@link createApiClient}. Off by\n * default; `true` enables the conservative built-in policy, which never\n * replays a write.\n */\n retry?: boolean | RetryOptions;\n /**\n * Where to send the browser when the session ends — a hard navigation via\n * `window.location.assign`, after the store is cleared.\n *\n * **Prefer leaving this unset.** `logout()` already clears the store, so a\n * `<RouteGuard when={isAuthenticated} redirectTo=\"/login\">` wrapped around\n * the protected area navigates on its own, which keeps the SPA alive and the\n * router history intact. Reach for this only when the expiry can happen\n * outside any guarded subtree and a full reload is acceptable.\n */\n redirectTo?: string;\n /**\n * Tear down per-user state when a session ends — on an explicit `logout()`,\n * when the client ends the session on its own after a failed refresh, and\n * when a successful `login()` replaces a live session. Without it, the automatic path had no place to hook into, and\n * state derived from the user (a push subscription, a persisted query\n * cache, a background-sync queue) survived into the next account.\n *\n * Order, on every path:\n *\n * 1. any refresh still in flight is superseded, so it cannot reinstall the\n * ending session's tokens;\n * 2. the store and the stored refresh token are cleared — synchronously, so\n * `isAuthenticated` is already `false` when `logout()` returns;\n * 3. this hook runs with a {@link TempestSessionEnd} whose `api` still sends\n * the ended session's access token;\n * 4. on `\"expired\"` with `redirectTo` set, the browser navigates — after the\n * hook settled, even if it threw; on `\"switch\"`, the new session is\n * installed — after the hook settled, even if it threw.\n *\n * It may be async. `logout()` resolves when it settles and rejects with what\n * it threw; on the automatic path the error is swallowed, because the\n * request that ended the session already rejects with its own `401`. It\n * runs once per session: a second `logout()`, or the other requests of a\n * burst of `401`s, find nothing left to end and skip it.\n *\n * On `\"switch\"` the hook runs only **after** the new credentials were\n * accepted, so a failed `login()` leaves the live session untouched. It runs\n * **before** the new session is installed: teardown of the previous\n * account's state (clearing a persisted cache, a background-sync queue) has\n * to finish before the new account's requests start filling them, or it\n * would wipe — or race with — the new account's data. The cost is that\n * `isAuthenticated` is `false` while the hook runs, which a route guard may\n * act on; keep the hook short. Its error is swallowed there, since the\n * login itself succeeded.\n *\n * Inside the hook, reach the backend only through `session.api`. `auth.api`\n * goes out with no token; `auth.login()` waits on the teardown in progress —\n * this hook — and never settles. Telling the hook apart from an outside\n * caller would need an async context the browser does not have, so this is\n * a documented rule, not a runtime check.\n */\n onSessionEnd?: (session: TempestSessionEnd<TUser>) => void | Promise<void>;\n}\n\nexport interface TempestAuth<TUser, TCredentials> {\n /** The persisted Zustand auth store hook (compatible with `<AuthGuard>`). */\n useAuthStore: ReturnType<typeof createAuthStore<TUser>>;\n /** A `createApiClient` wired with bearer auth + 401 → refresh → retry. */\n api: ApiClient;\n /** Authenticate, store the session, and resolve the user (or null). */\n login: (credentials: TCredentials) => Promise<TUser | null>;\n /**\n * End the session: supersede any refresh in flight, clear the store and the\n * stored refresh token, then run `onSessionEnd`.\n *\n * The store is cleared synchronously, before the first `await`, so callers\n * that ignore the promise see the signed-out state at once. The promise\n * resolves when `onSessionEnd` settled — and, with `logoutPath`, when the\n * server-side revocation settled too — and rejects with the hook's error;\n * a failed revocation never rejects it.\n */\n logout: () => Promise<void>;\n /**\n * Refresh the access token (deduplicated across concurrent callers).\n *\n * @throws {SessionSupersededError} When the session ended or changed while\n * the refresh was in flight; its tokens were discarded.\n */\n refresh: () => Promise<void>;\n /** The current access token, or null. */\n getToken: () => string | null;\n /**\n * The key of the session signed in now, or `null` when nobody is.\n *\n * It changes when the session is replaced — `login()`, even into the same\n * account, a sign-in or sign-out in another tab, `logout()` — and stays\n * the same while that session's tokens rotate: it is the session lineage\n * `login()` mints, not the token. That is the identity a per-session\n * resource needs. `useTicketEventStream`/`createTicketEventStream` read it\n * on their own from `api`, and `createResumableUpload` from `getToken`;\n * pass it as `sessionKey` or `getPrincipal` anywhere else.\n *\n * A session that has no lineage — persisted before lineages existed, or\n * restored from a refresh cookie without a `login()` in this storage —\n * answers `\"unlineaged\"`. Replacing it still takes a\n * `login()`, which mints one, so the key still changes on a switch.\n */\n sessionKey: () => string | null;\n /**\n * Stop following the other tabs: removes the `storage` listener this\n * preset adds to `window`. Idempotent.\n *\n * An app keeps one preset for the page's lifetime and never needs it; it\n * exists for tests and hot-module reload, which build several presets in\n * one window. A disposed preset still compares the shared storage with\n * its session before every refresh, so it never redeems another tab's\n * refresh token.\n */\n dispose: () => void;\n}\n\n/**\n * How long `login()` waits for pending `logoutPath` revocations, and how long a\n * cookie-mode revocation waits for the login or refresh responses still in\n * flight when `logout()` ran, before going ahead anyway.\n *\n * A bound, not a guess at latency: a fetcher that ignores abort, or a backend\n * that never answers, would otherwise leave the next `login()` waiting forever.\n * Ten seconds is past any healthy round trip and short enough that a stuck\n * revocation costs a slow sign-in, not a dead one.\n */\nconst LOGOUT_REVOCATION_WAIT_MS = 10_000;\n\n/**\n * How long a refresh waits for another tab's refresh to release the\n * origin-wide refresh lock before redeeming without it.\n *\n * The same reasoning as {@link LOGOUT_REVOCATION_WAIT_MS}: past any healthy\n * round trip, and a bound so that a tab stuck holding the lock costs a\n * duplicate redemption, not a request that never settles.\n */\nconst REFRESH_LOCK_WAIT_MS = 10_000;\n\n/**\n * Wait until every promise settled, or until `ms` passed, whichever is first.\n *\n * @param pending - What to wait for; rejections count as settled.\n * @param ms - The bound.\n * @returns A promise that always resolves.\n */\nfunction settleWithin(pending: readonly Promise<unknown>[], ms: number): Promise<void> {\n if (pending.length === 0) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, ms);\n void Promise.allSettled(pending).then(() => {\n clearTimeout(timer);\n resolve();\n });\n });\n}\n\n/**\n * Mint the identifier of a new session lineage: one per successful `login()`,\n * kept across every rotation of that session, see `createTempestAuth`.\n *\n * It only has to tell two sign-ins apart, never to resist guessing — it guards\n * nothing on the server and is readable by any script of the origin anyway. So\n * the fallback for a page without `crypto.randomUUID` (served over plain http,\n * where the browser withholds it) is a timestamp plus `Math.random`, not an\n * error.\n *\n * @returns A fresh lineage identifier.\n */\nfunction newLineage(): string {\n const host = globalThis.crypto as Partial<Crypto> | undefined;\n if (typeof host?.randomUUID === \"function\") return host.randomUUID();\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * The {@link TempestAuth.sessionKey} of a signed-in session that has no\n * lineage. One constant for all of them, since none can be told apart without\n * one — and no account switch can produce one.\n */\nconst UNLINEAGED_SESSION_KEY = \"unlineaged\";\n\n/**\n * The store names already warned about cookie mode without `logoutPath`, so a\n * hot-module reload that rebuilds the preset does not repeat the warning.\n */\nconst warnedCookieWithoutLogout = new Set<string>();\n\n/**\n * Warn, in a dev build and once per store, that cookie mode has no\n * `logoutPath` (#531).\n *\n * `logout()` cannot reach an HttpOnly refresh cookie, so without a revocation\n * the cookie stays redeemable and the boot `refresh()` of the next page load\n * signs the account that just signed out back in — for whoever uses the\n * browser next. Measured with the `cookieBackend` of\n * `create-tempest-auth.cookie.test.ts`: login, `logout()`, a new preset and\n * `refresh()` restore `A-tok-cookie-1`.\n *\n * A warning, not a requirement. Requiring `logoutPath` would break every app\n * whose backend cannot revoke — the tempest-fastapi-sdk mounts no logout route\n * with stateless refresh tokens — and would not close the hole for them\n * either: a route that answers `404` revokes nothing. Refusing the boot\n * `refresh()` after a logout would break the sign-ins that set the cookie\n * outside `login()`, such as an OAuth callback. Only the backend can end the\n * cookie; this makes the missing half visible while the app is being built.\n *\n * @param storeName - The preset's persist key.\n */\nfunction warnCookieWithoutLogout(storeName: string): void {\n if (!isDevBuild() || warnedCookieWithoutLogout.has(storeName)) return;\n warnedCookieWithoutLogout.add(storeName);\n console.warn(\n \"[tempest-react-sdk] createTempestAuth: withCredentials is set without logoutPath. \" +\n \"logout() cannot clear the HttpOnly refresh cookie, so the next refresh() — the \" +\n \"boot restore — signs the same account back in. Pass logoutPath (the backend's \" +\n \"cookie logout route) so the server revokes it.\",\n );\n}\n\nfunction defaultParseTokens(data: unknown): { token: string; refreshToken?: string } {\n const d = (data ?? {}) as TempestTokenResponse;\n return { token: d.access_token, refreshToken: d.refresh_token };\n}\n\n/**\n * Turn-key auth preset wiring `createAuthStore` + `createRefreshQueue` +\n * `createApiClient` to the Tempest FastAPI SDK auth contract: login returns\n * `{ access_token, token_type }`, requests carry `Authorization: Bearer`, and a\n * `401` triggers a single deduplicated refresh + replay.\n *\n * The session is cleared whenever that path ends unauthorized anyway — the\n * refresh threw, or the replay came back `401` — so a refresh token that the\n * backend has revoked cannot leave the app holding a dead session. With\n * `redirectTo` set, the browser also leaves the page; without it, clearing the\n * store is enough for a `<RouteGuard>` to navigate on its own.\n *\n * Every refresh is bound to a **session epoch**, bumped by `logout()` and by a\n * `login()` whose credentials were accepted. A refresh that resolves after its epoch ended discards\n * what it brought back and rejects with {@link SessionSupersededError}, which\n * the client passes through without ending the new session. Before 0.77.0 a\n * refresh that was in flight during `logout()` reinstalled the old tokens —\n * and after `logout()` + `login(B)`, replaced B's token with A's while the UI\n * showed B (#435). A `401` from a request sent under an ended session is\n * refused the same way, instead of being replayed as the account signed in now.\n *\n * A `401` from a request that carried no token, while no session is installed,\n * surfaces without a refresh: in cookie mode that refresh would be answered by\n * the HttpOnly cookie `logout()` cannot clear, signing the previous account\n * back in (#474). With a `login()` in flight, that `401` waits for it and\n * replays with the token it installed, or surfaces when it failed — still\n * without a refresh (#496). Restore a session at boot with an explicit\n * `refresh()`, and pass `logoutPath` so the backend revokes the cookie:\n * without a working revocation, that boot `refresh()` restores the previous\n * account for whoever uses the browser next.\n *\n * With `storage: \"local\"` the session belongs to the **origin**, not the tab:\n * every tab reads and writes the same keys and follows what another tab wrote\n * — on the `storage` event and, before any refresh, `logout()` or ending of\n * the session, by comparing the stored session with the one it holds. A\n * rotation elsewhere is adopted; a logout or another account's login\n * elsewhere ends the session here too, with `onSessionEnd` told it happened\n * `elsewhere`. Before 0.81.0 a tab left open after logout kept account A and,\n * on its next `401`, redeemed account B's refresh token from the shared\n * storage, persisting `{ user: A, token: B }` (#524). Whether the stored\n * session is the held one is decided by a **session lineage** that `login()`\n * mints and every rotation keeps — not by comparing users, which took two\n * sign-ins whose user had not loaded yet for the same account (#544). Two tabs\n * never redeem the same refresh token at once: the redemption runs under an\n * origin-wide Web Lock when the browser has one. `storage: \"session\"` is per\n * tab and behaves as before.\n *\n * Refreshes are collapsed per rotation, not just per overlap: a `401` whose\n * request left with a token that has since been replaced in the same session\n * replays with the new token and refreshes nothing. Three expired requests take\n * one refresh whether their `401`s arrive together or one after another.\n *\n * @example\n * const auth = createTempestAuth<User, { email: string; password: string }>({\n * baseURL: import.meta.env.VITE_API_URL,\n * mePath: \"/api/auth/me\",\n * });\n *\n * await auth.login({ email, password }); // stores session, returns the user\n * const orders = await auth.api.get(\"/api/orders\"); // sends the bearer token\n * await auth.logout(); // clears, then runs onSessionEnd\n *\n * @param options - The auth configuration.\n * @returns The store hook, a wired API client, and login/logout/refresh helpers.\n */\nexport function createTempestAuth<TUser, TCredentials = { email: string; password: string }>(\n options: CreateTempestAuthOptions<TUser>,\n): TempestAuth<TUser, TCredentials> {\n const {\n baseURL,\n prefix,\n loginPath = \"/api/auth/login\",\n refreshPath = \"/api/auth/refresh\",\n logoutPath,\n onLogoutError,\n mePath,\n storeName = \"tempest-auth\",\n storage = \"local\",\n withCredentials = false,\n csrf,\n fetcher,\n parseTokens = defaultParseTokens,\n parseUser,\n refreshBody = (rt) => (rt ? { refresh_token: rt } : undefined),\n retry,\n redirectTo,\n onSessionEnd,\n } = options;\n\n if (withCredentials && !logoutPath) warnCookieWithoutLogout(storeName);\n\n const useAuthStore = createAuthStore<TUser>({ name: storeName, storage });\n const refreshKey = `${storeName}-refresh`;\n\n function storageImpl(): Storage | null {\n if (typeof window === \"undefined\") return null;\n return storage === \"session\" ? window.sessionStorage : window.localStorage;\n }\n function readRefreshToken(): string | null {\n return storageImpl()?.getItem(refreshKey) ?? null;\n }\n let heldRefreshToken: string | null = readRefreshToken();\n function writeRefreshToken(token: string | null): void {\n heldRefreshToken = token;\n const s = storageImpl();\n if (!s) return;\n if (token) s.setItem(refreshKey, token);\n else s.removeItem(refreshKey);\n }\n\n const lineageKey = `${storeName}-lineage`;\n const refreshLockName = `tempest-react-sdk:${storeName}:refresh`;\n let heldLineage: string | null = storageImpl()?.getItem(lineageKey) ?? null;\n function writeLineage(lineage: string | null): void {\n heldLineage = lineage;\n const s = storageImpl();\n if (!s) return;\n if (lineage) s.setItem(lineageKey, lineage);\n else s.removeItem(lineageKey);\n }\n\n const state = (): AuthState<TUser> => useAuthStore.getState();\n const getToken = (): string | null => state().token;\n\n /**\n * Load the current user, without letting a `401` end the session.\n *\n * `skipAuthRetry` is what keeps this one client honest: the call is\n * authenticated, but a `401` here surfaces instead of triggering a refresh\n * and `onUnauthorized`. That was the behaviour of the throwaway client this\n * used to build per invocation, and it is the reason the preset needed\n * three clients before 0.66.0.\n *\n * Bound to the epoch current when the request leaves, like `rotate()`: a\n * profile that resolves after `logout()` — or after `logout()` +\n * `login(B)` — is discarded instead of written next to B's token, and the\n * `login()` that asked for it rejects as superseded (#473).\n *\n * Before the profile is written, the shared storage is followed (#544).\n * The write persists the whole `{ user, token }` this tab holds, so a tab\n * that had not yet seen another account's sign-in used to overwrite it\n * with its own token next to that account's refresh token — and the\n * other tab, following the write, paired that refresh token with this\n * account's user. Following first turns that into a session ended\n * elsewhere, and the profile is discarded.\n *\n * Bound to the session, not to the token the request carried: a token\n * that changed because another tab rotated the same session still\n * belongs to this user, and discarding the profile then would fail a\n * sign-in that succeeded.\n *\n * @throws {SessionSupersededError} When the epoch changed while the\n * request was in flight, on success and on failure alike, or another\n * tab ended or replaced the session.\n */\n async function fetchUser(): Promise<TUser | null> {\n if (!mePath) return state().user;\n const started = epoch;\n let user: TUser;\n try {\n user = await api.get<TUser>(mePath, { skipAuthRetry: true });\n } catch (error) {\n if (epoch !== started) throw new SessionSupersededError();\n throw error;\n }\n if (epoch !== started || !followSharedSession().continues) {\n throw new SessionSupersededError();\n }\n state().setUser(user);\n return user;\n }\n\n let epoch = 0;\n let ending: Promise<void> = Promise.resolve();\n let hooksRunning = 0;\n const loginsInFlight = new Set<Promise<unknown>>();\n const revocations = new Set<Promise<void>>();\n const credentialRequests = new Set<Promise<unknown>>();\n const rotatingEpochs = new Set<number>();\n\n /**\n * Track a login or refresh request until it settles, so a cookie-mode\n * revocation can wait for the response that sets the cookie it revokes.\n *\n * @param request - The request in flight.\n * @returns The same request.\n */\n function trackCredentialRequest<T>(request: Promise<T>): Promise<T> {\n const settled = request.then(\n () => undefined,\n () => undefined,\n );\n credentialRequests.add(settled);\n void settled.then(() => credentialRequests.delete(settled));\n return request;\n }\n\n /**\n * Surface a failed revocation: `onLogoutError`, plus a console warning in a\n * dev build.\n *\n * @param error - What the revocation rejected with.\n */\n function reportLogoutError(error: unknown): void {\n if (isDevBuild()) {\n console.warn(\n \"[tempest-react-sdk] createTempestAuth: logoutPath revocation failed\",\n error,\n );\n }\n try {\n onLogoutError?.(error);\n } catch {\n return;\n }\n }\n\n /**\n * Send one `logoutPath` revocation and track it until it settles. Never\n * rejects.\n *\n * @param build - Produces the request, after whatever wait it needs.\n * @returns A promise settling when the revocation settled.\n */\n function trackRevocation(build: () => Promise<unknown>): Promise<void> {\n const tracked = (async () => {\n try {\n await build();\n } catch (error) {\n reportLogoutError(error);\n }\n })();\n revocations.add(tracked);\n void tracked.then(() => revocations.delete(tracked));\n return tracked;\n }\n\n /**\n * Revoke, in body mode, the refresh token a superseded login or refresh\n * brought back. Nobody can use it — the client discarded it — but it would\n * stay valid on the server until it expires.\n *\n * Cookie mode is left to `revoke()`, which waits for these responses\n * instead: re-sending a cookie revocation here could carry whichever\n * account's cookie the browser holds by then.\n *\n * @param token - The superseded response's access token.\n * @param refreshToken - The superseded response's refresh token.\n */\n function revokeDiscarded(token: string | null, refreshToken: string | undefined): void {\n if (!logoutPath || withCredentials || !refreshToken) return;\n void trackRevocation(() =>\n endedSessionApi(token).post<unknown>(logoutPath, {\n body: refreshBody(refreshToken),\n }),\n );\n }\n\n /**\n * A client that sends an ended session's access token, and never refreshes\n * or ends a session: a `401` there just rejects.\n *\n * @param token - The ended session's access token.\n * @returns The client `onSessionEnd` and the `logoutPath` call go through.\n */\n function endedSessionApi(token: string | null): ApiClient {\n return createApiClient({\n baseURL,\n prefix,\n withCredentials,\n csrf,\n fetcher,\n getToken: () => token,\n });\n }\n\n /**\n * Start a new session epoch: supersede the refresh in flight and give the\n * new epoch a refresh queue of its own, so a `401` under the new session\n * never joins the old session's refresh.\n *\n * The client reads the epoch when each attempt leaves (`getSessionEpoch`),\n * which is what ties a `401` to the session that sent it — no set of\n * tokens to keep, and nothing that grows with the session's length.\n */\n function nextEpoch(): void {\n epoch += 1;\n queue = createRefreshQueue(rotate);\n }\n\n /**\n * Perform one refresh for the epoch that is current when it starts.\n *\n * Checked again after the round trip, on success and on failure alike: a\n * refresh that fails after `logout()` + `login(B)` must not reach\n * `onUnauthorized` either, or it would end B's session.\n *\n * Before the request, and again before installing its result, the stored\n * session is compared with the one this tab holds, see\n * `followSharedSession`. When another tab rotated the same account, its\n * tokens are adopted and nothing is redeemed: the replay goes out with\n * them. When another tab signed out, or signed in as someone else, nothing\n * is redeemed either — the refresh token in storage is not this session's\n * (#524) — and the call rejects as superseded.\n *\n * With `storage: \"local\"` the redemption runs under a Web Lock shared by\n * every tab of the origin, see `underRefreshLock`; the comparison with the\n * stored session happens once the lock is held, so a tab that waited\n * behind another tab's rotation adopts its tokens instead of presenting\n * the refresh token that rotation just spent.\n *\n * @throws {SessionSupersededError} When the epoch changed during the call,\n * or another tab ended or replaced the session.\n */\n async function rotate(): Promise<void> {\n const before = getToken();\n const started = epoch;\n rotatingEpochs.add(started);\n try {\n await underRefreshLock(() => redeem(before));\n } finally {\n rotatingEpochs.delete(started);\n }\n }\n\n /**\n * Run `run` while holding the origin-wide refresh lock, when there is one\n * to hold (run-7 hardening note).\n *\n * Two tabs whose requests expire together used to redeem the same refresh\n * token at once. A backend with reuse detection — the tempest-fastapi-sdk\n * has it — answers the second redemption by revoking the whole rotation\n * family, so the session ends in every tab. The common trigger is a\n * browser restart that restores several tabs, each calling the boot\n * `refresh()`: measured with two presets over a reuse-detecting backend,\n * both presented `ref-1`, the family was revoked, and no refresh token was\n * left alive.\n *\n * The lock is the Web Locks API (`navigator.locks`), held only for the\n * redemption round trip. Only `storage: \"local\"` shares a session between\n * tabs, so `\"session\"` takes no lock. Fail-open, by design: without the\n * API (SSR, an old browser, jsdom), when acquiring it throws (an opaque\n * origin), or after {@link REFRESH_LOCK_WAIT_MS} of waiting behind a tab\n * that never releases it, the redemption runs unlocked — the behaviour\n * before the lock existed — instead of leaving the request hanging.\n *\n * @param run - The redemption.\n * @returns A promise settling with `run`.\n */\n async function underRefreshLock(run: () => Promise<void>): Promise<void> {\n const locks =\n storage === \"local\" && typeof navigator !== \"undefined\"\n ? (navigator as Partial<Navigator>).locks\n : undefined;\n if (!locks) return run();\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), REFRESH_LOCK_WAIT_MS);\n let acquired = false;\n try {\n await locks.request(refreshLockName, { signal: controller.signal }, async () => {\n acquired = true;\n clearTimeout(timer);\n await run();\n });\n } catch (error) {\n if (acquired) throw error;\n clearTimeout(timer);\n await run();\n }\n }\n\n /**\n * The body of one rotation, run under the refresh lock.\n *\n * A tab that held no session when the rotation was asked for — the boot\n * `refresh()` — and finds one installed once the lock is held was restored\n * by another tab while it waited: that is the outcome it asked for, so it\n * resolves without redeeming.\n *\n * @param before - The access token held when the rotation was asked for.\n * @throws {SessionSupersededError} See `rotate()`.\n */\n async function redeem(before: string | null): Promise<void> {\n const held = before !== null || state().user !== null || heldRefreshToken !== null;\n const followed = followSharedSession();\n if (!held && getToken() !== null) return;\n if (!followed.continues) throw new SessionSupersededError();\n if (getToken() !== before) return;\n const started = epoch;\n let data: unknown;\n try {\n data = await trackCredentialRequest(\n api.post<unknown>(refreshPath, {\n body: refreshBody(readRefreshToken()),\n skipAuth: true,\n }),\n );\n } catch (error) {\n if (epoch !== started) throw new SessionSupersededError();\n throw error;\n }\n const { token, refreshToken } = parseTokens(data);\n if (epoch !== started || !followSharedSession().continues) {\n revokeDiscarded(token ?? null, refreshToken);\n throw new SessionSupersededError();\n }\n state().setToken(token);\n if (refreshToken) writeRefreshToken(refreshToken);\n }\n\n let queue = createRefreshQueue(rotate);\n\n /**\n * Whether a `401` must be left alone: no refresh, no ending the session.\n *\n * Two cases, both of the current epoch: an attempt that carried no token\n * while a session is now installed (it left before the sign-in, and\n * refreshing or ending the new session for it would punish the wrong\n * session); and an attempt whose token the session has since rotated past\n * (the rotation it would trigger already happened).\n *\n * @param context - The attempt's credential.\n * @returns Whether the attempt is stale within the current session.\n */\n function staleWithinSession(context: RequestAuthContext): boolean {\n const current = getToken();\n if (current === null) return false;\n return context.token === null || context.token !== current;\n }\n\n /**\n * Whether nothing could make a tokenless `401` worth a refresh: no access\n * token and no stored refresh token.\n *\n * With `withCredentials`, the refresh would otherwise be answered by an\n * HttpOnly cookie the client cannot see or clear — after `logout()`, that\n * signed the previous account back in for whoever used the browser next\n * (#474). A `login()` in flight does not count as a session either: the\n * cookie a refresh would present during it is still the ended account's\n * (#496). Restoring a session from the cookie is an explicit `refresh()`,\n * typically at boot, which this does not touch.\n *\n * @returns Whether no session is installed.\n */\n function signedOut(): boolean {\n return getToken() === null && readRefreshToken() === null;\n }\n\n /**\n * Settle a tokenless `401` that arrived with no session installed while a\n * `login()` is in flight: wait for every login in flight, then let the\n * request replay when one of them installed a token.\n *\n * No refresh is sent. In cookie mode one would present whatever cookie\n * the browser holds — after `logout()` without a working `logoutPath`,\n * the previous account's: a failed login then left the client signed in\n * as that account, and a successful one could have its cookie overwritten\n * by the refresh's late `Set-Cookie` (#496).\n *\n * Skipped while an `onSessionEnd` hook runs: an account switch waits on\n * that hook, so a hook awaiting `auth.api` would wait on itself.\n *\n * @throws {Error} When no login is in flight, a hook is running, or every\n * login settled without installing a token — the `401` surfaces as is.\n */\n async function awaitLogins(): Promise<void> {\n if (loginsInFlight.size > 0 && hooksRunning === 0) {\n await Promise.allSettled([...loginsInFlight]);\n if (getToken() !== null) return;\n }\n throw new Error(\"anonymous 401 with no session\");\n }\n\n /**\n * The `refresh` the client calls on a `401`.\n *\n * - An attempt from an ended epoch is refused rather than replayed as\n * whoever is signed in now.\n * - A token this session already rotated past: the replay just picks up the\n * new one — no second refresh.\n * - No token, while a session is now installed: the `401` surfaces as is.\n * - No token, and no session installed: joins this epoch's refresh when\n * one is already in flight — the boot `refresh()` restoring a session\n * from the cookie, which the request then replays under; otherwise waits\n * for a `login()` in flight and replays with its token, see\n * `awaitLogins`; otherwise surfaces the `401` as is, see `signedOut`.\n * - Otherwise: join or start this epoch's refresh.\n *\n * @param context - The credential and epoch the rejected attempt left with.\n * @throws {SessionSupersededError} When the attempt belongs to an ended\n * session, or the session changed during the refresh.\n */\n async function refreshFor(context: RequestAuthContext): Promise<void> {\n if (context.epoch !== null && context.epoch !== epoch) throw new SessionSupersededError();\n if (staleWithinSession(context)) {\n if (context.token === null) throw new Error(\"anonymous 401 under a live session\");\n return;\n }\n if (context.token === null && signedOut()) {\n if (rotatingEpochs.has(epoch)) return queue();\n return awaitLogins();\n }\n return queue();\n }\n\n /**\n * The client's `onUnauthorized`: end the session only when the `401` is the\n * current session's own.\n *\n * The replay after a refresh is checked here too — it can come back `401`\n * after the user signed out and another account signed in, and ending the\n * session then would sign the new account out. A tokenless `401` with no\n * session installed ends nothing either: there is no session to end, and\n * ending \"nothing\" used to move the epoch and supersede the boot\n * `refresh()` in flight. Neither does a `401` from a session another tab\n * already ended or replaced: ending it here would clear that tab's new\n * session from the shared storage.\n *\n * @param context - The credential and epoch of the attempt that failed.\n * @throws {SessionSupersededError} When that attempt belongs to an ended\n * session, here or in another tab.\n */\n async function onUnauthorized(_response: Response, context: RequestAuthContext): Promise<void> {\n if (context.epoch !== null && context.epoch !== epoch) throw new SessionSupersededError();\n if (!followSharedSession().continues) throw new SessionSupersededError();\n if (staleWithinSession(context)) return;\n if (context.token === null && signedOut()) return;\n await endSession();\n }\n\n /**\n * Authenticate and install the new session.\n *\n * The previous session ends only once the new credentials are accepted: a\n * login that fails leaves it, and the refresh it may have in flight,\n * untouched. When one was live, `onSessionEnd` runs with `\"switch\"` before\n * the new tokens are installed — see the option for why that order. A\n * `logout()` still tearing down is awaited the same way, so the new\n * account's state never starts before the previous one's teardown ended.\n * Never call it from inside `onSessionEnd`: it would wait on that hook.\n * Every `logoutPath` revocation still in flight is awaited before the\n * request leaves — at most {@link LOGOUT_REVOCATION_WAIT_MS} — so a\n * cookie-clearing response cannot land after the new account's cookies.\n *\n * @param credentials - Sent as the login body.\n * @returns The user of the new session, or null.\n * @throws {SessionSupersededError} When a `logout()` or another `login()`\n * moved the session while this one was in flight — during its request,\n * during the teardown or while `mePath` was loading the user; the new\n * tokens, or the user, are discarded.\n */\n async function login(credentials: TCredentials): Promise<TUser | null> {\n if (revocations.size > 0) await settleWithin([...revocations], LOGOUT_REVOCATION_WAIT_MS);\n const run = signIn(credentials);\n loginsInFlight.add(run);\n try {\n return await run;\n } finally {\n loginsInFlight.delete(run);\n }\n }\n\n /**\n * The body of `login()`, tracked in `loginsInFlight` by its caller so a\n * tokenless `401` during the sign-in waits for it and replays with the\n * token it installs, see `awaitLogins`. Tracking starts only after a\n * pending revocation settled.\n *\n * @param credentials - Sent as the login body.\n * @returns The user of the new session, or null.\n * @throws {SessionSupersededError} See `login()`.\n */\n async function signIn(credentials: TCredentials): Promise<TUser | null> {\n const started = epoch;\n const data = await trackCredentialRequest(\n api.post<unknown>(loginPath, {\n body: credentials,\n skipAuth: true,\n }),\n );\n const { token, refreshToken } = parseTokens(data);\n if (epoch !== started) {\n revokeDiscarded(token ?? null, refreshToken);\n throw new SessionSupersededError();\n }\n revokeDiscarded(getToken(), readRefreshToken() ?? undefined);\n const { done } = finish(\"switch\");\n const mine = epoch;\n await done.catch(() => undefined);\n if (epoch !== mine) throw new SessionSupersededError();\n writeLineage(newLineage());\n state().setToken(token);\n writeRefreshToken(refreshToken ?? null);\n const embedded = parseUser?.(data);\n if (embedded != null) {\n state().setUser(embedded);\n return embedded;\n }\n return fetchUser();\n }\n\n /**\n * End the current session, synchronously up to the hook.\n *\n * The epoch moves first, so a refresh resolving between here and the hook\n * is already superseded. The hook only runs when there was a session to\n * end — a token, a stored refresh token or a user — which is what keeps a\n * burst of `401`s from running it once per request.\n *\n * With nothing left to end, the caller waits on the teardown already under\n * way (`ending`, which never rejects, so a later no-op does not inherit an\n * old error). Two callers skip that wait while a hook is running, because\n * they may be the hook itself and would wait on their own teardown forever:\n * `endSession` — a hook awaiting `auth.api` goes out tokenless, gets a\n * `401`, and lands here — and a `logout()` with no session left. `login()`\n * (`\"switch\"`) always waits: the new account's state must not start while\n * the previous one's teardown is still clearing it. A hook awaiting\n * `auth.login()` therefore never settles — misuse the option documents.\n *\n * `\"expired\"` with nothing live leaves the epoch alone: there is nothing to\n * supersede but a refresh with no session behind it — the boot `refresh()`\n * restoring one from the cookie — and moving the epoch would throw that\n * away. `logout()` and `login()` always move it, since they must supersede\n * such a refresh.\n *\n * The returned `done` is a fresh promise derived from the hook, not the one\n * `ending` holds: a `logout()` nobody awaits still surfaces the hook's error\n * as an unhandled rejection instead of losing it.\n *\n * @param reason - Whether the caller signed out, the client gave up, or a\n * login replaced the session.\n * @returns Whether a live session ended here, and a promise settling with\n * the hook.\n */\n function finish(reason: TempestSessionEnd<TUser>[\"reason\"]): {\n live: boolean;\n done: Promise<void>;\n } {\n const { user, token } = state();\n const live = token !== null || user !== null || readRefreshToken() !== null;\n if (live || reason !== \"expired\") nextEpoch();\n state().logout();\n writeRefreshToken(null);\n writeLineage(null);\n if (!live) {\n const wait = reason === \"switch\" || hooksRunning === 0;\n return { live, done: wait ? ending : Promise.resolve() };\n }\n return { live, done: runSessionEnd({ reason, user, token, elsewhere: false }) };\n }\n\n /**\n * Run `onSessionEnd` for a session that just ended, tracked in `ending`\n * and `hooksRunning`.\n *\n * The returned promise is a fresh one derived from the hook, not the one\n * `ending` holds, so a caller that drops it still surfaces the hook's\n * error as an unhandled rejection instead of losing it.\n *\n * @param ended - What ended, minus the client, which is built here.\n * @returns A promise settling with the hook.\n */\n function runSessionEnd(ended: Omit<TempestSessionEnd<TUser>, \"api\">): Promise<void> {\n if (!onSessionEnd) return Promise.resolve();\n const sessionApi = endedSessionApi(ended.token);\n hooksRunning += 1;\n const run = (async () => {\n try {\n await onSessionEnd({ ...ended, api: sessionApi });\n } finally {\n hooksRunning -= 1;\n }\n })();\n ending = run.then(\n () => undefined,\n () => undefined,\n );\n return run.then(() => undefined);\n }\n\n /**\n * Read the session as the shared storage holds it: the persisted\n * `{ user, token }`, the stored refresh token and the session lineage.\n *\n * Read straight from storage rather than through\n * `useAuthStore.persist.rehydrate()`: a rehydration that finds no entry —\n * another tab ran `localStorage.clear()` — merges nothing and keeps the\n * session this tab holds, which is the stale session this exists to drop.\n * An entry that does not parse counts as no session.\n *\n * @returns The stored session, or null without storage (SSR).\n */\n function readSharedSession(): {\n user: TUser | null;\n token: string | null;\n refreshToken: string | null;\n lineage: string | null;\n } | null {\n const s = storageImpl();\n if (!s) return null;\n const refreshToken = s.getItem(refreshKey);\n const lineage = s.getItem(lineageKey);\n const raw = s.getItem(storeName);\n if (!raw) return { user: null, token: null, refreshToken, lineage };\n try {\n const parsed = JSON.parse(raw) as {\n state?: { user?: TUser | null; token?: string | null };\n };\n return {\n user: parsed.state?.user ?? null,\n token: parsed.state?.token ?? null,\n refreshToken,\n lineage,\n };\n } catch {\n return { user: null, token: null, refreshToken, lineage };\n }\n }\n\n /**\n * Catch up with what another tab wrote to the shared storage (#524).\n *\n * Every write this tab makes reaches the storage synchronously, so the\n * stored session differs from the held one only when another tab wrote\n * it. The stored one then wins, without redeeming or clearing anything:\n *\n * - a token of the same **lineage** — the identifier `login()` mints and\n * every rotation keeps — whether it is the same token (the other tab only\n * loaded the user) or a new one (it rotated): adopted, the session\n * continues;\n * - no token, or another lineage: the held session ended elsewhere. The\n * epoch moves, so nothing in flight from it can install tokens or end\n * the new session; the stored state is adopted; and `onSessionEnd` runs\n * with `elsewhere: true` — `\"logout\"` when no session is left,\n * `\"switch\"` when another sign-in is installed, even of the same user.\n *\n * Continuity used to be decided by comparing users, and two sessions whose\n * user had not loaded yet compared equal: a tab whose `login()` was still\n * waiting for `mePath` adopted another account's token as a rotation, and\n * its profile then persisted `{ user: A, token: B }` (#544). Requiring a\n * user would have closed that and turned every rotation of a session\n * without a user model into an account switch; the lineage answers the\n * actual question — is this the same sign-in — for both.\n *\n * A session persisted before lineages existed has none, on either side,\n * and keeps the old rule: the same token, or a token for the same user.\n * No `login()` of this version can produce that state, so a lineage-less\n * session can only have been rotated, never replaced.\n *\n * It never calls `finish()`: that clears the shared keys, which here would\n * erase the other tab's new session — and, with rotating refresh tokens,\n * sign every tab out whenever any tab rotates.\n *\n * The hook's error reaches only the callers that return `done`; the\n * automatic paths drop it.\n *\n * @returns Whether the held session continues, and a promise settling with\n * the hook when one ran.\n */\n function followSharedSession(): { continues: boolean; done: Promise<void> } {\n const shared = readSharedSession();\n const { user, token } = state();\n if (shared === null) return { continues: true, done: Promise.resolve() };\n const sameUser = JSON.stringify(shared.user) === JSON.stringify(user);\n if (\n shared.token === token &&\n shared.refreshToken === heldRefreshToken &&\n shared.lineage === heldLineage &&\n sameUser\n ) {\n return { continues: true, done: Promise.resolve() };\n }\n const sameSession =\n shared.lineage !== null || heldLineage !== null\n ? shared.lineage === heldLineage\n : shared.token === token || (token !== null && sameUser);\n const continues = shared.token !== null && sameSession;\n const live = token !== null || user !== null || heldRefreshToken !== null;\n if (!continues) nextEpoch();\n heldRefreshToken = shared.refreshToken;\n heldLineage = shared.lineage;\n useAuthStore.setState({\n user: shared.user,\n token: shared.token,\n isAuthenticated: shared.token !== null,\n });\n if (continues || !live) return { continues, done: Promise.resolve() };\n const reason = shared.token === null ? \"logout\" : \"switch\";\n const done = runSessionEnd({ reason, user, token, elsewhere: true });\n void done.catch(() => undefined);\n return { continues, done };\n }\n\n /**\n * Send the `logoutPath` revocation for the session about to end, with the\n * credentials it holds now — read before `finish` clears them.\n *\n * Skipped without `logoutPath`, and in body mode when there is nothing to\n * revoke; in cookie mode it always goes out, since the cookie it revokes is\n * invisible to the client. Never rejects.\n *\n * In cookie mode it first waits — at most\n * {@link LOGOUT_REVOCATION_WAIT_MS} — for the login and refresh responses\n * in flight right now: each one sets a cookie for the session this\n * `logout()` ends, and a revocation that left before it would leave that\n * cookie behind.\n *\n * @returns A promise settling when the revocation settled, or null when\n * none was sent.\n */\n function revoke(): Promise<void> | null {\n if (!logoutPath) return null;\n const path = logoutPath;\n const { token, user } = state();\n const refreshToken = readRefreshToken();\n if (!withCredentials && token === null && user === null && refreshToken === null) {\n return null;\n }\n const inFlight = withCredentials ? [...credentialRequests] : [];\n return trackRevocation(async () => {\n await settleWithin(inFlight, LOGOUT_REVOCATION_WAIT_MS);\n return endedSessionApi(token).post<unknown>(path, { body: refreshBody(refreshToken) });\n });\n }\n\n /**\n * End the session — unless another tab already did.\n *\n * A tab that has not caught up yet first follows the shared storage: when\n * the session it showed ended elsewhere, that is the whole sign-out. The\n * session live now belongs to another tab's sign-in, and revoking or\n * clearing it from here would sign that account out — before #524 it\n * also sent that account's refresh token to `logoutPath` next to the\n * ended account's bearer.\n *\n * @returns A promise settling with `onSessionEnd` and the revocation.\n */\n function logout(): Promise<void> {\n const followed = followSharedSession();\n if (!followed.continues) return followed.done;\n const revocation = revoke();\n const { done } = finish(\"logout\");\n if (!revocation) return done;\n return Promise.all([revocation, done]).then(() => undefined);\n }\n\n /**\n * End the session after the client gave up on it and, when `redirectTo`\n * is set, leave the page once `onSessionEnd` settled.\n *\n * Separate from `logout` so an explicit sign-out stays a pure state change:\n * a caller that already navigates itself would otherwise get a second,\n * competing navigation. The hook is awaited before navigating because a\n * hard navigation aborts whatever request it still had in flight. Only the\n * call that ended a live session navigates; the rest of a burst of `401`s\n * waits on the same teardown, or returns at once inside a hook.\n */\n async function endSession(): Promise<void> {\n const { live, done } = finish(\"expired\");\n await done.catch(() => undefined);\n if (live && redirectTo && typeof window !== \"undefined\") {\n window.location.assign(redirectTo);\n }\n }\n\n const api = createApiClient({\n baseURL,\n prefix,\n withCredentials,\n csrf,\n fetcher,\n getToken,\n getSessionEpoch: () => epoch,\n refresh: refreshFor,\n retry,\n onUnauthorized,\n });\n\n const refresh = (): Promise<void> => queue();\n\n /**\n * Read from the store's token and the held lineage. Both move before the\n * store notifies: `login()` writes the lineage before installing the\n * token, `finish()` clears the token in the notifying `logout()` call and\n * the lineage only after — which the token check already reads as `null` —\n * and following another tab updates the held lineage before `setState`.\n * So every store listener sees the key of the state it is told about.\n */\n const sessionKey = (): string | null =>\n getToken() === null ? null : (heldLineage ?? UNLINEAGED_SESSION_KEY);\n const identity: SessionIdentity = {\n current: sessionKey,\n subscribe: (listener) => useAuthStore.subscribe(listener),\n };\n bindSessionIdentity(api, identity);\n bindSessionIdentity(getToken, identity);\n\n /**\n * Follow a write another tab made to this session's keys. The browser\n * fires `storage` only in the tabs that did not write; `key` is null when\n * the other tab cleared the whole storage.\n *\n * @param event - The storage event.\n */\n function onStorage(event: StorageEvent): void {\n if (event.storageArea !== storageImpl()) return;\n if (\n event.key !== null &&\n event.key !== storeName &&\n event.key !== refreshKey &&\n event.key !== lineageKey\n ) {\n return;\n }\n followSharedSession();\n }\n\n const host = typeof window === \"undefined\" ? null : window;\n host?.addEventListener(\"storage\", onStorage);\n const dispose = (): void => host?.removeEventListener(\"storage\", onStorage);\n\n return { useAuthStore, api, login, logout, refresh, getToken, sessionKey, dispose };\n}\n"],"mappings":"A,uNAkSA,IAAMW,EAA4B,IAU5BC,EAAuB,IAS7B,SAASC,EAAa,EAAsC,EAA2B,CAEnF,OADIC,EAAQ,SAAW,EAAU,QAAQ,QAAQ,EAC1C,IAAI,QAAe,GAAY,CAClC,IAAMC,EAAQ,WAAWC,EAASC,CAAE,EACpC,QAAa,WAAWH,CAAO,CAAC,CAAC,SAAW,CACxC,aAAaC,CAAK,EAClBC,EAAQ,CACZ,CAAC,CACL,CAAC,CACL,CAcA,SAASE,IAAqB,CAC1B,IAAMC,EAAO,WAAW,OAExB,OADI,OAAOA,GAAM,YAAe,WAAmBA,EAAK,WAAW,EAC5D,GAAG,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,GAC3E,CAOA,IAAMC,GAAyB,aAMzBC,EAA4B,IAAI,IAuBtC,SAASC,G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AEQ,CACtF,C"}
|
|
1
|
+
{"version":3,"file":"create-tempest-auth.cjs","names":["isDevBuild","createAuthStore","SessionSupersededError","createApiClient","createRefreshQueue","require_dev_mode","require_errors","require_api_client","require_session_identity","require_create_auth_store","require_refresh_queue","LOGOUT_REVOCATION_WAIT_MS","REFRESH_LOCK_WAIT_MS","settleWithin","pending","timer","resolve","ms","newLineage","host","warnedCookieWithoutLogout","warnCookieWithoutLogout","storeName","defaultParseTokens","d","data","createTempestAuth","rt","options","withCredentials","logoutPath","useAuthStore","refreshKey","storageImpl","storage","readRefreshToken","heldRefreshToken","writeRefreshToken","token","s","lineageKey","refreshLockName","heldLineage","writeLineage","lineage","state","getToken","fetchUser","mePath","started","epoch","user","api","error","followSharedSession","ending","hooksRunning","loginsInFlight","revocations","credentialRequests","rotatingEpochs","trackCredentialRequest","settled","request","reportLogoutError","onLogoutError","trackRevocation","tracked","build","revokeDiscarded","refreshToken","endedSessionApi","refreshBody","nextEpoch","rotate","before","underRefreshLock","redeem","locks","run","controller","acquired","held","followed","refreshPath","parseTokens","queue","staleWithinSession","current","context","signedOut","awaitLogins","refreshFor","onUnauthorized","endSession","login","signIn","credentials","loginPath","finish","mine","done","embedded","parseUser","live","reason","runSessionEnd","onSessionEnd","sessionApi","ended","readSharedSession","raw","parsed","shared","sameUser","sameSession","continues","revoke","path","inFlight","logout","revocation","redirectTo","refresh","unlineaged","sessionKey","identity","listener","onStorage","event"],"sources":["../../src/auth/create-tempest-auth.ts"],"sourcesContent":["import { createApiClient, SessionSupersededError } from \"../http\";\nimport { bindSessionIdentity, type SessionIdentity } from \"./session-identity\";\nimport { isDevBuild } from \"../utils/dev-mode\";\nimport type { ApiClient, CsrfOptions, RequestAuthContext, RetryOptions } from \"../http\";\nimport { createAuthStore } from \"./create-auth-store\";\nimport type { AuthState } from \"./create-auth-store\";\nimport { createRefreshQueue } from \"./refresh-queue\";\n\n/** The token envelope returned by a Tempest FastAPI SDK login/refresh route. */\nexport interface TempestTokenResponse {\n /** The bearer access token. */\n access_token: string;\n /** Token type — always `\"bearer\"` for the SDK. */\n token_type?: string;\n /** Optional refresh token (when the API returns it in the body, not a cookie). */\n refresh_token?: string;\n}\n\n/**\n * What {@link CreateTempestAuthOptions.onSessionEnd} receives about the session\n * that just ended.\n */\nexport interface TempestSessionEnd<TUser> {\n /**\n * Why it ended: `\"logout\"` for an explicit `logout()`, `\"expired\"` when the\n * client ended it on its own — the refresh failed, or the request replayed\n * after a refresh still came back `401` — and `\"switch\"` when `login()`\n * succeeded for another set of credentials while this session was live.\n */\n reason: \"logout\" | \"expired\" | \"switch\";\n /** The user of the ended session, as the store held it. */\n user: TUser | null;\n /** The access token of the ended session, or `null` when it had none. */\n token: string | null;\n /**\n * A client that sends the ended session's access token — the store has\n * already been cleared, so `auth.api` no longer does.\n *\n * Use it for the server-side half of the teardown, such as deleting this\n * browser's push subscription. It never refreshes and never ends a session:\n * a `401` here just rejects. On `\"logout\"` the token is usually still\n * valid; on `\"expired\"` the server has already refused it, so expect the\n * call to fail and keep the local half of the teardown independent of it.\n */\n api: ApiClient;\n /**\n * Whether another tab of the origin ended or replaced the session, and this\n * tab is only catching up (#524). With `storage: \"local\"` the session's\n * keys are shared by every tab, so a `logout()` or a `login()` in one tab\n * ends the session in all of them: `reason` is `\"logout\"` when the other\n * tab left no session behind and `\"switch\"` when it installed another\n * account.\n *\n * The other tab already ran this hook for the same session. Teardown that\n * lives in this tab's memory (an in-memory cache, an open socket) still has\n * to run here; teardown of state the origin shares (IndexedDB, Cache\n * Storage, a push subscription) was done there, and on `\"switch\"` redoing\n * it here would wipe what the new account already wrote — skip it when\n * this is `true`.\n */\n elsewhere: boolean;\n}\n\nexport interface CreateTempestAuthOptions<TUser> {\n /** Base URL of the API. Required. */\n baseURL: string;\n /**\n * Path segment the API is mounted under, such as `\"/api\"`, forwarded to\n * every client this preset builds — see the `prefix` option of\n * `createApiClient`.\n *\n * Safe to combine with the default paths below: the prefix is applied at\n * most once, so `\"/api/auth/login\"` under a `\"/api\"` prefix stays\n * `\"/api/auth/login\"`.\n */\n prefix?: string;\n /** Login route (`POST`). Default: `\"/api/auth/login\"`. */\n loginPath?: string;\n /** Refresh route (`POST`). Default: `\"/api/auth/refresh\"`. */\n refreshPath?: string;\n /**\n * Server-side logout route (`POST`), called by an explicit `logout()` to\n * revoke the ending session. Off by default.\n *\n * `logout()` alone only clears client state, and an HttpOnly refresh\n * cookie is out of its reach: with `withCredentials`, the cookie stays\n * redeemable until the backend revokes it. The tempest-fastapi-sdk mounts\n * `POST /auth/logout` (`204`, idempotent) when it stores refresh tokens in\n * the database — at `/auth/cookie/logout` when it delivers tokens both in\n * the body and in cookies — and stateless refresh tokens cannot be\n * revoked, so the route is absent there.\n *\n * The request goes out through the ended session's client (the same one\n * `onSessionEnd` receives, carrying its access token), with the body that\n * `refreshBody` builds from the refresh token stored before the clear:\n * `{ refresh_token }` in body mode, no body in cookie mode, which is what\n * that route reads. The local clear does not wait on it — `isAuthenticated`\n * is still `false` when `logout()` returns — but the promise `logout()`\n * returns does, so a navigation after `await auth.logout()` does not abort\n * it. A failure (network, `4xx`, `5xx`) is swallowed: revocation is\n * best-effort and never keeps the user signed in. A `login()` started\n * while it is in flight waits for it, because the logout response clears\n * the auth cookies and would otherwise clear the new account's.\n *\n * An explicit `logout()` revokes, and so does a `\"switch\"` in body mode:\n * the replaced session's refresh token is still in the client's hands, and\n * the tempest-fastapi-sdk revokes by rotation family, so the session the\n * new login opened is untouched even for the same user. Before 0.82.0 a\n * switch revoked nothing and the replaced token stayed redeemable until it\n * expired. A `\"switch\"` in cookie mode does not revoke — the cookie jar\n * already holds the new account's cookie — and on `\"expired\"` the server\n * has already refused the session.\n *\n * Overlapping sign-outs each send their own revocation, and `login()` waits\n * for all of them — at most 10 seconds, so one that\n * never answers delays the sign-in instead of blocking it. In cookie mode,\n * a revocation also waits (within the same bound) for the login and\n * refresh responses that were in flight when `logout()` ran: the server\n * sets the ended session's cookie when that response arrives, and a\n * revocation sent earlier would leave it behind. In body mode, the refresh\n * token such a superseded response brings back is revoked on its own.\n */\n logoutPath?: string;\n /**\n * Called with the error when a `logoutPath` revocation fails — network\n * failure, `4xx` or `5xx`. `logout()` still resolves, since the local\n * sign-out already happened; this is where the app logs or retries. A dev\n * build also warns in the console. Errors it throws are swallowed.\n */\n onLogoutError?: (error: unknown) => void;\n /** Optional current-user route (`GET`) called after login/refresh. */\n mePath?: string;\n /** Persist key for the store. Default: `\"tempest-auth\"`. */\n storeName?: string;\n /** Storage backend. Default: `\"local\"`. */\n storage?: \"local\" | \"session\";\n /** Send cookies (needed when the refresh token lives in an httpOnly cookie). */\n withCredentials?: boolean;\n /**\n * CSRF token for every write, forwarded to `createApiClient`'s `csrf`. Off\n * by default; `true` echoes the `csrf_token` cookie as `X-CSRF-Token`.\n *\n * The pair to `withCredentials`: once the refresh token lives in a cookie,\n * the browser attaches it to a `POST /auth/refresh` that another site\n * triggers. Login and refresh carry the header too — they go out with\n * `skipAuth`, and the CSRF header does not follow auth.\n */\n csrf?: boolean | CsrfOptions;\n /** Custom fetch implementation (testing / SSR). Defaults to `globalThis.fetch`. */\n fetcher?: typeof fetch;\n /**\n * Extract tokens from a login/refresh response. Default reads\n * `access_token` + `refresh_token`.\n */\n parseTokens?: (data: unknown) => { token: string; refreshToken?: string };\n /** Pull the user out of the login response, when the API embeds it. */\n parseUser?: (data: unknown) => TUser | null;\n /**\n * Build the refresh request body. Default sends `{ refresh_token }` when a\n * refresh token is stored, else `undefined` (cookie-based refresh).\n */\n refreshBody?: (refreshToken: string | null) => unknown;\n /**\n * Retry policy for `api`, forwarded to {@link createApiClient}. Off by\n * default; `true` enables the conservative built-in policy, which never\n * replays a write.\n */\n retry?: boolean | RetryOptions;\n /**\n * Where to send the browser when the session ends — a hard navigation via\n * `window.location.assign`, after the store is cleared.\n *\n * **Prefer leaving this unset.** `logout()` already clears the store, so a\n * `<RouteGuard when={isAuthenticated} redirectTo=\"/login\">` wrapped around\n * the protected area navigates on its own, which keeps the SPA alive and the\n * router history intact. Reach for this only when the expiry can happen\n * outside any guarded subtree and a full reload is acceptable.\n */\n redirectTo?: string;\n /**\n * Tear down per-user state when a session ends — on an explicit `logout()`,\n * when the client ends the session on its own after a failed refresh, and\n * when a successful `login()` replaces a live session. Without it, the automatic path had no place to hook into, and\n * state derived from the user (a push subscription, a persisted query\n * cache, a background-sync queue) survived into the next account.\n *\n * Order, on every path:\n *\n * 1. any refresh still in flight is superseded, so it cannot reinstall the\n * ending session's tokens;\n * 2. the store and the stored refresh token are cleared — synchronously, so\n * `isAuthenticated` is already `false` when `logout()` returns;\n * 3. this hook runs with a {@link TempestSessionEnd} whose `api` still sends\n * the ended session's access token;\n * 4. on `\"expired\"` with `redirectTo` set, the browser navigates — after the\n * hook settled, even if it threw; on `\"switch\"`, the new session is\n * installed — after the hook settled, even if it threw.\n *\n * It may be async. `logout()` resolves when it settles and rejects with what\n * it threw; on the automatic path the error is swallowed, because the\n * request that ended the session already rejects with its own `401`. It\n * runs once per session: a second `logout()`, or the other requests of a\n * burst of `401`s, find nothing left to end and skip it.\n *\n * On `\"switch\"` the hook runs only **after** the new credentials were\n * accepted, so a failed `login()` leaves the live session untouched. It runs\n * **before** the new session is installed: teardown of the previous\n * account's state (clearing a persisted cache, a background-sync queue) has\n * to finish before the new account's requests start filling them, or it\n * would wipe — or race with — the new account's data. The cost is that\n * `isAuthenticated` is `false` while the hook runs, which a route guard may\n * act on; keep the hook short. Its error is swallowed there, since the\n * login itself succeeded.\n *\n * Inside the hook, reach the backend only through `session.api`. `auth.api`\n * goes out with no token; `auth.login()` waits on the teardown in progress —\n * this hook — and never settles. Telling the hook apart from an outside\n * caller would need an async context the browser does not have, so this is\n * a documented rule, not a runtime check.\n */\n onSessionEnd?: (session: TempestSessionEnd<TUser>) => void | Promise<void>;\n}\n\nexport interface TempestAuth<TUser, TCredentials> {\n /** The persisted Zustand auth store hook (compatible with `<AuthGuard>`). */\n useAuthStore: ReturnType<typeof createAuthStore<TUser>>;\n /** A `createApiClient` wired with bearer auth + 401 → refresh → retry. */\n api: ApiClient;\n /** Authenticate, store the session, and resolve the user (or null). */\n login: (credentials: TCredentials) => Promise<TUser | null>;\n /**\n * End the session: supersede any refresh in flight, clear the store and the\n * stored refresh token, then run `onSessionEnd`.\n *\n * The store is cleared synchronously, before the first `await`, so callers\n * that ignore the promise see the signed-out state at once. The promise\n * resolves when `onSessionEnd` settled — and, with `logoutPath`, when the\n * server-side revocation settled too — and rejects with the hook's error;\n * a failed revocation never rejects it.\n */\n logout: () => Promise<void>;\n /**\n * Refresh the access token (deduplicated across concurrent callers).\n *\n * @throws {SessionSupersededError} When the session ended or changed while\n * the refresh was in flight; its tokens were discarded.\n */\n refresh: () => Promise<void>;\n /** The current access token, or null. */\n getToken: () => string | null;\n /**\n * The key of the session signed in now, or `null` when nobody is.\n *\n * It changes when the session is replaced — `login()`, even into the same\n * account, a sign-in or sign-out in another tab, `logout()` — and stays\n * the same while that session's tokens rotate: it is the session lineage\n * `login()` mints, not the token. That is the identity a per-session\n * resource needs. `useTicketEventStream`/`createTicketEventStream` read it\n * on their own from `api`, and `createResumableUpload` from `getToken`;\n * pass it as `sessionKey` or `getPrincipal` anywhere else.\n *\n * A session restored by `refresh()` with none installed — the boot\n * restore from a refresh cookie, an OAuth callback — is a new sign-in and\n * gets a lineage of its own, like `login()` (#561). A session persisted\n * before lineages existed has none in storage; its key is minted by this\n * preset for as long as that session lasts, so it survives the session's\n * rotations but no other session ever shares it. Until 0.82.0 both cases\n * answered one constant for every account, and an upload bound by\n * `getToken: auth.getToken` was resumed by the next account restored the\n * same way.\n */\n sessionKey: () => string | null;\n /**\n * Stop following the other tabs: removes the `storage` listener this\n * preset adds to `window`. Idempotent.\n *\n * An app keeps one preset for the page's lifetime and never needs it; it\n * exists for tests and hot-module reload, which build several presets in\n * one window. A disposed preset still compares the shared storage with\n * its session before every refresh, so it never redeems another tab's\n * refresh token.\n */\n dispose: () => void;\n}\n\n/**\n * How long `login()` waits for pending `logoutPath` revocations, and how long a\n * cookie-mode revocation waits for the login or refresh responses still in\n * flight when `logout()` ran, before going ahead anyway.\n *\n * A bound, not a guess at latency: a fetcher that ignores abort, or a backend\n * that never answers, would otherwise leave the next `login()` waiting forever.\n * Ten seconds is past any healthy round trip and short enough that a stuck\n * revocation costs a slow sign-in, not a dead one.\n */\nconst LOGOUT_REVOCATION_WAIT_MS = 10_000;\n\n/**\n * How long a refresh waits for another tab's refresh to release the\n * origin-wide refresh lock before redeeming without it.\n *\n * The same reasoning as {@link LOGOUT_REVOCATION_WAIT_MS}: past any healthy\n * round trip, and a bound so that a tab stuck holding the lock costs a\n * duplicate redemption, not a request that never settles.\n */\nconst REFRESH_LOCK_WAIT_MS = 10_000;\n\n/**\n * Wait until every promise settled, or until `ms` passed, whichever is first.\n *\n * @param pending - What to wait for; rejections count as settled.\n * @param ms - The bound.\n * @returns A promise that always resolves.\n */\nfunction settleWithin(pending: readonly Promise<unknown>[], ms: number): Promise<void> {\n if (pending.length === 0) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, ms);\n void Promise.allSettled(pending).then(() => {\n clearTimeout(timer);\n resolve();\n });\n });\n}\n\n/**\n * Mint the identifier of a new session lineage: one per successful `login()`,\n * kept across every rotation of that session, see `createTempestAuth`.\n *\n * It only has to tell two sign-ins apart, never to resist guessing — it guards\n * nothing on the server and is readable by any script of the origin anyway. So\n * the fallback for a page without `crypto.randomUUID` (served over plain http,\n * where the browser withholds it) is a timestamp plus `Math.random`, not an\n * error.\n *\n * @returns A fresh lineage identifier.\n */\nfunction newLineage(): string {\n const host = globalThis.crypto as Partial<Crypto> | undefined;\n if (typeof host?.randomUUID === \"function\") return host.randomUUID();\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * The store names already warned about cookie mode without `logoutPath`, so a\n * hot-module reload that rebuilds the preset does not repeat the warning.\n */\nconst warnedCookieWithoutLogout = new Set<string>();\n\n/**\n * Warn, in a dev build and once per store, that cookie mode has no\n * `logoutPath` (#531).\n *\n * `logout()` cannot reach an HttpOnly refresh cookie, so without a revocation\n * the cookie stays redeemable and the boot `refresh()` of the next page load\n * signs the account that just signed out back in — for whoever uses the\n * browser next. Measured with the `cookieBackend` of\n * `create-tempest-auth.cookie.test.ts`: login, `logout()`, a new preset and\n * `refresh()` restore `A-tok-cookie-1`.\n *\n * A warning, not a requirement. Requiring `logoutPath` would break every app\n * whose backend cannot revoke — the tempest-fastapi-sdk mounts no logout route\n * with stateless refresh tokens — and would not close the hole for them\n * either: a route that answers `404` revokes nothing. Refusing the boot\n * `refresh()` after a logout would break the sign-ins that set the cookie\n * outside `login()`, such as an OAuth callback. Only the backend can end the\n * cookie; this makes the missing half visible while the app is being built.\n *\n * @param storeName - The preset's persist key.\n */\nfunction warnCookieWithoutLogout(storeName: string): void {\n if (!isDevBuild() || warnedCookieWithoutLogout.has(storeName)) return;\n warnedCookieWithoutLogout.add(storeName);\n console.warn(\n \"[tempest-react-sdk] createTempestAuth: withCredentials is set without logoutPath. \" +\n \"logout() cannot clear the HttpOnly refresh cookie, so the next refresh() — the \" +\n \"boot restore — signs the same account back in. Pass logoutPath (the backend's \" +\n \"cookie logout route) so the server revokes it.\",\n );\n}\n\nfunction defaultParseTokens(data: unknown): { token: string; refreshToken?: string } {\n const d = (data ?? {}) as TempestTokenResponse;\n return { token: d.access_token, refreshToken: d.refresh_token };\n}\n\n/**\n * Turn-key auth preset wiring `createAuthStore` + `createRefreshQueue` +\n * `createApiClient` to the Tempest FastAPI SDK auth contract: login returns\n * `{ access_token, token_type }`, requests carry `Authorization: Bearer`, and a\n * `401` triggers a single deduplicated refresh + replay.\n *\n * The session is cleared whenever that path ends unauthorized anyway — the\n * refresh threw, or the replay came back `401` — so a refresh token that the\n * backend has revoked cannot leave the app holding a dead session. With\n * `redirectTo` set, the browser also leaves the page; without it, clearing the\n * store is enough for a `<RouteGuard>` to navigate on its own.\n *\n * Every refresh is bound to a **session epoch**, bumped by `logout()` and by a\n * `login()` whose credentials were accepted. A refresh that resolves after its epoch ended discards\n * what it brought back and rejects with {@link SessionSupersededError}, which\n * the client passes through without ending the new session. Before 0.77.0 a\n * refresh that was in flight during `logout()` reinstalled the old tokens —\n * and after `logout()` + `login(B)`, replaced B's token with A's while the UI\n * showed B (#435). A `401` from a request sent under an ended session is\n * refused the same way, instead of being replayed as the account signed in now.\n *\n * A `401` from a request that carried no token, while no session is installed,\n * surfaces without a refresh: in cookie mode that refresh would be answered by\n * the HttpOnly cookie `logout()` cannot clear, signing the previous account\n * back in (#474). With a `login()` in flight, that `401` waits for it and\n * replays with the token it installed, or surfaces when it failed — still\n * without a refresh (#496). Restore a session at boot with an explicit\n * `refresh()`, and pass `logoutPath` so the backend revokes the cookie:\n * without a working revocation, that boot `refresh()` restores the previous\n * account for whoever uses the browser next.\n *\n * With `storage: \"local\"` the session belongs to the **origin**, not the tab:\n * every tab reads and writes the same keys and follows what another tab wrote\n * — on the `storage` event and, before any refresh, `logout()` or ending of\n * the session, by comparing the stored session with the one it holds. A\n * rotation elsewhere is adopted; a logout or another account's login\n * elsewhere ends the session here too, with `onSessionEnd` told it happened\n * `elsewhere`. Before 0.81.0 a tab left open after logout kept account A and,\n * on its next `401`, redeemed account B's refresh token from the shared\n * storage, persisting `{ user: A, token: B }` (#524). Whether the stored\n * session is the held one is decided by a **session lineage** that `login()`\n * mints and every rotation keeps — not by comparing users, which took two\n * sign-ins whose user had not loaded yet for the same account (#544). Two tabs\n * never redeem the same refresh token at once: the redemption runs under an\n * origin-wide Web Lock when the browser has one. `storage: \"session\"` is per\n * tab and behaves as before.\n *\n * Refreshes are collapsed per rotation, not just per overlap: a `401` whose\n * request left with a token that has since been replaced in the same session\n * replays with the new token and refreshes nothing. Three expired requests take\n * one refresh whether their `401`s arrive together or one after another.\n *\n * @example\n * const auth = createTempestAuth<User, { email: string; password: string }>({\n * baseURL: import.meta.env.VITE_API_URL,\n * mePath: \"/api/auth/me\",\n * });\n *\n * await auth.login({ email, password }); // stores session, returns the user\n * const orders = await auth.api.get(\"/api/orders\"); // sends the bearer token\n * await auth.logout(); // clears, then runs onSessionEnd\n *\n * @param options - The auth configuration.\n * @returns The store hook, a wired API client, and login/logout/refresh helpers.\n */\nexport function createTempestAuth<TUser, TCredentials = { email: string; password: string }>(\n options: CreateTempestAuthOptions<TUser>,\n): TempestAuth<TUser, TCredentials> {\n const {\n baseURL,\n prefix,\n loginPath = \"/api/auth/login\",\n refreshPath = \"/api/auth/refresh\",\n logoutPath,\n onLogoutError,\n mePath,\n storeName = \"tempest-auth\",\n storage = \"local\",\n withCredentials = false,\n csrf,\n fetcher,\n parseTokens = defaultParseTokens,\n parseUser,\n refreshBody = (rt) => (rt ? { refresh_token: rt } : undefined),\n retry,\n redirectTo,\n onSessionEnd,\n } = options;\n\n if (withCredentials && !logoutPath) warnCookieWithoutLogout(storeName);\n\n const useAuthStore = createAuthStore<TUser>({ name: storeName, storage });\n const refreshKey = `${storeName}-refresh`;\n\n function storageImpl(): Storage | null {\n if (typeof window === \"undefined\") return null;\n return storage === \"session\" ? window.sessionStorage : window.localStorage;\n }\n function readRefreshToken(): string | null {\n return storageImpl()?.getItem(refreshKey) ?? null;\n }\n let heldRefreshToken: string | null = readRefreshToken();\n function writeRefreshToken(token: string | null): void {\n heldRefreshToken = token;\n const s = storageImpl();\n if (!s) return;\n if (token) s.setItem(refreshKey, token);\n else s.removeItem(refreshKey);\n }\n\n const lineageKey = `${storeName}-lineage`;\n const refreshLockName = `tempest-react-sdk:${storeName}:refresh`;\n let heldLineage: string | null = storageImpl()?.getItem(lineageKey) ?? null;\n function writeLineage(lineage: string | null): void {\n heldLineage = lineage;\n const s = storageImpl();\n if (!s) return;\n if (lineage) s.setItem(lineageKey, lineage);\n else s.removeItem(lineageKey);\n }\n\n const state = (): AuthState<TUser> => useAuthStore.getState();\n const getToken = (): string | null => state().token;\n\n /**\n * Load the current user, without letting a `401` end the session.\n *\n * `skipAuthRetry` is what keeps this one client honest: the call is\n * authenticated, but a `401` here surfaces instead of triggering a refresh\n * and `onUnauthorized`. That was the behaviour of the throwaway client this\n * used to build per invocation, and it is the reason the preset needed\n * three clients before 0.66.0.\n *\n * Bound to the epoch current when the request leaves, like `rotate()`: a\n * profile that resolves after `logout()` — or after `logout()` +\n * `login(B)` — is discarded instead of written next to B's token, and the\n * `login()` that asked for it rejects as superseded (#473).\n *\n * Before the profile is written, the shared storage is followed (#544).\n * The write persists the whole `{ user, token }` this tab holds, so a tab\n * that had not yet seen another account's sign-in used to overwrite it\n * with its own token next to that account's refresh token — and the\n * other tab, following the write, paired that refresh token with this\n * account's user. Following first turns that into a session ended\n * elsewhere, and the profile is discarded.\n *\n * Bound to the session, not to the token the request carried: a token\n * that changed because another tab rotated the same session still\n * belongs to this user, and discarding the profile then would fail a\n * sign-in that succeeded.\n *\n * @throws {SessionSupersededError} When the epoch changed while the\n * request was in flight, on success and on failure alike, or another\n * tab ended or replaced the session.\n */\n async function fetchUser(): Promise<TUser | null> {\n if (!mePath) return state().user;\n const started = epoch;\n let user: TUser;\n try {\n user = await api.get<TUser>(mePath, { skipAuthRetry: true });\n } catch (error) {\n if (epoch !== started) throw new SessionSupersededError();\n throw error;\n }\n if (epoch !== started || !followSharedSession().continues) {\n throw new SessionSupersededError();\n }\n state().setUser(user);\n return user;\n }\n\n let epoch = 0;\n let ending: Promise<void> = Promise.resolve();\n let hooksRunning = 0;\n const loginsInFlight = new Set<Promise<unknown>>();\n const revocations = new Set<Promise<void>>();\n const credentialRequests = new Set<Promise<unknown>>();\n const rotatingEpochs = new Set<number>();\n\n /**\n * Track a login or refresh request until it settles, so a cookie-mode\n * revocation can wait for the response that sets the cookie it revokes.\n *\n * @param request - The request in flight.\n * @returns The same request.\n */\n function trackCredentialRequest<T>(request: Promise<T>): Promise<T> {\n const settled = request.then(\n () => undefined,\n () => undefined,\n );\n credentialRequests.add(settled);\n void settled.then(() => credentialRequests.delete(settled));\n return request;\n }\n\n /**\n * Surface a failed revocation: `onLogoutError`, plus a console warning in a\n * dev build.\n *\n * @param error - What the revocation rejected with.\n */\n function reportLogoutError(error: unknown): void {\n if (isDevBuild()) {\n console.warn(\n \"[tempest-react-sdk] createTempestAuth: logoutPath revocation failed\",\n error,\n );\n }\n try {\n onLogoutError?.(error);\n } catch {\n return;\n }\n }\n\n /**\n * Send one `logoutPath` revocation and track it until it settles. Never\n * rejects.\n *\n * @param build - Produces the request, after whatever wait it needs.\n * @returns A promise settling when the revocation settled.\n */\n function trackRevocation(build: () => Promise<unknown>): Promise<void> {\n const tracked = (async () => {\n try {\n await build();\n } catch (error) {\n reportLogoutError(error);\n }\n })();\n revocations.add(tracked);\n void tracked.then(() => revocations.delete(tracked));\n return tracked;\n }\n\n /**\n * Revoke, in body mode, the refresh token a superseded login or refresh\n * brought back. Nobody can use it — the client discarded it — but it would\n * stay valid on the server until it expires.\n *\n * Cookie mode is left to `revoke()`, which waits for these responses\n * instead: re-sending a cookie revocation here could carry whichever\n * account's cookie the browser holds by then.\n *\n * @param token - The superseded response's access token.\n * @param refreshToken - The superseded response's refresh token.\n */\n function revokeDiscarded(token: string | null, refreshToken: string | undefined): void {\n if (!logoutPath || withCredentials || !refreshToken) return;\n void trackRevocation(() =>\n endedSessionApi(token).post<unknown>(logoutPath, {\n body: refreshBody(refreshToken),\n }),\n );\n }\n\n /**\n * A client that sends an ended session's access token, and never refreshes\n * or ends a session: a `401` there just rejects.\n *\n * @param token - The ended session's access token.\n * @returns The client `onSessionEnd` and the `logoutPath` call go through.\n */\n function endedSessionApi(token: string | null): ApiClient {\n return createApiClient({\n baseURL,\n prefix,\n withCredentials,\n csrf,\n fetcher,\n getToken: () => token,\n });\n }\n\n /**\n * Start a new session epoch: supersede the refresh in flight and give the\n * new epoch a refresh queue of its own, so a `401` under the new session\n * never joins the old session's refresh.\n *\n * The client reads the epoch when each attempt leaves (`getSessionEpoch`),\n * which is what ties a `401` to the session that sent it — no set of\n * tokens to keep, and nothing that grows with the session's length.\n */\n function nextEpoch(): void {\n epoch += 1;\n queue = createRefreshQueue(rotate);\n }\n\n /**\n * Perform one refresh for the epoch that is current when it starts.\n *\n * Checked again after the round trip, on success and on failure alike: a\n * refresh that fails after `logout()` + `login(B)` must not reach\n * `onUnauthorized` either, or it would end B's session.\n *\n * Before the request, and again before installing its result, the stored\n * session is compared with the one this tab holds, see\n * `followSharedSession`. When another tab rotated the same account, its\n * tokens are adopted and nothing is redeemed: the replay goes out with\n * them. When another tab signed out, or signed in as someone else, nothing\n * is redeemed either — the refresh token in storage is not this session's\n * (#524) — and the call rejects as superseded.\n *\n * With `storage: \"local\"` the redemption runs under a Web Lock shared by\n * every tab of the origin, see `underRefreshLock`; the comparison with the\n * stored session happens once the lock is held, so a tab that waited\n * behind another tab's rotation adopts its tokens instead of presenting\n * the refresh token that rotation just spent.\n *\n * @throws {SessionSupersededError} When the epoch changed during the call,\n * or another tab ended or replaced the session.\n */\n async function rotate(): Promise<void> {\n const before = getToken();\n const started = epoch;\n rotatingEpochs.add(started);\n try {\n await underRefreshLock(() => redeem(before));\n } finally {\n rotatingEpochs.delete(started);\n }\n }\n\n /**\n * Run `run` while holding the origin-wide refresh lock, when there is one\n * to hold (run-7 hardening note).\n *\n * Two tabs whose requests expire together used to redeem the same refresh\n * token at once. A backend with reuse detection — the tempest-fastapi-sdk\n * has it — answers the second redemption by revoking the whole rotation\n * family, so the session ends in every tab. The common trigger is a\n * browser restart that restores several tabs, each calling the boot\n * `refresh()`: measured with two presets over a reuse-detecting backend,\n * both presented `ref-1`, the family was revoked, and no refresh token was\n * left alive.\n *\n * The lock is the Web Locks API (`navigator.locks`), held only for the\n * redemption round trip. Only `storage: \"local\"` shares a session between\n * tabs, so `\"session\"` takes no lock. Fail-open, by design: without the\n * API (SSR, an old browser, jsdom), when acquiring it throws (an opaque\n * origin), or after {@link REFRESH_LOCK_WAIT_MS} of waiting behind a tab\n * that never releases it, the redemption runs unlocked — the behaviour\n * before the lock existed — instead of leaving the request hanging.\n *\n * @param run - The redemption.\n * @returns A promise settling with `run`.\n */\n async function underRefreshLock(run: () => Promise<void>): Promise<void> {\n const locks =\n storage === \"local\" && typeof navigator !== \"undefined\"\n ? (navigator as Partial<Navigator>).locks\n : undefined;\n if (!locks) return run();\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), REFRESH_LOCK_WAIT_MS);\n let acquired = false;\n try {\n await locks.request(refreshLockName, { signal: controller.signal }, async () => {\n acquired = true;\n clearTimeout(timer);\n await run();\n });\n } catch (error) {\n if (acquired) throw error;\n clearTimeout(timer);\n await run();\n }\n }\n\n /**\n * The body of one rotation, run under the refresh lock.\n *\n * A tab that held no session when the rotation was asked for — the boot\n * `refresh()` — and finds one installed once the lock is held was restored\n * by another tab while it waited: that is the outcome it asked for, so it\n * resolves without redeeming.\n *\n * A redemption that installs a session where none was held is a sign-in,\n * not a rotation, so it mints a lineage before the token is installed —\n * the same order as `login()`, so every store listener reads the new key.\n * Without it every restored session shared one `sessionKey()` (#561). A\n * second tab is never told about a switch by it: one restoring at the\n * same time either finds this session once it holds the refresh lock and\n * adopts it, lineage included, or — without the lock — holds no session\n * yet, so following this one ends nothing and runs no `onSessionEnd`.\n *\n * @param before - The access token held when the rotation was asked for.\n * @throws {SessionSupersededError} See `rotate()`.\n */\n async function redeem(before: string | null): Promise<void> {\n const held = before !== null || state().user !== null || heldRefreshToken !== null;\n const followed = followSharedSession();\n if (!held && getToken() !== null) return;\n if (!followed.continues) throw new SessionSupersededError();\n if (getToken() !== before) return;\n const started = epoch;\n let data: unknown;\n try {\n data = await trackCredentialRequest(\n api.post<unknown>(refreshPath, {\n body: refreshBody(readRefreshToken()),\n skipAuth: true,\n }),\n );\n } catch (error) {\n if (epoch !== started) throw new SessionSupersededError();\n throw error;\n }\n const { token, refreshToken } = parseTokens(data);\n if (epoch !== started || !followSharedSession().continues) {\n revokeDiscarded(token ?? null, refreshToken);\n throw new SessionSupersededError();\n }\n if (!held) writeLineage(newLineage());\n state().setToken(token);\n if (refreshToken) writeRefreshToken(refreshToken);\n }\n\n let queue = createRefreshQueue(rotate);\n\n /**\n * Whether a `401` must be left alone: no refresh, no ending the session.\n *\n * Two cases, both of the current epoch: an attempt that carried no token\n * while a session is now installed (it left before the sign-in, and\n * refreshing or ending the new session for it would punish the wrong\n * session); and an attempt whose token the session has since rotated past\n * (the rotation it would trigger already happened).\n *\n * @param context - The attempt's credential.\n * @returns Whether the attempt is stale within the current session.\n */\n function staleWithinSession(context: RequestAuthContext): boolean {\n const current = getToken();\n if (current === null) return false;\n return context.token === null || context.token !== current;\n }\n\n /**\n * Whether nothing could make a tokenless `401` worth a refresh: no access\n * token and no stored refresh token.\n *\n * With `withCredentials`, the refresh would otherwise be answered by an\n * HttpOnly cookie the client cannot see or clear — after `logout()`, that\n * signed the previous account back in for whoever used the browser next\n * (#474). A `login()` in flight does not count as a session either: the\n * cookie a refresh would present during it is still the ended account's\n * (#496). Restoring a session from the cookie is an explicit `refresh()`,\n * typically at boot, which this does not touch.\n *\n * @returns Whether no session is installed.\n */\n function signedOut(): boolean {\n return getToken() === null && readRefreshToken() === null;\n }\n\n /**\n * Settle a tokenless `401` that arrived with no session installed while a\n * `login()` is in flight: wait for every login in flight, then let the\n * request replay when one of them installed a token.\n *\n * No refresh is sent. In cookie mode one would present whatever cookie\n * the browser holds — after `logout()` without a working `logoutPath`,\n * the previous account's: a failed login then left the client signed in\n * as that account, and a successful one could have its cookie overwritten\n * by the refresh's late `Set-Cookie` (#496).\n *\n * Skipped while an `onSessionEnd` hook runs: an account switch waits on\n * that hook, so a hook awaiting `auth.api` would wait on itself.\n *\n * @throws {Error} When no login is in flight, a hook is running, or every\n * login settled without installing a token — the `401` surfaces as is.\n */\n async function awaitLogins(): Promise<void> {\n if (loginsInFlight.size > 0 && hooksRunning === 0) {\n await Promise.allSettled([...loginsInFlight]);\n if (getToken() !== null) return;\n }\n throw new Error(\"anonymous 401 with no session\");\n }\n\n /**\n * The `refresh` the client calls on a `401`.\n *\n * - An attempt from an ended epoch is refused rather than replayed as\n * whoever is signed in now.\n * - A token this session already rotated past: the replay just picks up the\n * new one — no second refresh.\n * - No token, while a session is now installed: the `401` surfaces as is.\n * - No token, and no session installed: joins this epoch's refresh when\n * one is already in flight — the boot `refresh()` restoring a session\n * from the cookie, which the request then replays under; otherwise waits\n * for a `login()` in flight and replays with its token, see\n * `awaitLogins`; otherwise surfaces the `401` as is, see `signedOut`.\n * - Otherwise: join or start this epoch's refresh.\n *\n * @param context - The credential and epoch the rejected attempt left with.\n * @throws {SessionSupersededError} When the attempt belongs to an ended\n * session, or the session changed during the refresh.\n */\n async function refreshFor(context: RequestAuthContext): Promise<void> {\n if (context.epoch !== null && context.epoch !== epoch) throw new SessionSupersededError();\n if (staleWithinSession(context)) {\n if (context.token === null) throw new Error(\"anonymous 401 under a live session\");\n return;\n }\n if (context.token === null && signedOut()) {\n if (rotatingEpochs.has(epoch)) return queue();\n return awaitLogins();\n }\n return queue();\n }\n\n /**\n * The client's `onUnauthorized`: end the session only when the `401` is the\n * current session's own.\n *\n * The replay after a refresh is checked here too — it can come back `401`\n * after the user signed out and another account signed in, and ending the\n * session then would sign the new account out. A tokenless `401` with no\n * session installed ends nothing either: there is no session to end, and\n * ending \"nothing\" used to move the epoch and supersede the boot\n * `refresh()` in flight. Neither does a `401` from a session another tab\n * already ended or replaced: ending it here would clear that tab's new\n * session from the shared storage.\n *\n * @param context - The credential and epoch of the attempt that failed.\n * @throws {SessionSupersededError} When that attempt belongs to an ended\n * session, here or in another tab.\n */\n async function onUnauthorized(_response: Response, context: RequestAuthContext): Promise<void> {\n if (context.epoch !== null && context.epoch !== epoch) throw new SessionSupersededError();\n if (!followSharedSession().continues) throw new SessionSupersededError();\n if (staleWithinSession(context)) return;\n if (context.token === null && signedOut()) return;\n await endSession();\n }\n\n /**\n * Authenticate and install the new session.\n *\n * The previous session ends only once the new credentials are accepted: a\n * login that fails leaves it, and the refresh it may have in flight,\n * untouched. When one was live, `onSessionEnd` runs with `\"switch\"` before\n * the new tokens are installed — see the option for why that order. A\n * `logout()` still tearing down is awaited the same way, so the new\n * account's state never starts before the previous one's teardown ended.\n * Never call it from inside `onSessionEnd`: it would wait on that hook.\n * Every `logoutPath` revocation still in flight is awaited before the\n * request leaves — at most {@link LOGOUT_REVOCATION_WAIT_MS} — so a\n * cookie-clearing response cannot land after the new account's cookies.\n *\n * @param credentials - Sent as the login body.\n * @returns The user of the new session, or null.\n * @throws {SessionSupersededError} When a `logout()` or another `login()`\n * moved the session while this one was in flight — during its request,\n * during the teardown or while `mePath` was loading the user; the new\n * tokens, or the user, are discarded.\n */\n async function login(credentials: TCredentials): Promise<TUser | null> {\n if (revocations.size > 0) await settleWithin([...revocations], LOGOUT_REVOCATION_WAIT_MS);\n const run = signIn(credentials);\n loginsInFlight.add(run);\n try {\n return await run;\n } finally {\n loginsInFlight.delete(run);\n }\n }\n\n /**\n * The body of `login()`, tracked in `loginsInFlight` by its caller so a\n * tokenless `401` during the sign-in waits for it and replays with the\n * token it installs, see `awaitLogins`. Tracking starts only after a\n * pending revocation settled.\n *\n * @param credentials - Sent as the login body.\n * @returns The user of the new session, or null.\n * @throws {SessionSupersededError} See `login()`.\n */\n async function signIn(credentials: TCredentials): Promise<TUser | null> {\n const started = epoch;\n const data = await trackCredentialRequest(\n api.post<unknown>(loginPath, {\n body: credentials,\n skipAuth: true,\n }),\n );\n const { token, refreshToken } = parseTokens(data);\n if (epoch !== started) {\n revokeDiscarded(token ?? null, refreshToken);\n throw new SessionSupersededError();\n }\n revokeDiscarded(getToken(), readRefreshToken() ?? undefined);\n const { done } = finish(\"switch\");\n const mine = epoch;\n await done.catch(() => undefined);\n if (epoch !== mine) throw new SessionSupersededError();\n writeLineage(newLineage());\n state().setToken(token);\n writeRefreshToken(refreshToken ?? null);\n const embedded = parseUser?.(data);\n if (embedded != null) {\n state().setUser(embedded);\n return embedded;\n }\n return fetchUser();\n }\n\n /**\n * End the current session, synchronously up to the hook.\n *\n * The epoch moves first, so a refresh resolving between here and the hook\n * is already superseded. The hook only runs when there was a session to\n * end — a token, a stored refresh token or a user — which is what keeps a\n * burst of `401`s from running it once per request.\n *\n * With nothing left to end, the caller waits on the teardown already under\n * way (`ending`, which never rejects, so a later no-op does not inherit an\n * old error). Two callers skip that wait while a hook is running, because\n * they may be the hook itself and would wait on their own teardown forever:\n * `endSession` — a hook awaiting `auth.api` goes out tokenless, gets a\n * `401`, and lands here — and a `logout()` with no session left. `login()`\n * (`\"switch\"`) always waits: the new account's state must not start while\n * the previous one's teardown is still clearing it. A hook awaiting\n * `auth.login()` therefore never settles — misuse the option documents.\n *\n * `\"expired\"` with nothing live leaves the epoch alone: there is nothing to\n * supersede but a refresh with no session behind it — the boot `refresh()`\n * restoring one from the cookie — and moving the epoch would throw that\n * away. `logout()` and `login()` always move it, since they must supersede\n * such a refresh.\n *\n * The returned `done` is a fresh promise derived from the hook, not the one\n * `ending` holds: a `logout()` nobody awaits still surfaces the hook's error\n * as an unhandled rejection instead of losing it.\n *\n * @param reason - Whether the caller signed out, the client gave up, or a\n * login replaced the session.\n * @returns Whether a live session ended here, and a promise settling with\n * the hook.\n */\n function finish(reason: TempestSessionEnd<TUser>[\"reason\"]): {\n live: boolean;\n done: Promise<void>;\n } {\n const { user, token } = state();\n const live = token !== null || user !== null || readRefreshToken() !== null;\n if (live || reason !== \"expired\") nextEpoch();\n state().logout();\n writeRefreshToken(null);\n writeLineage(null);\n if (!live) {\n const wait = reason === \"switch\" || hooksRunning === 0;\n return { live, done: wait ? ending : Promise.resolve() };\n }\n return { live, done: runSessionEnd({ reason, user, token, elsewhere: false }) };\n }\n\n /**\n * Run `onSessionEnd` for a session that just ended, tracked in `ending`\n * and `hooksRunning`.\n *\n * The returned promise is a fresh one derived from the hook, not the one\n * `ending` holds, so a caller that drops it still surfaces the hook's\n * error as an unhandled rejection instead of losing it.\n *\n * @param ended - What ended, minus the client, which is built here.\n * @returns A promise settling with the hook.\n */\n function runSessionEnd(ended: Omit<TempestSessionEnd<TUser>, \"api\">): Promise<void> {\n if (!onSessionEnd) return Promise.resolve();\n const sessionApi = endedSessionApi(ended.token);\n hooksRunning += 1;\n const run = (async () => {\n try {\n await onSessionEnd({ ...ended, api: sessionApi });\n } finally {\n hooksRunning -= 1;\n }\n })();\n ending = run.then(\n () => undefined,\n () => undefined,\n );\n return run.then(() => undefined);\n }\n\n /**\n * Read the session as the shared storage holds it: the persisted\n * `{ user, token }`, the stored refresh token and the session lineage.\n *\n * Read straight from storage rather than through\n * `useAuthStore.persist.rehydrate()`: a rehydration that finds no entry —\n * another tab ran `localStorage.clear()` — merges nothing and keeps the\n * session this tab holds, which is the stale session this exists to drop.\n * An entry that does not parse counts as no session.\n *\n * @returns The stored session, or null without storage (SSR).\n */\n function readSharedSession(): {\n user: TUser | null;\n token: string | null;\n refreshToken: string | null;\n lineage: string | null;\n } | null {\n const s = storageImpl();\n if (!s) return null;\n const refreshToken = s.getItem(refreshKey);\n const lineage = s.getItem(lineageKey);\n const raw = s.getItem(storeName);\n if (!raw) return { user: null, token: null, refreshToken, lineage };\n try {\n const parsed = JSON.parse(raw) as {\n state?: { user?: TUser | null; token?: string | null };\n };\n return {\n user: parsed.state?.user ?? null,\n token: parsed.state?.token ?? null,\n refreshToken,\n lineage,\n };\n } catch {\n return { user: null, token: null, refreshToken, lineage };\n }\n }\n\n /**\n * Catch up with what another tab wrote to the shared storage (#524).\n *\n * Every write this tab makes reaches the storage synchronously, so the\n * stored session differs from the held one only when another tab wrote\n * it. The stored one then wins, without redeeming or clearing anything:\n *\n * - a token of the same **lineage** — the identifier `login()` mints and\n * every rotation keeps — whether it is the same token (the other tab only\n * loaded the user) or a new one (it rotated): adopted, the session\n * continues;\n * - no token, or another lineage: the held session ended elsewhere. The\n * epoch moves, so nothing in flight from it can install tokens or end\n * the new session; the stored state is adopted; and `onSessionEnd` runs\n * with `elsewhere: true` — `\"logout\"` when no session is left,\n * `\"switch\"` when another sign-in is installed, even of the same user.\n *\n * Continuity used to be decided by comparing users, and two sessions whose\n * user had not loaded yet compared equal: a tab whose `login()` was still\n * waiting for `mePath` adopted another account's token as a rotation, and\n * its profile then persisted `{ user: A, token: B }` (#544). Requiring a\n * user would have closed that and turned every rotation of a session\n * without a user model into an account switch; the lineage answers the\n * actual question — is this the same sign-in — for both.\n *\n * A session persisted before lineages existed has none, on either side,\n * and keeps the old rule: the same token, or a token for the same user.\n * No `login()` of this version can produce that state, so a lineage-less\n * session can only have been rotated, never replaced.\n *\n * It never calls `finish()`: that clears the shared keys, which here would\n * erase the other tab's new session — and, with rotating refresh tokens,\n * sign every tab out whenever any tab rotates.\n *\n * The hook's error reaches only the callers that return `done`; the\n * automatic paths drop it.\n *\n * @returns Whether the held session continues, and a promise settling with\n * the hook when one ran.\n */\n function followSharedSession(): { continues: boolean; done: Promise<void> } {\n const shared = readSharedSession();\n const { user, token } = state();\n if (shared === null) return { continues: true, done: Promise.resolve() };\n const sameUser = JSON.stringify(shared.user) === JSON.stringify(user);\n if (\n shared.token === token &&\n shared.refreshToken === heldRefreshToken &&\n shared.lineage === heldLineage &&\n sameUser\n ) {\n return { continues: true, done: Promise.resolve() };\n }\n const sameSession =\n shared.lineage !== null || heldLineage !== null\n ? shared.lineage === heldLineage\n : shared.token === token || (token !== null && sameUser);\n const continues = shared.token !== null && sameSession;\n const live = token !== null || user !== null || heldRefreshToken !== null;\n if (!continues) nextEpoch();\n heldRefreshToken = shared.refreshToken;\n heldLineage = shared.lineage;\n useAuthStore.setState({\n user: shared.user,\n token: shared.token,\n isAuthenticated: shared.token !== null,\n });\n if (continues || !live) return { continues, done: Promise.resolve() };\n const reason = shared.token === null ? \"logout\" : \"switch\";\n const done = runSessionEnd({ reason, user, token, elsewhere: true });\n void done.catch(() => undefined);\n return { continues, done };\n }\n\n /**\n * Send the `logoutPath` revocation for the session about to end, with the\n * credentials it holds now — read before `finish` clears them.\n *\n * Skipped without `logoutPath`, and in body mode when there is nothing to\n * revoke; in cookie mode it always goes out, since the cookie it revokes is\n * invisible to the client. Never rejects.\n *\n * In cookie mode it first waits — at most\n * {@link LOGOUT_REVOCATION_WAIT_MS} — for the login and refresh responses\n * in flight right now: each one sets a cookie for the session this\n * `logout()` ends, and a revocation that left before it would leave that\n * cookie behind.\n *\n * @returns A promise settling when the revocation settled, or null when\n * none was sent.\n */\n function revoke(): Promise<void> | null {\n if (!logoutPath) return null;\n const path = logoutPath;\n const { token, user } = state();\n const refreshToken = readRefreshToken();\n if (!withCredentials && token === null && user === null && refreshToken === null) {\n return null;\n }\n const inFlight = withCredentials ? [...credentialRequests] : [];\n return trackRevocation(async () => {\n await settleWithin(inFlight, LOGOUT_REVOCATION_WAIT_MS);\n return endedSessionApi(token).post<unknown>(path, { body: refreshBody(refreshToken) });\n });\n }\n\n /**\n * End the session — unless another tab already did.\n *\n * A tab that has not caught up yet first follows the shared storage: when\n * the session it showed ended elsewhere, that is the whole sign-out. The\n * session live now belongs to another tab's sign-in, and revoking or\n * clearing it from here would sign that account out — before #524 it\n * also sent that account's refresh token to `logoutPath` next to the\n * ended account's bearer.\n *\n * @returns A promise settling with `onSessionEnd` and the revocation.\n */\n function logout(): Promise<void> {\n const followed = followSharedSession();\n if (!followed.continues) return followed.done;\n const revocation = revoke();\n const { done } = finish(\"logout\");\n if (!revocation) return done;\n return Promise.all([revocation, done]).then(() => undefined);\n }\n\n /**\n * End the session after the client gave up on it and, when `redirectTo`\n * is set, leave the page once `onSessionEnd` settled.\n *\n * Separate from `logout` so an explicit sign-out stays a pure state change:\n * a caller that already navigates itself would otherwise get a second,\n * competing navigation. The hook is awaited before navigating because a\n * hard navigation aborts whatever request it still had in flight. Only the\n * call that ended a live session navigates; the rest of a burst of `401`s\n * waits on the same teardown, or returns at once inside a hook.\n */\n async function endSession(): Promise<void> {\n const { live, done } = finish(\"expired\");\n await done.catch(() => undefined);\n if (live && redirectTo && typeof window !== \"undefined\") {\n window.location.assign(redirectTo);\n }\n }\n\n const api = createApiClient({\n baseURL,\n prefix,\n withCredentials,\n csrf,\n fetcher,\n getToken,\n getSessionEpoch: () => epoch,\n refresh: refreshFor,\n retry,\n onUnauthorized,\n });\n\n const refresh = (): Promise<void> => queue();\n\n /**\n * Read from the store's token and the held lineage. Both move before the\n * store notifies: `login()` writes the lineage before installing the\n * token, `finish()` clears the token in the notifying `logout()` call and\n * the lineage only after — which the token check already reads as `null` —\n * and following another tab updates the held lineage before `setState`.\n * So every store listener sees the key of the state it is told about.\n *\n * A session persisted before lineages existed has no lineage to read.\n * Writing one for it would make every other tab holding the same session\n * see another lineage — an account switch — so its key is minted here, in\n * memory, once per epoch: the epoch moves whenever the session ends or is\n * replaced and never on a rotation, which is exactly the lifetime a\n * session key needs. A reload mints another, so an upload bound to such a\n * session starts over instead of resuming; the next `login()` gives it a\n * lineage and that cost goes away.\n */\n let unlineaged: { epoch: number; key: string } | null = null;\n const sessionKey = (): string | null => {\n if (getToken() === null) return null;\n if (heldLineage !== null) return heldLineage;\n if (unlineaged?.epoch !== epoch) unlineaged = { epoch, key: newLineage() };\n return unlineaged.key;\n };\n const identity: SessionIdentity = {\n current: sessionKey,\n subscribe: (listener) => useAuthStore.subscribe(listener),\n };\n bindSessionIdentity(api, identity);\n bindSessionIdentity(getToken, identity);\n\n /**\n * Follow a write another tab made to this session's keys. The browser\n * fires `storage` only in the tabs that did not write; `key` is null when\n * the other tab cleared the whole storage.\n *\n * @param event - The storage event.\n */\n function onStorage(event: StorageEvent): void {\n if (event.storageArea !== storageImpl()) return;\n if (\n event.key !== null &&\n event.key !== storeName &&\n event.key !== refreshKey &&\n event.key !== lineageKey\n ) {\n return;\n }\n followSharedSession();\n }\n\n const host = typeof window === \"undefined\" ? null : window;\n host?.addEventListener(\"storage\", onStorage);\n const dispose = (): void => host?.removeEventListener(\"storage\", onStorage);\n\n return { useAuthStore, api, login, logout, refresh, getToken, sessionKey, dispose };\n}\n"],"mappings":"A,uNAuSA,IAAMW,EAA4B,IAU5BC,EAAuB,IAS7B,SAASC,EAAa,EAAsC,EAA2B,CAEnF,OADIC,EAAQ,SAAW,EAAU,QAAQ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