diff --git a/docs/architecture/browser-file-and-origin-storage.md b/docs/architecture/browser-file-and-origin-storage.md index 72399f25..0144fdb5 100644 --- a/docs/architecture/browser-file-and-origin-storage.md +++ b/docs/architecture/browser-file-and-origin-storage.md @@ -371,10 +371,18 @@ digest 또는 별도 검토된 streaming hash adapter를 사용한다. 세션을 모른다(`src/adapters/browser-files/create-browser-file-runtime.ts:93`). `runtime.dispose()`(`:177-188`)가 이전 사용자가 고른 File 참조, preview lease, 진행 중 download(`download-delivery-adapter.ts:390-396`)를 한 번에 닫는다. - runtime을 route·feature보다 오래 사는 곳에서 만들었다면 server-state scope - reset participant(`src/adapters/query-cache/server-state-scope-runtime.ts:19`, - 등록 예 `src/bootstrap/runtime-adapters.ts:410-416`)로 `dispose()`를 등록하고 - 다음 세대에서 새 runtime을 만든다. dispose한 runtime은 다시 쓸 수 없다. + runtime을 route·feature보다 오래 사는 곳(`product-composition.ts`의 + capability)에서 만들었다면 제품 소유 파일만 고친다. `composeProduct`가 + `scopeParticipants`로 `dispose()`를 돌려주면 템플릿이 로그아웃·계정 전환마다 + FENCED와 READY 사이에서 부르고, 실패하면 READY로 가지 않는다 + (`ProductScopeParticipant`, `src/bootstrap/product-composition-contract.ts`). + `composeProduct`는 부팅 때 한 번만 불리므로 기능에는 runtime 대신 getter를 + 주고 그 뒤에서 세대마다 새 runtime을 만든다. 예제는 + `recipes/frontend-capabilities/browser-file-session-capability.ts`이고 + `tests/recipes/browser-file-session-capability.test.ts`가 계정 전환 뒤 이전 + runtime의 읽기가 `UNAVAILABLE`, 진행 중 download가 `ABORTED`(handoff 0회), + 다음 세대의 파일 선택이 성공함을 확인한다(2026-11-03 02-01). dispose한 + runtime은 다시 쓸 수 없다. - SVG, HTML, untrusted PDF 같은 active content를 same-origin object URL iframe에 직접 preview하지 않는다. 별도 격리 origin 또는 안전한 decode/re-encode 결과, 아니면 attachment-only 정책을 사용한다. diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index 1c13012f..1bb10385 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -103,6 +103,7 @@ release admission refused for staging: - `src/contexts//context-layout.tsx`: context가 `AppShell` 대신 자기 틀을 쓸 때. 예제: `tests/helpers/fixture-layout-product.tsx`. - `tests/e2e/accessibility.spec.ts`: 경로 파라미터가 `:resourceId`가 아닐 때, 또는 모든 API가 `[]`를 답하면 그려지지 않는 보호 페이지일 때. 치환 줄 고치는 법은 [01 문서 6단계](01-add-a-feature.md#6단계-라우트). - `src/bootstrap/product-composition.ts`: `needs`에 템플릿이 만들지 않는 capability를 적었을 때. 제품 인증 프로필의 자격 증명도 여기서 준다. + - 로그아웃·계정 전환 때 닫아야 하는 것(파일 runtime 등)은 `scopeParticipants`로 돌려준다. 예제: `recipes/frontend-capabilities/browser-file-session-capability.ts`. - 템플릿 파일 `src/bootstrap/runtime-adapters.ts`는 고치지 않는다. - `src/contracts/product-contracts.ts`: 제품 인증 프로필이나 제품 런타임 설정 키가 필요할 때. - 템플릿 파일 `src/contracts/rest-profiles.ts`는 고치지 않는다. diff --git a/recipes/frontend-capabilities/browser-file-session-capability.ts b/recipes/frontend-capabilities/browser-file-session-capability.ts new file mode 100644 index 00000000..04d95996 --- /dev/null +++ b/recipes/frontend-capabilities/browser-file-session-capability.ts @@ -0,0 +1,58 @@ +import type { BrowserFileRuntime } from "../../src/adapters/browser-files/index.ts"; +import type { ProductScopeParticipant } from "../../src/bootstrap/product-composition-contract.ts"; + +/** What features receive: this session's runtime, asked for per operation. */ +export type SessionBrowserFiles = Readonly<{ + /** + * The current session's runtime, built on first use. Ask again for each + * operation; one kept past a sign-out answers `UNAVAILABLE`. + */ + current(): BrowserFileRuntime; +}>; + +/** + * 2026-11-03 02-01. How a product gives features a browser file runtime that + * lives for one session. The runtime does not know the session, and + * `composeProduct` runs once at boot, so the capability is a getter and the + * runtime behind it is disposed by a scope participant on every sign-out and + * account switch: the previous user's selected files, preview object URLs and + * running downloads end there. The next call to `current()` builds a fresh one. + * + * file-transfer is an opt-in recipe (`productionComposition: false`), so the + * template does not build this. A product that installs a feature using it + * augments `FeaturePlatformCapabilities` with `files: SessionBrowserFiles` and + * returns both halves from `src/bootstrap/product-composition.ts`: + * + * const browserFiles = createSessionBrowserFileCapability(() => + * createBrowserFileRuntime({ input, policies, limits, download }), + * ); + * return { + * capabilities: { files: browserFiles.files }, + * credentialProviders: {}, + * scopeParticipants: [browserFiles.scopeParticipant], + * }; + * + * The runtime options are the product's decisions (policies, limits, the + * download capability resolver); none is chosen here. + */ +export function createSessionBrowserFileCapability( + create: () => BrowserFileRuntime, +): Readonly<{ + files: SessionBrowserFiles; + scopeParticipant: ProductScopeParticipant; +}> { + let runtime: BrowserFileRuntime | null = null; + return Object.freeze({ + files: Object.freeze({ + current: () => (runtime ??= create()), + }), + scopeParticipant: Object.freeze({ + label: "browser-files", + close() { + const ending = runtime; + runtime = null; + ending?.dispose(); + }, + }), + }); +} diff --git a/scripts/test-browser-file-storage-runtime-removal.ts b/scripts/test-browser-file-storage-runtime-removal.ts index 399d9910..2dd386de 100644 --- a/scripts/test-browser-file-storage-runtime-removal.ts +++ b/scripts/test-browser-file-storage-runtime-removal.ts @@ -36,8 +36,9 @@ const runtimePaths = [ "src/adapters/storage/opfs", "tests/browser-capabilities", "tests/fixtures/browser-file-storage-boundaries", - // The composition example of this runtime goes with it. + // The composition examples of this runtime go with it. "recipes/frontend-capabilities/indexeddb-feature-capability.ts", + "recipes/frontend-capabilities/browser-file-session-capability.ts", // [0929] 05-03. These recipe contracts re-export this runtime's ports and // their fakes implement them, so they go with it too, with their test. ...RUNTIME_RECIPE_MODULES.map( diff --git a/src/bootstrap/product-composition-contract.ts b/src/bootstrap/product-composition-contract.ts index 0f5190b3..5637335f 100644 --- a/src/bootstrap/product-composition-contract.ts +++ b/src/bootstrap/product-composition-contract.ts @@ -55,10 +55,29 @@ export type ProductCompositionContext = Readonly<{ isScopeReady(): boolean; }>; +/** + * 2026-11-03 02-01. Something a product built that must not outlive a session, + * such as a browser file runtime holding the previous user's files. The + * template closes it on every sign-out and account switch, after FENCED and + * before READY, at the step that releases offline leases. A close that throws + * or rejects keeps the scope from reaching READY, as the template's own do. + */ +export type ProductScopeParticipant = Readonly<{ + label: string; + close(): void | Promise; +}>; + export type ProductComposition = Readonly<{ capabilities: Readonly< Partial> >; /** Auth profile id → provider. An ANONYMOUS profile never reaches one. */ credentialProviders: Readonly>; + /** + * Closed in this order on each identity change. A capability that needs a + * fresh object for the next session hands features a getter and rebuilds + * behind it, as `recipes/frontend-capabilities/browser-file-session-capability.ts` + * does. + */ + scopeParticipants?: readonly ProductScopeParticipant[]; }>; diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index d419621b..7175108e 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -62,7 +62,10 @@ import { composeProduct, composeProductSessionOwner, } from "./product-composition.ts"; -import type { ProductComposition } from "./product-composition-contract.ts"; +import type { + ProductComposition, + ProductScopeParticipant, +} from "./product-composition-contract.ts"; import { createInstalledContractRegistry } from "../features/installed-contract-contributions.ts"; import { indexInvalidationRegistry, @@ -377,6 +380,11 @@ export async function createRuntimeAdapters( crossContextInvalidation?.getStatus() ?? "DEGRADED_LOCAL_ONLY", }); }); + // 2026-11-03 02-01. The product's closers. `composeProduct` runs after the + // scope exists (its context needs the fence), so they join through this one + // slot, filled below. Each runs even when an earlier one fails, and any + // failure keeps the scope from READY, as for the template's own. + const productScopeParticipants: ProductScopeParticipant[] = []; const serverStateScope = createServerStateScopeRuntime({ session: authSession, diagnostics, @@ -389,6 +397,21 @@ export async function createRuntimeAdapters( label: "conditional-validators", close: () => conditionalValidators.clear(), }, + { + order: 10, + label: "product", + async close() { + let failed = false; + for (const participant of productScopeParticipants) { + try { + await participant.close(); + } catch { + failed = true; + } + } + if (failed) throw new Error("A product scope participant failed."); + }, + }, ], activateNextGeneration: () => serverStateGeneration.activateNext(), }); @@ -615,6 +638,10 @@ export async function createRuntimeAdapters( }) satisfies ProductComposition; const productCredentialProviders: ProductComposition["credentialProviders"] = product.credentialProviders; + // `product` keeps its narrow type above so a missing capability still fails + // the typecheck; the optional field is read through the contract type. + const composedProduct: ProductComposition = product; + productScopeParticipants.push(...(composedProduct.scopeParticipants ?? [])); // Each installed contribution receives only the capabilities it declares. // 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 diff --git a/tests/recipes/browser-file-session-capability.test.ts b/tests/recipes/browser-file-session-capability.test.ts new file mode 100644 index 00000000..7afb7aab --- /dev/null +++ b/tests/recipes/browser-file-session-capability.test.ts @@ -0,0 +1,284 @@ +// @vitest-environment jsdom + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { LocalFileRef } from "../../src/application/ports/browser-file-storage/index.ts"; +import { + browserFilePolicyReference, + createBrowserFileRuntime, + type BrowserFilePolicyProfile, +} from "../../src/adapters/browser-files/index.ts"; +import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; +import { createSessionBrowserFileCapability } from "../../recipes/frontend-capabilities/browser-file-session-capability.ts"; + +/** + * 2026-11-03 02-01. A product wires the browser file runtime to the session by + * filling only its own `product-composition.ts`: the recipe capability goes to + * features, its scope participant to the template. The real + * `createRuntimeAdapters` runs; only the product-owned file is replaced, with + * what a product would write in it. + */ + +const selectPolicy = browserFilePolicyReference("session-file", "select-text"); +const downloadPolicy = browserFilePolicyReference( + "session-download", + "bounded-generated-bin", +); +const policies: readonly BrowserFilePolicyProfile[] = [ + { + reference: selectPolicy, + selection: { + policyId: "attachment-v1", + purpose: "attachment", + classification: "PERSONAL", + multiple: false, + maxCount: 1, + maxFileBytes: 8, + maxTotalBytes: 8, + allowEmpty: false, + accept: [{ mediaType: "text/plain", extensions: [".txt"] }], + }, + }, + { + reference: downloadPolicy, + download: { + strategy: "BOUNDED_OBJECT_URL", + mediaType: "application/octet-stream", + safeExtension: ".bin", + maxTransferBytes: 8, + maxBufferedBytes: 8, + integrity: "OPTIONAL", + }, + }, +]; + +const fixture = vi.hoisted(() => ({ + files: undefined as + | ReturnType["files"] + | undefined, + inputs: [] as HTMLInputElement[], + handoffs: 0, + owner: undefined as + | Readonly<{ switchUser(subject: string): void }> + | undefined, +})); + +function fileInput(): HTMLInputElement { + const input = document.createElement("input"); + input.type = "file"; + input.setAttribute("aria-label", "Attachment"); + Object.defineProperty(input, "click", { configurable: true, value: vi.fn() }); + document.body.append(input); + fixture.inputs.push(input); + return input; +} + +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: async () => ({ headers: {} }), + recoverSession: async () => "no-session", + notifyUnauthenticated: () => {}, + switchUser(next: string) { + subject = next; + for (const listener of listeners) listener(); + }, + }; +} + +/** The product-owned file, filled the way a product fills it. */ +vi.mock("../../src/bootstrap/product-composition.ts", () => ({ + composeProductSessionOwner: () => { + const owner = externalOwner(); + fixture.owner = owner; + return owner; + }, + composeProduct: () => { + const browserFiles = createSessionBrowserFileCapability(() => + createBrowserFileRuntime({ + input: fileInput(), + policies, + limits: { + hardMaxPreviewBytes: 8, + hardMaxObjectUrlBytes: 8, + hardMaxTransferBytes: 16, + }, + objectUrlApi: { + createObjectURL: () => "blob:session-download", + revokeObjectURL() {}, + }, + download: { + host: { + handoff() { + fixture.handoffs += 1; + }, + }, + browserManagedCapabilities: { + resolve: () => ({ + ok: false as const, + error: { + code: "POLICY_REJECTED" as const, + operation: "DOWNLOAD" as const, + retryable: false, + recovery: "NONE" as const, + }, + }), + }, + }, + }), + ); + fixture.files = browserFiles.files; + return { + capabilities: {}, + credentialProviders: {}, + scopeParticipants: [browserFiles.scopeParticipant], + }; + }, +})); + +let current: Awaited> | undefined; +afterEach(() => { + current?.infrastructure.dispose(); + current = undefined; + for (const input of fixture.inputs.splice(0)) input.remove(); + fixture.files = undefined; + fixture.handoffs = 0; +}); + +async function compose() { + current = await createRuntimeAdapters({ + runtime: { + config: { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + TELEMETRY_ENABLED: false, + AUTH_MODE: "external", + 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, + }, + release: { + schemaVersion: 2, + appVersion: "0.1.0", + buildId: "build-a", + commitSha: "abc123", + configSchemaVersion: "2.0", + contractSet: { + setAlgorithm: "CA_CONTRACT_SET_V1", + setDigest: `sha256:${"0".repeat(64)}`, + packages: [], + }, + assetManifestHash: "hash-a", + releaseId: "release-a", + builtAt: "2026-07-25T00:00:00Z", + routeChunks: { "route-home": "assets/home.js" }, + }, + host: {}, + }); + const files = fixture.files; + const owner = fixture.owner; + if (!files || !owner) throw new Error("The product composition did not run"); + return { adapters: current, files, owner }; +} + +async function selectOne( + runtime: ReturnType["current"]>, + name: string, +) { + const pending = runtime.baselinePicker.select({ policy: selectPolicy }); + const input = fixture.inputs.at(-1)!; + Object.defineProperty(input, "files", { + configurable: true, + value: [new File(["text"], name, { type: "text/plain", lastModified: 1 })], + }); + input.dispatchEvent(new Event("change")); + return await pending; +} + +describe("a session-scoped browser file runtime (2026-11-03 02-01)", () => { + it("closes the previous user's files and downloads on an account switch and serves the next session a new runtime", async () => { + const { adapters, files, owner } = await compose(); + const previous = files.current(); + const selected = await selectOne(previous, "user-a.txt"); + if (!selected.ok || selected.value.kind !== "SELECTED") { + throw new Error(`The first selection failed: ${JSON.stringify(selected)}`); + } + const ref: LocalFileRef = selected.value.files[0]!.ref; + let producing!: () => void; + const started = new Promise((resolve) => { + producing = resolve; + }); + const download = previous.downloads.deliver({ + policy: downloadPolicy, + source: { + kind: "GENERATED", + bytes: { + byteLength: 1, + async *stream() { + producing(); + await new Promise(() => {}); + yield { ok: true as const, value: new Uint8Array([1]) }; + }, + }, + }, + suggestedFileName: "user-a-report", + maxTransferBytes: 8, + maxBufferedBytes: 8, + signal: new AbortController().signal, + onProgress() {}, + }); + await started; + + owner.switchUser("user-b"); + await vi.waitFor(() => + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), + ); + + expect( + await previous.content.readRange({ + ref, + offset: 0, + length: 1, + signal: new AbortController().signal, + }), + ).toMatchObject({ ok: false, error: { code: "UNAVAILABLE" } }); + expect(await download).toMatchObject({ + ok: false, + error: { code: "ABORTED", operation: "DOWNLOAD" }, + }); + expect(fixture.handoffs).toBe(0); + + const next = files.current(); + expect(next).not.toBe(previous); + expect(await selectOne(next, "user-b.txt")).toMatchObject({ + ok: true, + value: { kind: "SELECTED" }, + }); + }); +}); diff --git a/tests/unit/runtime-adapters-product-scope-participants.test.ts b/tests/unit/runtime-adapters-product-scope-participants.test.ts new file mode 100644 index 00000000..698a7723 --- /dev/null +++ b/tests/unit/runtime-adapters-product-scope-participants.test.ts @@ -0,0 +1,152 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { ProductScopeParticipant } from "../../src/bootstrap/product-composition-contract.ts"; +import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; + +/** + * 2026-11-03 02-01. A product hands the template what must close with a + * session through `ProductComposition.scopeParticipants`, so it never edits + * `runtime-adapters.ts`. The real `createRuntimeAdapters` runs; only the + * product-owned file is replaced. + */ + +const fixture = vi.hoisted(() => ({ + participants: [] as ProductScopeParticipant[], + owner: undefined as Readonly<{ switchUser(subject: string): void }> | undefined, +})); + +vi.mock("../../src/bootstrap/product-composition.ts", () => ({ + composeProductSessionOwner: () => { + const listeners = new Set<() => void>(); + let subject = "user-a"; + const owner = { + readState: () => "authenticated", + readSubject: () => subject, + subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + beginSignIn: async () => {}, + signOut: async () => {}, + attachCredential: async () => ({ headers: {} }), + recoverSession: async () => "no-session", + notifyUnauthenticated: () => {}, + switchUser(next: string) { + subject = next; + for (const listener of listeners) listener(); + }, + }; + fixture.owner = owner; + return owner; + }, + composeProduct: () => ({ + capabilities: {}, + credentialProviders: {}, + scopeParticipants: fixture.participants, + }), +})); + +let current: Awaited> | undefined; +afterEach(() => { + current?.infrastructure.dispose(); + current = undefined; + fixture.participants = []; +}); + +async function compose() { + current = await createRuntimeAdapters({ + runtime: { + config: { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + TELEMETRY_ENABLED: false, + AUTH_MODE: "external", + 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, + }, + release: { + schemaVersion: 2, + appVersion: "0.1.0", + buildId: "build-a", + commitSha: "abc123", + configSchemaVersion: "2.0", + contractSet: { + setAlgorithm: "CA_CONTRACT_SET_V1", + setDigest: `sha256:${"0".repeat(64)}`, + packages: [], + }, + assetManifestHash: "hash-a", + releaseId: "release-a", + builtAt: "2026-07-25T00:00:00Z", + routeChunks: { "route-home": "assets/home.js" }, + }, + host: {}, + }); + const owner = fixture.owner; + if (!owner) throw new Error("The product session owner was not asked"); + return { scope: current.infrastructure.serverStateScope, owner }; +} + +describe("product scope participants (2026-11-03 02-01)", () => { + it("closes each one, in order, on every identity change before READY", async () => { + const closed: string[] = []; + fixture.participants = [ + { label: "first", close: () => void closed.push("first") }, + { + label: "second", + async close() { + await Promise.resolve(); + closed.push("second"); + }, + }, + ]; + const { scope, owner } = await compose(); + expect(closed).toEqual([]); + + owner.switchUser("user-b"); + expect(scope.getPhase()).toBe("FENCED"); + await vi.waitFor(() => expect(scope.getPhase()).toBe("READY")); + expect(closed).toEqual(["first", "second"]); + + owner.switchUser("user-c"); + await vi.waitFor(() => expect(closed).toHaveLength(4)); + await vi.waitFor(() => expect(scope.getPhase()).toBe("READY")); + }); + + it("keeps the scope from READY when one fails, and still closes the rest", async () => { + const closed: string[] = []; + fixture.participants = [ + { + label: "broken", + close() { + throw new Error("cannot close"); + }, + }, + { label: "after", close: () => void closed.push("after") }, + ]; + const { scope, owner } = await compose(); + + owner.switchUser("user-b"); + + await vi.waitFor(() => expect(scope.getPhase()).toBe("FAILED")); + expect(closed).toEqual(["after"]); + }); +});