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"; import { testRuntimeConfig } from "../helpers/runtime-config.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, createSessionCookieRejectionHandler, } = 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, }), // Manual 04 4.3's cookie wiring (1105/09-02): the server's 401 to a // SESSION_COOKIE_* request reaches the session. ...(fixture.mode === "cookie" ? { onCredentialRejected: createSessionCookieRejectionHandler(context) } : {}), }; }, }; }); 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: testRuntimeConfig({ 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, apiStatus: 200 | 401 = 200) { 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 }); } // The server session ended after boot (Redis TTL, signed out elsewhere). if (apiStatus === 401) { return Response.json( { success: false, error: { code: "AUTH_REQUIRED" } }, { 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"); }); // 1105/09-02. Manual 04 says a server 401 signs the cookie session out. The // template tells a product provider's 401 to the product only (1103/09-01), // so without the wiring above the page stayed signed in on the ended // session, with the previous scope still current. it.each([ ["read", OPERATIONS.cookieRead], ["write", OPERATIONS.cookieWrite], ] as const)("signs out when the server answers a cookie %s with 401", async (_label, entry) => { fixture.mode = "cookie"; const page = cookiePage(true, 401); const { adapters, http } = 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"), ); const scope = adapters.infrastructure.serverStateScope.getSnapshot(); await expect( http.execute(operation(entry), { limit: 1 }, { routeId: "R" }), ).resolves.toMatchObject({ kind: "UNAUTHENTICATED" }); await vi.waitFor(() => expect(session.getState()).toBe("unauthenticated")); await vi.waitFor(() => expect(scope.isCurrent()).toBe(false)); }); });