feat(bootstrap): 제품 capability·자격증명·설정 키를 제품 소유 파일로 받는다 (1101/09-02)

문제
제품이 http·telemetry·indexedDb 밖의 capability, 세션 밖 자격증명(BFF
쿠키 XSRF, Studio CSRF), 제품 런타임 설정 키를 넣으려면
runtime-adapters.ts, feature-adapter-contribution.ts, rest-profiles.ts,
release-artifacts.ts, runtime-config-schema.ts를 직접 고쳐야 한다. 이
파일들은 템플릿이 보안·계약 수정을 자주 넣는 곳이라, 동기화 때마다
fail-closed 코드를 손으로 병합한다(memento +61줄, tech-log +118줄).

고른 방법 (리뷰 09 4.2의 (B))
- FeaturePlatformCapabilities를 interface로 바꾼다. 제품은 이 repo의
  FeatureIndexedDbRepositories·ApplicationFeatureInputs와 같은
  declaration merging으로 capability를 더한다.
- 제품 소유 파일 둘을 빈 구현으로 둔다.
  - src/bootstrap/product-composition.ts: 추가 capability와 "인증 프로필
    id → 자격증명 제공자" 표. 계약 타입은 템플릿 소유
    product-composition-contract.ts에 둔다.
  - src/contracts/product-contracts.ts: 제품 인증 프로필과 런타임 설정
    zod 조각. 프로필 레지스트리와 strict 설정 스키마는 contracts 층에
    있고 빌드 스크립트도 읽는다. contracts는 bootstrap을 import할 수
    없어서 파일을 하나로 합치지 못했다.
- 판단 순서는 조립 루트가 쥔다: scope fence → ANONYMOUS 프로필 → 제품
  제공자 → 세션 → 응답 뒤 fence 재확인. 제공자가 throw하면 executor가
  CREDENTIAL_OWNER_FAILED로 닫는다. 나가는 헤더는 여전히 프로필 허용
  목록이 정한다.
- 제공자 계약은 기존 attachCredentials 시그니처를 그대로 쓴다.
- 제품 composition은 http capability가 생긴 뒤에 부른다. tech-log가
  두었던 전방 참조 stub이 필요 없다.
- 제품에 host 전체를 넘기지 않고 readCookie(name)만 넘긴다. host를 객체에
  담으면 browser-data-boundary/no-capability-alias가 막는다.
- http·telemetry는 spread 뒤에 둬서 제품이 바꿀 수 없다(타입에서도 뺀다).
  제품 프로필 id나 설정 키가 템플릿 이름과 겹치면 모듈 로드 때 throw한다.

버린 대안
- (A) 현 상태: 템플릿 비용은 0이지만 제품마다 동기화 비용이 반복된다.
- (C) 기능 계약 기여가 인증 프로필과 제공자를 함께 가져온다: 인증
  정책이 기능마다 흩어져 보안 리뷰 범위가 넓어진다.
- 제공자에 응답 관찰 훅 추가: tech-log의 401/403 토큰 폐기는 제품
  capability가 http를 감싸서 표현된다(픽스처). 제공자 계약을 작게 둔다.

위험·한계
- memento의 x-xsrf-token은 닫힌 자격증명 헤더 목록(VD-23,
  CREDENTIAL_HEADER_NAMES)에 없다. 그 이름을 쓰려면 여전히
  rest-profiles.ts를 고치거나 백엔드가 x-csrf-token을 받아야 한다.
  픽스처는 x-csrf-token으로 표현했다.
- 제품 설정 키의 FE-REG-ENV 행(src/contracts/env.ts)은 이 변경 밖이다.
  그 행을 요구하는 검사는 없다.
- tech-log가 부트 전에 BFF 세션 owner를 설치하는 코드
  (create-runtime-composition.ts)는 이 확장 지점 밖이다.
- 제공자 응답 뒤 fence 재확인은 executor가 같은 fence로 먼저 전송을
  끊어서 조립 루트 경유 테스트로는 따로 보이지 않는다. 세션 경로와 같은
  이중 방어로 둔다.
- V1 설정 문서도 제품 키를 받는다(없으면 기본값). V1은 한 릴리스 동안만
  쓰는 리더다.
- 초기 JS gzip 203,818 → 204,178 B(+360, 예산 204,800).

