diff --git a/config/recipes/frontend-capability-recipes.json b/config/recipes/frontend-capability-recipes.json index 16c13e8c..935a73c8 100644 --- a/config/recipes/frontend-capability-recipes.json +++ b/config/recipes/frontend-capability-recipes.json @@ -192,7 +192,7 @@ "port": "FilePickerPort / FileContentPort / TransientPreviewPort / DownloadDeliveryPort / PresignedDownloadSourcePort / PresignedUploadPartPort / ResumableUploadPort / ImageCdnPresentationPort", "fake": "Memory file/preview/download adapters plus injected deterministic capability, upload-control-plane, part-executor and image-verifier test doubles", "failureKinds": ["dismissed", "permission-denied", "count-or-size-rejection", "type-or-signature-rejection", "file-changed", "abort", "integrity-failure", "partial-save", "expired-or-revoked-capability", "part-or-session-conflict", "checkpoint-conflict", "quarantined", "image-policy-rejection"], - "lifecycleMethods": ["release-file-ref", "release-or-dispose-preview-leases", "cancel-via-AbortSignal", "reconcile-or-explicitly-abort-upload", "close-checkpoint-store", "dispose-capability-and-image-runtime"], + "lifecycleMethods": ["release-file-ref", "release-or-dispose-preview-leases", "cancel-via-AbortSignal", "reconcile-or-explicitly-abort-upload", "close-checkpoint-store", "dispose-capability-and-image-runtime", "dispose-browser-file-runtime-on-logout-or-account-switch"], "owner": "project-owner-required", "securityPrivacy": ["Treat file name, extension, MIME and lastModified as untrusted metadata.", "Resolve only exact composition-issued file and image policy object identities; callers cannot raise byte, candidate, pixel, quality, format, lifetime or origin ceilings.", "Use opaque file references and verification receipts bound to an inspected immutable file snapshot and the exact registered profile; reject replay through another profile even when an inspection rule ID matches.", "Treat presigned URLs as bearer capabilities; bind exact method, resource or upload part, offset, length, media type, checksum, origin, path, query, headers and expiry in an in-memory identity vault.", "Use credentials omit, redirect error, no-referrer and no-store for direct data-plane fetch; never persist or observe URL, query, signed header, capability, file name or raw backend message, and never emit digest, raw ETag or receipt values to diagnostics or telemetry.", "A strict account-partitioned upload checkpoint may persist only the protocol-defined SHA-256 file fingerprint, per-part checksum and bounded opaque non-authorizing part receipt token required for server reconciliation; no bearer token or raw signed capability is allowed.", "Persist only strict non-authorizing upload checkpoints and reconcile them with server-authoritative status and re-hashed local parts before completion.", "Require a synchronous server-issued browser-managed download capability whose receipt exactly equals the caller's branded capability receipt and whose resource, media type, safe extension, maximum bytes, optional digest and expiry all match before handoff.", "Expose File, OPFS, Cache and transfer byte streams only as chunk-level closed Results; stop after the first failure, cancel native readers and never throw a raw native exception across the port.", "Accept Image CDN assets only through immutable allowlisted or signature-verified descriptors and registered preset identities; reject active formats, arbitrary transforms, pixel/decode-budget overflow and unsafe cache policy.", "Upload completion remains QUARANTINED until backend scan and promotion; client capability checks are not an authorization boundary.", "Active content preview requires isolation or download-only treatment."], "bundleBudgetGzipBytes": 55600, diff --git a/docs/architecture/browser-file-and-origin-storage.md b/docs/architecture/browser-file-and-origin-storage.md index 45e72674..abe95cd4 100644 --- a/docs/architecture/browser-file-and-origin-storage.md +++ b/docs/architecture/browser-file-and-origin-storage.md @@ -353,8 +353,23 @@ digest 또는 별도 검토된 streaming hash adapter를 사용한다. - one-shot 작은 download는 click handoff 뒤 cross-engine scheduling을 위해 기본 30초 grace를 두고 revoke한다. feature/runtime dispose는 grace를 기다리지 않고 모든 active lease를 즉시 revoke한다. +- preview와 download는 runtime 하나의 lease registry를 같이 쓴다 + (`src/adapters/browser-files/create-browser-file-runtime.ts:154`, `:163`). + lease 개수나 합계 바이트 한도가 차면 둘 다 `LIMIT_EXCEEDED`를 + `retryable: true`, `recovery: "RETRY"`로 반환한다 + (`src/adapters/browser-files/object-url-lease.ts:48-73`, `:131-139`). download + lease는 grace(`download-delivery-adapter.ts:149`)가 끝나면 풀리므로 잠시 뒤 + 다시 시도하면 된다. Blob 하나가 단일 lease 상한을 넘으면 재시도 불가다. - URL을 global state, IndexedDB, query cache, log, analytics에 보관하지 않는다. - Service Worker에서 object URL을 사용하지 않는다. +- 로그아웃·계정 전환에서는 runtime 전체를 dispose한다. browser file runtime은 + 세션을 모른다(`src/adapters/browser-files/create-browser-file-runtime.ts:93`). + `runtime.dispose()`(`:177-185`)가 이전 사용자가 고른 File 참조, preview lease, + 진행 중 download(`download-delivery-adapter.ts:385-391`)를 한 번에 닫는다. + 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은 다시 쓸 수 없다. - SVG, HTML, untrusted PDF 같은 active content를 same-origin object URL iframe에 직접 preview하지 않는다. 별도 격리 origin 또는 안전한 decode/re-encode 결과, 아니면 attachment-only 정책을 사용한다. diff --git a/docs/architecture/client-cache-and-storage.md b/docs/architecture/client-cache-and-storage.md index 731cb08b..a71033be 100644 --- a/docs/architecture/client-cache-and-storage.md +++ b/docs/architecture/client-cache-and-storage.md @@ -41,8 +41,8 @@ | `NOT_SELECTED` | 제품 요구·owner·policy가 승인되지 않았다. | | `PLATFORM_LIMITED` | browser/platform이 요구 의미를 cross-browser로 보장하지 못한다. | -현재 `src/adapters/query-cache/tanstack-query-cache.ts`는 한 runtime당 -`QueryClient`를 만들고, query retry를 끄며, 30초 `staleTime`과 5분 `gcTime`을 +현재 `src/adapters/query-cache/tanstack-query-cache.ts`는 server-state +generation마다 `QueryClient`를 만들고, query retry를 끄며, 30초 `staleTime`과 5분 `gcTime`을 기본값으로 사용한다. `src/bootstrap/runtime-adapters.ts`와 `src/bootstrap/runtime-application.tsx`가 이 client를 실제 provider tree에 조립한다. @@ -79,13 +79,26 @@ native two-page browser spec은 BroadcastChannel primary와 localStorage fallbac delivery/cleanup을 검증한다. 다만 production QueryClient/coordinator까지 연결한 account transition, bfcache/StrictMode lifecycle E2E는 없고, 현재 보존 artifact도 Chromium/Firefox만 통과해 WebKit을 포함한 promotion evidence는 충족하지 않는다. -localStorage fallback physical key는 아직 storage registry 밖의 상수이고 native -`StorageEvent.storageArea`도 facade에서 검증하지 않는다. +localStorage fallback physical key는 storage registry의 +`CACHE_INVALIDATION_PULSE` 항목에서 온다(`src/contracts/storage-keys.ts:102`, +`src/adapters/cross-context-invalidation/browser-cross-context-host.ts:36-37`). +host facade는 native `StorageEvent.storageArea`를 캡처한 `localStorage` 객체와 +동일성으로 비교하고(`browser-cross-context-host.ts:286-296`), core는 +`EXPECTED_LOCAL_STORAGE`로 표시된 pulse만 받는다 +(`browser-cross-context-invalidation.ts:197-201`). -현재 epoch 구현은 `release.` 하나다. session/account epoch, opaque -account partition, scope 전환 시 새 QueryClient 생성과 durable namespace epoch는 -아직 구현되지 않았다. 따라서 현재 cross-tab event는 같은 release의 등록 query -topic을 빠르게 stale 처리하는 용도에 한정된다. +현재 epoch는 release 하나다. `cacheEpoch`는 release ID의 64-bit FNV-1a digest를 +`release.<16자리 hex>`로 쓴 값이다(`browser-cross-context-host.ts:45-51`, 조립 +`src/bootstrap/runtime-adapters.ts:364-366`). 세션 identity가 바뀌면 scope +runtime이 다음 server-state generation을 열고 +(`src/adapters/query-cache/server-state-scope-runtime.ts:148`), generation마다 +새 `QueryClient`와 새 cross-context transport(새 `sourceId`·`sourceEpoch`)를 +만든다(`src/bootstrap/server-state-generation-store.ts:50-57`, +`runtime-adapters.ts:359-372`). 이전 generation의 transport는 coordinator +dispose에서 닫힌다(`src/adapters/query-cache/tanstack-cache-coordinator.ts:276-280`). +session/account epoch, opaque account partition과 durable namespace epoch는 +아직 없다. wire event에 사용자·세션 scope가 없으므로 현재 cross-tab event는 같은 +release의 등록 query topic을 빠르게 stale 처리하는 용도에 한정된다. `QUERY_REGISTRY`의 모든 현재 entry와 `createTanStackCacheCoordinator()`는 `persistence: "disabled"`만 허용한다. @@ -113,10 +126,10 @@ blocked/versionchange를 다루는 reference runtime이 있다. 이 설계는 | capability | primary current status | current implementation | target delta | delta implementation status | | --- | --- | --- | --- | --- | -| memory QueryClient | `COMPOSED` | runtime별 생성, global stale/gc/retry default | session/account scope owner, generation fence, per-query policy | `DESIGNED_NOT_IMPLEMENTED` | +| memory QueryClient | `COMPOSED` | server-state generation별 생성(session identity 변경 시 FENCED 뒤 새 client), global stale/gc/retry default | per-query policy | `DESIGNED_NOT_IMPLEMENTED` | | application query bridge | `COMPOSED` | AbortSignal, stale error, optimistic rollback/conflict surface | old-generation query/mutation callback 폐기 | `DESIGNED_NOT_IMPLEMENTED` | | Web Storage | `COMPOSED` | 두 key, strict v1 envelope/codec, lazy TTL, global 16 KiB cap | per-key cap, HIT/MISS, durability, v2 scope, migration, sweep/logout | `DESIGNED_NOT_IMPLEMENTED` | -| cross-tab invalidation | `COMPOSED` | release epoch, versioned hint, duplicate/gap, BC→localStorage | composite scope epoch, registered pulse, storageArea, durable ledger hook | `DESIGNED_NOT_IMPLEMENTED` | +| cross-tab invalidation | `COMPOSED` | release epoch(FNV-1a digest), versioned hint, duplicate/gap, BC→localStorage, registry pulse key, storageArea 동일성 검사, generation별 transport | composite scope epoch, durable ledger hook | `DESIGNED_NOT_IMPLEMENTED` | | generic IndexedDB | `AVAILABLE_NOT_COMPOSED` | reusable repository/maintenance runtime | product dataset schema/codec/query/policy composition | product selection `NOT_SELECTED` | | query persistence facade | `DESIGNED_NOT_IMPLEMENTED` | 없음, registry가 disabled 강제 | stable per-query record, bounded restore, namespace epoch/CAS | `DESIGNED_NOT_IMPLEMENTED` | | product persistence | `NOT_SELECTED` | owner/query allowlist 없음 | measured need와 explicit composition | `NOT_SELECTED` | diff --git a/src/adapters/browser-files/download-delivery-adapter.ts b/src/adapters/browser-files/download-delivery-adapter.ts index 8e3eeed4..eaf478f2 100644 --- a/src/adapters/browser-files/download-delivery-adapter.ts +++ b/src/adapters/browser-files/download-delivery-adapter.ts @@ -31,6 +31,7 @@ import { } from "./file-observer.ts"; import { ObjectUrlLeaseRegistry, + objectUrlLimitFailure, type ObjectUrlLease, } from "./object-url-lease.ts"; import { BrowserFilePolicyRegistry } from "./browser-file-policy-registry.ts"; @@ -1032,7 +1033,7 @@ function mapDownloadException( return browserDataFailure("INTEGRITY_FAILED", "DOWNLOAD"); } if (error.name === "FileTooLargeError") { - return browserDataFailure("LIMIT_EXCEEDED", "DOWNLOAD"); + return objectUrlLimitFailure(error, "DOWNLOAD"); } } return mapBrowserDataException(error, "DOWNLOAD"); diff --git a/src/adapters/browser-files/file-observer.ts b/src/adapters/browser-files/file-observer.ts index e2026aa0..0e8de07d 100644 --- a/src/adapters/browser-files/file-observer.ts +++ b/src/adapters/browser-files/file-observer.ts @@ -17,7 +17,9 @@ type BrowserFileObservation = Readonly<{ /** * File adapters use the platform BrowserDataObserver as the telemetry SSOT. - * The helper below is the sole mapper from file-local dismissal semantics. + * The helper below is the sole mapper from file-local outcomes. A dismissal + * stays `DISMISSED` (02-06): folded into `SUCCEEDED` it hid the save-dialog + * cancel rate inside the browser handoff success rate. */ export type BrowserFileObserver = BrowserDataObserver; @@ -30,7 +32,7 @@ export function observeBrowserFile( Object.freeze({ operation: observation.operation, outcome: - observation.outcome === "FAILED" ? "FAILED" : "SUCCEEDED", + observation.outcome === "SUCCESS" ? "SUCCEEDED" : observation.outcome, ...(observation.failureCode ? { failureCode: observation.failureCode } : {}), diff --git a/src/adapters/browser-files/object-url-lease.ts b/src/adapters/browser-files/object-url-lease.ts index c1d82060..41784fbe 100644 --- a/src/adapters/browser-files/object-url-lease.ts +++ b/src/adapters/browser-files/object-url-lease.ts @@ -45,6 +45,31 @@ const DEFAULT_OBJECT_URL_LEASE_LIMITS: ObjectUrlLeaseLimits = hardMaxAggregateLeaseBytes: 256 * 1024 * 1024, }); +/** + * 02-04. Every lease slot or the aggregate byte budget is in use. Leases free + * up when released (a download after its revoke grace), so unlike one Blob + * above the single-lease ceiling this is reported as retryable. + */ +class ObjectUrlLeasesExhaustedError extends DOMException { + constructor() { + super("Object URL leases exhausted", "FileTooLargeError"); + } +} + +/** Maps a `FileTooLargeError` from the registry or a byte cap. */ +export function objectUrlLimitFailure( + error: DOMException, + operation: "PREVIEW" | "DOWNLOAD", +): BrowserDataResult { + return browserDataFailure( + "LIMIT_EXCEEDED", + operation, + error instanceof ObjectUrlLeasesExhaustedError + ? { retryable: true, recovery: "RETRY" } + : {}, + ); +} + /** * The only low-level owner of object URL creation/revocation. Every lease is * idempotent and dispose() is a final safety net for route/runtime teardown. @@ -97,17 +122,21 @@ export class ObjectUrlLeaseRegistry { create(blob: Blob): ObjectUrlLease { if ( !isValidByteLength(blob.size) || - blob.size > this.#limits.hardMaxSingleLeaseBytes || - this.#active.size >= this.#limits.hardMaxActiveLeases || - !Number.isSafeInteger(this.#aggregateByteLength + blob.size) || - this.#aggregateByteLength + blob.size > - this.#limits.hardMaxAggregateLeaseBytes + blob.size > this.#limits.hardMaxSingleLeaseBytes ) { throw new DOMException( "Object URL lease limit exceeded", "FileTooLargeError", ); } + if ( + this.#active.size >= this.#limits.hardMaxActiveLeases || + !Number.isSafeInteger(this.#aggregateByteLength + blob.size) || + this.#aggregateByteLength + blob.size > + this.#limits.hardMaxAggregateLeaseBytes + ) { + throw new ObjectUrlLeasesExhaustedError(); + } const url = this.#createObjectURL(blob); if (typeof url !== "string" || url.length === 0) { throw new DOMException( @@ -260,6 +289,10 @@ export class BrowserTransientPreview implements TransientPreviewPort { browserDataFailure("UNAVAILABLE", "PREVIEW"), ); } + // 02-01. The caller may abort while the file resolves; a lease created + // after that would never be released because the caller drops the result. + const abortedWhileResolving = abortedResult(input.signal, "PREVIEW"); + if (abortedWhileResolving) return this.#observe(abortedWhileResolving); const mediaType = resolved.value.mediaType.trim().toLowerCase(); if ( !EXACT_MEDIA_TYPE.test(mediaType) || @@ -299,9 +332,7 @@ export class BrowserTransientPreview implements TransientPreviewPort { error instanceof DOMException && error.name === "FileTooLargeError" ) { - return this.#observe( - browserDataFailure("LIMIT_EXCEEDED", "PREVIEW"), - ); + return this.#observe(objectUrlLimitFailure(error, "PREVIEW")); } return this.#observe(mapBrowserDataException(error, "PREVIEW")); } diff --git a/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts b/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts index f17a62f1..084936d6 100644 --- a/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts +++ b/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts @@ -14,7 +14,7 @@ import { isBrowserDataFailureCode } from "../../../application/ports/browser-fil import { browserDataFailure, browserDataSuccess, - mapBrowserDataException, + mapIndexedDbException, } from "../../browser-file-storage/result.ts"; import { snapshotAbortTimers } from "../../platform/abortable-operation.ts"; import { @@ -81,7 +81,7 @@ type ScopeBinding = Readonly<{ }>; /** - * `browserDataFailure` and `mapBrowserDataException` build a `Result`, while the + * `browserDataFailure` and `mapIndexedDbException` build a `Result`, while the * kernel's `translate` contract wants the failure on its own. Both only ever * build the failure arm, so the branch below is a narrowing, not a claim. */ @@ -103,7 +103,7 @@ function checkpointFailure( } function mappedFailure(error: unknown): BrowserDataFailure { - return failureOf(mapBrowserDataException(error, OPERATION)); + return failureOf(mapIndexedDbException(error, OPERATION)); } /** @@ -120,11 +120,9 @@ function admissionFailure(detail: unknown): BrowserDataFailure | null { } /** - * BT-UP-03. The checkpoint store keeps its own failure table rather than the - * `mapIndexedDbException` the other three IndexedDB adapters share: the same - * native error is a different answer here (a `ConstraintError` recovers by - * REOPEN, a quota failure is retryable), and unifying the four tables is a - * separate change from moving the mechanics onto the kernel. + * BT-UP-03. Native exceptions go through `mapIndexedDbException`, the one + * IndexedDB table the other IndexedDB adapters use (F-1, 05-11). Only the + * kernel causes below keep checkpoint-specific answers. */ const translate: IndexedDbTranslate = (cause) => { switch (cause.kind) { diff --git a/src/adapters/cache-storage/public-cache-codec.ts b/src/adapters/cache-storage/public-cache-codec.ts index 6482c0f3..000cf490 100644 --- a/src/adapters/cache-storage/public-cache-codec.ts +++ b/src/adapters/cache-storage/public-cache-codec.ts @@ -26,7 +26,7 @@ import { */ export type PublicCacheCryptoFacade = Readonly<{ - digestSha256(bytes: Uint8Array): Promise; + digestSha256(bytes: Uint8Array): Promise; }>; export type NormalizedAsset = Readonly<{ @@ -619,7 +619,7 @@ export function asFailure( export async function sha256Hex( crypto: PublicCacheCryptoFacade, - bytes: Uint8Array, + bytes: Uint8Array, ): Promise { const digest = await crypto.digestSha256(bytes); let hex = ""; diff --git a/src/adapters/cache-storage/public-cache-response-validation.ts b/src/adapters/cache-storage/public-cache-response-validation.ts index 383081c0..a8bdccc3 100644 --- a/src/adapters/cache-storage/public-cache-response-validation.ts +++ b/src/adapters/cache-storage/public-cache-response-validation.ts @@ -106,7 +106,7 @@ export async function readBodyBounded( expectedByteLength: number, maxEntryBytes: number, signal: AbortSignal | undefined, -): Promise { +): Promise> { if (expectedByteLength > maxEntryBytes) { throw new CacheValidationFailure("LIMIT_EXCEEDED"); } diff --git a/src/adapters/cache-storage/public-response-cache-adapter.ts b/src/adapters/cache-storage/public-response-cache-adapter.ts index 26fc4450..380228af 100644 --- a/src/adapters/cache-storage/public-response-cache-adapter.ts +++ b/src/adapters/cache-storage/public-response-cache-adapter.ts @@ -177,12 +177,11 @@ function snapshotCacheCrypto(crypto: Crypto): PublicCacheCryptoFacade { throw new TypeError("Public cache crypto capability is invalid."); } return Object.freeze({ - async digestSha256(bytes: Uint8Array): Promise { - return await digest.call( - subtle, - "SHA-256", - Uint8Array.from(bytes), - ); + // WebCrypto copies its input when called (02-07), so no copy here. + async digestSha256( + bytes: Uint8Array, + ): Promise { + return await digest.call(subtle, "SHA-256", bytes); }, }); } @@ -242,9 +241,13 @@ export function createPublicResponseCacheAdapter( }); try { + // 02-07. One keys() per lookup, shared by the pointer read and the + // eviction check below. + let names = await dependencies.cacheStorage.keys(); const pointerResult = await readActivePointer( dependencies.cacheStorage, policy, + names, ); if (!pointerResult.ok) { return observeFailure(pointerResult, dependencies.observer); @@ -257,7 +260,11 @@ export function createPublicResponseCacheAdapter( return browserDataSuccess(null); } const pointer = pointerResult.value; - const names = await dependencies.cacheStorage.keys(); + if (!names.includes(pointer.candidateCacheName)) { + // The name list predates the pointer read, which an activation may + // have moved to a newer cache; list again before reporting eviction. + names = await dependencies.cacheStorage.keys(); + } if (!names.includes(pointer.candidateCacheName)) { return observeFailure( browserDataFailure("STORAGE_EVICTED", "CACHE_LOOKUP", { @@ -866,10 +873,19 @@ export function createPublicResponseCacheAdapter( unreadableOwnedCacheCount += 1; continue; } + // 02-05. The marker only claims staging finished; `verified` means + // every entry is still present and matches, as activation checks. + const candidate = await verifyReleaseCandidate( + cache, + marker.value.assets, + policy, + dependencies.crypto, + undefined, + ); candidates.push( Object.freeze({ releaseRegistryId: marker.value.releaseRegistryId, - verified: true, + verified: candidate.kind === "VERIFIED", entryCount: marker.value.entryCount, }), ); @@ -986,10 +1002,11 @@ async function readMarker( async function readActivePointer( cacheStorage: PublicCacheStorageFacade, policy: PublicCacheRuntimePolicy, + names?: readonly string[], ): Promise> { try { const name = controlCacheName(policy); - if (!(await cacheStorage.keys()).includes(name)) { + if (!(names ?? (await cacheStorage.keys())).includes(name)) { return browserDataSuccess(null); } const cache = await cacheStorage.open(name); @@ -1007,8 +1024,12 @@ async function readActivePointer( } } -function byteSourceFrom(bytes: Uint8Array): ByteSource { - const stored = Uint8Array.from(bytes); +/** + * 02-07. Keeps the verified read buffer, which nothing else references, and + * gives each stream its own copy so a consumer that mutates a chunk cannot + * change the body a later stream serves. + */ +function byteSourceFrom(stored: Uint8Array): ByteSource { return Object.freeze({ byteLength: stored.byteLength, async *stream(signal: AbortSignal) { @@ -1049,7 +1070,7 @@ async function verifyReleaseCandidate( assets: readonly NormalizedAsset[], policy: PublicCacheRuntimePolicy, crypto: Readonly<{ - digestSha256(bytes: Uint8Array): Promise; + digestSha256(bytes: Uint8Array): Promise; }>, signal: AbortSignal | undefined, ): Promise { diff --git a/src/application/ports/browser-file-storage/shared.ts b/src/application/ports/browser-file-storage/shared.ts index 0a83b2b7..53036420 100644 --- a/src/application/ports/browser-file-storage/shared.ts +++ b/src/application/ports/browser-file-storage/shared.ts @@ -96,7 +96,8 @@ export type BrowserDataResult = Result; export type BrowserDataObservation = Readonly<{ operation: BrowserDataOperation; - outcome: "SUCCEEDED" | "FAILED" | "DEGRADED"; + /** `DISMISSED`: the user closed a picker or save dialog; not a failure. */ + outcome: "SUCCEEDED" | "FAILED" | "DEGRADED" | "DISMISSED"; failureCode?: BrowserDataFailureCode; durationBucket?: "LT100MS" | "100_TO_499MS" | "500_TO_1999MS" | "GTE2000MS"; byteBucket?: "ZERO" | "LT1MIB" | "1_TO_9MIB" | "10_TO_99MIB" | "GTE100MIB"; diff --git a/tests/unit/browser-file-content.test.ts b/tests/unit/browser-file-content.test.ts index e1f1e36c..a1de678e 100644 --- a/tests/unit/browser-file-content.test.ts +++ b/tests/unit/browser-file-content.test.ts @@ -83,6 +83,50 @@ function pngPolicies( }); } +async function verifiedPngPreview( + leases: ObjectUrlLeaseRegistry, + reportedType = "image/png", +) { + const policies = pngPolicies(); + const vault = new BrowserFileVault({ policies }); + const captured = vault.captureFiles( + [ + new File( + [new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])], + "preview.png", + { type: reportedType, lastModified: 1 }, + ), + ], + { ...pngSelectionPolicy, accept: Object.freeze([]) }, + ); + if (!captured.ok || !captured.value[0]) throw new Error("capture"); + const ref = captured.value[0].ref; + const inspected = await vault.inspect({ + ref, + policy: pngPolicy, + signal: new AbortController().signal, + }); + if (!inspected.ok || !inspected.value.verificationReceipt) { + throw new Error("inspect"); + } + const verificationReceipt = inspected.value.verificationReceipt; + const preview = new BrowserTransientPreview({ + files: vault, + policies, + leases, + hardMaxPreviewBytes: 10, + }); + return { + preview, + request: (signal: AbortSignal) => ({ + ref, + verificationReceipt, + policy: pngPolicy, + signal, + }), + }; +} + describe("browser file content policy", () => { it("neutralizes path, bidi, device-name and executable filename tricks", () => { expect( @@ -570,6 +614,80 @@ describe("browser file content policy", () => { }); }); + it("returns ABORTED without a lease when the caller aborts right after create() (02-01)", async () => { + const revoked: string[] = []; + let urlSequence = 0; + const leases = new ObjectUrlLeaseRegistry({ + createObjectURL: () => `blob:aborted-${urlSequence++}`, + revokeObjectURL: (url) => revoked.push(url), + }); + const { preview, request } = await verifiedPngPreview(leases); + + const controller = new AbortController(); + // Same-turn abort: the effect cleanup of a React StrictMode double effect. + const pending = preview.create(request(controller.signal)); + controller.abort(); + + expect(await pending).toMatchObject({ + ok: false, + error: { code: "ABORTED", operation: "PREVIEW" }, + }); + expect(leases.activeLeaseCount).toBe(0); + expect(urlSequence).toBe(0); + expect(revoked).toEqual([]); + }); + + it("reports a preview that finds every lease slot in use as retryable (02-04)", async () => { + let urlSequence = 0; + const leases = new ObjectUrlLeaseRegistry( + { + createObjectURL: () => `blob:slot-${urlSequence++}`, + revokeObjectURL() {}, + }, + { + hardMaxActiveLeases: 1, + hardMaxSingleLeaseBytes: 16, + hardMaxAggregateLeaseBytes: 16, + }, + ); + const { preview, request } = await verifiedPngPreview(leases); + const held = leases.create(new Blob([new Uint8Array(1)])); + + expect( + await preview.create(request(new AbortController().signal)), + ).toMatchObject({ + ok: false, + error: { + code: "LIMIT_EXCEEDED", + retryable: true, + recovery: "RETRY", + }, + }); + held.release(); + expect( + await preview.create(request(new AbortController().signal)), + ).toMatchObject({ ok: true }); + }); + + it("types the preview Blob from the signature, not from File.type (02-08)", async () => { + const blobs: Blob[] = []; + const leases = new ObjectUrlLeaseRegistry({ + createObjectURL: (blob) => { + blobs.push(blob); + return "blob:typed"; + }, + revokeObjectURL() {}, + }); + // An empty File.type still passes the signature check, so only the typed + // slice decides how the browser interprets the object URL. + const { preview, request } = await verifiedPngPreview(leases, ""); + + expect( + await preview.create(request(new AbortController().signal)), + ).toMatchObject({ ok: true, value: { mediaType: "image/png" } }); + expect(blobs.map((blob) => blob.type)).toEqual(["image/png"]); + }); + it("cannot weaken the built-in active-content preview denylist", async () => { const htmlPolicy = browserFilePolicyReference( "active-content", @@ -682,6 +800,37 @@ describe("browser file content policy", () => { expect(vault.activeReferenceCount).toBe(0); }); + it("caps retained bytes while reference slots remain (02-08)", () => { + let referenceSequence = 0; + const vault = new BrowserFileVault({ + policies: pngPolicies(), + createReference: () => `file:bytes-${referenceSequence++}`, + hardMaxActiveReferences: 8, + hardMaxRetainedBytes: 3, + }); + const permissive = { + ...pngSelectionPolicy, + accept: Object.freeze([]), + }; + expect( + vault.captureFiles( + [new File([new Uint8Array(2)], "one.bin")], + permissive, + ), + ).toMatchObject({ ok: true }); + expect( + vault.captureFiles( + [new File([new Uint8Array(2)], "two.bin")], + permissive, + ), + ).toMatchObject({ + ok: false, + error: { code: "LIMIT_EXCEEDED" }, + }); + expect(vault.activeReferenceCount).toBe(1); + expect(vault.retainedByteLength).toBe(2); + }); + it("caps retained files and aggregate object URL leases", () => { let referenceSequence = 0; const vault = new BrowserFileVault({ diff --git a/tests/unit/browser-file-download.test.ts b/tests/unit/browser-file-download.test.ts index 933bb36b..72ccc95a 100644 --- a/tests/unit/browser-file-download.test.ts +++ b/tests/unit/browser-file-download.test.ts @@ -292,34 +292,38 @@ describe("browser download delivery", () => { }); it("rejects cross-origin or query-bearing browser-managed targets", async () => { - const handoff = vi.fn(); - const adapter = createDownloadDeliveryAdapter({ - ...HARD_LIMITS, - policies, - host: { handoff }, - browserManagedCapabilities: capabilityResolver( - () => "https://evil.example/a?token=secret", - ), - baseOrigin: "https://app.example", - userActivation: { isActive: true }, - }); + // 02-08. Each href breaks one rule, so neither check hides the other. + for (const href of [ + "https://evil.example/downloads/a", + "/downloads/a?token=secret", + ]) { + const handoff = vi.fn(); + const adapter = createDownloadDeliveryAdapter({ + ...HARD_LIMITS, + policies, + host: { handoff }, + browserManagedCapabilities: capabilityResolver(() => href), + baseOrigin: "https://app.example", + userActivation: { isActive: true }, + }); - expect( - await adapter.deliver( - deliveryInput( - { - kind: "BROWSER_MANAGED_RESOURCE", - resourceId: "artifact-1", - capabilityReceipt, - }, - "BROWSER_MANAGED", + expect( + await adapter.deliver( + deliveryInput( + { + kind: "BROWSER_MANAGED_RESOURCE", + resourceId: "artifact-1", + capabilityReceipt, + }, + "BROWSER_MANAGED", + ), ), - ), - ).toMatchObject({ - ok: false, - error: { code: "POLICY_REJECTED" }, - }); - expect(handoff).not.toHaveBeenCalled(); + ).toMatchObject({ + ok: false, + error: { code: "POLICY_REJECTED" }, + }); + expect(handoff).not.toHaveBeenCalled(); + } }); it("requires an exact, unexpired, server-bound synchronous capability receipt", async () => { @@ -605,6 +609,46 @@ describe("browser download delivery", () => { expect(events).toEqual(["hash", "write:2", "abort"]); }); + it("records a save-picker dismissal apart from a browser handoff (02-06)", async () => { + const records: unknown[] = []; + const adapter = createDownloadDeliveryAdapter({ + ...HARD_LIMITS, + policies, + host: { handoff: vi.fn() }, + browserManagedCapabilities: capabilityResolver( + (resourceId) => `/downloads/${resourceId}`, + ), + showSaveFilePicker: async () => { + throw new DOMException("dismissed", "AbortError"); + }, + baseOrigin: "https://app.example", + userActivation: { isActive: true }, + observer: { record: (observation) => records.push(observation) }, + }); + + await adapter.deliver( + deliveryInput( + { + kind: "BROWSER_MANAGED_RESOURCE", + resourceId: "artifact-1", + capabilityReceipt, + }, + "BROWSER_MANAGED", + ), + ); + await adapter.deliver( + deliveryInput( + { kind: "GENERATED", bytes: byteSource([new Uint8Array([1])]) }, + "PROMPT_AND_STREAM", + ), + ); + + expect(records).toEqual([ + { operation: "DOWNLOAD", outcome: "SUCCEEDED" }, + { operation: "DOWNLOAD", outcome: "DISMISSED" }, + ]); + }); + it("distinguishes save-picker dismissal from active cancellation", async () => { const dismissed = createDownloadDeliveryAdapter({ ...HARD_LIMITS, diff --git a/tests/unit/browser-file-picker.test.ts b/tests/unit/browser-file-picker.test.ts index 17075a17..20c4ea46 100644 --- a/tests/unit/browser-file-picker.test.ts +++ b/tests/unit/browser-file-picker.test.ts @@ -98,6 +98,28 @@ describe("browser file pickers", () => { expect(baselineShowPicker).not.toHaveBeenCalled(); }); + it("refuses to open the native input without user activation (02-08)", async () => { + const input = labelledFileInput(); + const click = vi.fn(() => { + queueMicrotask(() => input.dispatchEvent(new Event("cancel"))); + }); + Object.defineProperty(input, "click", { + configurable: true, + value: click, + }); + const picker = new NativeInputFilePicker({ + input, + ...createHarness(), + userActivation: { isActive: false }, + }); + + expect(await picker.select({ policy })).toMatchObject({ + ok: false, + error: { code: "PERMISSION_DENIED", operation: "FILE_SELECT" }, + }); + expect(click).not.toHaveBeenCalled(); + }); + it("resets the native input and supports same-file reselection", async () => { const input = labelledFileInput(); const selected = new File(["hello"], "notes.txt", { diff --git a/tests/unit/browser-file-runtime.test.ts b/tests/unit/browser-file-runtime.test.ts index 62b71ab1..78155222 100644 --- a/tests/unit/browser-file-runtime.test.ts +++ b/tests/unit/browser-file-runtime.test.ts @@ -176,6 +176,72 @@ describe("browser file runtime hard limits and disposal", () => { expect(revoked).toEqual(["blob:runtime-download"]); }); + it("reports exhausted object URL leases as retryable until the grace ends (02-04)", async () => { + const scheduled: Array<() => void> = []; + let urlSequence = 0; + const runtime = createBrowserFileRuntime({ + input: fileInput(), + policies, + limits: { + hardMaxPreviewBytes: 8, + hardMaxObjectUrlBytes: 8, + hardMaxTransferBytes: 16, + hardMaxActiveObjectUrls: 2, + }, + objectUrlApi: { + createObjectURL: () => `blob:runtime-download-${urlSequence++}`, + revokeObjectURL() {}, + }, + download: { + host: { handoff: vi.fn() }, + browserManagedCapabilities: + unusedBrowserManagedCapabilities, + scheduler: { + setTimeout(callback) { + scheduled.push(callback); + return scheduled.length; + }, + }, + }, + }); + const deliver = () => + runtime.downloads.deliver({ + policy: downloadPolicy, + source: { + kind: "GENERATED", + bytes: { + byteLength: 3, + async *stream() { + yield { ok: true, value: new Uint8Array([1, 2, 3]) }; + }, + }, + }, + suggestedFileName: "artifact", + signal: new AbortController().signal, + onProgress() {}, + }); + + // Each handoff keeps its lease for the revoke grace, so the third + // download inside that window finds every slot in use. + expect(await deliver()).toMatchObject({ ok: true }); + expect(await deliver()).toMatchObject({ ok: true }); + expect(await deliver()).toMatchObject({ + ok: false, + error: { + code: "LIMIT_EXCEEDED", + retryable: true, + recovery: "RETRY", + }, + }); + + for (const release of scheduled.splice(0)) release(); + expect(await deliver()).toMatchObject({ + ok: true, + value: { kind: "BROWSER_HANDOFF" }, + }); + runtime.dispose(); + }); + it("aborts a pending native picker and prevents event resurrection", async () => { const input = fileInput(); Object.defineProperty(input, "click", { diff --git a/tests/unit/cross-tab-invalidation.test.ts b/tests/unit/cross-tab-invalidation.test.ts index 5ab6d474..c158edcc 100644 --- a/tests/unit/cross-tab-invalidation.test.ts +++ b/tests/unit/cross-tab-invalidation.test.ts @@ -502,6 +502,15 @@ describe("browser cross-context invalidation transport", () => { sequence: 1, }), ); + // 02-08. A source first seen mid-stream has already sent events this tab + // missed, so its first event is a gap on its own. + network.emit( + wireEvent({ + eventId: "joined-event-00000004", + sourceId: "joined-source-0000001", + sequence: 4, + }), + ); expect( delivered.map(({ event, ordering }) => [ @@ -512,6 +521,7 @@ describe("browser cross-context invalidation transport", () => { [1, "NEXT"], [3, "GAP"], [1, "NEXT"], + [4, "GAP"], ]); expect(observations).toContainEqual({ operation: "RECEIVE", diff --git a/tests/unit/public-response-cache.test.ts b/tests/unit/public-response-cache.test.ts index 30dd1df8..78c462db 100644 --- a/tests/unit/public-response-cache.test.ts +++ b/tests/unit/public-response-cache.test.ts @@ -1,9 +1,10 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import type { PublicCacheAsset, PublicCacheReleaseManifest, } from "../../src/application/ports/browser-file-storage/cache-storage-ports.ts"; +import type { ByteSource } from "../../src/application/ports/browser-file-storage/shared.ts"; import { assertPublicCachePolicy, createDefaultPublicCachePolicy, @@ -112,6 +113,54 @@ describe("public response Cache Storage adapter", () => { expect(match.ok && match.value !== null).toBe(true); }); + it("stages with an anonymous same-origin request that fails on redirect (02-02)", async () => { + const policy = createDefaultPublicCachePolicy( + "https://assets.example.test", + ); + const bytes = new Uint8Array([5, 5, 5, 5]); + const asset: PublicCacheAsset = { + absoluteUrl: "https://assets.example.test/anonymous.js", + expectedByteLength: bytes.byteLength, + expectedContentType: "application/javascript", + integrity: { + algorithm: "SHA-256", + digestHex: await digestHex(bytes), + }, + }; + const requests: Request[] = []; + const adapter = createPublicResponseCacheAdapter({ + cacheStorage: new MemoryCacheStorage() as unknown as CacheStorage, + crypto: globalThis.crypto, + mutationLock: immediateLock, + policy, + fetcher: async (request) => { + requests.push(request); + return new Response(bytes, { + headers: { + "cache-control": "public, max-age=31536000, immutable", + "content-type": "application/javascript", + }, + }); + }, + }); + const manifest = await manifestFor("anonymous-release", [asset], policy); + + expect(await adapter.admin.stageRelease(manifest)).toMatchObject({ + ok: true, + }); + // The Cache Storage is origin-wide and has no logout purge, so a cookie + // on this request would let a per-user response outlive the session. + expect( + requests.map(({ credentials, mode, redirect }) => ({ + credentials, + mode, + redirect, + })), + ).toEqual([ + { credentials: "omit", mode: "same-origin", redirect: "error" }, + ]); + }); + it("restages an evicted entry even when the release marker remains", async () => { const policy = createDefaultPublicCachePolicy( "https://assets.example.test", @@ -160,12 +209,23 @@ describe("public response Cache Storage adapter", () => { ); expect(payloadIndex).toBeGreaterThanOrEqual(0); cache.responses.splice(payloadIndex, 1); + const candidates = async () => { + const inspection = await adapter.admin.inspect(); + return inspection.ok ? inspection.value.releaseCandidates : null; + }; + // 02-05. inspect() does not report the marker's claim as verified. + expect(await candidates()).toEqual([ + { releaseRegistryId: "evicted-release", verified: false, entryCount: 1 }, + ]); // A marker is a claim, not evidence: restaging must repair. expect(await adapter.admin.stageRelease(manifest)).toMatchObject({ ok: true, }); expect(fetches).toBe(2); + expect(await candidates()).toEqual([ + { releaseRegistryId: "evicted-release", verified: true, entryCount: 1 }, + ]); expect( await adapter.admin.activateRelease( manifest.releaseRegistryId, @@ -1458,6 +1518,80 @@ describe("public response Cache Storage adapter", () => { expect(await cacheStorage.keys()).toEqual([]); }); + it("spends one keys() and at most two body copies per lookup (02-07)", async () => { + const policy = createDefaultPublicCachePolicy( + "https://assets.example.test", + ); + const bytes = new Uint8Array([6, 6, 6, 6, 6]); + const asset: PublicCacheAsset = { + absoluteUrl: "https://assets.example.test/cost.js", + expectedByteLength: bytes.byteLength, + expectedContentType: "application/javascript", + integrity: { + algorithm: "SHA-256", + digestHex: await digestHex(bytes), + }, + }; + const cacheStorage = new MemoryCacheStorage(); + let keysCalls = 0; + const listKeys = cacheStorage.keys.bind(cacheStorage); + cacheStorage.keys = async () => { + keysCalls += 1; + return await listKeys(); + }; + const adapter = createPublicResponseCacheAdapter({ + cacheStorage: cacheStorage as unknown as CacheStorage, + crypto: globalThis.crypto, + mutationLock: immediateLock, + policy, + fetcher: async () => + new Response(Uint8Array.from(bytes), { + headers: { + "cache-control": "public", + "content-type": "application/javascript", + }, + }), + }); + const manifest = await manifestFor("cost-release", [asset], policy); + expect(await adapter.admin.stageRelease(manifest)).toMatchObject({ + ok: true, + }); + expect( + await adapter.admin.activateRelease( + manifest.releaseRegistryId, + manifest.manifestDigestHex, + ), + ).toMatchObject({ ok: true }); + const read = async (body: ByteSource): Promise => { + const chunks: Uint8Array[] = []; + for await (const chunk of body.stream(new AbortController().signal)) { + if (chunk.ok) chunks.push(chunk.value); + } + return chunks; + }; + + keysCalls = 0; + const copy = vi.spyOn(Uint8Array, "from"); + const match = await adapter.responses.matchActiveExact({ + absoluteUrl: asset.absoluteUrl, + }); + if (!match.ok || !match.value) throw new Error("lookup"); + const [chunk] = await read(match.value.body); + const bodyCopies = copy.mock.calls.filter( + ([source]) => + source instanceof Uint8Array && + source.byteLength === bytes.byteLength, + ).length; + copy.mockRestore(); + + expect(keysCalls).toBe(1); + // The bounded read buffer plus one copy for the stream consumer. + expect(bodyCopies).toBe(1); + // That copy is the consumer's own: changing it leaves the body intact. + chunk!.fill(0); + expect(await read(match.value.body)).toEqual([bytes]); + }); + it("reuses a verified release marker across lookups (Q-6.2-6)", async () => { const policy = createDefaultPublicCachePolicy( "https://assets.example.test", diff --git a/tests/unit/resumable-upload-checkpoint.test.ts b/tests/unit/resumable-upload-checkpoint.test.ts index e96c8906..ba8b4572 100644 --- a/tests/unit/resumable-upload-checkpoint.test.ts +++ b/tests/unit/resumable-upload-checkpoint.test.ts @@ -7,6 +7,7 @@ import { createIndexedDbResumableUploadCheckpointStore, uploadCheckpointDatabaseName, } from "../../src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts"; +import { mapIndexedDbException } from "../../src/adapters/browser-file-storage/result.ts"; import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts"; const scope = Object.freeze({ @@ -514,6 +515,37 @@ describe("IndexedDB resumable upload checkpoint", () => { }); }); + // F-1 (05-11). The store maps native errors with the one IndexedDB table, so + // a missing store is a schema problem and a quota failure is not retried. + it("maps native request errors with the shared IndexedDB table", async () => { + for (const name of [ + "ConstraintError", + "NotFoundError", + "QuotaExceededError", + "InvalidStateError", + "UnknownError", + "SecurityError", + ]) { + const scripted = scriptedFactory(); + const store = createIndexedDbResumableUploadCheckpointStore({ + scope, + factory: scripted.factory, + }); + const pending = store.read("upload_key_01"); + const transaction = await openedCheckpointTransaction(scripted); + const read = transaction.requests[0]; + if (!read) throw new Error("the checkpoint read queued no request"); + const error = new DOMException("native detail", name); + + read.error = error; + read.onerror?.(new Event("error")); + + expect(await pending).toEqual( + mapIndexedDbException(error, "UPLOAD_RECONCILE"), + ); + } + }); + // CP-4. The transaction can already be durably committed while its completion // event is still queued, which is when `abort()` throws. Claiming the abort // would report a committed checkpoint as ABORTED.