diff --git a/docs/architecture/frontend-application-foundation.md b/docs/architecture/frontend-application-foundation.md index 5ecc6466..affa03ae 100644 --- a/docs/architecture/frontend-application-foundation.md +++ b/docs/architecture/frontend-application-foundation.md @@ -166,10 +166,20 @@ runtime (`productionComposition: false` in `recipes/frontend-capabilities/indexeddb-feature-capability.ts` (`createLocalDraftIndexedDbCapability`, exercised by `tests/recipes/indexeddb-feature-capability.test.ts`). A product that installs a -feature with `needs: ["indexedDb"]` copies it and adds `indexedDb` to the feature -capabilities in `src/bootstrap/runtime-adapters.ts`. Until it does, that object -fails the app typecheck, and `composeFeatureAdapterInputs()` rejects the -composition with `feature needs indexedDb, which the host did not provide`. +feature with `needs: ["indexedDb"]` copies it and returns `indexedDb` from the +product-owned `src/bootstrap/product-composition.ts`. Until it does, the feature +capabilities in `src/bootstrap/runtime-adapters.ts` fail the app typecheck, and +`composeFeatureAdapterInputs()` rejects the composition with +`feature needs indexedDb, which the host did not provide`. + +The same file is where a product adds any other capability (it augments +`FeaturePlatformCapabilities`) and the credential provider for a product auth +profile. The composition root keeps the order: scope fence, `ANONYMOUS` +profile, product provider, session, scope fence again +(`tests/unit/runtime-adapters-credential-order.test.ts`). Product auth profiles +and runtime-config keys go in `src/contracts/product-contracts.ts`; both join +the template's registries under the same checks +(`tests/unit/product-composition-fixture.test.ts`). ## Presentation consumer surface diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index 6db25faa..f2aee656 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -167,7 +167,8 @@ Files outside the feature directory: | `src/.generated/*` | regenerated automatically | | `src/contexts//context-module.ts` | only when the feature needs a new context | | `config/runtime/.json` | optional `FEATURE_OVERRIDES` entry to switch the feature off | -| `src/bootstrap/runtime-adapters.ts` | only when `needs` includes `indexedDb`: add the capability, built as in `recipes/frontend-capabilities/indexeddb-feature-capability.ts` | +| `src/bootstrap/product-composition.ts` (product-owned) | only when `needs` names a capability the template does not build: augment `FeaturePlatformCapabilities` and return the capability here. `indexedDb` is built as in `recipes/frontend-capabilities/indexeddb-feature-capability.ts`. Credentials for a product auth profile are returned here too | +| `src/contracts/product-contracts.ts` (product-owned) | only for a product auth profile or a product runtime-config key | The central catalogs (`src/features/installed-*.ts`) and the registry governance file do not change: consumer directories there are globs over every diff --git a/recipes/frontend-capabilities/indexeddb-feature-capability.ts b/recipes/frontend-capabilities/indexeddb-feature-capability.ts index c5b7aeb7..380a3e94 100644 --- a/recipes/frontend-capabilities/indexeddb-feature-capability.ts +++ b/recipes/frontend-capabilities/indexeddb-feature-capability.ts @@ -25,9 +25,9 @@ type LocalDraftRuntime = ReturnType< * (`offline-indexeddb` in config/recipes/frontend-capability-recipes.json, * `productionComposition: false`), so `src/bootstrap/runtime-adapters.ts` does * not build it. A product that installs a feature with `needs: ["indexedDb"]` - * copies this into its composition, replaces the codec, migrations and storage - * policy with its own decisions, and adds `indexedDb` to the feature - * capabilities there; until it does, that object fails the app typecheck and + * copies this into `src/bootstrap/product-composition.ts`, replaces the codec, + * migrations and storage policy with its own decisions, and returns `indexedDb` + * there; until it does, the feature capabilities fail the app typecheck and * `composeFeatureAdapterInputs` names the missing capability. * * The scope tokens come from the product's storage registry and the lifecycle diff --git a/src/bootstrap/product-composition-contract.ts b/src/bootstrap/product-composition-contract.ts new file mode 100644 index 00000000..7ff68812 --- /dev/null +++ b/src/bootstrap/product-composition-contract.ts @@ -0,0 +1,45 @@ +import type { + ContractHttpExecutorDependencies, + InstalledHttpOperationExecutor, +} from "../adapters/http/index.ts"; +import type { FeaturePlatformCapabilities } from "../features/feature-adapter-contribution.ts"; +import type { RuntimeConfig } from "./runtime-config-schema.ts"; + +/** + * 09-02. The template's half of the product extension point. A product fills + * `product-composition.ts` (and `src/contracts/product-contracts.ts` for auth + * profiles and runtime-config keys) and never edits `runtime-adapters.ts`. + */ + +/** Built by the template; a product cannot return or replace them. */ +export type TemplatePlatformCapabilityId = "http" | "telemetry"; + +/** + * Credentials for one product auth profile, in the same contract as the + * composition root's own `attachCredentials`. The template calls it only after + * the scope fence and the ANONYMOUS check, before the session, and checks the + * fence again after it answers. A throw closes as `CREDENTIAL_OWNER_FAILED`; + * the executor still sends only the headers the profile allows. + */ +export type ProductCredentialProvider = + ContractHttpExecutorDependencies["attachCredentials"]; + +export type ProductCompositionContext = Readonly<{ + /** Validated runtime config, product keys included. */ + config: RuntimeConfig; + /** A cookie of the page (double-submit CSRF), read when called. */ + readCookie(name: string): string | undefined; + fetcher?: typeof fetch; + /** The `http` capability features receive. Call it per request, not while composing. */ + http: InstalledHttpOperationExecutor; + /** False while a session change fences server state; send nothing then. */ + isScopeReady(): boolean; +}>; + +export type ProductComposition = Readonly<{ + capabilities: Readonly< + Partial> + >; + /** Auth profile id โ†’ provider. An ANONYMOUS profile never reaches one. */ + credentialProviders: Readonly>; +}>; diff --git a/src/bootstrap/product-composition.ts b/src/bootstrap/product-composition.ts new file mode 100644 index 00000000..11708fc3 --- /dev/null +++ b/src/bootstrap/product-composition.ts @@ -0,0 +1,15 @@ +import type { + ProductComposition, + ProductCompositionContext, +} from "./product-composition-contract.ts"; + +/** + * Product-owned. The template ships it empty and does not change it after a + * copy; the contract is in `product-composition-contract.ts`. + */ +export function composeProduct(context: ProductCompositionContext) { + return { + capabilities: {}, + credentialProviders: {}, + } satisfies ProductComposition; +} diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 161449c4..47ddb848 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -64,6 +64,8 @@ import { } from "./load-release-manifest.ts"; import type { RuntimeConfigLoadResult } from "./load-runtime-config.ts"; import { createServerStateGenerationStore } from "./server-state-generation-store.ts"; +import { composeProduct } from "./product-composition.ts"; +import type { ProductComposition } from "./product-composition-contract.ts"; import { createInstalledContractRegistry } from "../features/installed-contract-contributions.ts"; import { indexInvalidationRegistry, @@ -170,6 +172,31 @@ function hostValue( } } +/** + * 09-02. The one host value a product credential reads: a double-submit CSRF + * cookie such as a BFF's `XSRF-TOKEN`. The host itself is not handed out. + */ +function hostCookie( + host: Record, + name: string, +): string | undefined { + const page = hostValue(host, "document"); + const cookie = isRecord(page) ? hostValue(page, "cookie") : undefined; + if (typeof cookie !== "string") return undefined; + const prefix = `${encodeURIComponent(name)}=`; + const entry = cookie + .split(";") + .map((part) => part.trim()) + .find((part) => part.startsWith(prefix)); + try { + return entry === undefined + ? undefined + : decodeURIComponent(entry.slice(prefix.length)); + } catch { + return undefined; + } +} + function storageOrUndefined(value: unknown): Storage | undefined { if (!value || typeof value !== "object") return undefined; const candidate = value as Record; @@ -520,6 +547,17 @@ export async function createRuntimeAdapters( ) { return Object.freeze({ kind: "READY" as const, headers: {} }); } + // 09-02. A product provider answers for its own profiles, between the + // checks above and the session. A throw is left to the executor, which + // closes it as CREDENTIAL_OWNER_FAILED. `productCredentialProviders` is + // set below, before any request can run. + if (Object.hasOwn(productCredentialProviders, operation.authProfileId)) { + const provider = productCredentialProviders[operation.authProfileId]; + const answer = await provider(operation, authContext); + return serverStateScope.getPhase() === "READY" + ? answer + : Object.freeze({ kind: "SCOPE_FENCED" as const }); + } const state = authSession.getState(); if (state === "integration-failed") { return Object.freeze({ kind: "UNAVAILABLE" as const }); @@ -622,13 +660,26 @@ export async function createRuntimeAdapters( ...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }), ...(telemetryCollector === undefined ? {} : { collector: telemetryCollector }), }); + // 09-02. The product half of the composition. It runs after `http` exists, + // so a provider can fetch its token through it, and before any feature loads. + const product = composeProduct({ + config, + readCookie: (name) => hostCookie(host, name), + ...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }), + http: contractOperations, + isScopeReady: () => serverStateScope.getPhase() === "READY", + }) satisfies ProductComposition; + const productCredentialProviders: ProductComposition["credentialProviders"] = + product.credentialProviders; // Each installed contribution receives only the capabilities it declares. - // 09-05. `indexedDb` is not built here: IndexedDB is an opt-in reference - // runtime (`productionComposition: false`). Installing a feature that needs - // it makes this object fail the app typecheck until the product adds - // `indexedDb`, built as in recipes/frontend-capabilities/ - // indexeddb-feature-capability.ts. + // The template's own capabilities come last, so a product cannot replace + // them. 09-05. `indexedDb` is not built here: IndexedDB is an opt-in + // reference runtime (`productionComposition: false`). Installing a feature + // that needs it makes this object fail the app typecheck until the product + // returns `indexedDb` from product-composition.ts, built as in + // recipes/frontend-capabilities/indexeddb-feature-capability.ts. const featureCapabilities = Object.freeze({ + ...product.capabilities, http: contractOperations, telemetry: featureTelemetry, }); diff --git a/src/bootstrap/runtime-config-schema.ts b/src/bootstrap/runtime-config-schema.ts index 6eae5b04..1d6aca3c 100644 --- a/src/bootstrap/runtime-config-schema.ts +++ b/src/bootstrap/runtime-config-schema.ts @@ -1,4 +1,5 @@ import type { ProductFeatureOverrideMap } from "../contracts/product-features.ts"; +import { PRODUCT_RUNTIME_CONFIG_FIELDS } from "../contracts/product-contracts.ts"; import { runtimeConfigV1ArtifactSchema, runtimeConfigV2ArtifactSchema, @@ -28,6 +29,12 @@ export const runtimeConfigV1Schema = runtimeConfigV1ArtifactSchema; export type RuntimeConfigV2 = RuntimeConfigV2Artifact; export type RuntimeConfigV1 = RuntimeConfigV1Artifact; +/** 09-02. The product's keys from `product-contracts.ts`, as validated. */ +type ProductRuntimeConfig = Pick< + RuntimeConfigV2, + keyof typeof PRODUCT_RUNTIME_CONFIG_FIELDS +>; + /** * The composition-facing shape. V1 documents are normalized onto it so the rest * of the runtime never branches on config schema version. @@ -52,7 +59,8 @@ export type RuntimeConfig = Readonly<{ FEATURE_OVERRIDES: ProductFeatureOverrideMap; /** Present only while a V1 document is still accepted. */ LEGACY_API_CONTRACT_VERSION?: string; -}>; +}> & + Readonly; export type RuntimeConfigValidation = | Readonly<{ success: true; data: RuntimeConfig; schema: "V1" | "V2" }> @@ -68,6 +76,15 @@ const DEFAULT_OVERRIDES: CapabilityOverrides = Object.freeze({ OFFLINE_COMMANDS: "DEFAULT" as const, }); +function productRuntimeConfig(parsed: object): ProductRuntimeConfig { + return Object.fromEntries( + Object.keys(PRODUCT_RUNTIME_CONFIG_FIELDS).flatMap((key) => { + const value: unknown = Reflect.get(parsed, key); + return value === undefined ? [] : [[key, value]]; + }), + ) as ProductRuntimeConfig; +} + function canonicalUrl(value: string): string { return new URL(value).href; } @@ -130,6 +147,7 @@ export function validateRuntimeConfig(value: unknown): RuntimeConfigValidation { RELEASE_MANIFEST_URL: parsed.RELEASE_MANIFEST_URL, ...(parsed.RELEASE_ID ? { RELEASE_ID: parsed.RELEASE_ID } : {}), ...(parsed.BUILD_ID ? { BUILD_ID: parsed.BUILD_ID } : {}), + ...productRuntimeConfig(parsed), CAPABILITY_OVERRIDES: Object.freeze({ ...(isV2 ? (parsed as RuntimeConfigV2).CAPABILITY_OVERRIDES diff --git a/src/contracts/product-contracts.ts b/src/contracts/product-contracts.ts new file mode 100644 index 00000000..05d12598 --- /dev/null +++ b/src/contracts/product-contracts.ts @@ -0,0 +1,14 @@ +/** + * Product-owned. The template ships both values empty and does not change + * this file after a copy. + * + * - `PRODUCT_RUNTIME_CONFIG_FIELDS`: zod fields joined to the strict runtime + * config document (`release-artifacts.ts`). + * - `PRODUCT_REST_AUTH_PROFILES`: auth profiles installed next to the + * template's (`rest-profiles.ts`); credentials for them come from + * `src/bootstrap/product-composition.ts`. + */ + +export const PRODUCT_RUNTIME_CONFIG_FIELDS = Object.freeze({}); + +export const PRODUCT_REST_AUTH_PROFILES = Object.freeze({}); diff --git a/src/contracts/release-artifacts.ts b/src/contracts/release-artifacts.ts index f662b422..a5f7fba7 100644 --- a/src/contracts/release-artifacts.ts +++ b/src/contracts/release-artifacts.ts @@ -1,6 +1,7 @@ import { z } from "./zod.ts"; import { contractSetSchema } from "./contract-set.ts"; +import { PRODUCT_RUNTIME_CONFIG_FIELDS } from "./product-contracts.ts"; const versionSchema = z.string().regex(/^\d+(?:\.\d+){0,2}$/); @@ -151,6 +152,22 @@ const runtimeConfigArtifactFields = { BUILD_ID: z.string().min(1).optional(), } as const; +/** + * 09-02. The product's keys (`product-contracts.ts`) join the strict document + * and are validated with it. A product key cannot take a template key's name. + */ +function withProductFields>( + shape: Shape, +) { + const reused = Object.keys(PRODUCT_RUNTIME_CONFIG_FIELDS).find((key) => + Object.hasOwn(shape, key), + ); + if (reused !== undefined) { + throw new TypeError(`Product runtime config key ${reused} is a template key.`); + } + return { ...shape, ...PRODUCT_RUNTIME_CONFIG_FIELDS }; +} + /** * @deprecated V1 reader kept for one release after the V2-only writer * (change evidence `FE-REG-ENV:API_CONTRACT_VERSION:*:removed`, 2026-09-24). @@ -159,21 +176,25 @@ const runtimeConfigArtifactFields = { * (owner: frontend-platform). */ export const runtimeConfigV1ArtifactSchema = z - .object({ - ...runtimeConfigArtifactFields, - CONFIG_SCHEMA_VERSION: z.literal("1"), - API_CONTRACT_VERSION: versionSchema, - }) + .object( + withProductFields({ + ...runtimeConfigArtifactFields, + CONFIG_SCHEMA_VERSION: z.literal("1"), + API_CONTRACT_VERSION: versionSchema, + }), + ) .strict() .superRefine(runtimeConfigArtifactInvariants); export const runtimeConfigV2ArtifactSchema = z - .object({ - ...runtimeConfigArtifactFields, - CONFIG_SCHEMA_VERSION: z.literal("2.0"), - CAPABILITY_OVERRIDES: capabilityOverrideArtifactSchema, - FEATURE_OVERRIDES: featureOverrideArtifactSchema, - }) + .object( + withProductFields({ + ...runtimeConfigArtifactFields, + CONFIG_SCHEMA_VERSION: z.literal("2.0"), + CAPABILITY_OVERRIDES: capabilityOverrideArtifactSchema, + FEATURE_OVERRIDES: featureOverrideArtifactSchema, + }), + ) .strict() .superRefine(runtimeConfigArtifactInvariants); diff --git a/src/contracts/rest-profiles.ts b/src/contracts/rest-profiles.ts index 796eb39a..1bbdfd8c 100644 --- a/src/contracts/rest-profiles.ts +++ b/src/contracts/rest-profiles.ts @@ -4,6 +4,7 @@ import { } from "./read-only-registry.ts"; import { snapshotExactArray, snapshotExactObject } from "./exact-snapshot.ts"; import { isLoopbackHostname } from "./deployment-admission.ts"; +import { PRODUCT_REST_AUTH_PROFILES } from "./product-contracts.ts"; export type FetchCredentialsMode = "omit" | "same-origin" | "include"; @@ -238,9 +239,25 @@ function installedAuthProfiles( ); } -/** The single installed registry every composition root shares. */ +function withProductProfiles(): Readonly> { + const reused = Object.keys(PRODUCT_REST_AUTH_PROFILES).find((id) => + Object.hasOwn(REST_AUTH_PROFILES, id), + ); + if (reused !== undefined) { + throw new TypeError( + `Product REST auth profile ${reused} reuses a template profile id.`, + ); + } + return { ...REST_AUTH_PROFILES, ...PRODUCT_REST_AUTH_PROFILES }; +} + +/** + * The single installed registry every composition root shares. 09-02. It + * holds the product's profiles (`product-contracts.ts`) too, under the same + * checks. + */ export const INSTALLED_REST_AUTH_PROFILES: InstalledRestAuthProfiles = - installRestAuthProfileRegistry(); + installRestAuthProfileRegistry(withProductProfiles()); export const REST_CSRF_PROFILES = Object.freeze({ NO_CSRF_BEARER: Object.freeze({ diff --git a/src/features/feature-adapter-contribution.ts b/src/features/feature-adapter-contribution.ts index 087a482a..fcda2418 100644 --- a/src/features/feature-adapter-contribution.ts +++ b/src/features/feature-adapter-contribution.ts @@ -43,12 +43,16 @@ export function createIndexedDbRepositoryProvider( }); } -export type FeaturePlatformCapabilities = Readonly<{ - http: InstalledHttpOperationExecutor; - indexedDb: IndexedDbRepositoryProvider; +/** + * 09-02. A product adds a capability by augmenting this interface and + * returning the value from `src/bootstrap/product-composition.ts`. + */ +export interface FeaturePlatformCapabilities { + readonly http: InstalledHttpOperationExecutor; + readonly indexedDb: IndexedDbRepositoryProvider; /** Spec ยง24. Provider-neutral, bounded, fail-open feature telemetry. */ - telemetry: TelemetryPort; -}>; + readonly telemetry: TelemetryPort; +} export type FeaturePlatformCapabilityId = keyof FeaturePlatformCapabilities; diff --git a/tests/unit/product-composition-fixture.test.ts b/tests/unit/product-composition-fixture.test.ts new file mode 100644 index 00000000..fac1d988 --- /dev/null +++ b/tests/unit/product-composition-fixture.test.ts @@ -0,0 +1,465 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts"; +import type { + ProductComposition, + ProductCompositionContext, +} 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 and its product runtime-config key โ€” expressed by + * filling only the two product-owned files: + * + * - `src/contracts/product-contracts.ts`: product auth profiles and config keys + * - `src/bootstrap/product-composition.ts`: 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, + 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"[], + ) => + 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"), + }), + PRODUCT_REST_AUTH_PROFILES: Object.freeze({ + MEMENTO_BFF_READ: cookieProfile("MEMENTO_BFF_READ", []), + MEMENTO_BFF_WRITE: cookieProfile("MEMENTO_BFF_WRITE", ["x-csrf-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); + + 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-csrf-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 }; +}); + +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; +}); + +async function compose(options: Readonly<{ cookie?: string; studioStatus?: number }> = {}) { + const validated = validateRuntimeConfig({ + ...CONFIG_DOCUMENT, + TECH_LOG_STUDIO_SOURCE: "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/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.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-csrf-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-csrf-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" }); + }); +}); + +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: { PRODUCT_RUNTIME_CONFIG_FIELDS: {}, 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: { PRODUCT_RUNTIME_CONFIG_FIELDS: { APP_ENV: {} }, PRODUCT_REST_AUTH_PROFILES: {} }, + error: "Product runtime config 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); + }); +}); diff --git a/tests/unit/runtime-adapters-credential-order.test.ts b/tests/unit/runtime-adapters-credential-order.test.ts new file mode 100644 index 00000000..618cb9b5 --- /dev/null +++ b/tests/unit/runtime-adapters-credential-order.test.ts @@ -0,0 +1,341 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts"; +import type { ProductCredentialProvider } from "../../src/bootstrap/product-composition-contract.ts"; +import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; +import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts"; + +/** + * 09-02. The composition root alone decides the order a credential is looked + * for, so a product credential provider can never run outside the fences: + * + * scope fence -> ANONYMOUS profile -> product provider -> session -> scope fence again + * + * Each row runs the real `createRuntimeAdapters`. Replaced: the installed + * contract set (adds the fixture operations), the feature-input composer (to + * reach the `http` capability) and the product-owned composition file (the + * provider table under test). + */ + +const fixture = vi.hoisted(() => ({ + http: undefined as InstalledHttpOperationExecutor | undefined, + providers: {} as Record, + withProfile( + contract: T, + operationId: string, + authProfileId: string, + ): T { + return { + ...contract, + contract: { ...contract.contract, operationId }, + frontend: { ...contract.frontend, authProfileId }, + }; + }, +})); + +vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => { + const original = + await importOriginal(); + const { TEST_CONTRACT_CONTRIBUTION, TEST_LIST_HTTP_CONTRACT: list } = + await import("../helpers/external-contract-fixture.ts"); + const source = TEST_CONTRACT_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(TEST_CONTRACT_CONTRIBUTION.featureId, [ + { + ...TEST_CONTRACT_CONTRIBUTION, + http: [ + list, + fixture.withProfile(list, "TEST_LIST_ENTITIES_BEARER", "REFERENCE_EXTERNAL_BEARER"), + ] as typeof TEST_CONTRACT_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 typeof fixture.http; + return original.createInstalledFeatureLoaders(...args); + }, + }; +}); + +/** The product-owned file, filled the way a product fills it. */ +vi.mock("../../src/bootstrap/product-composition.ts", () => ({ + composeProduct: () => ({ + capabilities: {}, + credentialProviders: fixture.providers, + }), +})); + +type Runtime = Parameters[0]["runtime"]; +type Adapters = Awaited>; + +function runtimeFor(authMode: "demo" | "external"): Runtime { + return { + config: { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + TELEMETRY_ENABLED: false, + AUTH_MODE: authMode, + 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, + }; +} + +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" }, +}; + +const ANONYMOUS_OPERATION = TEST_LIST_HTTP_CONTRACT; +/** The only non-anonymous profile the template installs. */ +const PROFILE_OPERATION = fixture.withProfile( + TEST_LIST_HTTP_CONTRACT, + "TEST_LIST_ENTITIES_BEARER", + "REFERENCE_EXTERNAL_BEARER", +); + +function externalOwner() { + const listeners = new Set<() => void>(); + let subject = "user-a"; + return { + readState: () => "authenticated", + readSubject: () => subject, + subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + beginSignIn: async () => {}, + signOut: async () => {}, + attachCredential: vi.fn(async () => ({ + headers: { authorization: "Bearer owner-token" }, + })), + recoverSession: async () => "no-session", + notifyUnauthenticated: () => {}, + switchUser() { + subject = "user-b"; + for (const listener of listeners) listener(); + }, + }; +} + +let current: Adapters | undefined; +afterEach(() => { + current?.infrastructure.dispose(); + current = undefined; + fixture.http = undefined; + fixture.providers = {}; +}); + +async function compose( + authMode: "demo" | "external", + host: Record = {}, +) { + const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => + Response.json([{ id: "entity-1", name: "Entity" }]), + ); + current = await createRuntimeAdapters({ + runtime: runtimeFor(authMode), + release, + host, + fetcher: fetcher as unknown as typeof fetch, + }); + const http = fixture.http; + if (!http) throw new Error("The http capability was not composed"); + return { adapters: current, http, fetcher }; +} + +const productToken: ProductCredentialProvider = async () => ({ + kind: "READY", + headers: { authorization: "Bearer product-token" }, +}); + +type Row = Readonly<{ + step: string; + /** Builds the product provider table; may close over the composed state. */ + providers: (owner: ReturnType) => Record; + authMode: "demo" | "external"; + /** Runs after composition, before the request. */ + before?: (adapters: Adapters) => void; + operation: typeof PROFILE_OPERATION; + outcome: Record; + sentAuthorization: string | null; + providerCalls: number; + ownerCalls: number; +}>; + +const ROWS: readonly Row[] = [ + { + step: "1 scope fence comes before the product provider", + providers: () => ({ REFERENCE_EXTERNAL_BEARER: productToken }), + authMode: "demo", + // The session change fences the scope synchronously; READY comes later. + before: (adapters) => void adapters.outputPorts.session.beginSignIn(), + operation: PROFILE_OPERATION, + outcome: { kind: "CONTRACT_VIOLATION", violation: { kind: "SCOPE_FENCED" } }, + sentAuthorization: null, + providerCalls: 0, + ownerCalls: 0, + }, + { + step: "2 an ANONYMOUS profile never reaches a provider", + providers: () => ({ ANONYMOUS: productToken }), + authMode: "demo", + operation: ANONYMOUS_OPERATION, + outcome: { kind: "SUCCESS" }, + sentAuthorization: null, + providerCalls: 0, + ownerCalls: 0, + }, + { + step: "3 a registered provider answers before the session (signed out)", + providers: () => ({ REFERENCE_EXTERNAL_BEARER: productToken }), + authMode: "demo", + operation: PROFILE_OPERATION, + outcome: { kind: "SUCCESS" }, + sentAuthorization: "Bearer product-token", + providerCalls: 1, + ownerCalls: 0, + }, + { + step: "3 a registered provider answers before the external owner", + providers: () => ({ REFERENCE_EXTERNAL_BEARER: productToken }), + authMode: "external", + operation: PROFILE_OPERATION, + outcome: { kind: "SUCCESS" }, + sentAuthorization: "Bearer product-token", + providerCalls: 1, + ownerCalls: 0, + }, + { + step: "4 a profile without a provider still needs the session", + providers: () => ({}), + authMode: "demo", + operation: PROFILE_OPERATION, + outcome: { kind: "UNAUTHENTICATED", effect: "NOT_APPLICABLE" }, + sentAuthorization: null, + providerCalls: 0, + ownerCalls: 0, + }, + { + step: "5 the scope fence is checked again after the provider answers", + providers: (owner) => ({ + REFERENCE_EXTERNAL_BEARER: async (...args) => { + owner.switchUser(); + return productToken(...args); + }, + }), + authMode: "external", + operation: PROFILE_OPERATION, + // A fence during the credential wait aborts the transport (Q-6.3-6). The + // composition root's own re-check behind it is not visible from here. + outcome: { kind: "TRANSPORT_FAILURE", failure: { kind: "ABORTED_BY_SCOPE" } }, + sentAuthorization: null, + providerCalls: 1, + ownerCalls: 0, + }, + { + step: "6 a provider that throws fails closed", + providers: () => ({ + REFERENCE_EXTERNAL_BEARER: async () => { + throw new Error("product provider down"); + }, + }), + authMode: "demo", + operation: PROFILE_OPERATION, + outcome: { + kind: "AUTH_INTEGRATION_FAILURE", + reason: "CREDENTIAL_OWNER_FAILED", + }, + sentAuthorization: null, + providerCalls: 1, + ownerCalls: 0, + }, +]; + +describe("09-02 credential order in the composition root", () => { + it.each(ROWS)("$step", async (row) => { + const owner = externalOwner(); + const providerCalls = vi.fn(); + fixture.providers = Object.fromEntries( + Object.entries(row.providers(owner)).map(([profileId, provider]) => [ + profileId, + ((...args) => { + providerCalls(profileId); + return provider(...args); + }) satisfies ProductCredentialProvider, + ]), + ); + const { http, fetcher, adapters } = await compose( + row.authMode, + row.authMode === "external" ? { __CA_FRONTEND_AUTH_OWNER__: owner } : {}, + ); + row.before?.(adapters); + + const outcome = await http.execute( + row.operation, + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + expect(outcome).toMatchObject(row.outcome); + expect(providerCalls).toHaveBeenCalledTimes(row.providerCalls); + expect(owner.attachCredential).toHaveBeenCalledTimes(row.ownerCalls); + if (row.sentAuthorization === null) { + for (const [, init] of fetcher.mock.calls) { + expect(new Headers(init?.headers).has("authorization")).toBe(false); + } + } else { + expect(fetcher).toHaveBeenCalledOnce(); + expect( + new Headers(fetcher.mock.calls[0]?.[1]?.headers).get("authorization"), + ).toBe(row.sentAuthorization); + } + }); +});