검증
- RED: tests/unit/runtime-adapters-credential-order.test.ts 7행 중 제품
  제공자를 기대하는 4행 실패(세션이 먼저 답해 UNAUTHENTICATED, owner가
  먼저 답해 SUCCESS). fence·ANONYMOUS·세션 3행은 통과.
- GREEN: 같은 파일 7/7. tests/unit/product-composition-fixture.test.ts
  9/9(가짜 제품 파일 두 개로 offsetUpload, runtime, BFF 쿠키 XSRF 읽기·
  쓰기, Studio CSRF 발급·403 폐기, 제품 설정 키, 이름 충돌 거절). 09-01
  tests/unit/runtime-adapters-auth-profile.test.ts 12/12.
- 회귀: tests/unit·contract·runtime-schema 182 files 2590 tests 통과.
  integration·component 47 files 386 tests 통과(pnpm을 띄우는
  security-followup-archive 제외). tsc app·test·node·recipes·web-worker·
  service-worker 통과. 바꾼 파일 eslint 통과. check:registries PASS
  (compatibility=breaking은 기존 route·storage 행). verify:documentation
  PASS_SCOPED. check:adapter-inventory PASS. check:architecture는 pnpm 대신
  exec 전용 shim으로 그래프·fixture PASS. 템플릿 런타임 설정 JSON
  schema는 baseline과 같다.
This commit is contained in:
DongHyeonka
2026-11-03 00:56:40 +09:00
parent de379ea78d
commit da1e128999
13 changed files with 1034 additions and 32 deletions
@@ -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 <id> 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 <id> 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
+2 -1
View File
@@ -167,7 +167,8 @@ Files outside the feature directory:
| `src/.generated/*` | regenerated automatically |
| `src/contexts/<context>/context-module.ts` | only when the feature needs a new context |
| `config/runtime/<profile>.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
@@ -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
@@ -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<Omit<FeaturePlatformCapabilities, TemplatePlatformCapabilityId>>
>;
/** Auth profile id → provider. An ANONYMOUS profile never reaches one. */
credentialProviders: Readonly<Record<string, ProductCredentialProvider>>;
}>;
+15
View File
@@ -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;
}
+56 -5
View File
@@ -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<string, unknown>,
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<string, unknown>;
@@ -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,
});
+19 -1
View File
@@ -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<ProductRuntimeConfig>;
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
+14
View File
@@ -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({});
+32 -11
View File
@@ -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 extends Record<string, z.ZodType>>(
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);
+19 -2
View File
@@ -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<Record<string, RestAuthProfile>> {
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({
+9 -5
View File
@@ -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;
@@ -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<number | "NO_CREDENTIAL">;
}>;
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<string, unknown> | undefined,
withProfile<T extends { contract: object; frontend: object }>(
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<string> | 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<InstalledHttpOperationExecutor["execute"]>) {
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<typeof import("../../src/features/installed-contract-contributions.ts")>();
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<typeof import("../../src/features/installed-feature-adapters.ts")>();
return {
...original,
createInstalledFeatureLoaders: (
...args: Parameters<typeof original.createInstalledFeatureLoaders>
) => {
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<typeof createRuntimeAdapters>[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<ReturnType<typeof createRuntimeAdapters>> | 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<typeof vi.fn>, 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<unknown>;
};
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<string, unknown>) => 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);
});
});
@@ -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<string, unknown>,
withProfile<T extends { contract: object; frontend: object }>(
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<typeof import("../../src/features/installed-contract-contributions.ts")>();
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<typeof import("../../src/features/installed-feature-adapters.ts")>();
return {
...original,
createInstalledFeatureLoaders: (
...args: Parameters<typeof original.createInstalledFeatureLoaders>
) => {
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<typeof createRuntimeAdapters>[0]["runtime"];
type Adapters = Awaited<ReturnType<typeof createRuntimeAdapters>>;
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<typeof createRuntimeAdapters>[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<string, unknown> = {},
) {
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<typeof externalOwner>) => Record<string, ProductCredentialProvider>;
authMode: "demo" | "external";
/** Runs after composition, before the request. */
before?: (adapters: Adapters) => void;
operation: typeof PROFILE_OPERATION;
outcome: Record<string, unknown>;
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);
}
});
});