From ece944d08b8ea006b545634023ddc18d567e76fe Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 20:22:29 +0900 Subject: [PATCH] =?UTF-8?q?feat(bootstrap):=20=EC=A0=9C=ED=92=88=20?= =?UTF-8?q?=EC=84=B8=EC=85=98=20owner=EC=99=80=20FE-REG-ENV=20=ED=96=89?= =?UTF-8?q?=EC=9D=84=20=EC=A0=9C=ED=92=88=20=ED=8C=8C=EC=9D=BC=EB=A1=9C=20?= =?UTF-8?q?=EB=B0=9B=EB=8A=94=EB=8B=A4=20(1101/09-02)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 09-02(da1e128) 뒤에도 tech-log가 하는 일 두 가지는 템플릿 파일을 고쳐야 한다(리뷰 1101 README 14.4 "09-02 이식"). - 제품 설정 키의 FE-REG-ENV 행: tech-log는 템플릿 src/contracts/env.ts의 ENV_REGISTRY에 TECH_LOG_STUDIO_SOURCE·TECH_LOG_PUBLIC_SOURCE 행을 직접 넣었다(tech-log env.ts:63-70). - 부트 전 BFF 세션 owner: 세션이 httpOnly 쿠키라 owner가 백엔드에 묻는다. tech-log는 템플릿 create-runtime-composition.ts에서 AUTH_MODE external이고 Studio가 HTTP일 때 createRuntimeAdapters 전에 host 전역 __CA_FRONTEND_AUTH_OWNER__에 owner를 넣는다(:2, :36-52, bff-session-owner.ts:188-194). composeProduct는 http가 생긴 뒤에 불리고 http는 세션이 필요해서 이 일을 받을 수 없다. 고른 방법 - product-contracts.ts에 PRODUCT_ENV_REGISTRY를 빈 값으로 둔다. env.ts는 PRODUCT_REST_AUTH_PROFILES·PRODUCT_RUNTIME_CONFIG_FIELDS와 같은 모양으로 그 행을 ENV_REGISTRY에 합친다. 템플릿 키와 이름이 겹치면 모듈 로드 때 throw한다. check:registries와 vite.config.ts가 같은 객체를 읽으므로 제품 행도 같은 필드 검사를 받는다. 행을 더하기만 하면 additive라 기준선을 고치지 않는다(실험: 제품 행 2개 → compatibility=additive PASS, 허용 밖 classification → 실패). - product-composition.ts에 composeProductSessionOwner(context)를 둔다. 템플릿은 null을 돌려준다. 조립 루트가 세션을 고르기 전에, AUTH_MODE가 external일 때만 부른다. 제품 owner가 host 전역보다 먼저다. null이면 지금처럼 host 전역, 없으면 unavailable이다. demo 모드는 묻지 않는다. context는 config와 fetcher뿐이다(http 전이라 capability가 없다). 버린 대안 - owner를 composeProduct 반환값에 넣기: http가 세션을 쓰므로 순서가 꼬인다. - 제품이 host 전역에 계속 넣게 두고 문서화: 부트 전 훅이 템플릿 파일 (create-runtime-composition.ts)에 남는다. - FE-REG-ENV 행을 PRODUCT_RUNTIME_CONFIG_FIELDS에서 자동으로 만들기: zod 필드로는 classification·required를 알 수 없다. - 행 타입·도우미를 product-contracts.ts가 env.ts에서 import: 순환 의존 (no-circular-dependencies)이다. 타입 검사는 env.ts의 대입에서 한다. 위험·한계 - product-composition.ts에 export가 하나 늘었다. 이 파일을 이미 복사한 제품은 composeProductSessionOwner를 더해야 한다. da1e128은 아직 main에 없고 두 다운스트림 모두 받지 않았다. - 제품 행을 as const 없이 쓰면 phase가 string으로 넓어져 tsc 오류가 env.ts:78(템플릿 파일)에서 난다. 메시지에 키 이름은 나온다. product- contracts.ts 주석에 as const를 적었다. - 제품 설정 키에 FE-REG-ENV 행이 있는지 요구하는 검사는 여전히 없다. 템플릿 키도 RELEASE_ID·BUILD_ID는 행이 없어서 이 변경에서 넣지 않았다. - 제품 owner가 throw하면 createRuntimeAdapters가 실패해 부트 실패 화면이 된다. composeProduct와 같다. - tech-log의 owner는 subject를 null로 돌려준다(템플릿 동작대로 매 변경 fence). 이 변경과 무관하다. 검증 - RED: tests/unit/product-composition-fixture.test.ts 13건 중 3건 실패. FE-REG-ENV 행 없음, external 모드 세션이 authenticated가 아니라 integration-failed, env 이름 충돌을 거절하지 않음. - GREEN: 같은 파일 13/13, runtime-adapters-credential-order 7/7(mock에 composeProductSessionOwner: () => null 추가). - fixture는 vi.mock 대상이 제품 소유 두 파일(머리 주석 "Product-owned.")과 설치 기능 seam 두 개뿐이고, tech-log가 고친 템플릿 파일 4개(env.ts, create-runtime-composition.ts, runtime-config-schema.ts, runtime-adapters.ts)는 대상이 아님을 이 파일의 소스를 읽어 확인한다. - 회귀: tests/unit·contract·runtime-schema·integration 198 files 2861 tests 통과(heavy lock 아래). - tsc app·node·test 통과, 바꾼 파일 eslint 통과, check:registries PASS (compatibility=none, 재승인 불필요), verify:documentation PASS_SCOPED, check:adapter-inventory PASS. - 초기 JS gzip 202,770 → 202,931 B(+161, 예산 204,800). 같은 방법(dist manifest의 초기 파일 26개, gzipSync 기본 레벨)으로 전·후를 쟀다. - 미실행: check:architecture(pnpm 필요), test:component, e2e. --- .../frontend-application-foundation.md | 11 +- docs/architecture/starter-experience.md | 4 +- src/bootstrap/product-composition-contract.ts | 19 ++ src/bootstrap/product-composition.ts | 8 + src/bootstrap/runtime-adapters.ts | 16 +- src/contracts/env.ts | 22 +- src/contracts/product-contracts.ts | 10 +- .../unit/product-composition-fixture.test.ts | 222 +++++++++++++++++- .../runtime-adapters-credential-order.test.ts | 1 + 9 files changed, 293 insertions(+), 20 deletions(-) diff --git a/docs/architecture/frontend-application-foundation.md b/docs/architecture/frontend-application-foundation.md index affa03ae..d9fe275e 100644 --- a/docs/architecture/frontend-application-foundation.md +++ b/docs/architecture/frontend-application-foundation.md @@ -176,9 +176,14 @@ 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/runtime-adapters-credential-order.test.ts`). A product that owns +the session itself (a BFF whose session is an httpOnly cookie) returns its +session owner from `composeProductSessionOwner` in the same file. It is asked +first, before `http` exists, only when `AUTH_MODE` is `external`, and it comes +before the host's `__CA_FRONTEND_AUTH_OWNER__`; `null` leaves the session to +that global. Product auth profiles, runtime-config keys and the keys' +FE-REG-ENV rows go in `src/contracts/product-contracts.ts`; each joins the +template's registry 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 620edd09..76bac2e1 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -183,8 +183,8 @@ Files outside the feature directory. Everything else a feature needs is in | `src/contexts//context-layout.tsx` | the context needs its own frame instead of `AppShell` (see "Product home and layouts" below) | nothing: without it the context renders in `AppShell` | | `artifacts/tests/a11y-manual/.md` | every route the feature adds. Copy a record and reset it to `Status: pending-manual-review` | `test:unit` (`tests/unit/manual-a11y-evidence.test.ts`), `verify:documentation` (names the route IDs) and FE-GATE-009 (`review:a11y-manual -- --format-only`). FE-GATE-028 requires the signed review at release | | `tests/e2e/accessibility.spec.ts` | a route path has a parameter other than `:resourceId`, or a protected page cannot render while every API answers `[]` | `test:a11y` (FE-GATE-009): the spec fills in only `:resourceId` and answers every API with `[]` | -| `src/bootstrap/product-composition.ts` (product-owned) | `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 | `check:types`; at runtime `feature needs , which the host did not provide` | -| `src/contracts/product-contracts.ts` (product-owned) | a product auth profile or a product runtime-config key | auth profile: every gate that loads the operation, with `REST security profiles are incoherent for : unknown authProfileId …`. Config key: `check:types` where it is read | +| `src/bootstrap/product-composition.ts` (product-owned) | `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. A product that owns the session (a BFF's httpOnly cookie) returns its session owner from `composeProductSessionOwner` instead of installing it on the host global before boot | `check:types`; at runtime `feature needs , which the host did not provide`. Without the session owner, `AUTH_MODE: "external"` boots with the session `integration-failed` | +| `src/contracts/product-contracts.ts` (product-owned) | a product auth profile, or a product runtime-config key and its FE-REG-ENV row (`PRODUCT_ENV_REGISTRY`) | auth profile: every gate that loads the operation, with `REST security profiles are incoherent for : unknown authProfileId …`. Config key: `check:types` where it is read. FE-REG-ENV row: `check:registries` checks its fields; nothing requires the row | | `config/runtime/.json` | optional: a `FEATURE_OVERRIDES` entry switches the feature off | nothing | | `package.json`, the lockfile, `config/security/dependency-change-evidence.json` | the contract contribution imports a generated `@org-contracts/*` package as a production dependency | `generate:supply-chain` (in `check:bundle`): `high-risk dependency missing review: add:` | diff --git a/src/bootstrap/product-composition-contract.ts b/src/bootstrap/product-composition-contract.ts index 7ff68812..0f5190b3 100644 --- a/src/bootstrap/product-composition-contract.ts +++ b/src/bootstrap/product-composition-contract.ts @@ -1,3 +1,4 @@ +import type { ExternalSessionOwner } from "../adapters/auth/index.ts"; import type { ContractHttpExecutorDependencies, InstalledHttpOperationExecutor, @@ -11,6 +12,24 @@ import type { RuntimeConfig } from "./runtime-config-schema.ts"; * profiles and runtime-config keys) and never edits `runtime-adapters.ts`. */ +/** + * What a product session owner is built from. It is asked first, before + * `http` exists (`http` needs the session), so it gets no capability. + */ +export type ProductSessionOwnerContext = Readonly<{ + /** Validated runtime config, product keys included. */ + config: RuntimeConfig; + fetcher?: typeof fetch; +}>; + +/** + * The session owner when the product owns the session itself, such as a BFF + * whose session is an httpOnly cookie only the backend can read. Asked only + * when `AUTH_MODE` is `external`; it comes before the host's + * `__CA_FRONTEND_AUTH_OWNER__`, and `null` leaves the session to that global. + */ +export type ProductSessionOwner = ExternalSessionOwner | null; + /** Built by the template; a product cannot return or replace them. */ export type TemplatePlatformCapabilityId = "http" | "telemetry"; diff --git a/src/bootstrap/product-composition.ts b/src/bootstrap/product-composition.ts index 11708fc3..7d0c12ce 100644 --- a/src/bootstrap/product-composition.ts +++ b/src/bootstrap/product-composition.ts @@ -1,12 +1,20 @@ import type { ProductComposition, ProductCompositionContext, + ProductSessionOwner, + ProductSessionOwnerContext, } 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 composeProductSessionOwner( + context: ProductSessionOwnerContext, +): ProductSessionOwner { + return null; +} + export function composeProduct(context: ProductCompositionContext) { return { capabilities: {}, diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 3563b814..8cdff959 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -64,7 +64,10 @@ 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 { + composeProduct, + composeProductSessionOwner, +} from "./product-composition.ts"; import type { ProductComposition } from "./product-composition-contract.ts"; import { createInstalledContractRegistry } from "../features/installed-contract-contributions.ts"; import { @@ -343,7 +346,16 @@ export async function createRuntimeAdapters( context.host ?? (globalThis as unknown as Record); const config = context.runtime.config; const mutationIntentFactory = createBrowserMutationIntentFactory(); - const externalOwner = externalOwnerFrom(host); + // 09-02. A product that owns the session (a BFF's httpOnly cookie) returns + // its owner before anything resolves the session; the host global is the + // fallback. Demo mode keeps its own session and never asks. + const externalOwner = + config.AUTH_MODE === "demo" + ? null + : (composeProductSessionOwner({ + config, + ...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }), + }) ?? externalOwnerFrom(host)); const authSession = config.AUTH_MODE === "demo" ? createDemoSessionAdapter() diff --git a/src/contracts/env.ts b/src/contracts/env.ts index 56c63159..9c86dc71 100644 --- a/src/contracts/env.ts +++ b/src/contracts/env.ts @@ -1,3 +1,5 @@ +import { PRODUCT_ENV_REGISTRY } from "./product-contracts.ts"; + /** * §6.3. Case-insensitive key fragments that can never appear in a client * configuration document. @@ -39,7 +41,7 @@ export type EnvironmentDefinition = Readonly<{ defaultValue: unknown; }>; -export const ENV_REGISTRY = Object.freeze({ +export const ENV_REGISTRY = Object.freeze(withProductRows({ // F-6. Required: a staging or production build fails without it // (scripts/generate-runtime-config.ts). Local and development builds fall // back to the placeholder, which admission refuses for public targets. @@ -64,7 +66,23 @@ export const ENV_REGISTRY = Object.freeze({ // scripts/generate-product-feature-index.ts (09-02). A feature left out here // is not imported by any registry and never reaches the bundle. VITE_PRODUCT_FEATURES: build("compile-time", false, null), -}); +})); + +/** + * 09-02. The product's rows (`product-contracts.ts`) join FE-REG-ENV and are + * checked with it. A product row cannot take a template key's name. + */ +function withProductRows>>( + rows: Rows, +) { + const product: Readonly> = + PRODUCT_ENV_REGISTRY; + const reused = Object.keys(product).find((name) => Object.hasOwn(rows, name)); + if (reused !== undefined) { + throw new TypeError(`Product env key ${reused} is a template key.`); + } + return { ...rows, ...product }; +} function build( classification: string, diff --git a/src/contracts/product-contracts.ts b/src/contracts/product-contracts.ts index 05d12598..56ead834 100644 --- a/src/contracts/product-contracts.ts +++ b/src/contracts/product-contracts.ts @@ -1,9 +1,15 @@ /** - * Product-owned. The template ships both values empty and does not change + * Product-owned. The template ships every value 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_ENV_REGISTRY`: FE-REG-ENV rows joined to `ENV_REGISTRY` + * (`env.ts`), one per product key, in the template's row shape: + * `KEY: { phase: "runtime", classification: "public", required: false, + * defaultValue: "MOCK" }`, the whole object `as const` so `phase` stays a + * literal. `check:registries` checks them like the template's rows; adding + * rows is additive and needs no baseline change. * - `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`. @@ -11,4 +17,6 @@ export const PRODUCT_RUNTIME_CONFIG_FIELDS = Object.freeze({}); +export const PRODUCT_ENV_REGISTRY = Object.freeze({}); + export const PRODUCT_REST_AUTH_PROFILES = Object.freeze({}); diff --git a/tests/unit/product-composition-fixture.test.ts b/tests/unit/product-composition-fixture.test.ts index 0088f31f..3d301c44 100644 --- a/tests/unit/product-composition-fixture.test.ts +++ b/tests/unit/product-composition-fixture.test.ts @@ -1,9 +1,13 @@ +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"; @@ -14,11 +18,14 @@ 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: + * 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 and config keys - * - `src/bootstrap/product-composition.ts`: capabilities and credential providers + * - `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 @@ -47,6 +54,7 @@ const PRODUCT_NEEDS: readonly FeaturePlatformCapabilityId[] = [ const fixture = vi.hoisted(() => ({ capabilities: undefined as Record | undefined, + sessionOwnerRequests: 0, withProfile( contract: T, operationId: string, @@ -78,6 +86,15 @@ vi.mock("../../src/contracts/product-contracts.ts", async () => { 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). @@ -102,6 +119,47 @@ vi.mock("../../src/bootstrap/product-composition.ts", async () => { ); 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. @@ -187,7 +245,7 @@ vi.mock("../../src/bootstrap/product-composition.ts", async () => { }, } satisfies ProductComposition; } - return { composeProduct }; + return { composeProduct, composeProductSessionOwner }; }); vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => { @@ -272,16 +330,30 @@ afterEach(() => { current?.infrastructure.dispose(); current = undefined; fixture.capabilities = undefined; + fixture.sessionOwnerRequests = 0; }); -async function compose(options: Readonly<{ cookie?: string; studioStatus?: number }> = {}) { +async function compose( + options: Readonly<{ + cookie?: string; + studioStatus?: number; + authMode?: "demo" | "external"; + studioSource?: "MOCK" | "HTTP"; + studioSessionStatus?: number; + host?: Record; + }> = {}, +) { const validated = validateRuntimeConfig({ ...CONFIG_DOCUMENT, - TECH_LOG_STUDIO_SOURCE: "HTTP", + 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" }); } @@ -306,7 +378,10 @@ async function compose(options: Readonly<{ cookie?: string; studioStatus?: numbe validationDurationMs: 0, }, release, - host: options.cookie === undefined ? {} : { document: { cookie: options.cookie } }, + host: { + ...options.host, + ...(options.cookie === undefined ? {} : { document: { cookie: options.cookie } }), + }, fetcher: fetcher as unknown as typeof fetch, }); const capabilities = fixture.capabilities; @@ -436,8 +511,129 @@ describe("09-02 product needs through the product-owned files only", () => { 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"); @@ -448,15 +644,21 @@ describe("09-02 a product row cannot take a template name", () => { { registry: "auth profiles", load: () => import("../../src/contracts/rest-profiles.ts"), - product: { PRODUCT_RUNTIME_CONFIG_FIELDS: {}, PRODUCT_REST_AUTH_PROFILES: { ANONYMOUS: {} } }, + 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: { PRODUCT_RUNTIME_CONFIG_FIELDS: { APP_ENV: {} }, PRODUCT_REST_AUTH_PROFILES: {} }, + 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); diff --git a/tests/unit/runtime-adapters-credential-order.test.ts b/tests/unit/runtime-adapters-credential-order.test.ts index 2fc7f2bf..489b23c2 100644 --- a/tests/unit/runtime-adapters-credential-order.test.ts +++ b/tests/unit/runtime-adapters-credential-order.test.ts @@ -77,6 +77,7 @@ vi.mock("../../src/features/installed-feature-adapters.ts", async (importOrigina /** The product-owned file, filled the way a product fills it. */ vi.mock("../../src/bootstrap/product-composition.ts", () => ({ + composeProductSessionOwner: () => null, composeProduct: () => ({ capabilities: {}, credentialProviders: fixture.providers,