import { readFile } from "node:fs/promises"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts"; import type { ProductComposition, ProductCompositionContext, ProductSessionOwner, ProductSessionOwnerContext, } from "../../src/bootstrap/product-composition-contract.ts"; import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; import { validateRuntimeConfig } from "../../src/bootstrap/runtime-config-schema.ts"; import { runtimeConfigV2ArtifactSchema } from "../../src/contracts/release-artifacts.ts"; import type { FeaturePlatformCapabilityId } from "../../src/features/feature-adapter-contribution.ts"; import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts"; /** * 09-02 completion check. The two products' current needs — memento's * `offsetUpload` and `runtime` capabilities and its BFF cookie XSRF write, * tech-log's Studio CSRF, its product runtime-config key with its FE-REG-ENV * row, and its BFF session owner installed before boot — expressed by filling * only the two product-owned files: * * - `src/contracts/product-contracts.ts`: product auth profiles, config keys * and their FE-REG-ENV rows * - `src/bootstrap/product-composition.ts`: the session owner, capabilities and * credential providers * * Both are replaced below by what a product would write in them. Everything * else is the template as shipped; only the installed contract set (adds the * operations) and the feature-input composer (to read the capability context * a feature receives) are swapped, as in the 09-01 test. */ declare module "../../src/features/feature-adapter-contribution.ts" { interface FeaturePlatformCapabilities { readonly offsetUpload: Readonly<{ upload(path: string, body: Blob): Promise; }>; readonly runtime: Readonly<{ appEnvironment: string; apiBaseUrl: string }>; readonly studioSource: "MOCK" | "HTTP"; readonly studioHttp: InstalledHttpOperationExecutor; } } /** Fails to compile unless the capability interface takes product keys. */ const PRODUCT_NEEDS: readonly FeaturePlatformCapabilityId[] = [ "offsetUpload", "runtime", "studioSource", "studioHttp", ]; const fixture = vi.hoisted(() => ({ capabilities: undefined as Record | undefined, sessionOwnerRequests: 0, 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`. */ vi.mock("../../src/contracts/product-contracts.ts", async () => { const { z } = await import("../../src/contracts/zod.ts"); const cookieProfile = ( authProfileId: string, header: readonly ("x-csrf-token" | "x-xsrf-token")[], ) => Object.freeze({ authProfileId, transport: "SAME_ORIGIN_COOKIE" as const, credentials: "include" as const, allowedCredentialHeaders: Object.freeze([...header]), requiredCredentialHeaders: Object.freeze([...header]), }); return { PRODUCT_RUNTIME_CONFIG_FIELDS: Object.freeze({ TECH_LOG_STUDIO_SOURCE: z.enum(["MOCK", "HTTP"]).default("MOCK"), }), // tech-log added this row to the template's `env.ts`. PRODUCT_ENV_REGISTRY: Object.freeze({ TECH_LOG_STUDIO_SOURCE: Object.freeze({ phase: "runtime", classification: "public", required: false, defaultValue: "MOCK", }), }), PRODUCT_REST_AUTH_PROFILES: Object.freeze({ MEMENTO_BFF_READ: cookieProfile("MEMENTO_BFF_READ", []), // The paired backend's default CSRF header (Spring CookieCsrfTokenRepository). MEMENTO_BFF_WRITE: cookieProfile("MEMENTO_BFF_WRITE", ["x-xsrf-token"]), TECH_LOG_STUDIO_BOOTSTRAP: cookieProfile("TECH_LOG_STUDIO_BOOTSTRAP", []), TECH_LOG_STUDIO_SESSION: cookieProfile("TECH_LOG_STUDIO_SESSION", ["x-csrf-token"]), }), }; }); const OPERATIONS = vi.hoisted(() => ({ bffRead: ["MEMENTO_READ", "MEMENTO_BFF_READ"], bffWrite: ["MEMENTO_WRITE", "MEMENTO_BFF_WRITE"], studio: ["STUDIO_LIST", "TECH_LOG_STUDIO_SESSION"], studioSession: ["STUDIO_SESSION", "TECH_LOG_STUDIO_BOOTSTRAP"], } as const)); /** The product's `src/bootstrap/product-composition.ts`. */ vi.mock("../../src/bootstrap/product-composition.ts", async () => { const { TEST_DETAIL_HTTP_CONTRACT: detail } = await import( "../helpers/external-contract-fixture.ts" ); const studioSession = fixture.withProfile(detail, ...OPERATIONS.studioSession); /** * tech-log's BFF session owner (`bff-session-owner.ts`), which it put on the * host global from the template's `create-runtime-composition.ts`. The * session is an httpOnly cookie, so the owner asks the backend. */ function composeProductSessionOwner( context: ProductSessionOwnerContext, ): ProductSessionOwner { fixture.sessionOwnerRequests += 1; if (Reflect.get(context.config, "TECH_LOG_STUDIO_SOURCE") !== "HTTP") return null; const fetcher = context.fetcher ?? fetch; let state: "recovery-pending" | "authenticated" | "unauthenticated" = "recovery-pending"; const listeners = new Set<() => void>(); const probe = async () => { const response = await fetcher( new URL("api/v1/studio/session", context.config.API_BASE_URL), { method: "GET", credentials: "include" }, ); state = response.ok ? "authenticated" : "unauthenticated"; for (const listener of listeners) listener(); return response.ok ? ("restored" as const) : ("no-session" as const); }; void probe(); return Object.freeze({ readState: () => state, readSubject: () => (state === "authenticated" ? "studio-user" : null), subscribe(listener: () => void) { listeners.add(listener); return () => listeners.delete(listener); }, beginSignIn: async () => {}, signOut: async () => {}, attachCredential: async () => ({ headers: {} }), recoverSession: probe, notifyUnauthenticated() { state = "unauthenticated"; }, }); } function composeProduct(context: ProductCompositionContext) { // tech-log: one Studio CSRF token per session, fetched through `http` with // the credential-free bootstrap profile and dropped on 401/403. let csrfToken: Promise | null = null; const csrf = { token(signal?: AbortSignal) { csrfToken ??= context.http .execute(studioSession, { entityId: "session" }, { routeId: "STUDIO", ...(signal === undefined ? {} : { signal }), }) .then((outcome) => { if (outcome.kind !== "SUCCESS") throw new Error("no studio session"); return outcome.value.id; }); return csrfToken.catch((error: unknown) => { csrfToken = null; throw error; }); }, invalidate() { csrfToken = null; }, }; return { capabilities: { // memento: its resumable upload transport, fenced like every request. offsetUpload: Object.freeze({ async upload(path: string, body: Blob) { const token = context.isScopeReady() ? context.readCookie("XSRF-TOKEN") : undefined; if (token === undefined) return "NO_CREDENTIAL" as const; const fetcher = context.fetcher ?? fetch; const response = await fetcher( new URL(path, context.config.API_BASE_URL), { method: "PATCH", credentials: "include", headers: { "x-xsrf-token": token }, body, }, ); return response.status; }, }), // memento: runtime values its features read. runtime: Object.freeze({ appEnvironment: context.config.APP_ENV, apiBaseUrl: context.config.API_BASE_URL, }), // tech-log: a product runtime-config key. Read untyped here only // because the shipped `product-contracts.ts` declares no keys. studioSource: Reflect.get(context.config, "TECH_LOG_STUDIO_SOURCE") as | "MOCK" | "HTTP", // tech-log: Studio calls go through `http`; a 401/403 drops the token. studioHttp: Object.freeze({ async execute(...args: Parameters) { const outcome = await context.http.execute(...args); if (outcome.kind === "UNAUTHENTICATED" || outcome.kind === "FORBIDDEN") { csrf.invalidate(); } return outcome; }, }) as InstalledHttpOperationExecutor, }, credentialProviders: { // memento BFF: the cookie is the session; writes add the XSRF cookie. MEMENTO_BFF_READ: () => ({ kind: "READY" as const, headers: {} }), MEMENTO_BFF_WRITE: () => { const token = context.readCookie("XSRF-TOKEN"); return token === undefined ? { kind: "UNAVAILABLE" as const } : { kind: "READY" as const, headers: { "x-xsrf-token": token } }; }, // tech-log Studio: the token's own issuing call carries none. TECH_LOG_STUDIO_BOOTSTRAP: () => ({ kind: "READY" as const, headers: {} }), TECH_LOG_STUDIO_SESSION: async (_operation, { signal }) => ({ kind: "READY" as const, headers: { "x-csrf-token": await csrf.token(signal) }, }), }, } satisfies ProductComposition; } return { composeProduct, composeProductSessionOwner }; }); vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => { const original = await importOriginal(); const fixtures = await import("../helpers/external-contract-fixture.ts"); const { TEST_CONTRACT_CONTRIBUTION: contribution } = fixtures; 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: [ fixture.withProfile(fixtures.TEST_LIST_HTTP_CONTRACT, ...OPERATIONS.bffRead), fixture.withProfile(fixtures.TEST_LIST_HTTP_CONTRACT, ...OPERATIONS.bffWrite), fixture.withProfile(fixtures.TEST_LIST_HTTP_CONTRACT, ...OPERATIONS.studio), fixture.withProfile(fixtures.TEST_DETAIL_HTTP_CONTRACT, ...OPERATIONS.studioSession), ] 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.capabilities = { ...args[0] }; return original.createInstalledFeatureLoaders(...args); }, }; }); const CONFIG_DOCUMENT = { APP_ENV: "local", API_BASE_URL: "http://localhost:8080", TELEMETRY_ENABLED: false, AUTH_MODE: "demo", 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; const release: Parameters[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" }, }; let current: Awaited> | undefined; afterEach(() => { current?.infrastructure.dispose(); current = undefined; fixture.capabilities = undefined; fixture.sessionOwnerRequests = 0; }); async function compose( options: Readonly<{ cookie?: string; studioStatus?: number; authMode?: "demo" | "external"; studioSource?: "MOCK" | "HTTP"; studioSessionStatus?: number; host?: Record; }> = {}, ) { const validated = validateRuntimeConfig({ ...CONFIG_DOCUMENT, AUTH_MODE: options.authMode ?? CONFIG_DOCUMENT.AUTH_MODE, TECH_LOG_STUDIO_SOURCE: options.studioSource ?? "HTTP", }); if (!validated.success) throw new Error(JSON.stringify(validated.issues)); const fetcher = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => { const url = String(input); if (url.endsWith("/api/v1/studio/session")) { return new Response(null, { status: options.studioSessionStatus ?? 200 }); } if (url.endsWith("/api/test-entities/session")) { return Response.json({ id: "studio-csrf", name: "session" }); } if (url.includes("/api/test-entities?") && options.studioStatus !== undefined) { return Response.json( { type: "about:blank", title: "Forbidden", status: options.studioStatus }, { status: options.studioStatus }, ); } return Response.json([{ id: "entity-1", name: "Entity" }]); }); current = await createRuntimeAdapters({ runtime: { config: validated.data, configSchema: "V2", build: { buildId: "build-a", commitSha: "abc123", routerBasePath: "/", runtimeConfigUrl: "/config.json", }, validationDurationMs: 0, }, release, host: { ...options.host, ...(options.cookie === undefined ? {} : { document: { cookie: options.cookie } }), }, fetcher: fetcher as unknown as typeof fetch, }); const capabilities = fixture.capabilities; if (!capabilities) throw new Error("feature capabilities were not composed"); return { capabilities, http: capabilities.http as InstalledHttpOperationExecutor, studioHttp: capabilities.studioHttp as InstalledHttpOperationExecutor, fetcher, }; } const list = (operation: readonly [string, string]) => fixture.withProfile(TEST_LIST_HTTP_CONTRACT, ...operation); function sent(fetcher: ReturnType, index: number) { const [url, init] = fetcher.mock.calls[index] as [RequestInfo | URL, RequestInit]; return { url: String(url), credentials: init.credentials, headers: new Headers(init.headers) }; } describe("09-02 product needs through the product-owned files only", () => { it("adds product capabilities next to the template's own", async () => { const { capabilities } = await compose(); expect(Object.keys(capabilities).sort()).toEqual( [...PRODUCT_NEEDS, "http", "telemetry"].sort(), ); expect(capabilities.runtime).toEqual({ appEnvironment: "local", apiBaseUrl: "http://localhost:8080/", }); expect(capabilities.studioSource).toBe("HTTP"); }); it("memento: offsetUpload sends the XSRF cookie while the scope is ready", async () => { const { capabilities, fetcher } = await compose({ cookie: "XSRF-TOKEN=xsrf-1" }); const offsetUpload = capabilities.offsetUpload as { upload(path: string, body: Blob): Promise; }; await expect(offsetUpload.upload("/api/uploads/1", new Blob(["chunk"]))).resolves.toBe(200); expect(sent(fetcher, 0).headers.get("x-xsrf-token")).toBe("xsrf-1"); }); it("memento: BFF reads go out signed out, with the cookie and no header", async () => { const { http, fetcher } = await compose(); const outcome = await http.execute(list(OPERATIONS.bffRead), { limit: 1 }, { routeId: "R" }); expect(outcome.kind).toBe("SUCCESS"); expect(sent(fetcher, 0).credentials).toBe("include"); expect([...sent(fetcher, 0).headers.keys()]).not.toContain("x-xsrf-token"); }); it("memento: BFF writes carry the XSRF cookie and fail closed without it", async () => { const withCookie = await compose({ cookie: "theme=dark; XSRF-TOKEN=xsrf-1" }); await expect( withCookie.http.execute(list(OPERATIONS.bffWrite), { limit: 1 }, { routeId: "R" }), ).resolves.toMatchObject({ kind: "SUCCESS" }); expect(sent(withCookie.fetcher, 0).headers.get("x-xsrf-token")).toBe("xsrf-1"); current?.infrastructure.dispose(); const without = await compose(); await expect( without.http.execute(list(OPERATIONS.bffWrite), { limit: 1 }, { routeId: "R" }), ).resolves.toMatchObject({ kind: "AUTH_INTEGRATION_FAILURE", reason: "CREDENTIAL_OWNER_UNAVAILABLE", }); expect(without.fetcher).not.toHaveBeenCalled(); }); it("tech-log: Studio calls fetch the CSRF token once and then send it", async () => { const { studioHttp, fetcher } = await compose(); for (let call = 0; call < 2; call += 1) { await expect( studioHttp.execute(list(OPERATIONS.studio), { limit: 1 }, { routeId: "STUDIO" }), ).resolves.toMatchObject({ kind: "SUCCESS" }); } expect(fetcher.mock.calls.map((_, index) => sent(fetcher, index).url)).toEqual([ "http://localhost:8080/api/test-entities/session", "http://localhost:8080/api/test-entities?limit=1", "http://localhost:8080/api/test-entities?limit=1", ]); expect(sent(fetcher, 0).headers.has("x-csrf-token")).toBe(false); expect(sent(fetcher, 2).headers.get("x-csrf-token")).toBe("studio-csrf"); }); it("tech-log: a 403 drops the Studio token so the next call fetches a new one", async () => { const { studioHttp, fetcher } = await compose({ studioStatus: 403 }); for (let call = 0; call < 2; call += 1) { await expect( studioHttp.execute(list(OPERATIONS.studio), { limit: 1 }, { routeId: "STUDIO" }), ).resolves.toMatchObject({ kind: "FORBIDDEN" }); } const sessionFetches = fetcher.mock.calls.filter(([url]) => String(url).endsWith("/session"), ); expect(sessionFetches).toHaveLength(2); }); it("tech-log: the product config key joins the strict document", () => { const parsed = (document: Record) => validateRuntimeConfig(document); expect(parsed({ ...CONFIG_DOCUMENT, TECH_LOG_STUDIO_SOURCE: "HTTP" })).toMatchObject({ success: true, data: { TECH_LOG_STUDIO_SOURCE: "HTTP" }, }); expect(parsed(CONFIG_DOCUMENT)).toMatchObject({ success: true, data: { TECH_LOG_STUDIO_SOURCE: "MOCK" }, }); expect(parsed({ ...CONFIG_DOCUMENT, TECH_LOG_STUDIO_SOURCE: "LIVE" })).toMatchObject({ success: false, issues: [{ path: "TECH_LOG_STUDIO_SOURCE" }], }); expect(parsed({ ...CONFIG_DOCUMENT, TECH_LOG_TYPO: "HTTP" })).toMatchObject({ success: false, issues: [{ path: "TECH_LOG_TYPO", code: "unrecognized_keys" }], }); // The build scripts read the same schema (generate-runtime-config.ts). expect( runtimeConfigV2ArtifactSchema.parse({ ...CONFIG_DOCUMENT, TECH_LOG_STUDIO_SOURCE: "HTTP" }), ).toMatchObject({ TECH_LOG_STUDIO_SOURCE: "HTTP" }); }); it("tech-log: the config key's FE-REG-ENV row joins ENV_REGISTRY", async () => { // check:registries and vite.config.ts read this same object. const { ENV_REGISTRY } = await import("../../src/contracts/env.ts"); expect(ENV_REGISTRY).toMatchObject({ APP_ENV: { phase: "runtime", classification: "public", required: true }, TECH_LOG_STUDIO_SOURCE: { phase: "runtime", classification: "public", required: false, defaultValue: "MOCK", }, }); }); it("tech-log: the BFF session owner is the session from boot, in external mode only", async () => { const session = async (options: Parameters[0]) => { const { fetcher } = await compose(options); const port = current?.outputPorts.session; if (!port) throw new Error("not composed"); await vi.waitFor(() => expect(port.getState()).not.toBe("recovery-pending")); const state = port.getState(); current?.infrastructure.dispose(); current = undefined; return { state, fetcher }; }; const signedIn = await session({ authMode: "external" }); expect(signedIn.state).toBe("authenticated"); expect(sent(signedIn.fetcher, 0)).toMatchObject({ url: "http://localhost:8080/api/v1/studio/session", credentials: "include", }); await expect( session({ authMode: "external", studioSessionStatus: 401 }), ).resolves.toMatchObject({ state: "unauthenticated" }); // The product's owner comes before the host's global owner. await expect( session({ authMode: "external", host: { __CA_FRONTEND_AUTH_OWNER__: hostOwner() } }), ).resolves.toMatchObject({ state: "authenticated" }); // The product returns none: the host's owner, or no owner, as before. await expect( session({ authMode: "external", studioSource: "MOCK", host: { __CA_FRONTEND_AUTH_OWNER__: hostOwner() }, }), ).resolves.toMatchObject({ state: "unauthenticated" }); await expect( session({ authMode: "external", studioSource: "MOCK" }), ).resolves.toMatchObject({ state: "integration-failed" }); expect(fixture.sessionOwnerRequests).toBe(5); // Demo mode keeps its own session and does not ask the product. fixture.sessionOwnerRequests = 0; await expect(session({})).resolves.toMatchObject({ state: "unauthenticated" }); expect(fixture.sessionOwnerRequests).toBe(0); }); }); /** A host-published owner that is signed out. */ function hostOwner() { return { readState: () => "unauthenticated", readSubject: () => null, subscribe: () => () => {}, beginSignIn: async () => {}, signOut: async () => {}, attachCredential: async () => ({ headers: {} }), recoverSession: async () => "no-session", notifyUnauthenticated() {}, }; } /** * The template files tech-log edited (af3d8e6 sync) for the needs above. They * stay template-owned; this fixture reaches the same result without them. */ const TECH_LOG_EDITED_TEMPLATE_FILES = [ "src/contracts/env.ts", "src/bootstrap/create-runtime-composition.ts", "src/bootstrap/runtime-config-schema.ts", "src/bootstrap/runtime-adapters.ts", ]; /** Stand in for an installed feature and observe its capabilities; not product code. */ const INSTALLED_FEATURE_SEAMS = [ "src/features/installed-contract-contributions.ts", "src/features/installed-feature-adapters.ts", ]; describe("09-02 the fixture replaces product-owned files only", () => { const source = (file: string) => readFile(new URL(`../../${file}`, import.meta.url), "utf8"); it("mocks the two product-owned files and none tech-log edited", async () => { const mocked = [ ...(await source("tests/unit/product-composition-fixture.test.ts")).matchAll( /vi\.(?:doMock|mock)\(\s*"\.\.\/\.\.\/(src\/[^"]+)"/g, ), ].flatMap((match) => (match[1] === undefined ? [] : [match[1]])); const product = [...new Set(mocked)] .filter((file) => !INSTALLED_FEATURE_SEAMS.includes(file)) .sort(); expect(product).toEqual([ "src/bootstrap/product-composition.ts", "src/contracts/product-contracts.ts", ]); for (const file of product) { expect(await source(file), file).toContain("Product-owned."); } for (const file of TECH_LOG_EDITED_TEMPLATE_FILES) { expect(await source(file), file).not.toContain("Product-owned."); } }); }); const EMPTY_PRODUCT = { PRODUCT_RUNTIME_CONFIG_FIELDS: {}, PRODUCT_REST_AUTH_PROFILES: {}, PRODUCT_ENV_REGISTRY: {}, }; describe("09-02 a product row cannot take a template name", () => { afterEach(() => { vi.doUnmock("../../src/contracts/product-contracts.ts"); vi.resetModules(); }); it.each([ { registry: "auth profiles", load: () => import("../../src/contracts/rest-profiles.ts"), product: { ...EMPTY_PRODUCT, PRODUCT_REST_AUTH_PROFILES: { ANONYMOUS: {} } }, error: "Product REST auth profile ANONYMOUS reuses a template profile id.", }, { registry: "runtime config", load: () => import("../../src/contracts/release-artifacts.ts"), product: { ...EMPTY_PRODUCT, PRODUCT_RUNTIME_CONFIG_FIELDS: { APP_ENV: {} } }, error: "Product runtime config key APP_ENV is a template key.", }, { registry: "FE-REG-ENV", load: () => import("../../src/contracts/env.ts"), product: { ...EMPTY_PRODUCT, PRODUCT_ENV_REGISTRY: { APP_ENV: {} } }, error: "Product env key APP_ENV is a template key.", }, ])("refuses to load ($registry)", async ({ load, product, error }) => { vi.resetModules(); vi.doMock("../../src/contracts/product-contracts.ts", () => product); await expect(load()).rejects.toThrow(error); }); });