diff --git a/recipes/session-owners/cookie-session-owner.ts b/recipes/session-owners/cookie-session-owner.ts new file mode 100644 index 00000000..ca602495 --- /dev/null +++ b/recipes/session-owners/cookie-session-owner.ts @@ -0,0 +1,199 @@ +import type { ExternalSessionOwner } from "../../src/adapters/auth/index.ts"; +import type { CredentialPatchOutcome } from "../../src/adapters/http/index.ts"; +import type { SessionState } from "../../src/application/ports/auth-session-port.ts"; +import type { + ProductCredentialProvider, + SessionOwnerFetch, +} from "../../src/bootstrap/product-composition-contract.ts"; +import type { RestAuthProfile } from "../../src/contracts/rest-profiles.ts"; + +/** + * 1103/09-03. A session owner and CSRF credential providers for the paired + * backend's Redis session mode (`APP_SECURITY_AUTH_MODE=redis-session`). The + * backend's filter chain (`SecurityConfig` in its inbound web adapter) gives: + * + * - the session as an httpOnly, Secure, SameSite=Lax cookie (`CA_SESSION`), + * which the browser sends and script never reads; + * - Spring's `CookieCsrfTokenRepository`: a readable `XSRF-TOKEN` cookie whose + * value goes back unchanged (plain, not XOR-masked) in `X-XSRF-TOKEN` on + * every state-changing request. + * + * It gives no endpoint to sign in, sign out or ask who is signed in; its + * tests use fixture controllers. Those three are the product's, so this owner + * takes their URLs and the sign-in start with no defaults. The session + * endpoint must read the CSRF token (in Spring, `CsrfToken.getToken()`), since + * the deferred token sets no cookie until something reads it. + * + * The `XSRF-TOKEN` cookie is readable only on the API's host, so the page + * and the API share a host: same origin behind one proxy, or `localhost` on + * two ports in development. + * + * State transitions follow `SessionState` in + * `src/application/ports/auth-session-port.ts`. The cookie is the credential + * and the server is the judge: a server 401 signs out, and nothing is + * refreshed here. + * + * Copy this file into `src/bootstrap/`, the profiles into + * `PRODUCT_REST_AUTH_PROFILES` and the providers into `credentialProviders`; + * `docs/manual/04-paired-backend-session.md` shows the wiring. + */ + +const cookieProfile = ( + authProfileId: string, + headers: readonly ("x-xsrf-token" | "x-csrf-token")[], +): RestAuthProfile => + Object.freeze({ + authProfileId, + transport: "SAME_ORIGIN_COOKIE", + // `include`, not `same-origin`: development serves the page and the API + // from two ports of `localhost`, which is same-site but cross-origin. + credentials: "include", + allowedCredentialHeaders: Object.freeze([...headers]), + requiredCredentialHeaders: Object.freeze([...headers]), + }); + +/** + * Reads go with the cookie alone; writes must carry the CSRF header, and the + * executor sends nothing without it. Header names are the backend's default + * (`APP_SESSION_CSRF_HEADER_NAME`). + */ +export const SESSION_COOKIE_AUTH_PROFILES = Object.freeze({ + SESSION_COOKIE_READ: cookieProfile("SESSION_COOKIE_READ", []), + SESSION_COOKIE_WRITE: cookieProfile("SESSION_COOKIE_WRITE", ["x-xsrf-token"]), +} satisfies Readonly>); + +/** The backend's defaults (`APP_SESSION_CSRF_COOKIE_NAME`, `..._HEADER_NAME`). */ +const CSRF_COOKIE = "XSRF-TOKEN"; +const CSRF_HEADER = "x-xsrf-token"; +const MAX_SUBJECT_LENGTH = 255; + +export type CookieSessionOwnerOptions = Readonly<{ + /** The product's GET endpoint: 200 when signed in (body read by `subjectFrom`), 401 when not. */ + sessionUrl: string; + /** The opaque, stable id of who is signed in, from the 200 body; `null` for nobody. */ + subjectFrom(body: unknown): string | null; + /** The product's POST endpoint that ends the session. */ + signOutUrl: string; + /** Starts the product's sign-in: its login page, or a Spring `oauth2Login` redirect. */ + beginSignIn(returnTo?: string): Promise; + fetch: SessionOwnerFetch; + readCookie(name: string): string | undefined; + csrfCookieName?: string; +}>; + +export function createCookieSessionOwner( + options: CookieSessionOwnerOptions, +): ExternalSessionOwner { + let state: SessionState = "recovery-pending"; + let subject: string | null = null; + let probing: Promise<"restored" | "no-session"> | null = null; + const listeners = new Set<() => void>(); + + function publish(nextState: SessionState, nextSubject: string | null): void { + if (nextState === state && nextSubject === subject) return; + state = nextState; + subject = nextSubject; + for (const listener of [...listeners]) { + try { + listener(); + } catch { + // One subscriber cannot stop the others hearing the change. + } + } + } + + /** Who is signed in, asked of the server; one question at a time. */ + function probe(): Promise<"restored" | "no-session"> { + probing ??= (async () => { + // A rejection here (network, timeout, a body over the cap) leaves the + // state as it is, so a recovering session can be retried. + const response = await options.fetch(options.sessionUrl, { + method: "GET", + credentials: "include", + headers: { accept: "application/json" }, + }); + if (response.status === 401) { + publish("unauthenticated", null); + return "no-session" as const; + } + if (response.status !== 200) { + throw new Error(`The session endpoint answered ${response.status}.`); + } + const named = options.subjectFrom(await response.json()); + if (typeof named !== "string" || named.length === 0 || named.length > MAX_SUBJECT_LENGTH) { + publish("unauthenticated", null); + return "no-session" as const; + } + publish("authenticated", named); + return "restored" as const; + })().finally(() => { + probing = null; + }); + return probing; + } + + void probe().catch(() => { + // Unreachable at boot: stay recovering, and the user can retry. + }); + + return Object.freeze({ + readState: () => state, + readSubject: () => (state === "authenticated" ? subject : null), + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + beginSignIn: (returnTo?: string) => options.beginSignIn(returnTo), + async signOut() { + const token = options.readCookie(options.csrfCookieName ?? CSRF_COOKIE); + const response = await options.fetch(options.signOutUrl, { + method: "POST", + credentials: "include", + headers: token === undefined ? {} : { [CSRF_HEADER]: token }, + }); + // 401: already gone. Anything else but success leaves the server session + // alive, so this page must not claim it ended. + if (!response.ok && response.status !== 401) { + throw new Error(`The sign-out endpoint answered ${response.status}.`); + } + publish("unauthenticated", null); + }, + async attachCredential() { + throw new TypeError( + "A cookie session sends no bearer header; give the operation a SESSION_COOKIE_* profile.", + ); + }, + recoverSession: probe, + notifyUnauthenticated() { + publish("unauthenticated", null); + }, + }); +} + +/** + * The providers for `SESSION_COOKIE_AUTH_PROFILES`. They read the CSRF cookie + * when the request goes, since the backend may issue a new one at any answer. + * They do not ask the session state: the cookie is the proof and the server + * decides, and its 401 reaches the owner. + */ +export function createSessionCookieCredentialProviders( + options: Readonly<{ + readCookie(name: string): string | undefined; + csrfCookieName?: string; + }>, +): Readonly> { + const ready = (headers: Readonly>): CredentialPatchOutcome => + Object.freeze({ kind: "READY" as const, headers: Object.freeze(headers) }); + return Object.freeze({ + SESSION_COOKIE_READ: async () => ready({}), + SESSION_COOKIE_WRITE: async () => { + const token = options.readCookie(options.csrfCookieName ?? CSRF_COOKIE); + // Without it Spring answers 403; fail closed with nothing sent. + return token === undefined || token.length === 0 + ? Object.freeze({ kind: "UNAVAILABLE" as const }) + : ready({ [CSRF_HEADER]: token }); + }, + }); +} diff --git a/recipes/session-owners/oidc-pkce-session-owner.ts b/recipes/session-owners/oidc-pkce-session-owner.ts new file mode 100644 index 00000000..72301076 --- /dev/null +++ b/recipes/session-owners/oidc-pkce-session-owner.ts @@ -0,0 +1,651 @@ +import type { ExternalSessionOwner } from "../../src/adapters/auth/index.ts"; +import type { + CredentialPatch, + SessionState, +} from "../../src/application/ports/auth-session-port.ts"; +import type { + ProductSessionOwnerContext, + ProductSessionOwnerPage, + SessionOwnerFetch, +} from "../../src/bootstrap/product-composition-contract.ts"; + +/** + * 1103/09-03. A session owner for the paired backend's JWT mode + * (`APP_SECURITY_AUTH_MODE=jwt`, the default): a Spring resource server that + * accepts a Keycloak access token whose `iss` is `APP_SECURITY_JWT_ISSUER` and + * whose `aud` names `APP_SECURITY_JWT_AUDIENCE`. Operations keep the + * template's `EXTERNAL_BEARER` profile. + * + * The owner signs in with the OAuth 2.0 authorization code flow and PKCE + * (S256) against a public client, with WebCrypto and the context's bounded + * fetch; there is no library. + * + * - Tokens live in memory only. A reload signs out; a Keycloak SSO session + * makes the next sign-in a redirect without a password. + * - `redirectStorage` (sessionStorage) holds one sign-in transaction — the + * PKCE verifier, `state`, `nonce` and the return path — for at most ten + * minutes, and the callback deletes it before anything else. + * - The bearer goes only to `apiOrigins`. + * - The ID token's claims are checked, not its signature: it comes straight + * from the token endpoint over the context's fetch (OIDC Core 3.1.3.7 (6)). + * The backend verifies the access token's signature. + * + * State transitions follow `SessionState` in + * `src/application/ports/auth-session-port.ts`. + * + * The backend's realm (`infra/keycloak/realms/ca-skeleton-realm.json` there) + * has only a confidential service client; a product registers the public + * client this owner signs in with. Copy this file into `src/bootstrap/` and + * return it from `composeProductSessionOwner`; `docs/manual/04-paired-backend-session.md` + * shows the realm client and the wiring. + */ + +/** `buildPhysicalKey("auth", 1, "oidc-pkce-transaction")`; never a token. */ +export const OIDC_PKCE_TRANSACTION_KEY = "ca-frontend:auth:v1:oidc-pkce-transaction"; + +export type OidcPkceSessionOwnerOptions = Readonly<{ + /** Exact issuer, e.g. `http://localhost:8081/realms/ca-skeleton`. HTTPS off this machine. */ + issuer: string; + /** The public client (standard flow, PKCE S256) registered for this app. */ + clientId: string; + /** + * The app's base URL, origin plus router base path, registered as the + * client's redirect URI. The sign-in returns here and the owner then + * replaces the URL with the return path under this base. + */ + redirectUri: string; + /** Default `openid`. */ + scope?: string; + /** Origins the bearer may go to: normally `new URL(API_BASE_URL).origin`. */ + apiOrigins: readonly string[]; + /** Registered post-logout redirect URI; without it sign-out stays local. */ + postLogoutRedirectUri?: string; + fetch: SessionOwnerFetch; + page: ProductSessionOwnerPage; + redirectStorage: ProductSessionOwnerContext["redirectStorage"]; + /** Defaults to the page's WebCrypto. */ + crypto?: Readonly<{ + getRandomValues(array: Uint8Array): Uint8Array; + subtle: Pick; + }>; + /** Epoch milliseconds. */ + now?: () => number; + /** Refresh this long before the access token expires. Default 30 s. */ + refreshLeewayMs?: number; +}>; + +const TRANSACTION_TTL_MS = 10 * 60_000; +const MAX_SUBJECT_LENGTH = 255; +/** RFC 6750 b64token, and short enough for the 8 KiB credential header cap. */ +const TOKEN_PATTERN = /^[A-Za-z0-9\-._~+/]+=*$/u; +const MAX_TOKEN_LENGTH = 8_000; +/** Authorization response parameters; anything else in the query is the app's. */ +const CALLBACK_PARAMETERS = [ + "code", + "state", + "iss", + "session_state", + "error", + "error_description", + "error_uri", +] as const; + +type Endpoints = Readonly<{ + authorization: string; + token: string; + endSession?: string; +}>; + +type Transaction = Readonly<{ + state: string; + nonce: string; + verifier: string; + returnTo: string; + createdAt: number; +}>; + +type Tokens = Readonly<{ + accessToken: string; + expiresAt: number; + refreshToken?: string; +}>; + +/** `definitive`: the IdP said no; anything else could answer differently later. */ +class OwnerFailure extends Error { + constructor( + message: string, + readonly definitive: boolean, + ) { + super(message); + } +} + +const isRecord = (value: unknown): value is Record => + Boolean(value) && typeof value === "object" && !Array.isArray(value); + +function isLoopback(url: URL): boolean { + return ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); +} + +/** HTTPS, or HTTP on this machine for local Keycloak. */ +function endpointUrl(value: unknown): URL | null { + if (typeof value !== "string") return null; + try { + const url = new URL(value); + const secure = + url.protocol === "https:" || (url.protocol === "http:" && isLoopback(url)); + return secure && url.username === "" && url.password === "" && url.hash === "" + ? url + : null; + } catch { + return null; + } +} + +function base64Url(bytes: Uint8Array): string { + let binary = ""; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, ""); +} + +function claimsOf(token: string): Record | null { + const payload = token.split(".")[1]; + if (payload === undefined || token.split(".").length !== 3) return null; + try { + const base64 = payload.replaceAll("-", "+").replaceAll("_", "/"); + const binary = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")); + const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0)); + const claims: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); + return isRecord(claims) ? claims : null; + } catch { + return null; + } +} + +/** A path of this app: one leading slash, no scheme, no host, no control character. */ +function appPath(value: unknown): string | null { + return typeof value === "string" && + value.length <= 2_048 && + /^\/(?![/\\])/u.test(value) && + !value.includes("\\") && + ![...value].some((character) => { + const code = character.charCodeAt(0); + return code < 0x20 || code === 0x7f; + }) + ? value + : null; +} + +function readTransaction( + storage: OidcPkceSessionOwnerOptions["redirectStorage"], +): Transaction | null { + try { + const raw = storage?.getItem(OIDC_PKCE_TRANSACTION_KEY); + if (!raw) return null; + const value: unknown = JSON.parse(raw); + if ( + !isRecord(value) || + value.v !== 1 || + typeof value.state !== "string" || + typeof value.nonce !== "string" || + typeof value.verifier !== "string" || + typeof value.createdAt !== "number" || + appPath(value.returnTo) === null + ) { + return null; + } + return value as unknown as Transaction; + } catch { + return null; + } +} + +/** The same owner shape, closed: nothing can sign in. */ +function misconfiguredOwner(): ExternalSessionOwner { + return Object.freeze({ + readState: () => "integration-failed" as const, + readSubject: () => null, + subscribe: () => () => {}, + beginSignIn: async () => { + throw new TypeError("The OIDC session owner is misconfigured."); + }, + signOut: async () => {}, + attachCredential: async () => { + throw new TypeError("The OIDC session owner is misconfigured."); + }, + recoverSession: async () => "no-session" as const, + notifyUnauthenticated: () => {}, + }); +} + +export function createOidcPkceSessionOwner( + options: OidcPkceSessionOwnerOptions, +): ExternalSessionOwner { + const issuer = endpointUrl(options.issuer); + const redirect = endpointUrl(options.redirectUri); + const apiOrigins = new Set(options.apiOrigins); + const storage = options.redirectStorage; + if ( + issuer === null || + issuer.search !== "" || + redirect === null || + options.clientId.length === 0 || + storage === undefined || + apiOrigins.size === 0 || + [...apiOrigins].some((origin) => endpointUrl(origin)?.origin !== origin) + ) { + return misconfiguredOwner(); + } + const issuerId = options.issuer; + const clientId = options.clientId; + const crypto: NonNullable = + options.crypto ?? globalThis.crypto; + const now = options.now ?? Date.now; + const leewayMs = options.refreshLeewayMs ?? 30_000; + const basePath = redirect.pathname.replace(/\/$/u, ""); + + let state: SessionState = "unauthenticated"; + let subject: string | null = null; + /** Who signed in, kept while a 401 recovers: a refresh must give the same one back. */ + let lastSubject: string | null = null; + let tokens: Tokens | null = null; + /** Set by a 401's automatic refresh; a second 401 then signs out. */ + let refreshedAfter401 = false; + let discovery: Promise | null = null; + let refreshing: Promise | null = null; + let recovering: Promise<"restored" | "no-session"> | null = null; + const listeners = new Set<() => void>(); + + function publish(nextState: SessionState, nextSubject: string | null): void { + if (nextState === state && nextSubject === subject) return; + state = nextState; + subject = nextSubject; + for (const listener of [...listeners]) { + try { + listener(); + } catch { + // One subscriber cannot stop the others hearing the change. + } + } + } + + function signedOut(): void { + tokens = null; + lastSubject = null; + refreshedAfter401 = false; + publish("unauthenticated", null); + } + + async function readJson(response: Response): Promise> { + const type = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase(); + if (type !== "application/json") { + throw new OwnerFailure("The identity provider did not answer JSON.", true); + } + try { + const value: unknown = await response.json(); + if (isRecord(value)) return value; + } catch { + // Falls through to the same refusal. + } + throw new OwnerFailure("The identity provider answered malformed JSON.", true); + } + + async function send(url: string, init: Parameters[1]): Promise { + try { + return await options.fetch(url, { credentials: "omit", ...init }); + } catch (error) { + // A body over the cap is the IdP misbehaving, not the network. + throw new OwnerFailure("The identity provider could not be reached.", error instanceof RangeError); + } + } + + function discover(): Promise { + discovery ??= (async () => { + const response = await send( + `${issuerId.replace(/\/$/u, "")}/.well-known/openid-configuration`, + { method: "GET", headers: { accept: "application/json" } }, + ); + if (!response.ok) { + throw new OwnerFailure("OIDC discovery failed.", response.status < 500); + } + const document = await readJson(response); + const authorization = endpointUrl(document.authorization_endpoint); + const token = endpointUrl(document.token_endpoint); + const endSession = endpointUrl(document.end_session_endpoint); + // OIDC Discovery 4.3: the document must name exactly this issuer. + if (document.issuer !== issuerId || authorization === null || token === null) { + throw new OwnerFailure("OIDC discovery named another issuer.", true); + } + return Object.freeze({ + authorization: authorization.href, + token: token.href, + ...(endSession === null ? {} : { endSession: endSession.href }), + }); + })(); + discovery.catch(() => { + discovery = null; + }); + return discovery; + } + + /** Token endpoint call; the answer is checked before anything is kept. */ + async function requestTokens( + form: Readonly>, + expected: Readonly<{ nonce?: string; subject?: string }>, + ): Promise> { + const endpoints = await discover(); + const response = await send(endpoints.token, { + method: "POST", + headers: { accept: "application/json" }, + body: new URLSearchParams(form), + }); + if (!response.ok) { + // 400 invalid_grant / 401 invalid_client: this grant will never work. + throw new OwnerFailure("The identity provider refused the grant.", response.status < 500); + } + const body = await readJson(response); + const accessToken = body.access_token; + const refreshToken = body.refresh_token; + const expiresIn = body.expires_in; + if ( + typeof accessToken !== "string" || + accessToken.length > MAX_TOKEN_LENGTH || + !TOKEN_PATTERN.test(accessToken) || + typeof body.token_type !== "string" || + body.token_type.toLowerCase() !== "bearer" || + typeof expiresIn !== "number" || + !Number.isFinite(expiresIn) || + expiresIn <= 0 || + (refreshToken !== undefined && + (typeof refreshToken !== "string" || refreshToken.length === 0)) + ) { + throw new OwnerFailure("The token response is not a bearer token.", true); + } + const idSubject = checkIdToken(body.id_token, expected); + const nextSubject = idSubject ?? expected.subject; + if (nextSubject === undefined) { + throw new OwnerFailure("The token response names nobody.", true); + } + return { + subject: nextSubject, + tokens: Object.freeze({ + accessToken, + expiresAt: now() + expiresIn * 1_000, + ...(typeof refreshToken === "string" ? { refreshToken } : {}), + }), + }; + } + + /** OIDC Core 3.1.3.7 and 12.2, without the signature (see the file comment). */ + function checkIdToken( + idToken: unknown, + expected: Readonly<{ nonce?: string; subject?: string }>, + ): string | undefined { + if (idToken === undefined && expected.nonce === undefined) return undefined; + const claims = typeof idToken === "string" ? claimsOf(idToken) : null; + const audience = claims?.aud; + const sub = claims?.sub; + if ( + claims === null || + claims.iss !== issuerId || + !(audience === clientId || (Array.isArray(audience) && audience.includes(clientId))) || + (claims.azp !== undefined && claims.azp !== clientId) || + typeof claims.exp !== "number" || + claims.exp * 1_000 <= now() || + typeof sub !== "string" || + sub.length === 0 || + sub.length > MAX_SUBJECT_LENGTH || + (expected.nonce !== undefined && claims.nonce !== expected.nonce) || + (expected.subject !== undefined && sub !== expected.subject) + ) { + throw new OwnerFailure("The ID token is not for this sign-in.", true); + } + return sub; + } + + /** One refresh at a time; every caller waits for the same one. */ + function refresh(): Promise { + refreshing ??= (async () => { + const refreshToken = tokens?.refreshToken; + const expectedSubject = lastSubject; + if (refreshToken === undefined || expectedSubject === null) { + throw new OwnerFailure("There is no session to refresh.", true); + } + const answer = await requestTokens( + { grant_type: "refresh_token", refresh_token: refreshToken, client_id: clientId }, + { subject: expectedSubject }, + ); + tokens = Object.freeze({ + ...answer.tokens, + // Keycloak may rotate the refresh token; without a new one the old one stays. + ...(answer.tokens.refreshToken === undefined ? { refreshToken } : {}), + }); + lastSubject = answer.subject; + publish("authenticated", answer.subject); + })().finally(() => { + refreshing = null; + }); + return refreshing; + } + + function recover(): Promise<"restored" | "no-session"> { + recovering ??= (async () => { + try { + await refresh(); + return "restored" as const; + } catch (error) { + if (error instanceof OwnerFailure && error.definitive) { + signedOut(); + return "no-session" as const; + } + throw error; + } + })().finally(() => { + recovering = null; + }); + return recovering; + } + + /** The page load that returns from the IdP. Synchronous up to the exchange. */ + function completeSignIn(): void { + let url: URL; + try { + url = new URL(options.page.href()); + } catch { + return; + } + const params = url.searchParams; + const atRedirect = + url.origin === redirect!.origin && + url.pathname.replace(/\/$/u, "") === basePath; + if (!atRedirect || !params.has("state") || !(params.has("code") || params.has("error"))) { + return; + } + const transaction = readTransaction(storage); + try { + storage?.removeItem(OIDC_PKCE_TRANSACTION_KEY); + } catch { + // A transaction that cannot be removed is still never used twice here. + } + const code = params.get("code"); + const valid = + transaction !== null && + code !== null && + params.get("state") === transaction.state && + !params.has("error") && + // RFC 9207: a response from another issuer is a mix-up, not a sign-in. + (!params.has("iss") || params.get("iss") === issuerId) && + now() - transaction.createdAt <= TRANSACTION_TTL_MS && + now() >= transaction.createdAt; + // The code leaves the URL before any network call, so a reload or a copied + // address cannot replay it. + if (transaction !== null) { + options.page.replaceUrl(`${basePath}${transaction.returnTo}`); + } else { + for (const name of CALLBACK_PARAMETERS) params.delete(name); + options.page.replaceUrl(`${url.pathname}${url.search}${url.hash}`); + } + if (!valid || code === null || transaction === null) return; + state = "recovery-pending"; + recovering = (async () => { + try { + const answer = await requestTokens( + { + grant_type: "authorization_code", + code, + redirect_uri: options.redirectUri, + client_id: clientId, + code_verifier: transaction.verifier, + }, + { nonce: transaction.nonce }, + ); + tokens = answer.tokens; + lastSubject = answer.subject; + refreshedAfter401 = false; + publish("authenticated", answer.subject); + return "restored" as const; + } catch { + // The code is single-use and the verifier is gone: nothing to retry. + signedOut(); + return "no-session" as const; + } + })().finally(() => { + recovering = null; + }); + } + + completeSignIn(); + + return Object.freeze({ + readState: () => state, + readSubject: () => (state === "authenticated" ? subject : null), + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + async beginSignIn(returnTo?: string) { + const endpoints = await discover(); + const random = (size: number) => base64Url(crypto.getRandomValues(new Uint8Array(size))); + const verifier = random(32); + const transaction = { + v: 1, + state: random(16), + nonce: random(16), + verifier, + returnTo: appPath(returnTo) ?? "/", + createdAt: now(), + }; + const challenge = base64Url( + new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))), + ); + storage.setItem(OIDC_PKCE_TRANSACTION_KEY, JSON.stringify(transaction)); + const authorize = new URL(endpoints.authorization); + for (const [name, value] of [ + ["response_type", "code"], + ["client_id", clientId], + ["redirect_uri", options.redirectUri], + ["scope", options.scope ?? "openid"], + ["state", transaction.state], + ["nonce", transaction.nonce], + ["code_challenge", challenge], + ["code_challenge_method", "S256"], + ] as const) { + authorize.searchParams.set(name, value); + } + options.page.assign(authorize.href); + }, + async signOut() { + // Local first: the tokens are gone even if the IdP never answers. + signedOut(); + try { + storage.removeItem(OIDC_PKCE_TRANSACTION_KEY); + } catch { + // Nothing of the session is in it once the tokens are gone. + } + if (options.postLogoutRedirectUri === undefined) return; + const endSession = await discover().then( + (endpoints) => endpoints.endSession, + () => undefined, + ); + if (endSession === undefined) return; + // No `id_token_hint`: an ID token does not belong in a URL. Keycloak then + // asks the user to confirm the sign-out. + const logout = new URL(endSession); + logout.searchParams.set("client_id", clientId); + logout.searchParams.set("post_logout_redirect_uri", options.postLogoutRedirectUri); + options.page.assign(logout.href); + }, + async attachCredential(binding, context): Promise { + if (!apiOrigins.has(binding.origin)) { + throw new TypeError("The bearer token goes to the API origin only."); + } + if (state !== "authenticated" || tokens === null) { + throw new TypeError("Nobody is signed in."); + } + if (tokens.expiresAt - leewayMs <= now()) { + try { + await raceSignal(refresh(), context?.signal); + refreshedAfter401 = false; + } catch (error) { + if (error instanceof OwnerFailure && error.definitive) signedOut(); + // A refresh that could not be reached leaves a token still inside its life. + if (tokens === null || tokens.expiresAt <= now() || !(error instanceof OwnerFailure)) { + throw error; + } + } + } + if (tokens === null) throw new TypeError("Nobody is signed in."); + return Object.freeze({ + headers: Object.freeze({ authorization: `Bearer ${tokens.accessToken}` }), + }); + }, + recoverSession() { + if (recovering !== null) return recovering; + if (state === "authenticated" && tokens !== null && tokens.expiresAt - leewayMs > now()) { + return Promise.resolve("restored" as const); + } + if (tokens?.refreshToken === undefined) { + signedOut(); + return Promise.resolve("no-session" as const); + } + return recover(); + }, + notifyUnauthenticated() { + if (state !== "authenticated") return; + const refreshToken = tokens?.refreshToken; + if (refreshToken === undefined || refreshedAfter401) { + signedOut(); + return; + } + // The access token was refused; only the refresh token is worth keeping. + refreshedAfter401 = true; + tokens = Object.freeze({ accessToken: "", expiresAt: 0, refreshToken }); + publish("recovery-pending", null); + void recover().catch(() => { + // Unreachable IdP: stay recovering, and the user can retry. + }); + }, + }); +} + +/** Waits for `work`, or stops waiting when the request ends; `work` goes on. */ +function raceSignal(work: Promise, signal: AbortSignal | undefined): Promise { + if (signal === undefined) return work; + if (signal.aborted) return Promise.reject(new DOMException("Aborted", "AbortError")); + return new Promise((resolve, reject) => { + const onAbort = () => reject(new DOMException("Aborted", "AbortError")); + signal.addEventListener("abort", onAbort, { once: true }); + work.then( + (value) => { + signal.removeEventListener("abort", onAbort); + resolve(value); + }, + (error: unknown) => { + signal.removeEventListener("abort", onAbort); + reject(error); + }, + ); + }); +} diff --git a/scripts/check-optional-recipe-fixtures.ts b/scripts/check-optional-recipe-fixtures.ts index 6647ee0c..e2956a0d 100644 --- a/scripts/check-optional-recipe-fixtures.ts +++ b/scripts/check-optional-recipe-fixtures.ts @@ -148,7 +148,14 @@ const results = [ }, { id: "production-imports-recipe", - passed: ruleIds.has("PRODUCTION_IMPORTS_RECIPE"), + // 1103/09-03. Both recipe folders, one fixture each. + passed: ["bad.ts", "bad-session-owner.ts"].every((file) => + productionViolations.some( + (violation) => + violation.ruleId === "PRODUCTION_IMPORTS_RECIPE" && + violation.path.endsWith(`/src/${file}`), + ), + ), }, { id: "reference-runtime-not-composed", diff --git a/scripts/lib/optional-recipes.ts b/scripts/lib/optional-recipes.ts index 38244793..9434ad05 100644 --- a/scripts/lib/optional-recipes.ts +++ b/scripts/lib/optional-recipes.ts @@ -261,7 +261,10 @@ export async function scanOptionalRecipeSources( (path.basename(path.resolve(root)) === "src" && !relativeToRoot.startsWith(".."))) && imports.some((specifier) => - /(?:^|\/)recipes\/frontend-capabilities(?:\/|$)/.test(specifier), + // 1103/09-03. Session owner recipes are copied too, never imported. + /(?:^|\/)recipes\/(?:frontend-capabilities|session-owners)(?:\/|$)/.test( + specifier, + ), ) ) { violations.push({ ruleId: "PRODUCTION_IMPORTS_RECIPE", path: relative }); diff --git a/tests/fixtures/optional-recipes/forbidden/production-import/src/bad-session-owner.ts b/tests/fixtures/optional-recipes/forbidden/production-import/src/bad-session-owner.ts new file mode 100644 index 00000000..d9de6148 --- /dev/null +++ b/tests/fixtures/optional-recipes/forbidden/production-import/src/bad-session-owner.ts @@ -0,0 +1,3 @@ +import { createCookieSessionOwner } from "../../../../../../recipes/session-owners/cookie-session-owner.ts"; + +export const sessionOwnerRecipeInProduction = createCookieSessionOwner; diff --git a/tests/recipes/cookie-session-owner.test.ts b/tests/recipes/cookie-session-owner.test.ts new file mode 100644 index 00000000..00575f51 --- /dev/null +++ b/tests/recipes/cookie-session-owner.test.ts @@ -0,0 +1,241 @@ +import { describe, expect, it, vi } from "vitest"; + +import type { SessionOwnerFetch } from "../../src/bootstrap/product-composition-contract.ts"; +import { installRestAuthProfileRegistry } from "../../src/contracts/rest-profiles.ts"; +import { + createCookieSessionOwner, + createSessionCookieCredentialProviders, + SESSION_COOKIE_AUTH_PROFILES, + type CookieSessionOwnerOptions, +} from "../../recipes/session-owners/cookie-session-owner.ts"; + +/** + * 1103/09-03. The paired backend's Redis session mode + * (`APP_SECURITY_AUTH_MODE=redis-session`): an httpOnly `CA_SESSION` cookie, + * and Spring's `CookieCsrfTokenRepository` with the `XSRF-TOKEN` cookie and + * the `X-XSRF-TOKEN` header. The backend template ships no sign-in, sign-out + * or session endpoint, so their URLs are the product's and have no default. + */ + +const SESSION_URL = "http://localhost:8080/api/session"; +const SIGN_OUT_URL = "http://localhost:8080/api/session/sign-out"; + +/** The product's session endpoint answers the backend's Envelope. */ +const subjectFrom: CookieSessionOwnerOptions["subjectFrom"] = (body) => { + const data = (body as { data?: { subject?: unknown } } | null)?.data; + return typeof data?.subject === "string" ? data.subject : null; +}; + +function harness( + answers: Array<() => Response | Promise> = [], + cookie: Record = { "XSRF-TOKEN": "xsrf-1" }, +) { + const fetch = vi.fn(async (input) => { + const answer = answers.shift(); + if (!answer) throw new TypeError(`unexpected ${String(input)}`); + return answer(); + }); + const beginSignIn = vi.fn(async (_returnTo?: string) => {}); + const options: CookieSessionOwnerOptions = { + sessionUrl: SESSION_URL, + signOutUrl: SIGN_OUT_URL, + subjectFrom, + beginSignIn, + fetch, + readCookie: (name) => cookie[name], + }; + return { options, fetch, beginSignIn, answers, cookie }; +} + +const signedIn = (subject = "user-1") => () => + Response.json({ success: true, data: { subject } }); +const status = (code: number) => () => + Response.json({ success: false, error: { code: "AUTH" } }, { status: code }); + +describe("cookie session owner: state", () => { + it("asks the session endpoint at boot with the cookie and recovers until it answers", async () => { + const setup = harness([signedIn()]); + const owner = createCookieSessionOwner(setup.options); + + expect(owner.readState()).toBe("recovery-pending"); + await vi.waitFor(() => expect(owner.readState()).toBe("authenticated")); + expect(owner.readSubject()).toBe("user-1"); + expect(setup.fetch).toHaveBeenCalledWith(SESSION_URL, { + method: "GET", + credentials: "include", + headers: { accept: "application/json" }, + }); + }); + + it("is signed out when the session endpoint answers 401", async () => { + const setup = harness([status(401)]); + const owner = createCookieSessionOwner(setup.options); + + await vi.waitFor(() => expect(owner.readState()).toBe("unauthenticated")); + expect(owner.readSubject()).toBeNull(); + }); + + it("is signed out when the 200 names nobody", async () => { + const setup = harness([() => Response.json({ success: true, data: {} })]); + const owner = createCookieSessionOwner(setup.options); + + await vi.waitFor(() => expect(owner.readState()).toBe("unauthenticated")); + }); + + it("stays recovering when the endpoint cannot answer, and recovers on request", async () => { + const setup = harness([ + () => { + throw new DOMException("timed out", "TimeoutError"); + }, + status(503), + signedIn(), + ]); + const owner = createCookieSessionOwner(setup.options); + + // The first joins the boot probe, which times out; the second gets a 503. + await expect(owner.recoverSession()).rejects.toThrow("timed out"); + await expect(owner.recoverSession()).rejects.toThrow("503"); + expect(owner.readState()).toBe("recovery-pending"); + await expect(owner.recoverSession()).resolves.toBe("restored"); + expect(setup.fetch).toHaveBeenCalledTimes(3); + expect(owner.readState()).toBe("authenticated"); + }); + + it("answers no-session already signed out, never still recovering", async () => { + const setup = harness([status(401), status(401)]); + const owner = createCookieSessionOwner(setup.options); + await vi.waitFor(() => expect(owner.readState()).toBe("unauthenticated")); + + await expect(owner.recoverSession()).resolves.toBe("no-session"); + expect(owner.readState()).toBe("unauthenticated"); + }); + + it("shares one probe between boot and a recovery that starts meanwhile", async () => { + const setup = harness([signedIn()]); + const owner = createCookieSessionOwner(setup.options); + + await expect(owner.recoverSession()).resolves.toBe("restored"); + expect(setup.fetch).toHaveBeenCalledTimes(1); + }); + + it("signs out on a server 401 and notifies once per change", async () => { + const setup = harness([signedIn()]); + const owner = createCookieSessionOwner(setup.options); + await vi.waitFor(() => expect(owner.readState()).toBe("authenticated")); + const listener = vi.fn(); + owner.subscribe(listener); + + owner.notifyUnauthenticated(); + owner.notifyUnauthenticated(); + + expect(owner.readState()).toBe("unauthenticated"); + expect(listener).toHaveBeenCalledTimes(1); + }); + + it("refuses an over-long or empty subject", async () => { + const setup = harness([signedIn("x".repeat(256))]); + const owner = createCookieSessionOwner(setup.options); + + await vi.waitFor(() => expect(owner.readState()).toBe("unauthenticated")); + }); +}); + +describe("cookie session owner: sign-in, sign-out, credentials", () => { + it("hands sign-in to the product", async () => { + const setup = harness([status(401)]); + const owner = createCookieSessionOwner(setup.options); + + await owner.beginSignIn("/items"); + + expect(setup.beginSignIn).toHaveBeenCalledWith("/items"); + }); + + it("signs out with the CSRF header and is signed out after the server agrees", async () => { + const setup = harness([signedIn(), () => new Response(null, { status: 204 })]); + const owner = createCookieSessionOwner(setup.options); + await vi.waitFor(() => expect(owner.readState()).toBe("authenticated")); + + await owner.signOut(); + + expect(setup.fetch).toHaveBeenLastCalledWith(SIGN_OUT_URL, { + method: "POST", + credentials: "include", + headers: { "x-xsrf-token": "xsrf-1" }, + }); + expect(owner.readState()).toBe("unauthenticated"); + }); + + it("keeps the session when the server did not sign it out", async () => { + const setup = harness([signedIn(), status(403)]); + const owner = createCookieSessionOwner(setup.options); + await vi.waitFor(() => expect(owner.readState()).toBe("authenticated")); + + await expect(owner.signOut()).rejects.toThrow(); + expect(owner.readState()).toBe("authenticated"); + }); + + it("sends no bearer header: operations use the cookie profiles", async () => { + const setup = harness([signedIn()]); + const owner = createCookieSessionOwner(setup.options); + + await expect( + owner.attachCredential({ origin: "http://localhost:8080", method: "GET", operationId: "X" }), + ).rejects.toThrow("SESSION_COOKIE_"); + }); +}); + +describe("session cookie credential providers", () => { + const operation = (authProfileId: string, method = "POST") => + Object.freeze({ operationId: "WRITE", authProfileId, method }); + const context = Object.freeze({ + signal: new AbortController().signal, + deadlineAtMonotonicMs: 0, + }); + + it("installs as product auth profiles under the template's checks", () => { + const registry = installRestAuthProfileRegistry(SESSION_COOKIE_AUTH_PROFILES); + + expect(registry.get("SESSION_COOKIE_READ")).toMatchObject({ + transport: "SAME_ORIGIN_COOKIE", + credentials: "include", + requiredCredentialHeaders: [], + }); + expect(registry.get("SESSION_COOKIE_WRITE")).toMatchObject({ + transport: "SAME_ORIGIN_COOKIE", + credentials: "include", + allowedCredentialHeaders: ["x-xsrf-token"], + requiredCredentialHeaders: ["x-xsrf-token"], + }); + }); + + it("sends the XSRF-TOKEN cookie as X-XSRF-TOKEN on writes", async () => { + const providers = createSessionCookieCredentialProviders({ + readCookie: (name) => (name === "XSRF-TOKEN" ? "xsrf-1" : undefined), + }); + + await expect( + providers.SESSION_COOKIE_WRITE(operation("SESSION_COOKIE_WRITE"), context), + ).resolves.toEqual({ kind: "READY", headers: { "x-xsrf-token": "xsrf-1" } }); + await expect( + providers.SESSION_COOKIE_READ(operation("SESSION_COOKIE_READ", "GET"), context), + ).resolves.toEqual({ kind: "READY", headers: {} }); + }); + + it("fails a write closed without the cookie, so nothing is sent", async () => { + const providers = createSessionCookieCredentialProviders({ readCookie: () => undefined }); + + await expect( + providers.SESSION_COOKIE_WRITE(operation("SESSION_COOKIE_WRITE"), context), + ).resolves.toEqual({ kind: "UNAVAILABLE" }); + }); + + it("reads the cookie when the request goes, not when composed", async () => { + let token: string | undefined; + const providers = createSessionCookieCredentialProviders({ readCookie: () => token }); + token = "xsrf-2"; + + await expect( + providers.SESSION_COOKIE_WRITE(operation("SESSION_COOKIE_WRITE"), context), + ).resolves.toEqual({ kind: "READY", headers: { "x-xsrf-token": "xsrf-2" } }); + }); +}); diff --git a/tests/recipes/oidc-pkce-session-owner.test.ts b/tests/recipes/oidc-pkce-session-owner.test.ts new file mode 100644 index 00000000..d05a2610 --- /dev/null +++ b/tests/recipes/oidc-pkce-session-owner.test.ts @@ -0,0 +1,503 @@ +import { createHash } from "node:crypto"; + +import { describe, expect, it, vi } from "vitest"; + +import type { SessionOwnerFetch } from "../../src/bootstrap/product-composition-contract.ts"; +import { + createOidcPkceSessionOwner, + OIDC_PKCE_TRANSACTION_KEY, + type OidcPkceSessionOwnerOptions, +} from "../../recipes/session-owners/oidc-pkce-session-owner.ts"; + +/** + * 1103/09-03. The paired backend's JWT mode: a Spring resource server that + * checks a Keycloak access token's issuer and audience. This owner gets that + * token in the browser with the authorization code flow and PKCE, keeps it in + * memory only, and follows the session state contract on `SessionState`. + */ + +// The backend's local issuer (application-local.yml, APP_SECURITY_JWT_ISSUER). +const ISSUER = "http://localhost:8081/realms/ca-skeleton"; +const CLIENT_ID = "ca-frontend"; +const APP = "http://localhost:5173"; +const API_ORIGIN = "http://localhost:8080"; +const AUTHORIZE = `${ISSUER}/protocol/openid-connect/auth`; +const TOKEN = `${ISSUER}/protocol/openid-connect/token`; +const END_SESSION = `${ISSUER}/protocol/openid-connect/logout`; + +const encode = (value: unknown) => + Buffer.from(JSON.stringify(value)).toString("base64url"); +/** The owner reads claims; it does not verify the signature (OIDC Core 3.1.3.7 (6)). */ +const jwt = (claims: Record) => + `${encode({ alg: "RS256", typ: "JWT" })}.${encode(claims)}.signature`; + +type Call = Readonly<{ url: string; init: Parameters[1] }>; + +function harness( + overrides: Partial = {}, + setup: Readonly<{ href?: string; storage?: Record }> = {}, +) { + let now = Date.parse("2026-11-04T00:00:00Z"); + let href = setup.href ?? `${APP}/`; + const storage = new Map(Object.entries(setup.storage ?? {})); + const calls: Call[] = []; + const tokenAnswers: Array<() => Response | Promise> = []; + let tokenCounter = 0; + // The nonce of the sign-in this page load returns from, as Keycloak echoes it. + const nonce = (() => { + try { + return (JSON.parse(storage.get(OIDC_PKCE_TRANSACTION_KEY) ?? "null") as { nonce?: string } | null) + ?.nonce; + } catch { + return undefined; + } + })(); + const idToken = (claims: Record = {}) => + jwt({ + iss: ISSUER, + aud: CLIENT_ID, + sub: "user-1", + exp: Math.floor(now / 1000) + 300, + ...(nonce === undefined ? {} : { nonce }), + ...claims, + }); + /** A token response as Keycloak sends one. */ + const tokens = ( + fields: Record = {}, + claims: Record = {}, + ) => { + tokenCounter += 1; + return Response.json({ + access_token: `access-${tokenCounter}`, + token_type: "Bearer", + expires_in: 300, + refresh_token: `refresh-${tokenCounter}`, + id_token: idToken(claims), + ...fields, + }); + }; + const discovery = { value: () => Response.json({ + issuer: ISSUER, + authorization_endpoint: AUTHORIZE, + token_endpoint: TOKEN, + end_session_endpoint: END_SESSION, + }) }; + const fetch = vi.fn(async (input, init) => { + const url = String(input); + calls.push({ url, init }); + if (url === `${ISSUER}/.well-known/openid-configuration`) return discovery.value(); + if (url === TOKEN) { + const answer = tokenAnswers.shift(); + return answer ? answer() : tokens(); + } + throw new TypeError(`unexpected ${url}`); + }); + const page = { + href: () => href, + replaceUrl: vi.fn((url: string) => { + href = new URL(url, href).href; + }), + assign: vi.fn((url: string) => { + href = url; + }), + }; + const redirectStorage = { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => void storage.set(key, value), + removeItem: (key: string) => void storage.delete(key), + }; + const create = () => + createOidcPkceSessionOwner({ + issuer: ISSUER, + clientId: CLIENT_ID, + redirectUri: `${APP}/`, + apiOrigins: [API_ORIGIN], + postLogoutRedirectUri: `${APP}/`, + fetch, + page, + redirectStorage, + now: () => now, + ...overrides, + }); + return { + create, + fetch, + calls, + page, + storage, + tokens, + tokenAnswers, + discovery, + idToken, + advance(ms: number) { + now += ms; + }, + tokenRequests: () => + calls + .filter((call) => call.url === TOKEN) + .map((call) => Object.fromEntries(call.init?.body as URLSearchParams)), + }; +} + +/** Starts a sign-in on one page and returns the callback URL the IdP sends back. */ +async function signInRedirect( + setup: ReturnType, + returnTo = "/items?limit=1", + params: Readonly> = {}, +) { + const owner = setup.create(); + await owner.beginSignIn(returnTo); + const authorize = new URL(setup.page.assign.mock.calls.at(-1)![0]); + const callback = new URL(`${APP}/`); + callback.searchParams.set("code", "code-1"); + callback.searchParams.set("state", authorize.searchParams.get("state")!); + callback.searchParams.set("iss", ISSUER); + for (const [name, value] of Object.entries(params)) callback.searchParams.set(name, value); + return { authorize, callback: callback.href, storage: Object.fromEntries(setup.storage) }; +} + +/** A signed-in owner, as on the page load that returns from Keycloak. */ +async function signedIn(overrides: Partial = {}) { + const first = harness(overrides); + const { callback, storage } = await signInRedirect(first); + const setup = harness(overrides, { href: callback, storage }); + const owner = setup.create(); + await expect(owner.recoverSession()).resolves.toBe("restored"); + return { ...setup, owner }; +} + +const binding = (origin = API_ORIGIN) => + Object.freeze({ origin, method: "GET", operationId: "LIST" }); + +describe("OIDC PKCE session owner: sign-in", () => { + it("starts the code flow with PKCE S256 and keeps only the transaction", async () => { + const setup = harness(); + const owner = setup.create(); + expect(owner.readState()).toBe("unauthenticated"); + + await owner.beginSignIn("/items?limit=1"); + + const authorize = new URL(setup.page.assign.mock.calls[0]![0]); + expect(`${authorize.origin}${authorize.pathname}`).toBe(AUTHORIZE); + const transaction = JSON.parse(setup.storage.get(OIDC_PKCE_TRANSACTION_KEY)!); + expect(Object.fromEntries(authorize.searchParams)).toEqual({ + response_type: "code", + client_id: CLIENT_ID, + redirect_uri: `${APP}/`, + scope: "openid", + state: transaction.state, + nonce: transaction.nonce, + code_challenge: s256(transaction.verifier), + code_challenge_method: "S256", + }); + expect(transaction.returnTo).toBe("/items?limit=1"); + expect(transaction.verifier).toMatch(/^[A-Za-z0-9_-]{43}$/u); + expect(setup.storage.size).toBe(1); + }); + + it("returns only to a path of this app", async () => { + for (const returnTo of ["//evil.example/x", "https://evil.example/", "/\\evil", "items"]) { + const setup = harness(); + await setup.create().beginSignIn(returnTo); + expect(JSON.parse(setup.storage.get(OIDC_PKCE_TRANSACTION_KEY)!).returnTo).toBe("/"); + } + }); + + it("exchanges the code on the page load that returns, and drops it from the URL first", async () => { + const first = harness(); + const { callback, storage } = await signInRedirect(first); + const setup = harness({}, { href: callback, storage }); + + const owner = setup.create(); + + // Before any network answer: the code is out of the URL and the + // transaction is spent, so a reload cannot replay it. + expect(owner.readState()).toBe("recovery-pending"); + expect(setup.page.replaceUrl).toHaveBeenCalledWith("/items?limit=1"); + expect(setup.storage.has(OIDC_PKCE_TRANSACTION_KEY)).toBe(false); + await expect(owner.recoverSession()).resolves.toBe("restored"); + expect(owner.readState()).toBe("authenticated"); + expect(owner.readSubject()).toBe("user-1"); + expect(setup.tokenRequests()).toEqual([ + { + grant_type: "authorization_code", + code: "code-1", + redirect_uri: `${APP}/`, + client_id: CLIENT_ID, + code_verifier: JSON.parse(storage[OIDC_PKCE_TRANSACTION_KEY]!).verifier, + }, + ]); + const tokenCall = setup.calls.find((call) => call.url === TOKEN)!; + expect(tokenCall.init).toMatchObject({ method: "POST", credentials: "omit" }); + }); + + it("returns under the router base path", async () => { + const overrides = { redirectUri: `${APP}/app/` }; + const first = harness(overrides); + const { callback, storage } = await signInRedirect(first, "/items"); + const setup = harness(overrides, { href: callback.replace(`${APP}/`, `${APP}/app/`), storage }); + + setup.create(); + + expect(setup.page.replaceUrl).toHaveBeenCalledWith("/app/items"); + }); + + it.each([ + ["a state that is not the one sent", { state: "forged" }], + ["an error from the IdP", { error: "access_denied" }], + ["another issuer (RFC 9207)", { iss: "http://evil.example/realms/x" }], + ])("signs nobody in on %s", async (_case, params) => { + const first = harness(); + const { callback, storage } = await signInRedirect(first, "/items", params); + const setup = harness({}, { href: callback, storage }); + + const owner = setup.create(); + + expect(owner.readState()).toBe("unauthenticated"); + await expect(owner.recoverSession()).resolves.toBe("no-session"); + expect(setup.tokenRequests()).toEqual([]); + expect(setup.page.replaceUrl).toHaveBeenCalled(); + expect(setup.storage.has(OIDC_PKCE_TRANSACTION_KEY)).toBe(false); + }); + + it("signs nobody in from a transaction older than ten minutes", async () => { + const first = harness(); + const { callback, storage } = await signInRedirect(first); + const setup = harness({}, { href: callback, storage }); + setup.advance(10 * 60_000 + 1); + + expect(setup.create().readState()).toBe("unauthenticated"); + expect(setup.tokenRequests()).toEqual([]); + }); + + it.each([ + ["a nonce that is not the one sent", { nonce: "other" }], + ["an id token for another client", { aud: "other-client" }], + ["an id token from another issuer", { iss: "http://evil.example" }], + ["an id token without a subject", { sub: "" }], + ])("refuses %s", async (_case, claims) => { + const first = harness(); + const { callback, storage } = await signInRedirect(first); + const setup = harness({}, { href: callback, storage }); + const nonce = JSON.parse(storage[OIDC_PKCE_TRANSACTION_KEY]!).nonce; + setup.tokenAnswers.push(() => setup.tokens({}, { nonce, ...claims })); + + const owner = setup.create(); + + await expect(owner.recoverSession()).resolves.toBe("no-session"); + expect(owner.readState()).toBe("unauthenticated"); + expect(owner.readSubject()).toBeNull(); + }); + + it("refuses a token response that is not a bearer token", async () => { + const first = harness(); + const { callback, storage } = await signInRedirect(first); + const setup = harness({}, { href: callback, storage }); + setup.tokenAnswers.push(() => setup.tokens({ token_type: "DPoP" })); + + await expect(setup.create().recoverSession()).resolves.toBe("no-session"); + }); + + it("leaves a page that is not a sign-in callback alone", () => { + const setup = harness({}, { href: `${APP}/items?code=x&state=y` }); + + expect(setup.create().readState()).toBe("unauthenticated"); + expect(setup.page.replaceUrl).not.toHaveBeenCalled(); + }); + + it("refuses a discovery document for another issuer", async () => { + const setup = harness(); + setup.discovery.value = () => + Response.json({ issuer: "http://evil.example", authorization_endpoint: AUTHORIZE, token_endpoint: TOKEN }); + + await expect(setup.create().beginSignIn("/")).rejects.toThrow(); + expect(setup.page.assign).not.toHaveBeenCalled(); + expect(setup.storage.size).toBe(0); + }); + + it("keeps tokens out of storage", async () => { + const { storage, owner } = await signedIn(); + await owner.attachCredential(binding()); + + expect([...storage.values()].join("")).not.toMatch(/access-|refresh-/u); + }); +}); + +describe("OIDC PKCE session owner: credentials", () => { + it("sends the access token to the API origin and nowhere else", async () => { + const { owner } = await signedIn(); + + await expect(owner.attachCredential(binding())).resolves.toEqual({ + headers: { authorization: "Bearer access-1" }, + }); + await expect(owner.attachCredential(binding("https://other.example"))).rejects.toThrow( + "API origin", + ); + }); + + it("has no credential while signed out", async () => { + const setup = harness(); + + await expect(setup.create().attachCredential(binding())).rejects.toThrow(); + }); + + it("refreshes once before expiry, for every waiting request, without a notification", async () => { + const setup = await signedIn(); + const listener = vi.fn(); + setup.owner.subscribe(listener); + setup.advance(290_000); + + const patches = await Promise.all([ + setup.owner.attachCredential(binding()), + setup.owner.attachCredential(binding()), + ]); + + expect(patches.map((patch) => patch.headers.authorization)).toEqual([ + "Bearer access-2", + "Bearer access-2", + ]); + expect(setup.tokenRequests().at(-1)).toEqual({ + grant_type: "refresh_token", + refresh_token: "refresh-1", + client_id: CLIENT_ID, + }); + expect(setup.tokenRequests()).toHaveLength(2); + expect(setup.owner.readState()).toBe("authenticated"); + expect(setup.owner.readSubject()).toBe("user-1"); + expect(listener).not.toHaveBeenCalled(); + }); + + it("signs out when the refresh token is refused", async () => { + const setup = await signedIn(); + setup.advance(290_000); + setup.tokenAnswers.push(() => Response.json({ error: "invalid_grant" }, { status: 400 })); + + await expect(setup.owner.attachCredential(binding())).rejects.toThrow(); + expect(setup.owner.readState()).toBe("unauthenticated"); + expect(setup.owner.readSubject()).toBeNull(); + }); + + it("keeps a still-valid token when the refresh cannot be reached", async () => { + const setup = await signedIn(); + setup.advance(290_000); + setup.tokenAnswers.push(() => { + throw new DOMException("timed out", "TimeoutError"); + }); + + await expect(setup.owner.attachCredential(binding())).resolves.toEqual({ + headers: { authorization: "Bearer access-1" }, + }); + expect(setup.owner.readState()).toBe("authenticated"); + }); + + it("signs out when a refresh names another subject", async () => { + const setup = await signedIn(); + setup.advance(290_000); + setup.tokenAnswers.push(() => setup.tokens({}, { sub: "user-2" })); + + await expect(setup.owner.attachCredential(binding())).rejects.toThrow(); + expect(setup.owner.readState()).toBe("unauthenticated"); + }); +}); + +describe("OIDC PKCE session owner: 401 and recovery", () => { + it("restores the session with the refresh token after a 401, once", async () => { + const setup = await signedIn(); + const states: string[] = []; + setup.owner.subscribe(() => states.push(setup.owner.readState())); + + setup.owner.notifyUnauthenticated(); + + expect(setup.owner.readState()).toBe("recovery-pending"); + expect(setup.owner.readSubject()).toBeNull(); + await expect(setup.owner.recoverSession()).resolves.toBe("restored"); + expect(setup.owner.readSubject()).toBe("user-1"); + await expect(setup.owner.attachCredential(binding())).resolves.toEqual({ + headers: { authorization: "Bearer access-2" }, + }); + + // The fresh token is refused too: a refresh will not help. + setup.owner.notifyUnauthenticated(); + + expect(setup.owner.readState()).toBe("unauthenticated"); + expect(states).toEqual(["recovery-pending", "authenticated", "unauthenticated"]); + expect(setup.tokenRequests()).toHaveLength(2); + }); + + it("signs out on a 401 when nothing can restore the session", async () => { + const withoutRefresh = harness(); + const { callback, storage } = await signInRedirect(withoutRefresh); + const bare = harness({}, { href: callback, storage }); + bare.tokenAnswers.push(() => bare.tokens({ refresh_token: undefined })); + const owner = bare.create(); + await owner.recoverSession(); + + owner.notifyUnauthenticated(); + + expect(owner.readState()).toBe("unauthenticated"); + await expect(owner.recoverSession()).resolves.toBe("no-session"); + }); + + it("answers no-session from unauthenticated, never leaving it recovering", async () => { + const owner = harness().create(); + + await expect(owner.recoverSession()).resolves.toBe("no-session"); + expect(owner.readState()).toBe("unauthenticated"); + }); + + it("rejects and stays recovering when the IdP cannot be reached", async () => { + const setup = await signedIn(); + setup.tokenAnswers.push(() => Response.json({ error: "temporarily_unavailable" }, { status: 503 })); + + setup.owner.notifyUnauthenticated(); + + await vi.waitFor(() => expect(setup.tokenRequests()).toHaveLength(2)); + expect(setup.owner.readState()).toBe("recovery-pending"); + await expect(setup.owner.recoverSession()).resolves.toBe("restored"); + }); + + it("answers no-session after a refused refresh, signed out", async () => { + const setup = await signedIn(); + setup.tokenAnswers.push(() => Response.json({ error: "invalid_grant" }, { status: 400 })); + + setup.owner.notifyUnauthenticated(); + + await vi.waitFor(() => expect(setup.owner.readState()).toBe("unauthenticated")); + await expect(setup.owner.recoverSession()).resolves.toBe("no-session"); + }); +}); + +describe("OIDC PKCE session owner: sign-out and configuration", () => { + it("forgets the tokens and ends the IdP session without an id token in the URL", async () => { + const setup = await signedIn(); + + await setup.owner.signOut(); + + expect(setup.owner.readState()).toBe("unauthenticated"); + await expect(setup.owner.attachCredential(binding())).rejects.toThrow(); + const logout = new URL(setup.page.assign.mock.calls.at(-1)![0]); + expect(`${logout.origin}${logout.pathname}`).toBe(END_SESSION); + expect(Object.fromEntries(logout.searchParams)).toEqual({ + client_id: CLIENT_ID, + post_logout_redirect_uri: `${APP}/`, + }); + }); + + it.each([ + ["a plain-HTTP issuer off this machine", { issuer: "http://idp.example/realms/x" }], + ["no client id", { clientId: "" }], + ["an API origin that is not an origin", { apiOrigins: ["http://localhost:8080/api"] }], + ["no storage to survive the redirect", { redirectStorage: undefined }], + ])("fails closed as integration-failed with %s", async (_case, overrides) => { + const owner = harness(overrides as Partial).create(); + + expect(owner.readState()).toBe("integration-failed"); + await expect(owner.beginSignIn("/")).rejects.toThrow(); + await expect(owner.recoverSession()).resolves.toBe("no-session"); + expect(owner.readState()).toBe("integration-failed"); + }); +}); + +function s256(verifier: string): string { + return createHash("sha256").update(verifier).digest("base64url"); +} diff --git a/tests/recipes/session-owners-runtime.test.ts b/tests/recipes/session-owners-runtime.test.ts new file mode 100644 index 00000000..460e92ab --- /dev/null +++ b/tests/recipes/session-owners-runtime.test.ts @@ -0,0 +1,396 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts"; +import type { + ProductCompositionContext, + ProductSessionOwnerContext, +} from "../../src/bootstrap/product-composition-contract.ts"; +import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; +import { OIDC_PKCE_TRANSACTION_KEY } from "../../recipes/session-owners/oidc-pkce-session-owner.ts"; +import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts"; + +/** + * 1103/09-03 completion check, short of the real backend: each recipe wired + * the way docs/manual/04-paired-backend-session.md tells a product to, through + * the template's real composition root. Only the two product-owned files, the + * installed contract set (adds the operations) and the feature-input composer + * (to reach the `http` capability) are replaced. + */ + +const ISSUER = "http://localhost:8081/realms/ca-skeleton"; +const APP = "http://localhost:5173"; +const API = "http://localhost:8080"; + +const fixture = vi.hoisted(() => ({ + mode: "oidc" as "oidc" | "cookie", + http: undefined as InstalledHttpOperationExecutor | undefined, + withProfile( + contract: T, + operationId: string, + authProfileId: string, + ): T { + return { + ...contract, + contract: { ...contract.contract, operationId }, + frontend: { ...contract.frontend, authProfileId }, + }; + }, +})); + +/** The product's `src/contracts/product-contracts.ts` for the cookie mode. */ +vi.mock("../../src/contracts/product-contracts.ts", async () => { + const { SESSION_COOKIE_AUTH_PROFILES } = await import( + "../../recipes/session-owners/cookie-session-owner.ts" + ); + return { + PRODUCT_RUNTIME_CONFIG_FIELDS: Object.freeze({}), + PRODUCT_ENV_REGISTRY: Object.freeze({}), + PRODUCT_REST_AUTH_PROFILES: SESSION_COOKIE_AUTH_PROFILES, + }; +}); + +/** The product's `src/bootstrap/product-composition.ts`, one mode at a time. */ +vi.mock("../../src/bootstrap/product-composition.ts", async () => { + const { createOidcPkceSessionOwner } = await import( + "../../recipes/session-owners/oidc-pkce-session-owner.ts" + ); + const { createCookieSessionOwner, createSessionCookieCredentialProviders } = await import( + "../../recipes/session-owners/cookie-session-owner.ts" + ); + return { + composeProductSessionOwner(context: ProductSessionOwnerContext) { + const api = new URL(context.config.API_BASE_URL); + return fixture.mode === "oidc" + ? createOidcPkceSessionOwner({ + issuer: ISSUER, + clientId: "ca-frontend", + redirectUri: `${APP}/`, + apiOrigins: [api.origin], + fetch: context.fetch, + page: context.page, + redirectStorage: context.redirectStorage, + }) + : createCookieSessionOwner({ + sessionUrl: new URL("api/session", api).href, + signOutUrl: new URL("api/session/sign-out", api).href, + subjectFrom: (body) => + (body as { data?: { subject?: string } }).data?.subject ?? null, + beginSignIn: async () => context.page.assign(`${APP}/login`), + fetch: context.fetch, + readCookie: context.readCookie, + }); + }, + composeProduct(context: ProductCompositionContext) { + return { + capabilities: {}, + credentialProviders: createSessionCookieCredentialProviders({ + readCookie: context.readCookie, + }), + }; + }, + }; +}); + +const OPERATIONS = vi.hoisted(() => ({ + bearer: ["LIST_BEARER", "EXTERNAL_BEARER"], + cookieRead: ["LIST_COOKIE_READ", "SESSION_COOKIE_READ"], + cookieWrite: ["LIST_COOKIE_WRITE", "SESSION_COOKIE_WRITE"], +} as const)); + +vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => { + const original = + await importOriginal(); + const { TEST_CONTRACT_CONTRIBUTION: contribution, TEST_LIST_HTTP_CONTRACT: list } = + await import("../helpers/external-contract-fixture.ts"); + const source = contribution.source; + if (source.kind !== "EXTERNAL_PACKAGE") throw new Error("fixture source changed"); + return { + ...original, + createInstalledContractRegistry: () => { + const registry = original.createInstalledContractRegistry([ + ...original.EXPECTED_CONTRACT_SET_PACKAGES, + source.package, + ]); + registry.install(contribution.featureId, [ + { + ...contribution, + http: Object.values(OPERATIONS).map(([operationId, authProfileId]) => + fixture.withProfile(list, operationId, authProfileId), + ) as unknown as typeof contribution.http, + }, + ]); + return registry; + }, + }; +}); + +vi.mock("../../src/features/installed-feature-adapters.ts", async (importOriginal) => { + const original = + await importOriginal(); + return { + ...original, + createInstalledFeatureLoaders: ( + ...args: Parameters + ) => { + fixture.http = Reflect.get(args[0], "http") as InstalledHttpOperationExecutor; + return original.createInstalledFeatureLoaders(...args); + }, + }; +}); + +const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url"); +const jwt = (claims: Record) => + `${encode({ alg: "RS256" })}.${encode(claims)}.signature`; + +let dispose: (() => void) | undefined; +afterEach(() => { + dispose?.(); + dispose = undefined; + fixture.http = undefined; +}); + +async function compose( + host: Record, + respond: (url: string, init: RequestInit) => Response, +) { + const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => + respond(String(input), init ?? {}), + ); + const adapters = await createRuntimeAdapters({ + runtime: { + config: { + APP_ENV: "local", + API_BASE_URL: `${API}/`, + TELEMETRY_ENABLED: false, + AUTH_MODE: "external", + REQUEST_TIMEOUT_MS: 10_000, + MAX_RETRY_ATTEMPTS: 0, + RELEASE_MANIFEST_URL: "/release-manifest.json", + CONFIG_SCHEMA_VERSION: "2.0", + CAPABILITY_OVERRIDES: { + REALTIME: "DEFAULT", + WEB_WORKER: "DEFAULT", + SERVICE_WORKER: "DEFAULT", + OFFLINE_COMMANDS: "DEFAULT", + }, + FEATURE_OVERRIDES: {}, + }, + configSchema: "V2", + build: { + buildId: "build-a", + commitSha: "abc123", + routerBasePath: "/", + runtimeConfigUrl: "/config.json", + }, + validationDurationMs: 0, + }, + release: { + schemaVersion: 2, + appVersion: "0.1.0", + buildId: "build-a", + commitSha: "abc123", + configSchemaVersion: "2.0", + contractSet: { + setAlgorithm: "CA_CONTRACT_SET_V1", + setDigest: `sha256:${"0".repeat(64)}`, + packages: [], + }, + assetManifestHash: "hash-a", + releaseId: "release-a", + builtAt: "2026-07-25T00:00:00Z", + routeChunks: { "route-home": "assets/home.js" }, + }, + host, + fetcher: fetcher as unknown as typeof fetch, + }); + dispose = () => adapters.infrastructure.dispose(); + const http = fixture.http; + if (!http) throw new Error("The http capability was not composed"); + return { adapters, http, fetcher }; +} + +const operation = (entry: readonly [string, string]) => + fixture.withProfile(TEST_LIST_HTTP_CONTRACT, ...entry); + +function apiCalls(fetcher: ReturnType) { + return fetcher.mock.calls + .map(([url, init]) => ({ url: String(url), init: (init ?? {}) as RequestInit })) + .filter((call) => call.url.startsWith(`${API}/api/test-entities`)); +} + +describe("OIDC PKCE owner in the composition root (JWT mode)", () => { + function signInReturn() { + const storage = new Map([ + [ + OIDC_PKCE_TRANSACTION_KEY, + JSON.stringify({ + v: 1, + state: "state-1", + nonce: "nonce-1", + verifier: "v".repeat(43), + returnTo: "/items", + createdAt: Date.now(), + }), + ], + ]); + const replaceState = vi.fn(); + const host = { + location: { href: `${APP}/?code=code-1&state=state-1&iss=${encodeURIComponent(ISSUER)}`, assign: vi.fn() }, + history: { state: null, replaceState }, + sessionStorage: { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => void storage.set(key, value), + removeItem: (key: string) => void storage.delete(key), + }, + }; + let issued = 0; + let apiStatus = 200; + const respond = (url: string) => { + if (url.endsWith("/.well-known/openid-configuration")) { + return Response.json({ + issuer: ISSUER, + authorization_endpoint: `${ISSUER}/protocol/openid-connect/auth`, + token_endpoint: `${ISSUER}/protocol/openid-connect/token`, + }); + } + if (url === `${ISSUER}/protocol/openid-connect/token`) { + issued += 1; + return Response.json({ + access_token: `access-${issued}`, + token_type: "Bearer", + expires_in: 300, + refresh_token: `refresh-${issued}`, + id_token: jwt({ + iss: ISSUER, + aud: "ca-frontend", + sub: "user-1", + nonce: "nonce-1", + exp: Math.floor(Date.now() / 1000) + 300, + }), + }); + } + if (apiStatus === 401) { + apiStatus = 200; + return Response.json( + { success: false, error: { code: "AUTH_TOKEN_EXPIRED" } }, + { status: 401, headers: { "www-authenticate": "Bearer" } }, + ); + } + return Response.json([{ id: "entity-1", name: "Entity" }]); + }; + return { + host, + storage, + replaceState, + respond, + failNextApiCall() { + apiStatus = 401; + }, + }; + } + + it("signs in on the returning page load and sends the bearer on EXTERNAL_BEARER", async () => { + fixture.mode = "oidc"; + const page = signInReturn(); + const { adapters, http, fetcher } = await compose(page.host, page.respond); + const session = adapters.outputPorts.session; + + expect(page.replaceState).toHaveBeenCalledWith(null, "", "/items"); + expect(page.storage.size).toBe(0); + await vi.waitFor(() => expect(session.getState()).toBe("authenticated")); + expect(session.getSubject()).toBe("user-1"); + await vi.waitFor(() => + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), + ); + + const outcome = await http.execute(operation(OPERATIONS.bearer), { limit: 1 }, { routeId: "R" }); + + expect(outcome.kind).toBe("SUCCESS"); + const [call] = apiCalls(fetcher); + expect(new Headers(call!.init.headers).get("authorization")).toBe("Bearer access-1"); + expect(call!.init.credentials).toBe("omit"); + }); + + it("turns a server 401 into one refresh and keeps the same subject", async () => { + fixture.mode = "oidc"; + const page = signInReturn(); + const { adapters, http, fetcher } = await compose(page.host, page.respond); + const session = adapters.outputPorts.session; + await vi.waitFor(() => expect(session.getState()).toBe("authenticated")); + await vi.waitFor(() => + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), + ); + page.failNextApiCall(); + + await expect( + http.execute(operation(OPERATIONS.bearer), { limit: 1 }, { routeId: "R" }), + ).resolves.toMatchObject({ kind: "UNAUTHENTICATED" }); + + await vi.waitFor(() => expect(session.getState()).toBe("authenticated")); + expect(session.getSubject()).toBe("user-1"); + await vi.waitFor(() => + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), + ); + await http.execute(operation(OPERATIONS.bearer), { limit: 1 }, { routeId: "R" }); + expect(new Headers(apiCalls(fetcher).at(-1)!.init.headers).get("authorization")).toBe( + "Bearer access-2", + ); + }); +}); + +describe("cookie owner and CSRF providers in the composition root (Redis session mode)", () => { + function cookiePage(signedIn = true) { + const host = { + location: { href: `${APP}/items`, assign: vi.fn() }, + history: { state: null, replaceState: vi.fn() }, + document: { cookie: "XSRF-TOKEN=xsrf-1" }, + }; + const respond = (url: string) => { + if (url === `${API}/api/session`) { + return signedIn + ? Response.json({ success: true, data: { subject: "user-1" } }) + : Response.json({ success: false }, { status: 401 }); + } + return Response.json([{ id: "entity-1", name: "Entity" }]); + }; + return { host, respond }; + } + + it("asks the session at boot and sends writes with the cookie and X-XSRF-TOKEN", async () => { + fixture.mode = "cookie"; + const page = cookiePage(); + const { adapters, http, fetcher } = await compose(page.host, page.respond); + const session = adapters.outputPorts.session; + expect(session.getState()).toBe("recovery-pending"); + await vi.waitFor(() => expect(session.getState()).toBe("authenticated")); + expect(fetcher.mock.calls[0]?.[1]).toMatchObject({ credentials: "include", redirect: "error" }); + await vi.waitFor(() => + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), + ); + + await expect( + http.execute(operation(OPERATIONS.cookieWrite), { limit: 1 }, { routeId: "R" }), + ).resolves.toMatchObject({ kind: "SUCCESS" }); + await expect( + http.execute(operation(OPERATIONS.cookieRead), { limit: 1 }, { routeId: "R" }), + ).resolves.toMatchObject({ kind: "SUCCESS" }); + + const [write, read] = apiCalls(fetcher); + expect(write!.init.credentials).toBe("include"); + expect(new Headers(write!.init.headers).get("x-xsrf-token")).toBe("xsrf-1"); + expect(read!.init.credentials).toBe("include"); + expect(new Headers(read!.init.headers).has("x-xsrf-token")).toBe(false); + expect(new Headers(read!.init.headers).has("authorization")).toBe(false); + }); + + it("is signed out when the session endpoint says nobody is", async () => { + fixture.mode = "cookie"; + const page = cookiePage(false); + const { adapters } = await compose(page.host, page.respond); + + await vi.waitFor(() => + expect(adapters.outputPorts.session.getState()).toBe("unauthenticated"), + ); + await expect(adapters.outputPorts.session.recover()).resolves.toBe("no-session"); + }); +});