import { afterEach, describe, expect, it, vi } from "vitest"; import type { ProductSessionOwnerContext } from "../../src/bootstrap/product-composition-contract.ts"; import { createSessionOwnerFetch, SESSION_OWNER_FETCH_MAXIMUM_BYTES, } from "../../src/bootstrap/session-owner-fetch.ts"; import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; import { validateRuntimeConfig } from "../../src/bootstrap/runtime-config-schema.ts"; /** * 1103/09-03. A session owner is asked for at boot, before `http` exists, and * the shipped context gave it a raw `fetcher`: a session probe or a token call * that never answered left the session `recovery-pending` for good. The * context now carries a fetch with one deadline over the whole exchange. */ const fixture = vi.hoisted(() => ({ context: undefined as ProductSessionOwnerContext | undefined, })); vi.mock("../../src/bootstrap/product-composition.ts", () => ({ composeProductSessionOwner(context: ProductSessionOwnerContext) { fixture.context = context; return null; }, composeProduct: () => ({ capabilities: {}, credentialProviders: {} }), })); const never = () => new Promise(() => {}); /** A body that sends one chunk and then nothing. */ function stalledBody(): ReadableStream { return new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode("{")); }, }); } describe("createSessionOwnerFetch", () => { it("answers with the whole body read, status and headers kept", async () => { const fetcher = vi.fn(async () => Response.json({ sub: "user-1" }, { status: 201, headers: { "x-extra": "1" } }), ); const bounded = createSessionOwnerFetch({ fetcher, timeoutMs: 1_000 }); const response = await bounded("https://idp.example/token", { method: "POST", credentials: "omit", }); expect(response.status).toBe(201); expect(response.headers.get("x-extra")).toBe("1"); await expect(response.json()).resolves.toEqual({ sub: "user-1" }); const [, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit]; expect(init).toMatchObject({ method: "POST", credentials: "omit", cache: "no-store", redirect: "error", }); expect(init.signal).toBeInstanceOf(AbortSignal); }); it("refuses to follow a redirect even when asked", async () => { const fetcher = vi.fn(async () => new Response("{}")); const bounded = createSessionOwnerFetch({ fetcher, timeoutMs: 1_000 }); await bounded("https://api.example/session", { redirect: "follow", } as unknown as Parameters[1]); expect((fetcher.mock.calls[0] as unknown as [string, RequestInit])[1].redirect).toBe("error"); }); it("times out a request that never answers", async () => { const bounded = createSessionOwnerFetch({ fetcher: never, timeoutMs: 20 }); await expect(bounded("https://api.example/session")).rejects.toMatchObject({ name: "TimeoutError", }); }); it("times out a body that stops arriving: the deadline covers the body", async () => { const bounded = createSessionOwnerFetch({ fetcher: async () => new Response(stalledBody()), timeoutMs: 20, }); await expect(bounded("https://api.example/session")).rejects.toMatchObject({ name: "TimeoutError", }); }); it("lets one call shorten the deadline but never extend it", async () => { const shorter = createSessionOwnerFetch({ fetcher: never, timeoutMs: 10_000 }); const started = Date.now(); await expect( shorter("https://api.example/session", { timeoutMs: 20 }), ).rejects.toMatchObject({ name: "TimeoutError" }); expect(Date.now() - started).toBeLessThan(5_000); const capped = createSessionOwnerFetch({ fetcher: never, timeoutMs: 20 }); await expect( capped("https://api.example/session", { timeoutMs: 60_000 }), ).rejects.toMatchObject({ name: "TimeoutError" }); }); it("stops when the caller aborts", async () => { const bounded = createSessionOwnerFetch({ fetcher: never, timeoutMs: 10_000 }); const caller = new AbortController(); const pending = bounded("https://api.example/session", { signal: caller.signal }); caller.abort(); await expect(pending).rejects.toMatchObject({ name: "AbortError" }); }); it("refuses a body over the cap and cancels it", async () => { const cancel = vi.fn(); const chunk = new Uint8Array(SESSION_OWNER_FETCH_MAXIMUM_BYTES); const body = new ReadableStream({ pull(controller) { controller.enqueue(chunk); }, cancel, }); const bounded = createSessionOwnerFetch({ fetcher: async () => new Response(body), timeoutMs: 1_000, }); await expect(bounded("https://api.example/session")).rejects.toBeInstanceOf(RangeError); expect(cancel).toHaveBeenCalled(); }); it("passes the fetcher's own rejection through", async () => { const bounded = createSessionOwnerFetch({ fetcher: async () => { throw new TypeError("Failed to fetch"); }, timeoutMs: 1_000, }); await expect(bounded("https://api.example/session")).rejects.toThrow("Failed to fetch"); }); it("answers a body-less status without a body", async () => { const bounded = createSessionOwnerFetch({ fetcher: async () => new Response(null, { status: 204 }), timeoutMs: 1_000, }); const response = await bounded("https://api.example/sign-out", { method: "POST" }); expect(response.status).toBe(204); expect(response.body).toBeNull(); }); }); const CONFIG = { APP_ENV: "local", API_BASE_URL: "http://localhost:8080", REQUEST_TIMEOUT_MS: 150, TELEMETRY_ENABLED: false, AUTH_MODE: "external", CONFIG_SCHEMA_VERSION: "2.0", RELEASE_MANIFEST_URL: "/release-manifest.json", CAPABILITY_OVERRIDES: { REALTIME: "DEFAULT", WEB_WORKER: "DEFAULT", SERVICE_WORKER: "DEFAULT", OFFLINE_COMMANDS: "DEFAULT", }, FEATURE_OVERRIDES: {}, } as const; describe("the session owner context the composition root builds", () => { let dispose: (() => void) | undefined; afterEach(() => { dispose?.(); dispose = undefined; fixture.context = undefined; }); async function compose(host: Record, fetcher: typeof fetch) { const validated = validateRuntimeConfig(CONFIG); if (!validated.success) throw new Error(JSON.stringify(validated.issues)); const adapters = await createRuntimeAdapters({ runtime: { config: validated.data, 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, }); dispose = () => adapters.infrastructure.dispose(); const context = fixture.context; if (!context) throw new Error("the session owner was not asked"); return context; } it("bounds the owner's fetch by REQUEST_TIMEOUT_MS", async () => { const context = await compose({}, never as unknown as typeof fetch); await expect(context.fetch("http://localhost:8080/session")).rejects.toMatchObject({ name: "TimeoutError", }); }); it("reads the page, its session storage and its cookies through the host", async () => { const replaceState = vi.fn(); const assign = vi.fn(); const storage = new Map(); const 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), }; const context = await compose( { location: { href: "http://localhost:5173/callback?code=c&state=s", assign }, history: { state: { idx: 3 }, replaceState }, sessionStorage, document: { cookie: "theme=dark; XSRF-TOKEN=xsrf-1" }, }, (async () => new Response("{}")) as unknown as typeof fetch, ); expect(context.page.href()).toBe("http://localhost:5173/callback?code=c&state=s"); context.page.replaceUrl("/items?limit=1"); // The router's own history state is kept, so its index survives. expect(replaceState).toHaveBeenCalledWith({ idx: 3 }, "", "/items?limit=1"); context.page.assign("https://idp.example/auth"); expect(assign).toHaveBeenCalledWith("https://idp.example/auth"); context.redirectStorage?.setItem("k", "v"); expect(storage.get("k")).toBe("v"); expect(context.readCookie("XSRF-TOKEN")).toBe("xsrf-1"); }); it("fails closed when the host has no page", async () => { const context = await compose({}, (async () => new Response("{}")) as unknown as typeof fetch); expect(context.redirectStorage).toBeUndefined(); expect(() => context.page.href()).toThrow("page is unavailable"); expect(() => context.page.assign("https://idp.example/auth")).toThrow("page is unavailable"); expect(context.readCookie("XSRF-TOKEN")).toBeUndefined(); }); });