diff --git a/.dependency-cruiser.json b/.dependency-cruiser.json index b3c60795..1e022fd6 100644 --- a/.dependency-cruiser.json +++ b/.dependency-cruiser.json @@ -167,6 +167,17 @@ "path": "^src/(application|features)" } }, + { + "name": "contracts-do-not-know-presentation-or-bootstrap", + "comment": "Q-6.7-12. `src/contracts` is shared vocabulary read by every layer, including the service worker and web worker builds. Importing presentation or the composition root from it would pull React and the whole app into those builds. There is no such import today; this keeps it that way.", + "severity": "error", + "from": { + "path": "^src/contracts" + }, + "to": { + "path": "^src/(presentation|bootstrap)" + } + }, { "name": "generic-presentation-does-not-compose-the-product", "comment": "§4 / §9. Which features are installed is a product decision that belongs to bootstrap. Generic presentation reads the installed registries directly today; the paths below are the exact set that does so, frozen so the coupling cannot spread while the assembly is lifted into bootstrap.", diff --git a/SPEC.md b/SPEC.md index ef12230a..5ee156c4 100644 --- a/SPEC.md +++ b/SPEC.md @@ -101,3 +101,113 @@ | D-5 (R-8.3) | 로케일 저장은 테마와 같은 `preferences` 경로를 쓴다. Locale/Theme provider는 scope fence 바깥으로 올린다. | 이미 있는 테마 패턴을 재사용한다. | | D-6 (R-9.2) | 누적 count는 dedup 창이 닫힐 때나 다음 flush 때 요약 이벤트의 `occurrences`로 보낸다. | 기존 이벤트 스키마(`occurrences`)를 그대로 쓴다. | | D-7 (R-6.3) | previous 캐시 fallback은 hashed URL에만 적용한다. | hashed URL은 같은 URL이면 같은 내용이라 안전하다. | + +--- + +# 2차 라운드: 권장·사소 항목과 1차 후속 결정 + +1차 라운드(R-0 ~ R-9.3)는 `9bef702`로 main에 병합했다. 2차 라운드에서는 리뷰의 **권장·사소 항목 전부**와 1차에서 남긴 결정 두 건을 처리한다. 요구사항 ID는 `Q-<리뷰 섹션>` 형식이다(예: Q-6.1-5 = 리뷰 6.1-5). + +## 공통 완료 기준 (2차) + +1차 공통 기준과 같다. 여기에 두 가지를 더한다. +- **동작을 바꾸지 않는 정리(파일 분리, 중복 합치기)**: 새 RED 테스트 대신 기존 테스트가 안전망이다. 해당 경로에 테스트가 없으면 현재 동작을 고정하는 테스트(characterization)를 먼저 추가한다. +- **번들**: 정리가 끝난 뒤 `check:optional-recipes`가 통과해야 한다. 예산은 올리지 않는다(D-11). + +## 요구사항 + +### browser-transfer +- Q-6.1-5 worker 하나가 실패하면 transfer 단위 abort로 나머지 worker를 즉시 멈춘다. +- Q-6.1-6 해석할 수 없는 checkpoint 행이 있어도 abort는 그 행을 지우고 ORPHANED로 보고한다. +- Q-6.1-7 PRIMARY_REQUIRED probe를 쓰는 preset은 fit이 cover/contain/fill일 때만 정책을 통과한다(D-12). +- Q-6.1-8 probe의 decode는 EXIF/irot 회전을 적용하지 않는다(`imageOrientation: "none"`). +- Q-6.1-9 presigned HTTP helper를 한 모듈로 합친다. statusFailure recovery를 통일하고, 쓰지 않는 `compensateLateResponse`는 삭제한다. download Content-Length를 엄격하게 파싱하고, runtime attempt는 kernel `createAbortableOperation`을 쓴다. +- Q-6.1-3b part마다 일어나는 방어적 복사 중 겹치는 것(`Uint8Array.from`과 `slice()`)을 하나로 줄인다. +- Q-6.1-10 `resumable-upload-runtime.ts`에서 서버 응답 검증과 의존성 snapshot 래퍼를 별도 모듈로 분리한다. 동작은 바꾸지 않는다. +- Q-6.1-11 vault `register`는 snapshot 값만 읽는다. + +### browser-files / cache-storage / cross-context +- Q-6.2-6 cache 조회 비용: JSON은 chunk를 모아 읽고, 검증된 marker는 메모리에 캐시하고, asset 탐색은 Map으로 한다. +- Q-6.2-7 browser-files의 abort race를 kernel `race`와 compensate로 교체한다. 늦게 도착한 lease와 writable은 닫는다. +- Q-6.2-8 native `cancel`을 한 번이라도 관찰했으면 focus fallback을 끈다. +- Q-6.2-9 host factory가 비활성으로 끝날 때 observe로 보고한다. epoch는 releaseId를 인코딩해서 만든다. +- Q-6.2-10 파일명 자르기를 O(n)으로 바꾸고, 중복 호출을 하나로 줄인다. +- Q-6.2-11 `public-response-cache-adapter.ts`와 `download-delivery-adapter.ts`에서 코덱·검증 모듈을 분리한다. 동작은 바꾸지 않는다. +- Q-6.2-12 `MEDIA_TYPE`/opaque 정규식과 `positiveSafeInteger` 중복을 합치고, `object-url-lease.ts`의 죽은 분기를 지운다. + +### http / browser-rpc / query-cache / auth +- Q-6.3-6 요청 종료 사유 판정을 `terminalOutcomeFor` 하나로 모은다. 백오프 중 scope fence는 scope 종료로 분류된다. +- Q-6.3-7 명령의 최종 effect는 누적 certainty와 합친다. `MAYBE_APPLIED`면 재시도하지 않는다. +- Q-6.3-8 namespace 무효화를 병렬로 실행한다. +- Q-6.3-9 RPC 명령이 전송 뒤 실패하면 `MAYBE_APPLIED`로 보고한다. 재시도 전에 scope를 확인하고, 소비자가 abort한 stream은 정리한다. +- Q-6.3-11 V2 401 복구를 재시도 예산과 분리한다. "롤백 가능 seam" 문서의 잘못된 주장을 고친다(V2와 V3는 wire 형식이 다르다). +- Q-6.3-12 cursor pagination의 누적 직렬화와 `push(...)` 한도 문제를 고친다. 쓰지 않는 `validTransportFailure`를 삭제하고, 따옴표가 닫히지 않은 `W/"` ETag를 거부한다. +- Q-6.3-3b V2도 5xx/408/425의 HTML/빈 바디를 status를 담은 서버 장애로 분류하고 재시도 대상으로 둔다. + +### realtime +- Q-6.4-5 chunk당 item 상한을 넘으면 실패하지 않고 다음 처리로 넘긴다. COMMENT는 상수 객체를 쓴다. +- Q-6.4-6 dedupe는 FIFO로 제거하고, fingerprint는 해시로 저장하고, prune은 `break`한다. 가득 차도 전체 recovery를 하지 않는다. +- Q-6.4-7 재시도 예산은 유효 신호가 있고 `stableOpenMs`가 지났을 때만 초기화한다. +- Q-6.4-8 realtime 내부의 DataSnapshot과 abort/timeout race 헬퍼를 한 벌로 합친다. Retry-After 파싱과 JSON 중복 키 스캐너는 kernel(`src/adapters/platform/`)로 올리고, http retry-policy와 web-push codec도 이를 쓴다. +- Q-6.4-9 반복되는 attempt 정리를 `endAttempt()`로 뽑고, 무시되던 `_recovery` 파라미터를 없앤다. +- Q-6.4-10 probe 버퍼 상한을 현재 버퍼 기준으로 계산한다. +- Q-6.4-11 사소 항목: poll execute가 throw하면 retryable OFFLINE으로 둔다. BOM은 한 번만 제거하고, 이중 encode와 이벤트마다 만드는 TextEncoder를 없애고, 잘못 붙은 JSDoc을 옮긴다. + +### storage +- Q-6.5-6 openObject는 사전 검증에서 manifest만 대조하고, root digest는 스트림 끝에서 확인한다. +- Q-6.5-7 IndexedDB 저장 행 타입·검증기·측정 공식을 `indexeddb-records.ts` 하나로 모은다. 동작은 바꾸지 않는다. +- Q-6.5-8 삭제 후 재생성하면 revision/generation이 다시 시작한다는 점을 port 주석과 문서에 명시한다(D-13). +- Q-6.5-9 보상이 실패해도 put의 원래 실패 코드를 유지하고, recovery만 RECONCILE로 바꾼다. +- Q-6.5-10 kernel: `succeed` 뒤에 온 `fail`이 이기도록 하고, settle된 뒤의 upgrade는 abort한다. + +### service-worker / web-push +- Q-6.6-6b fetch 가로채기를 "same-origin GET, navigate 아님, 해시 파일명 또는 manifest URL"로 넓힌다. previous 캐시 fallback이 옛 빌드 chunk에 실제로 동작해야 한다(1차 T29/T32 후속, 사용자 결정). +- Q-6.6-8 후보 캐시 이름이 active 캐시와 같으면 설치 실패 시 지우지 않는다. +- Q-6.6-9 activate는 오래된 캐시부터 지우고, marker 쓰기 실패가 삭제를 막지 않는다. +- Q-6.6-10b 페이지 쪽 활성화 deadline에 워커 drain 시간과 여유분을 더한다. +- Q-6.6-11 알림 클릭이 거절되면 handoff 데이터 없이 앱 루트를 연다. 조용한 push drop은 트레이드오프를 문서에 명시한다(D-14). +- Q-6.6-12 web-push codec primitive(base64url, OPAQUE_ID, validAuthority, exactRecord)를 한 모듈로 합친다. page controller가 주입받은 document를 쓴다. + +### contracts +- Q-6.7-6 exact-key/스냅샷 구현을 `exact-snapshot.ts` 하나로 모으고 배열 스냅샷을 추가한다. iterator·getter 우회를 막는다. +- Q-6.7-7 검증된 인덱스·레지스트리는 `createReadOnlyRegistry`를 쓰고 row마다 스냅샷해서 얼린다. +- Q-6.7-8 검증기 프로토콜과 `MappingResult`의 기준 모양을 하나로 정하고, 나머지는 호환 alias나 어댑터로 둔다(D-15). +- Q-6.7-9 REST 인증 프로필은 설치된 레지스트리 하나를 기준으로 한다. V2 resolve도 검증된 레지스트리를 쓴다. +- Q-6.7-10 배포 승인은 IPv6 loopback·ULA·link-local, IPv4-mapped, CGNAT, `0.0.0.0/8`, `.internal`/`.local`을 사설 주소로 본다. 로컬 호스트 목록은 한 곳에 둔다. +- Q-6.7-11 레지스트리 조회는 `Object.hasOwn`으로 한다. 목록에 없는 offline 전이는 false를 반환한다. +- Q-6.7-12 release-tokens는 비교하지 않은 값을 통과로 보고하지 않는다. contract-set 중복은 실패 코드로 반환한다. query-keys 정렬은 필요할 때만 한다. dependency-cruiser에 contracts → presentation/bootstrap 금지 규칙을 추가한다. + +### presentation +- Q-6.8-9 디자인시스템 링크(`PageActionBar`, `Breadcrumbs`, `LinkButton`)는 router `Link`로 렌더한다. Pagination은 다른 검색 파라미터를 보존한다. +- Q-6.8-10 로딩·인증필요·404 화면을 하나씩으로 합치고, 세션 액션은 hook 하나로 묶는다. reject 시 멈추던 임시 로딩도 고친다. +- Q-6.8-11 Tooltip: `aria-describedby`를 포커스되는 자식에 붙이고, Escape로 닫는다. +- Q-6.8-12 Pagination은 현재 페이지 주변과 처음·끝만 보여주고(windowing), landmark 중첩을 없앤다. +- Q-6.8-13a 플랫폼 라우트의 `none` 코덱은 모르는 쿼리 파라미터를 거부하지 않고 무시한다(D-16). +- Q-6.8-13b 폼 제출은 비동기 검증 중에도 두 번 일어나지 않는다. 저장 직후 이동할 때 dirty guard가 뜨지 않는다. +- Q-6.8-13c 기본 fallback 문구는 현재 로케일을 따른다. SearchField를 지우면 입력으로 포커스를 돌려준다. +- Q-6.8-13d `theme.css`를 여러 파일로 나눈다. 빌드 결과 CSS 바이트가 달라지지 않아야 한다. + +### application / features / bootstrap / platform (+ telemetry adapter) +- Q-6.9-4 텔레메트리 전송 계층을 하나로 합친다(rate limit, credentials `omit`, `pagehide` flush, dispose abort). best-effort fetch에 타임아웃을 둔다(6.3-10 포함). +- Q-6.9-5 킬스위치로 끈 feature는 `features.get()`이 API를 돌려주지 않는다. +- Q-6.9-6 adapter contribution의 featureId가 중복되거나 소속 module과 다르면 throw한다. +- Q-6.9-7 execution context interaction에 완료/정리 API를 두어 부모 signal listener가 남지 않게 한다. +- Q-6.9-8 부트 중에 정적 boot shell(로딩 표시, `aria-busy`)을 보여준다. +- Q-6.9-9 chunk와 boot의 "한 번만 reload" 가드를 공용 guard 하나로 합친다. +- Q-6.9-10 검증을 통과한 config 값만 safe 에러에 싣는다. +- Q-6.9-11 텔레메트리 버퍼는 필요한 공간이 확보될 때만 낮은 severity를 지운다. 주석을 코드와 맞춘다. +- Q-6.9-12 re-export만 하는 `reference-feature-runtime.tsx`를 삭제한다. CI 전용 정책(`promotion-readiness`, `performance-budgets`)은 src 소비자가 없으면 `scripts/`로 옮긴다. 메시지 로케일은 하드코딩하지 않고 카탈로그에서 도출한다. + +### 통합 +- Q-B 번들 예산: 모든 레인을 병합한 뒤 `check:optional-recipes`를 통과시킨다. 필요하면 해당 번들 코드를 줄인다(D-11). + +## 결정 (2차) + +| ID | 결정 | +|---|---| +| D-11 | 번들 예산은 올리지 않는다. 코드를 줄여 맞춘다(사용자 결정). | +| D-12 | PRIMARY_REQUIRED는 fit cover/contain/fill만 허용한다. 비율을 유지하는 fit은 probe를 쓰지 않는 preset에서만 허용한다. | +| D-13 | 삭제 뒤 revision 재시작(ABA)은 스키마를 바꾸지 않고 문서로 계약을 명시한다. tombstone 도입은 저장 스키마 변경이라 범위 밖이다. | +| D-14 | 클릭 실패 시 앱 루트를 연다. push drop은 설계 의도로 두고 문서에 명시한다. | +| D-15 | `external-contract-runtime`의 모양을 기준으로 삼는다. 다른 쪽은 호환 alias나 어댑터로 유지한다(공개 타입을 삭제하지 않음). | +| D-16 | 플랫폼 라우트의 모르는 쿼리 파라미터는 무시한다(strip). URL은 건드리지 않는다. | diff --git a/config/testing/risk-coverage.json b/config/testing/risk-coverage.json index 11cbb039..f3b5eb7b 100644 --- a/config/testing/risk-coverage.json +++ b/config/testing/risk-coverage.json @@ -119,26 +119,6 @@ "branches": 75 } }, - { - "path": "src/application/policies/performance-budgets.ts", - "owner": "application-policy", - "minimum": { - "lines": 80, - "statements": 80, - "functions": 80, - "branches": 40 - } - }, - { - "path": "src/application/policies/promotion-readiness.ts", - "owner": "release-runtime", - "minimum": { - "lines": 95, - "statements": 95, - "functions": 95, - "branches": 95 - } - }, { "path": "src/application/use-cases/decide-chunk-recovery.ts", "owner": "application-runtime", @@ -212,8 +192,6 @@ "src/adapters/telemetry/best-effort-telemetry.ts", "src/application/create-application.ts", "src/contracts/compatibility.ts", - "src/application/policies/performance-budgets.ts", - "src/application/policies/promotion-readiness.ts", "src/application/use-cases/decide-chunk-recovery.ts", "src/bootstrap/load-release-manifest.ts", "src/bootstrap/read-bounded-boot-json.ts", diff --git a/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md b/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md index cd0c5d76..a7bec984 100644 --- a/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md +++ b/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md @@ -2604,7 +2604,7 @@ export const DEFAULT_REALTIME_RECONNECT_POLICY = Object.freeze({ - remaining episode budget 초과 hint: reconnect 종료; - attempts/exhausted: `DEGRADED`, explicit recovery action; - automatic new episode cooldown: 300,000ms; -- valid event/heartbeat 또는 60s stable open 후 attempt counter reset; +- valid event/heartbeat를 받고 60s stable open도 지난 뒤에만 attempt counter reset; - offline state에서는 timer 대신 `online` signal을 기다림. ### 14.4 error classification diff --git a/docs/architecture/browser-file-and-origin-storage.md b/docs/architecture/browser-file-and-origin-storage.md index e3e787b5..8389839f 100644 --- a/docs/architecture/browser-file-and-origin-storage.md +++ b/docs/architecture/browser-file-and-origin-storage.md @@ -525,6 +525,14 @@ recipe의 feature-facing `StoredRecord` view model과 혼동하지 않는다. `writtenAtEpochMs`, synchronization, `measuredBytes`, `eligibleAtEpochMs`는 record envelope에 중복 저장하지 않고 `retentionStore` sidecar에 둔다. +revision은 살아 있는 record 하나 안에서만 순서를 매긴다(D-13). `remove`는 행을 +tombstone 없이 지우므로 같은 key를 다시 만들면 revision이 1부터 다시 시작한다. +그래서 `(key, revision)`은 key의 전체 수명에서 유일하지 않다. 삭제 전에 +revision N을 읽은 writer는 재생성된 record가 N에 도달하면 `expectedRevision: N` +CAS로 그 record를 덮어쓸 수 있다. 이 구분이 필요한 호출자는 revision과 함께 +자기가 소유한 값(server version, payload 안의 ID)을 비교한다. tombstone으로 +번호를 이어 가는 방식은 저장 스키마 변경이라 이 템플릿 범위 밖이다. + - structured clone 성공을 업무 schema 검증으로 간주하지 않는다. - 모든 read는 `unknown`에서 runtime codec으로 envelope와 payload version을 검증한 뒤 domain value로 mapping한다. @@ -752,7 +760,9 @@ CLEANED -> journal 제거 - journal row와 budget reservation은 physical cleanup effect가 `CLEANED` 또는 `ALREADY_CLEAN`으로 확인된 뒤에만 해제한다. timeout, crash, malformed response, `EFFECT_UNKNOWN`은 성공이 아니며 `PREPARING`/`FILES_READY`를 - 그대로 남기고 `OBJECT_RECONCILE`로 반환한다. + 그대로 남긴다. 이때 put은 자기 실패 코드(취소면 `ABORTED`, 쿼터 초과면 + `QUOTA_EXCEEDED` 등)를 그대로 반환하고 recovery만 `RECONCILE`로 바꾼다 + (Q-6.5-9). journal rollback이 실패해도 같다. - coordinator가 `abortPreparedPut()` 하나만 소유한다. worker client는 prepare 실패 시 별도의 fire-and-forget abort를 발행하지 않는다. 중복 보상은 아직 남아 있어야 할 journal row를 조기에 지우는 경로였다. @@ -771,6 +781,11 @@ CLEANED -> journal 제거 `STORAGE_EVICTED`; reconstructable만 rehydrate한다. - delete는 logical row tombstone을 먼저 commit해 신규 open을 막고 physical bytes를 나중에 정리한다. +- delete가 끝나면 logical row가 없어지므로 같은 object ID의 다음 put은 + generation 1부터 다시 시작한다(D-13). 삭제 전에 기억한 generation이나 + `expectedGeneration`은 다른 객체와 일치할 수 있다. `(objectId, generation)`을 + 객체 수명 전체의 식별자로 쓰지 않고, 필요하면 integrity root digest를 함께 + 비교한다. - operation ID로 replay를 deduplicate한다. `Web Locks`를 쓰면 고정된 origin mutation lock과 AbortSignal/timeout을 사용한다. diff --git a/docs/architecture/presigned-transfer-and-image-cdn.md b/docs/architecture/presigned-transfer-and-image-cdn.md index 3a96f604..2a07e968 100644 --- a/docs/architecture/presigned-transfer-and-image-cdn.md +++ b/docs/architecture/presigned-transfer-and-image-cdn.md @@ -360,7 +360,10 @@ resume through upload() 정한 `schemaVersion: 2`가 필요하다. 기존 schema에 필드를 몰래 추가하지 않는다. 현재 checkpoint store도 single-key `read/CAS/remove`와 account partition 전체 -삭제만 제공한다. abandoned upload가 같은 `uploadKey`로 다시 열리지 않으면 local +삭제만 제공한다. 예외로 읽을 수 없는 행(손상, 또는 이 빌드가 모르는 +`schemaVersion`)은 명시적 `abort()`가 `removeUnreadable`로 지우고 `ORPHANED`로 +보고한다. 그 행에서는 session을 알 수 없으므로 server session은 만료에 맡긴다. +`upload()`는 같은 행에서 계속 `CORRUPT_DATA`로 fail-closed한다. abandoned upload가 같은 `uploadKey`로 다시 열리지 않으면 local checkpoint를 retention 기준으로 자동 발견·정리하지 못한다. 향후 admin lifecycle은 다음을 제공한다. @@ -545,6 +548,9 @@ DOM, persisted state, telemetry 또는 query cache에 장기 보관하지 않는 private delivery는 `PRIMARY_REQUIRED` browser probe가 필수이며 이를 `NONE`으로 낮출 수 없다. probe는 `credentials: omit`, redirect 금지, exact response URL과 `Cache-Control: no-store`를 실제 response에서 확인한다. +probe는 decode 크기가 primary 후보의 pixel 크기와 정확히 같아야 통과하므로 +`PRIMARY_REQUIRED` preset의 `fit`은 `cover`/`contain`/`fill`만 허용한다(D-12). +원본 비율을 유지하는 `inside`/`outside`는 probe를 쓰지 않는 preset에서만 쓴다. 실제 ``는 same-origin일 때 cookie를 보낼 수 있으므로 registry는 CDN origin이 composition의 application origin과 같으면 생성 단계에서 거절한다. private CDN 응답은 cookie나 ambient authorization에 diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index 27c735fb..fc581c94 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -618,7 +618,8 @@ stream + epoch별 `lastAppliedSequence`를 기준으로 처리한다. | `sequence == lastApplied + 1` | 순차 적용 | | `sequence > lastApplied + 1` | gap; delta 적용 중지, `RESYNC_REQUIRED` | | unknown `streamEpoch` | old/new epoch를 섞지 않고 registered snapshot 또는 session rebuild | -| dedupe/queue ceiling 초과 | 임의 eviction 후 계속 적용하지 않고 registered recovery | +| dedupe window 가득 참 | 가장 오래된 항목부터 제거(FIFO)하고 계속 적용. 창에서 밀려난 재전송은 `sequence <= lastApplied`로 drop | +| queue ceiling 초과 | 임의 eviction 후 계속 적용하지 않고 registered recovery | | captured old runtime generation | late callback safe drop + aggregate diagnostic | | current connection의 `scopeBinding` mismatch | effect/sequence/cursor 0, freshness `UNKNOWN`, close + session revalidation + registered recovery | @@ -763,8 +764,9 @@ effectiveDelay = max(localDelay, validServerNotBefore) bound로 취급한다. `effectiveDelay`가 implementation max delay나 남은 elapsed budget을 넘으면 낮춰 clamp하지 않고 reconnect/poll을 종료해 `DEGRADED`/`STALE`로 전환한다. -- connection이 잠깐 열렸다는 이유로 attempt를 0으로 만들지 않는다. stable-open - window 또는 valid heartbeat/event 뒤에만 reset한다. +- connection이 잠깐 열렸다는 이유로 attempt를 0으로 만들지 않는다. valid + heartbeat/event를 받았고 stable-open window도 지났을 때만 reset한다(둘 중 + 하나만으로는 reset하지 않는다). - stream reconnect는 realtime recovery coordinator, credential recovery는 session owner, Poll attempt 사이 cadence는 poll coordinator가 각각 소유한다. Poll-bound REST transport retry와 Query retry는 끈다. 같은 logical recovery의 @@ -1411,6 +1413,20 @@ Service Worker는 언제든 종료될 수 있다. in-memory cursor, queue, auth timer를 authority로 사용하지 않는다. `waitUntil`도 무제한 lifetime을 보장하지 않으므로 large fetch, retry loop, data migration을 넣지 않는다. +**조용한 drop은 설계 의도다(D-14).** 검증에 실패한 push(EXPIRED, +RELEASE_MISMATCH, association mismatch, fence 읽기 실패, handler deadline 초과, +malformed/unknown)는 알림을 띄우지 않고 끝난다. 계정 정보가 없는 generic +알림으로 대신 띄우지 않는 이유는 logout·계정 전환 뒤에 도착한 push가 어떤 +형태로든 사용자에게 보이면 안 되기 때문이다. 대가는 두 가지다. + +- Chrome은 `userVisibleOnly` push가 알림 없이 끝나면 "This site has been updated + in the background" 같은 기본 알림을 대신 띄울 수 있다. +- Safari(WebKit)는 알림 없는 push가 반복되면 구독을 취소할 수 있다. + +그래서 drop은 드물어야 한다. backend는 ACTIVE association에만 보내고, 짧은 +server TTL을 쓰고, release를 바꾼 직후에는 이전 release epoch로 보내지 않는다. +drop은 `web_push_hint_processed`의 `FAILED` + reason으로 관측한다. + ### 8.5 Notification content와 click - title/body/icon/action은 closed notification registry가 만든다. @@ -1438,8 +1454,14 @@ type NotificationClickDataV1 = Readonly<{ worker가 종료·재시작된 뒤에도 click을 처리할 수 있도록 이 bounded, non-sensitive envelope만 `NotificationOptions.data`에 넣는다. click handler는 codec/size/expiry, -current local `ACTIVE` fence와 release epoch를 다시 검증한다. unknown/mismatch는 -route를 열지 않고 notification을 닫는다. 이미 표시된 notification은 logout 뒤 +current local `ACTIVE` fence와 release epoch를 다시 검증한다. unknown/mismatch +(만료, fence·release 불일치, fence 읽기 실패, 모르는 route)는 notification을 닫고 +요청한 route 대신 **앱 루트(`/`)를 handoff 데이터 없이 연다**(D-14). +사용자의 탭이 아무 반응 없이 사라지지 않게 하되, 거절된 click의 route와 +notification 정보는 페이지로 넘기지 않는다. 결과는 여전히 실패로 보고하고 +(`web_push_click_dispatched` `FAILED` + reason, `nativeEffect`는 루트 창의 +확실성), 브라우저가 창 열기를 거절한 native 실패나 deadline/abort 뒤에는 루트를 +다시 시도하지 않는다. 이미 표시된 notification은 logout 뒤 OS notification center에 남을 수 있으므로 copy는 항상 account-neutral하고 민감하지 않아야 하며, `getNotifications()` cleanup 성공을 privacy 보장으로 과장하지 않는다. diff --git a/docs/operations/client-cache-and-storage-recovery.md b/docs/operations/client-cache-and-storage-recovery.md index 4f606e2a..5780b9c5 100644 --- a/docs/operations/client-cache-and-storage-recovery.md +++ b/docs/operations/client-cache-and-storage-recovery.md @@ -78,6 +78,8 @@ session/account Query lifecycle, strict query policy와 Web Storage v2 lifecycle - `BROADCAST_PUBLISH_FAILED` - `STORAGE_LISTENER_FAILED` - `STORAGE_PUBLISH_FAILED` +- `INVALID_CACHE_EPOCH`, `SECURE_RANDOM_UNAVAILABLE`(OPEN FAILED): runtime을 + 만들지 못해 이 tab은 cross-tab 무효화 없이 `DEGRADED_LOCAL_ONLY`로 동작한다 - runtime status `DEGRADED_STORAGE_FALLBACK` 또는 `DEGRADED_LOCAL_ONLY` ### 확인 diff --git a/docs/reviews/adapters/01-network-and-state.md b/docs/reviews/adapters/01-network-and-state.md index 7a4046ef..1938c688 100644 --- a/docs/reviews/adapters/01-network-and-state.md +++ b/docs/reviews/adapters/01-network-and-state.md @@ -16,7 +16,7 @@ No Critical issue was found. Five High findings are implementation blockers or n 4. N-04: telemetry dispose only removes pagehide; queued callbacks, future emit calls, and in-flight delivery survive runtime teardown. 5. N-05: the conditional-validator key codec is delimiter-ambiguous and lets two valid bindings overwrite each other. It is not composed into HTTP yet, so this is a rollout blocker rather than a current request-path incident. -The current reference feature uses V3. The older createHttpClient path remains exported and is still the documented rollback/compatibility seam, so its replay and cancellation defects cannot be dismissed as dead code. +The current reference feature uses V3. The older createHttpClient path remains exported and is still the documented rollback/compatibility seam, so its replay and cancellation defects cannot be dismissed as dead code. (2026-09-24, Q-6.3-11: the comments no longer call it a rollback seam; V2 and V3 use different wire shapes, so a rollback also needs a V2-envelope server.) ## 2. Method, severity, and confidence @@ -60,17 +60,19 @@ All 24 files below were read in full. | src/adapters/diagnostics/bounded-diagnostics.ts | Bounded in-memory diagnostics projection/sink and safe pre-mount boot evidence | DiagnosticsPort; contracts/diagnostics.ts and telemetry.ts; bootstrap | Preserve fail-isolated projection and cloning. Harden non-finite capacity. V3 producer fix belongs primarily in bootstrap. | | src/adapters/http/bounded-body-reader.ts | Declared-length and streamed byte ceilings, stream cancellation/release isolation, forbidden-body probing, strict UTF-8/JSON decode | V3 executor; bounded-body-reader tests | Keep as the single bounded response primitive. It already contains the cleanup behavior missing from bounded-json.ts. | | src/adapters/http/bounded-json.ts | Legacy response stream reader and JSON decoder | legacy client.ts | Replace internals with bounded-body-reader delegation, then remove with V2 retirement. Current cancel/release failures can reject. | -| src/adapters/http/client.ts | Legacy/V2 operation lookup, profiles, auth recovery, retries, total deadline, response validation/mapping, diagnostics and telemetry | legacy contracts and ports; runtime-adapters createRuntimeHttpClient | Compatibility-only but exported. Fix empty keyed replay, cooperative auth cancellation, and common body-reader use before relying on it for rollback. Deprecate after callers are migrated. | +| src/adapters/http/client.ts | Legacy/V2 operation lookup, profiles, auth recovery, retries, total deadline, response validation/mapping, diagnostics and telemetry | legacy contracts and ports; runtime-adapters createRuntimeHttpClient | Compatibility-only but exported. Fix empty keyed replay, cooperative auth cancellation, and common body-reader use before relying on it for rollback. Not a drop-in rollback for V3: V2 validates the `{success,data,meta}` envelope and V3 the bare DTO, so a rollback needs the four slots and a V2-envelope server (Q-6.3-11). 401 recovery is a single replay outside the retry budget. Deprecate after callers are migrated. | | src/adapters/http/http-contract-bridge.ts | V3 request projection, URL/body bounds, credential patch type, final request invariant | external-contract-runtime.ts; V3 executor | Preserve descriptor-owned request projection. Change credential authority: patch cannot own credentials or transport headers; final invariant must compare exact resolved profile. | | src/adapters/http/http-effect-certainty.ts | Converts physical-attempt state and problem descriptors into mutation certainty/UI projection | V3 executor; contracts | Preserve explicit certainty vocabulary. Add a monotonic logical-execution certainty join used across retries. | | src/adapters/http/http-execution-v3.ts | Descriptor-driven V3 lifetime: validation, projection, credentials, deadline, retry, fetch, response admission, effect verdict and observation | external contracts, scope, mutation intent, bridge, bounded reader, certainty, retry policy | Main correction site for N-01, N-02, N-03 and cooperative cancellation. Keep one retry authority and closed result union. | | src/adapters/http/request-builder.ts | Legacy path/query construction and origin/base-prefix checks | legacy client; ApiOperation | Keep while V2 remains. Do not reuse it to weaken V3 descriptor projection. | | src/adapters/http/resource-mapper.ts | Thin legacy operation-payload mapper delegation | boundary-mapper; legacy client | No standalone defect. Remove only with V2, not as part of the correctness patch. | -| src/adapters/http/retry-policy.ts | Legacy retry decision/backoff plus parseRetryAfter reused by V3 | legacy client and V3 executor | Keep deterministic parse/backoff seam. V2 must additionally prove a valid key before keyed replay. | +| src/adapters/http/retry-policy.ts | Legacy retry decision/backoff plus parseRetryAfter reused by V3; parsing delegates to kernel platform/retry-after.ts (Q-6.4-8) | legacy client and V3 executor; platform/retry-after.ts | Keep deterministic parse/backoff seam. V2 must additionally prove a valid key before keyed replay. | | src/adapters/http/platform-error-mapping.ts | Maps feature-less V3 transport outcomes (cancel, timeout, network, response-invalid) to the platform AppError envelope; feature-owned outcomes return null | http-execution-v3.ts outcomes; platform/errors; feature HTTP binding | Keep. Registered 2026-09-24 (added in 6f6c48e without a ledger row). | | src/adapters/http/schema-registry.ts | Legacy Zod envelope/request/payload validation and clone | legacy client/tests | No standalone defect. Remains V2-only and should not be merged with installed external validators. | | src/adapters/platform/browser-lifecycle.ts | Single owner of visibility/network/focus/page/beforeunload listeners and lifecycle snapshots | optional-runtime-host.ts | Preserve centralized listener ownership and idempotent dispose. Clarify or redesign dirty-source attachment semantics; selection item O-02. | | src/adapters/platform/browser-mutation-intent-factory.ts | Secure intent/idempotency UUIDs plus monotonic creation time, normalized by defineMutationIntent | MutationIntentFactory port; bootstrap | Keep. Share one idempotency-key validator so external inputs and generated values have identical bounds. | +| src/adapters/platform/json-member-scanner.ts | Non-recursive duplicate-member and structure-budget scan before `JSON.parse`; moved from realtime in 2nd round (Q-6.4-8) | realtime event codec and WS protocol; web-push hint codec | Keep. Single scanner; web-push now checks every depth, not only top-level keys. | +| src/adapters/platform/retry-after.ts | Strict Retry-After parser: delta-seconds or IMF-fixdate, no guessed delays (Q-6.4-8) | realtime reconnect policy / SSE; http retry-policy.ts | Keep. Rejects blank, decimal and exponent values the old http copy accepted. | | src/adapters/platform/system-clock.ts | Wall clock and abortable sleep with listener/timer cleanup | ClockPort; legacy HTTP | Keep. Existing unit test covers abort cleanup behavior. | | src/adapters/query-cache/conditional-validator-store.ts | In-memory ETag CAS sidecar keyed by scope, definition, identity, representation and cache revision | bootstrap scope reset; future conditional HTTP/query join | Fix tuple codec before composition. Preserve validator grammar, generation/revision checks and bounded capacity. | | src/adapters/query-cache/cursor-pagination-runtime.ts | Bounded cursor chain, page/snapshot/loop/item/byte validation | cursor pagination contract; currently available but not composed | Add post-await abort admission or an abort race. Current pre-await-only check can admit a late page. | @@ -79,6 +81,7 @@ All 24 files below were read in full. | src/adapters/query-cache/tanstack-query-cache.ts | Creates QueryClient defaults and QueryCachePort read/write/invalidate adapter with diagnostics | TanStack Query, QueryCachePort, errors/diagnostics | Keep retry disabled and clone-on-write. Clone-on-read is an optional port-semantics decision, not a confirmed production defect. | | src/adapters/telemetry/best-effort-telemetry.ts | Allowlisted bounded oldest-drop telemetry queue, scheduled/pagehide flush, sink isolation and evidence | TelemetryPort, telemetry/diagnostic contracts, bootstrap | Add terminal lifecycle state, joined flush promise and in-flight abort; ensure runtime composition disposes it. | | src/adapters/telemetry/feature-telemetry.ts | Feature TelemetryPort adapter over the platform telemetry pipeline; fetch transport to the collector endpoint | platform/telemetry pipeline; TelemetryPort; bootstrap | Keep. Registered 2026-09-24 (added in 6f6c48e without a ledger row); shares the collector with best-effort-telemetry (review 6.9-4). | +| src/adapters/telemetry/telemetry-collector.ts | The one collector transport behind both telemetry ports: shared send-rate window, `credentials: "omit"`, `cache: "no-store"`, per-request deadline through the kernel abort primitive, one `pagehide` fan-out | platform/telemetry send rate; adapters/platform abort and capacity kernel; bootstrap | Keep. Added 2026-09-24 for review 6.9-4 / 6.3-10: a hung collector no longer stalls later flushes, and the two ports no longer send 20+20 per minute. | ## 4. Traced boundary inventory diff --git a/docs/reviews/adapters/02-realtime-and-browser-rpc.md b/docs/reviews/adapters/02-realtime-and-browser-rpc.md index e5659056..43d43e32 100644 --- a/docs/reviews/adapters/02-realtime-and-browser-rpc.md +++ b/docs/reviews/adapters/02-realtime-and-browser-rpc.md @@ -6,9 +6,9 @@ - 방식: 코드 리뷰만 수행했다. 이 문서 외 구현 파일은 수정하지 않았다. - 결론: **Critical 0, High 4, Medium 3**이다. R-01~R-06은 코드상 확정된 lifecycle/immutability/resource 문제이고, R-07은 문서에도 미완료라고 명시된 production promotion blocker다. 두 runtime 모두 현재 `AVAILABLE_NOT_COMPOSED`이므로 production traffic 사고로 과장하지 않는다. -## 1. 21/21 파일 inventory와 책임 +## 1. 20/20 파일 inventory와 책임 -아래 경로는 모두 저장소 루트 기준 full path이며, 범위의 구현 파일 21개를 모두 읽었다. +아래 경로는 모두 저장소 루트 기준 full path이며, 범위의 구현 파일 21개를 모두 읽었다. 2차 라운드(Q-6.4-8)에서 `json-member-scanner.ts`는 kernel `src/adapters/platform/`로 옮겨 [Network/state](./01-network-and-state.md) 표에서 다룬다. | # | full path | 책임 | 주요 의존성 / downstream | 판정 | |---:|---|---|---|---| @@ -16,23 +16,22 @@ | 2 | `src/adapters/browser-rpc/index.ts` | Browser RPC public adapter export surface | runtime, transport, unavailable adapter | 새 lease/install type export 필요 | | 3 | `src/adapters/browser-rpc/transport.ts` | provider-neutral unary/stream transport result와 runtime identity 계약 | `src/contracts/browser-rpc.ts` | R-01, R-07 | | 4 | `src/adapters/browser-rpc/unavailable-browser-rpc-transport.ts` | 선택되지 않은 runtime의 명시적 fail-closed Null Object | `transport.ts` | 유지; 새 stream lease shape만 맞춤 | -| 5 | `src/adapters/realtime/event-codec.ts` | raw JSON byte/shape/registry/schema 검증, immutable DTO와 semantic fingerprint 생성 | realtime contracts, schema registry, JSON scanner, result codec | 유지 | +| 5 | `src/adapters/realtime/event-codec.ts` | raw JSON byte/shape/registry/schema 검증, immutable DTO와 semantic fingerprint 생성 | realtime contracts, schema registry, kernel JSON scanner, result codec | 유지 | | 6 | `src/adapters/realtime/event-consumer.ts` | SSE/WS cursor 규칙을 codec 결과와 결합하고 common stream coordinator outcome으로 투영 | realtime ports/contracts, event codec, stream coordinator | 유지 | | 7 | `src/adapters/realtime/index.ts` | common realtime adapter public export surface | codec, consumer, reconnect, handoff, stream, sub-index | R-02/R-03 lifecycle type export 필요 | -| 8 | `src/adapters/realtime/json-member-scanner.ts` | `JSON.parse` 전 duplicate member와 structure budget을 비재귀적으로 검사 | 독립 utility | 유지 | -| 9 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | LIVE/POLL 단일 effect writer, generation fence, quiescence/checkpoint, probe buffer와 전환 | `ClockPort`, realtime result/ports | R-03 | -| 10 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | visible/online finite lease, single-flight poll, retry hint, response/apply deadline, non-cooperative task drain | bounded polling policy, `ClockPort`, realtime result | 유지 | -| 11 | `src/adapters/realtime/polling/index.ts` | polling public exports | bounded poll coordinator | 유지 | -| 12 | `src/adapters/realtime/reconnect-coordinator.ts` | 단일 reconnect owner, online gate, retry budget, session close authority, exact recovery proof, post-abort DRAINING | reconnect policy, `ClockPort`, realtime ports/result | 유지 | -| 13 | `src/adapters/realtime/reconnect-policy.ts` | immutable reconnect policy, full jitter, elapsed budget, Retry-After 계산/검증 | 독립 policy | 유지 | -| 14 | `src/adapters/realtime/result.ts` | hostile/mutable collaborator result를 exact own-data snapshot으로 canonicalize | realtime ports/contracts | 유지; R-04의 기준 패턴 | -| 15 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | fixed same-origin fetch-stream SSE, response/media/open gate, read/event deadline, cursor rule, bounded reader cancel | `ClockPort`, event authority/result, parser, reconnect policy | 유지; R-02 common drain과 함께 검증 | -| 16 | `src/adapters/realtime/sse/index.ts` | SSE public exports | fetch connection, parser | 유지 | -| 17 | `src/adapters/realtime/sse/sse-parser.ts` | strict incremental UTF-8 SSE parser, BOM/line ending/id/retry/event buffer ceiling | realtime contracts/result | 유지 | -| 18 | `src/adapters/realtime/stream-coordinator.ts` | per-stream sequential effect, dedupe/order, recovery, checkpoint/barrier, scope generation fence | event authority port, realtime contracts, mapper registry, codec/result | R-02 | -| 19 | `src/adapters/realtime/websocket/index.ts` | WebSocket connection/protocol public exports | connection, protocol | 유지 | -| 20 | `src/adapters/realtime/websocket/websocket-connection.ts` | 한 physical WS의 handshake/subscription/tombstone/FIFO/heartbeat/apply gate/recovery close | `ClockPort`, realtime contracts/result, WS protocol | 유지; R-02 upstream timeout과 함께 검증 | -| 21 | `src/adapters/realtime/websocket/websocket-protocol.ts` | exact closed JSON frame decode/encode, duplicate key/structure/sequence/frame byte 검증 | realtime contracts, JSON scanner | R-05 | +| 8 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | LIVE/POLL 단일 effect writer, generation fence, quiescence/checkpoint, probe buffer와 전환 | `ClockPort`, realtime result/ports | R-03 | +| 9 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | visible/online finite lease, single-flight poll, retry hint, response/apply deadline, non-cooperative task drain | bounded polling policy, `ClockPort`, realtime result | 유지 | +| 10 | `src/adapters/realtime/polling/index.ts` | polling public exports | bounded poll coordinator | 유지 | +| 11 | `src/adapters/realtime/reconnect-coordinator.ts` | 단일 reconnect owner, online gate, retry budget, session close authority, exact recovery proof, post-abort DRAINING | reconnect policy, `ClockPort`, realtime ports/result | 유지 | +| 12 | `src/adapters/realtime/reconnect-policy.ts` | immutable reconnect policy, full jitter, elapsed budget; Retry-After 파서는 kernel `platform/retry-after.ts`를 re-export | kernel retry-after | 유지 | +| 13 | `src/adapters/realtime/result.ts` | hostile/mutable collaborator result를 exact own-data snapshot으로 canonicalize | realtime ports/contracts | 유지; R-04의 기준 패턴 | +| 14 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | fixed same-origin fetch-stream SSE, response/media/open gate, read/event deadline, cursor rule, bounded reader cancel | `ClockPort`, event authority/result, parser, reconnect policy | 유지; R-02 common drain과 함께 검증 | +| 15 | `src/adapters/realtime/sse/index.ts` | SSE public exports | fetch connection, parser | 유지 | +| 16 | `src/adapters/realtime/sse/sse-parser.ts` | strict incremental UTF-8 SSE parser, BOM/line ending/id/retry/event buffer ceiling | realtime contracts/result | 유지 | +| 17 | `src/adapters/realtime/stream-coordinator.ts` | per-stream sequential effect, dedupe/order, recovery, checkpoint/barrier, scope generation fence | event authority port, realtime contracts, mapper registry, codec/result | R-02 | +| 18 | `src/adapters/realtime/websocket/index.ts` | WebSocket connection/protocol public exports | connection, protocol | 유지 | +| 19 | `src/adapters/realtime/websocket/websocket-connection.ts` | 한 physical WS의 handshake/subscription/tombstone/FIFO/heartbeat/apply gate/recovery close | `ClockPort`, realtime contracts/result, WS protocol | 유지; R-02 upstream timeout과 함께 검증 | +| 20 | `src/adapters/realtime/websocket/websocket-protocol.ts` | exact closed JSON frame decode/encode, duplicate key/structure/sequence/frame byte 검증 | realtime contracts, kernel JSON scanner | R-05 | ## 2. 추적한 contracts, ports, bootstrap, tests, docs diff --git a/docs/reviews/adapters/03-storage-and-browser-files.md b/docs/reviews/adapters/03-storage-and-browser-files.md index b9dea4f1..93fb3d38 100644 --- a/docs/reviews/adapters/03-storage-and-browser-files.md +++ b/docs/reviews/adapters/03-storage-and-browser-files.md @@ -43,6 +43,7 @@ | `src/adapters/browser-files/browser-file-vault.ts` | transient native File/handle 보관, opaque ref, inspection receipt, bounded range/source | file port/shared/result/policy registry. File이 application 경계를 넘지 않고 receipt가 exact file/profile에 묶이는 설계가 좋다. | | `src/adapters/browser-files/create-browser-file-runtime.ts` | vault/picker/preview/download를 선택적으로 조립하고 일괄 dispose | 위 adapters 및 application contracts. optional capability를 제품 선택 없이 bootstrap에 암묵 조립하지 않는 점을 유지. preview 조립 전 GAP-01 gate 필요. | | `src/adapters/browser-files/download-delivery-adapter.ts` | browser handoff, foreground save stream, bounded object URL download, integrity/progress/cancellation | file/authorized-download ports, policy registry, object URL lease, Result. STO-02와 STO-08; stream close truth/backpressure는 유지. | +| `src/adapters/browser-files/download-input-validation.ts` | download 요청 snapshot, policy/limit/activation 검증, presigned·browser-managed capability 검증, canonical handoff target 해석 | file/authorized-download ports, policy registry, `file-policy.ts`, Result. Q-6.2-11에서 adapter에서 그대로 옮겼다(동작 불변). | | `src/adapters/browser-files/file-observer.ts` | file-safe observation DTO를 공통 browser observation으로 변환 | shared port/result. raw filename/ref 비노출 유지. | | `src/adapters/browser-files/file-policy.ts` | policy input validation, MIME/extension/signature/hard byte caps, immutable resolved policy | file/shared contracts. closed allowlist 및 absolute ceiling을 유지. | | `src/adapters/browser-files/index.ts` | browser-file public exports | 위 모듈. native implementation detail export 확장을 피한다. | @@ -53,7 +54,9 @@ | 파일 | 책임 | 주요 의존성 / 리뷰 결과 | | --- | --- | --- | | `src/adapters/cache-storage/index.ts` | public cache policy/adapter barrel | optional public static cache만 export; private/range cache로 일반화하지 않는다. | +| `src/adapters/cache-storage/public-cache-codec.ts` | manifest 정규화·canonical digest 입력, marker/active pointer 검증, bounded control JSON 읽기, owned cache 이름, 검증 실패 → Result 매핑 | cache ports/result/policy. Q-6.2-11에서 adapter에서 그대로 옮겼다(동작 불변). | | `src/adapters/cache-storage/public-cache-policy.ts` | same-origin/public-only release 정책, URL/header/query/size/retention hard limits | cache ports/shared. STO-03 policy cross-field invariant 누락. 기본 policy에는 `vary`가 있어 기본-path 테스트는 통과한다. | +| `src/adapters/cache-storage/public-cache-response-validation.ts` | network/cached response 수용 검증: status, cache directive, Content-Type, Vary, bounded body, digest | `public-cache-codec.ts`, policy, Result. Q-6.2-11에서 adapter에서 그대로 옮겼다(동작 불변). | | `src/adapters/cache-storage/public-response-cache-adapter.ts` | manifest canonicalization/digest, anonymous fetch, bounded body 검증, candidate marker-last staging, explicit activation, exact lookup/reverify, owned cleanup/inspect | cache ports/result/policy, CacheStorage/fetch/Crypto/Web Lock snapshot. STO-03~05 및 GAP-02. private/auth/opaque/206 거절과 current+previous 보존은 유지. | ### 1.4 `storage` root / IndexedDB @@ -67,6 +70,7 @@ | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | opaque dataset scope/physical DB identity 및 frozen policy binding | indexeddb/shared ports. account/business ID를 physical name에 쓰지 않는 양방향 binding 유지. | | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | post-open codec migration 및 idempotency receipt prune, keyset checkpoint, budget/revision fencing | IndexedDB port/types/failure/governance. async transform outside tx, row+sidecar+budget+checkpoint atomic commit은 좋다. STO-06 및 temporal drain lease 개선 후보. | | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | additive-only contiguous DDL planner/validator | indexeddb types. destructive DDL 거절 유지. | +| `src/adapters/storage/indexeddb/indexeddb-records.ts` | runtime·maintenance·dataset binding이 함께 쓰는 저장 행 타입, 검증기, record 바이트 측정, `countBucket`/`failureOf` | IndexedDB port/shared/types. Q-6.5-7: 복사본 3벌을 하나로 합쳤다. 실패 코드는 호출부가 정한다(runtime `INVALID_INPUT`, maintenance `MIGRATION_FAILED`). budget의 `hardBudgetBytes` 상한은 binding 검증에서만 본다. | | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | generic repository open/read/query/CAS/delete, idempotency, retention, lifecycle purge, connection lifecycle | indexeddb ports/types/governance/failure/migrations. transaction `complete` truth, versionchange close, shared open/abort isolation, exact budgets 유지. lifecycle proof는 현재 문서 계약(형식 검증 후 폐기)과 일치하므로 결함으로 분류하지 않았다. | | `src/adapters/storage/indexeddb/indexeddb-types.ts` | adapter-local codec/query/schema/dependency contracts | application indexeddb/shared ports. `isOldWriterDrainConfirmed()` boolean은 provider가 전체 window를 보장한다는 문서 전제; lease형으로 강화 권고. | diff --git a/docs/reviews/adapters/04-browser-transfer.md b/docs/reviews/adapters/04-browser-transfer.md index 262f0e5c..6ac58ca4 100644 --- a/docs/reviews/adapters/04-browser-transfer.md +++ b/docs/reviews/adapters/04-browser-transfer.md @@ -35,6 +35,7 @@ | --- | --- | --- | --- | | `browser-transfer/index.ts` | 하위 capability export | KEEP | public export 증가는 각 capability 계획에서만 수행 | | `presigned/index.ts` | presigned public surface | KEEP | `BT-PRE-04`에서 vault issuer 노출만 축소 검토 | +| `presigned/http-common.ts` | executor·provider 공용 HTTP 메커니즘(abort scope, status 표, Content-Length 파싱, body 취소) | KEEP | Q-6.1-9. 두 벌이던 사본을 합쳤다. status 표는 여기 한 벌만 둔다 | | `presigned/incremental-sha256.ts` | streaming SHA-256 | KEEP | WebCrypto `digest()`로 바꾸면 전체 buffering이 되므로 교체 금지 | | `presigned/presigned-capability-http-provider.ts` | BFF capability 발급, strict decode | CONTRACT_GAP | `BT-PRE-02`, `BT-PRE-03`, `BT-X-01` | | `presigned/presigned-capability-vault.ts` | identity capability 보관/폐기 | REFACTOR | `BT-PRE-04` | @@ -45,8 +46,10 @@ | `resumable-upload/index.ts` | resumable public surface | KEEP | facade 호환 유지 | | `resumable-upload/indexeddb-checkpoint-store.ts` | scope-bound CAS store/admin | VERIFIED_DEFECT | `BT-UP-03` | | `resumable-upload/presigned-upload-part-executor.ts` | multipart와 presigned bridge | VERIFIED_DEFECT | `BT-UP-04` | -| `resumable-upload/resumable-upload-runtime.ts` | session state/retry/part scheduling/commit | REFACTOR | `BT-UP-05`, `BT-UP-06` | +| `resumable-upload/resumable-upload-runtime.ts` | session state/retry/part scheduling/commit | REFACTOR | `BT-UP-05`, `BT-UP-06`. Q-6.1-10에서 검증·snapshot 래퍼를 분리 | +| `resumable-upload/runtime-dependencies.ts` | runtime 주입 의존성 검증과 메서드 snapshot, clock/random guard | KEEP | Q-6.1-10. runtime 파일에서 분리, 동작 불변 | | `resumable-upload/runtime-policy.ts` | hard bound snapshot | KEEP | 값 변경은 contract migration으로만 수행 | +| `resumable-upload/upload-response-validation.ts` | session/status/part capability/receipt strict decoder | KEEP | Q-6.1-10. runtime 파일에서 분리, 동작 불변 | | `resumable-upload/upload-byte-source.ts` | stream/range source snapshot과 hashing | KEEP/REFACTOR | runtime에서 source preparation Strategy로 주입 | | `resumable-upload/upload-cancellation-channel.ts` | best-effort cross-context cancel hint | KEEP | backend/CAS가 authority라는 주석과 동작 유지 | | `resumable-upload/upload-mutation-lock.ts` | Web Lock exclusive mutation | PLANNED_GAP | `BT-UP-07` | diff --git a/docs/reviews/adapters/05-service-worker-and-web-push.md b/docs/reviews/adapters/05-service-worker-and-web-push.md index a2e98fdf..66fff55b 100644 --- a/docs/reviews/adapters/05-service-worker-and-web-push.md +++ b/docs/reviews/adapters/05-service-worker-and-web-push.md @@ -30,6 +30,7 @@ Web Push는 현재 `AVAILABLE_NOT_COMPOSED`이고 제품 선택도 `NOT_SELECTED | `service-worker-protocol.ts` | page-worker strict message codec/nonce | CONTRACT_GAP | `SW-06`, `SW-10` | | `service-worker-removal.ts` | exact registration/cache ownership cleanup | VERIFIED_DEFECT | `SW-03` | | `service-worker-static-assets.ts` | static manifest/install/cache policy | KEEP/REFACTOR | `SW-01`, `SW-05`, `SW-09` | +| `web-push/codec-primitives.ts` | 공유 검증 primitive(base64url decode, opaque id, authority, exact record) | KEEP | Q-6.6-12에서 4개 파일의 복사본을 합침. 복사본이 다르던 곳은 더 엄격한 쪽을 유지 | | `web-push/index.ts` | public exports | KEEP | product selection 전 surface 확대 금지 | | `web-push/notification-registry.ts` | closed copy/route registry | KEEP | arbitrary copy/URL 허용 금지 | | `web-push/push-association-fence-store.ts` | durable authority state machine | VERIFIED_DEFECT | `WP-01`, `WP-02` | diff --git a/docs/reviews/adapters/INVENTORY.md b/docs/reviews/adapters/INVENTORY.md index 87666385..d4829486 100644 --- a/docs/reviews/adapters/INVENTORY.md +++ b/docs/reviews/adapters/INVENTORY.md @@ -18,132 +18,142 @@ | 8 | `src/adapters/browser-files/browser-file-vault.ts` | [Storage/files](./03-storage-and-browser-files.md) | | 9 | `src/adapters/browser-files/create-browser-file-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | | 10 | `src/adapters/browser-files/download-delivery-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 11 | `src/adapters/browser-files/file-observer.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 12 | `src/adapters/browser-files/file-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 13 | `src/adapters/browser-files/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 14 | `src/adapters/browser-files/object-url-lease.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 15 | `src/adapters/browser-rpc/browser-rpc-runtime.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 16 | `src/adapters/browser-rpc/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 17 | `src/adapters/browser-rpc/transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 18 | `src/adapters/browser-rpc/unavailable-browser-rpc-transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 19 | `src/adapters/browser-transfer/image-cdn/README.md` | [Browser transfer](./04-browser-transfer.md) | -| 20 | `src/adapters/browser-transfer/image-cdn/browser-image-probe.ts` | [Browser transfer](./04-browser-transfer.md) | -| 21 | `src/adapters/browser-transfer/image-cdn/image-cdn-policy.ts` | [Browser transfer](./04-browser-transfer.md) | -| 22 | `src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts` | [Browser transfer](./04-browser-transfer.md) | -| 23 | `src/adapters/browser-transfer/image-cdn/image-header-metadata.ts` | [Browser transfer](./04-browser-transfer.md) | -| 24 | `src/adapters/browser-transfer/image-cdn/index.ts` | [Browser transfer](./04-browser-transfer.md) | -| 25 | `src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts` | [Browser transfer](./04-browser-transfer.md) | -| 26 | `src/adapters/browser-transfer/index.ts` | [Browser transfer](./04-browser-transfer.md) | -| 27 | `src/adapters/browser-transfer/presigned/incremental-sha256.ts` | [Browser transfer](./04-browser-transfer.md) | -| 28 | `src/adapters/browser-transfer/presigned/index.ts` | [Browser transfer](./04-browser-transfer.md) | -| 29 | `src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts` | [Browser transfer](./04-browser-transfer.md) | -| 30 | `src/adapters/browser-transfer/presigned/presigned-capability-vault.ts` | [Browser transfer](./04-browser-transfer.md) | -| 31 | `src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts` | [Browser transfer](./04-browser-transfer.md) | -| 32 | `src/adapters/browser-transfer/resumable-upload/checkpoint-schema.ts` | [Browser transfer](./04-browser-transfer.md) | -| 33 | `src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts` | [Browser transfer](./04-browser-transfer.md) | -| 34 | `src/adapters/browser-transfer/resumable-upload/http-control-plane-adapter.ts` | [Browser transfer](./04-browser-transfer.md) | -| 35 | `src/adapters/browser-transfer/resumable-upload/index.ts` | [Browser transfer](./04-browser-transfer.md) | -| 36 | `src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts` | [Browser transfer](./04-browser-transfer.md) | -| 37 | `src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts` | [Browser transfer](./04-browser-transfer.md) | -| 38 | `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts` | [Browser transfer](./04-browser-transfer.md) | -| 39 | `src/adapters/browser-transfer/resumable-upload/runtime-policy.ts` | [Browser transfer](./04-browser-transfer.md) | -| 40 | `src/adapters/browser-transfer/resumable-upload/upload-byte-source.ts` | [Browser transfer](./04-browser-transfer.md) | -| 41 | `src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts` | [Browser transfer](./04-browser-transfer.md) | -| 42 | `src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts` | [Browser transfer](./04-browser-transfer.md) | -| 43 | `src/adapters/cache-storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 44 | `src/adapters/cache-storage/public-cache-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 45 | `src/adapters/cache-storage/public-response-cache-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 46 | `src/adapters/cross-context-invalidation/browser-cross-context-host.ts` | [Network/state](./01-network-and-state.md) | -| 47 | `src/adapters/cross-context-invalidation/browser-cross-context-invalidation.ts` | [Network/state](./01-network-and-state.md) | -| 48 | `src/adapters/cross-context-invalidation/index.ts` | [Network/state](./01-network-and-state.md) | -| 49 | `src/adapters/diagnostics/bounded-diagnostics.ts` | [Network/state](./01-network-and-state.md) | -| 50 | `src/adapters/diagnostics/index.ts` | [Network/state](./01-network-and-state.md) | -| 51 | `src/adapters/http/bounded-body-reader.ts` | [Network/state](./01-network-and-state.md) | -| 52 | `src/adapters/http/bounded-json.ts` | [Network/state](./01-network-and-state.md) | -| 53 | `src/adapters/http/client.ts` | [Network/state](./01-network-and-state.md) | -| 54 | `src/adapters/http/feature-http-binding.ts` | [Network/state](./01-network-and-state.md) | -| 55 | `src/adapters/http/http-contract-bridge.ts` | [Network/state](./01-network-and-state.md) | -| 56 | `src/adapters/http/http-effect-certainty.ts` | [Network/state](./01-network-and-state.md) | -| 57 | `src/adapters/http/http-execution-v3.ts` | [Network/state](./01-network-and-state.md) | -| 58 | `src/adapters/http/http-retry-lifecycle.ts` | [Network/state](./01-network-and-state.md) | -| 59 | `src/adapters/http/index.ts` | [Network/state](./01-network-and-state.md) | -| 60 | `src/adapters/http/platform-error-mapping.ts` | [Network/state](./01-network-and-state.md) | -| 61 | `src/adapters/http/request-builder.ts` | [Network/state](./01-network-and-state.md) | -| 62 | `src/adapters/http/resource-mapper.ts` | [Network/state](./01-network-and-state.md) | -| 63 | `src/adapters/http/retry-policy.ts` | [Network/state](./01-network-and-state.md) | -| 64 | `src/adapters/http/schema-registry.ts` | [Network/state](./01-network-and-state.md) | -| 65 | `src/adapters/platform/abortable-operation.ts` | [Network/state](./01-network-and-state.md) | -| 66 | `src/adapters/platform/bounded-capacity.ts` | [Network/state](./01-network-and-state.md) | -| 67 | `src/adapters/platform/browser-lifecycle.ts` | [Network/state](./01-network-and-state.md) | -| 68 | `src/adapters/platform/browser-mutation-intent-factory.ts` | [Network/state](./01-network-and-state.md) | -| 69 | `src/adapters/platform/index.ts` | [Network/state](./01-network-and-state.md) | -| 70 | `src/adapters/platform/indexeddb-connection.ts` | [Network/state](./01-network-and-state.md) | -| 71 | `src/adapters/platform/indexeddb-transaction.ts` | [Network/state](./01-network-and-state.md) | -| 72 | `src/adapters/platform/system-clock.ts` | [Network/state](./01-network-and-state.md) | -| 73 | `src/adapters/query-cache/conditional-validator-store.ts` | [Network/state](./01-network-and-state.md) | -| 74 | `src/adapters/query-cache/cursor-pagination-contract.ts` | [Network/state](./01-network-and-state.md) | -| 75 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | [Network/state](./01-network-and-state.md) | -| 76 | `src/adapters/query-cache/index.ts` | [Network/state](./01-network-and-state.md) | -| 77 | `src/adapters/query-cache/server-state-scope-runtime.ts` | [Network/state](./01-network-and-state.md) | -| 78 | `src/adapters/query-cache/tanstack-cache-coordinator.ts` | [Network/state](./01-network-and-state.md) | -| 79 | `src/adapters/query-cache/tanstack-query-cache.ts` | [Network/state](./01-network-and-state.md) | -| 80 | `src/adapters/realtime/event-codec.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 81 | `src/adapters/realtime/event-consumer.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 82 | `src/adapters/realtime/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 83 | `src/adapters/realtime/json-member-scanner.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 84 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 85 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 86 | `src/adapters/realtime/polling/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 87 | `src/adapters/realtime/reconnect-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 88 | `src/adapters/realtime/reconnect-policy.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 89 | `src/adapters/realtime/result.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 90 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 91 | `src/adapters/realtime/sse/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 92 | `src/adapters/realtime/sse/sse-parser.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 93 | `src/adapters/realtime/stream-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 94 | `src/adapters/realtime/websocket/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 95 | `src/adapters/realtime/websocket/websocket-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 96 | `src/adapters/realtime/websocket/websocket-protocol.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 97 | `src/adapters/service-worker/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 98 | `src/adapters/service-worker/service-worker-entry.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 99 | `src/adapters/service-worker/service-worker-lifecycle.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 100 | `src/adapters/service-worker/service-worker-page-controller.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 101 | `src/adapters/service-worker/service-worker-protocol.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 102 | `src/adapters/service-worker/service-worker-removal.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 103 | `src/adapters/service-worker/service-worker-static-assets.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 104 | `src/adapters/storage/browser-storage-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 105 | `src/adapters/storage/browser-storage-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 106 | `src/adapters/storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 107 | `src/adapters/storage/indexeddb/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 108 | `src/adapters/storage/indexeddb/indexeddb-failure.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 109 | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 110 | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 111 | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 112 | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 113 | `src/adapters/storage/indexeddb/indexeddb-types.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 114 | `src/adapters/storage/opfs/browser-opfs-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 115 | `src/adapters/storage/opfs/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 116 | `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 117 | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 118 | `src/adapters/storage/opfs/opfs-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 119 | `src/adapters/storage/opfs/opfs-prepared-object.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 120 | `src/adapters/storage/opfs/opfs-worker-client.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 121 | `src/adapters/storage/opfs/opfs-worker-protocol.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 122 | `src/adapters/storage/opfs/opfs-worker-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 123 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) | -| 124 | `src/adapters/telemetry/feature-telemetry.ts` | [Network/state](./01-network-and-state.md) | -| 125 | `src/adapters/telemetry/index.ts` | [Network/state](./01-network-and-state.md) | -| 126 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 127 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 128 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 129 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 130 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 131 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 132 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 133 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 134 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 135 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 136 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 11 | `src/adapters/browser-files/download-input-validation.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 12 | `src/adapters/browser-files/file-observer.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 13 | `src/adapters/browser-files/file-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 14 | `src/adapters/browser-files/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 15 | `src/adapters/browser-files/object-url-lease.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 16 | `src/adapters/browser-rpc/browser-rpc-runtime.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 17 | `src/adapters/browser-rpc/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 18 | `src/adapters/browser-rpc/transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 19 | `src/adapters/browser-rpc/unavailable-browser-rpc-transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 20 | `src/adapters/browser-transfer/image-cdn/README.md` | [Browser transfer](./04-browser-transfer.md) | +| 21 | `src/adapters/browser-transfer/image-cdn/browser-image-probe.ts` | [Browser transfer](./04-browser-transfer.md) | +| 22 | `src/adapters/browser-transfer/image-cdn/image-cdn-policy.ts` | [Browser transfer](./04-browser-transfer.md) | +| 23 | `src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts` | [Browser transfer](./04-browser-transfer.md) | +| 24 | `src/adapters/browser-transfer/image-cdn/image-header-metadata.ts` | [Browser transfer](./04-browser-transfer.md) | +| 25 | `src/adapters/browser-transfer/image-cdn/index.ts` | [Browser transfer](./04-browser-transfer.md) | +| 26 | `src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts` | [Browser transfer](./04-browser-transfer.md) | +| 27 | `src/adapters/browser-transfer/index.ts` | [Browser transfer](./04-browser-transfer.md) | +| 28 | `src/adapters/browser-transfer/presigned/http-common.ts` | [Browser transfer](./04-browser-transfer.md) | +| 29 | `src/adapters/browser-transfer/presigned/incremental-sha256.ts` | [Browser transfer](./04-browser-transfer.md) | +| 30 | `src/adapters/browser-transfer/presigned/index.ts` | [Browser transfer](./04-browser-transfer.md) | +| 31 | `src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts` | [Browser transfer](./04-browser-transfer.md) | +| 32 | `src/adapters/browser-transfer/presigned/presigned-capability-vault.ts` | [Browser transfer](./04-browser-transfer.md) | +| 33 | `src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts` | [Browser transfer](./04-browser-transfer.md) | +| 34 | `src/adapters/browser-transfer/resumable-upload/checkpoint-schema.ts` | [Browser transfer](./04-browser-transfer.md) | +| 35 | `src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts` | [Browser transfer](./04-browser-transfer.md) | +| 36 | `src/adapters/browser-transfer/resumable-upload/http-control-plane-adapter.ts` | [Browser transfer](./04-browser-transfer.md) | +| 37 | `src/adapters/browser-transfer/resumable-upload/index.ts` | [Browser transfer](./04-browser-transfer.md) | +| 38 | `src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts` | [Browser transfer](./04-browser-transfer.md) | +| 39 | `src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts` | [Browser transfer](./04-browser-transfer.md) | +| 40 | `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts` | [Browser transfer](./04-browser-transfer.md) | +| 41 | `src/adapters/browser-transfer/resumable-upload/runtime-dependencies.ts` | [Browser transfer](./04-browser-transfer.md) | +| 42 | `src/adapters/browser-transfer/resumable-upload/runtime-policy.ts` | [Browser transfer](./04-browser-transfer.md) | +| 43 | `src/adapters/browser-transfer/resumable-upload/upload-byte-source.ts` | [Browser transfer](./04-browser-transfer.md) | +| 44 | `src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts` | [Browser transfer](./04-browser-transfer.md) | +| 45 | `src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts` | [Browser transfer](./04-browser-transfer.md) | +| 46 | `src/adapters/browser-transfer/resumable-upload/upload-response-validation.ts` | [Browser transfer](./04-browser-transfer.md) | +| 47 | `src/adapters/cache-storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 48 | `src/adapters/cache-storage/public-cache-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 49 | `src/adapters/cache-storage/public-cache-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 50 | `src/adapters/cache-storage/public-cache-response-validation.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 51 | `src/adapters/cache-storage/public-response-cache-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 52 | `src/adapters/cross-context-invalidation/browser-cross-context-host.ts` | [Network/state](./01-network-and-state.md) | +| 53 | `src/adapters/cross-context-invalidation/browser-cross-context-invalidation.ts` | [Network/state](./01-network-and-state.md) | +| 54 | `src/adapters/cross-context-invalidation/index.ts` | [Network/state](./01-network-and-state.md) | +| 55 | `src/adapters/diagnostics/bounded-diagnostics.ts` | [Network/state](./01-network-and-state.md) | +| 56 | `src/adapters/diagnostics/index.ts` | [Network/state](./01-network-and-state.md) | +| 57 | `src/adapters/http/bounded-body-reader.ts` | [Network/state](./01-network-and-state.md) | +| 58 | `src/adapters/http/bounded-json.ts` | [Network/state](./01-network-and-state.md) | +| 59 | `src/adapters/http/client.ts` | [Network/state](./01-network-and-state.md) | +| 60 | `src/adapters/http/feature-http-binding.ts` | [Network/state](./01-network-and-state.md) | +| 61 | `src/adapters/http/http-contract-bridge.ts` | [Network/state](./01-network-and-state.md) | +| 62 | `src/adapters/http/http-effect-certainty.ts` | [Network/state](./01-network-and-state.md) | +| 63 | `src/adapters/http/http-execution-v3.ts` | [Network/state](./01-network-and-state.md) | +| 64 | `src/adapters/http/http-retry-lifecycle.ts` | [Network/state](./01-network-and-state.md) | +| 65 | `src/adapters/http/index.ts` | [Network/state](./01-network-and-state.md) | +| 66 | `src/adapters/http/platform-error-mapping.ts` | [Network/state](./01-network-and-state.md) | +| 67 | `src/adapters/http/request-builder.ts` | [Network/state](./01-network-and-state.md) | +| 68 | `src/adapters/http/resource-mapper.ts` | [Network/state](./01-network-and-state.md) | +| 69 | `src/adapters/http/retry-policy.ts` | [Network/state](./01-network-and-state.md) | +| 70 | `src/adapters/http/schema-registry.ts` | [Network/state](./01-network-and-state.md) | +| 71 | `src/adapters/platform/abortable-operation.ts` | [Network/state](./01-network-and-state.md) | +| 72 | `src/adapters/platform/bounded-capacity.ts` | [Network/state](./01-network-and-state.md) | +| 73 | `src/adapters/platform/browser-lifecycle.ts` | [Network/state](./01-network-and-state.md) | +| 74 | `src/adapters/platform/browser-mutation-intent-factory.ts` | [Network/state](./01-network-and-state.md) | +| 75 | `src/adapters/platform/index.ts` | [Network/state](./01-network-and-state.md) | +| 76 | `src/adapters/platform/indexeddb-connection.ts` | [Network/state](./01-network-and-state.md) | +| 77 | `src/adapters/platform/indexeddb-transaction.ts` | [Network/state](./01-network-and-state.md) | +| 78 | `src/adapters/platform/json-member-scanner.ts` | [Network/state](./01-network-and-state.md) | +| 79 | `src/adapters/platform/retry-after.ts` | [Network/state](./01-network-and-state.md) | +| 80 | `src/adapters/platform/system-clock.ts` | [Network/state](./01-network-and-state.md) | +| 81 | `src/adapters/query-cache/conditional-validator-store.ts` | [Network/state](./01-network-and-state.md) | +| 82 | `src/adapters/query-cache/cursor-pagination-contract.ts` | [Network/state](./01-network-and-state.md) | +| 83 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | [Network/state](./01-network-and-state.md) | +| 84 | `src/adapters/query-cache/index.ts` | [Network/state](./01-network-and-state.md) | +| 85 | `src/adapters/query-cache/server-state-scope-runtime.ts` | [Network/state](./01-network-and-state.md) | +| 86 | `src/adapters/query-cache/tanstack-cache-coordinator.ts` | [Network/state](./01-network-and-state.md) | +| 87 | `src/adapters/query-cache/tanstack-query-cache.ts` | [Network/state](./01-network-and-state.md) | +| 88 | `src/adapters/realtime/event-codec.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 89 | `src/adapters/realtime/event-consumer.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 90 | `src/adapters/realtime/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 91 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 92 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 93 | `src/adapters/realtime/polling/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 94 | `src/adapters/realtime/reconnect-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 95 | `src/adapters/realtime/reconnect-policy.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 96 | `src/adapters/realtime/result.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 97 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 98 | `src/adapters/realtime/sse/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 99 | `src/adapters/realtime/sse/sse-parser.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 100 | `src/adapters/realtime/stream-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 101 | `src/adapters/realtime/websocket/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 102 | `src/adapters/realtime/websocket/websocket-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 103 | `src/adapters/realtime/websocket/websocket-protocol.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 104 | `src/adapters/service-worker/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 105 | `src/adapters/service-worker/service-worker-entry.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 106 | `src/adapters/service-worker/service-worker-lifecycle.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 107 | `src/adapters/service-worker/service-worker-page-controller.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 108 | `src/adapters/service-worker/service-worker-protocol.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 109 | `src/adapters/service-worker/service-worker-removal.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 110 | `src/adapters/service-worker/service-worker-static-assets.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 111 | `src/adapters/storage/browser-storage-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 112 | `src/adapters/storage/browser-storage-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 113 | `src/adapters/storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 114 | `src/adapters/storage/indexeddb/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 115 | `src/adapters/storage/indexeddb/indexeddb-failure.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 116 | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 117 | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 118 | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 119 | `src/adapters/storage/indexeddb/indexeddb-records.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 120 | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 121 | `src/adapters/storage/indexeddb/indexeddb-types.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 122 | `src/adapters/storage/opfs/browser-opfs-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 123 | `src/adapters/storage/opfs/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 124 | `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 125 | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 126 | `src/adapters/storage/opfs/opfs-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 127 | `src/adapters/storage/opfs/opfs-prepared-object.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 128 | `src/adapters/storage/opfs/opfs-worker-client.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 129 | `src/adapters/storage/opfs/opfs-worker-protocol.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 130 | `src/adapters/storage/opfs/opfs-worker-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 131 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) | +| 132 | `src/adapters/telemetry/feature-telemetry.ts` | [Network/state](./01-network-and-state.md) | +| 133 | `src/adapters/telemetry/index.ts` | [Network/state](./01-network-and-state.md) | +| 134 | `src/adapters/telemetry/telemetry-collector.ts` | [Network/state](./01-network-and-state.md) | +| 135 | `src/adapters/web-push/codec-primitives.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 136 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 137 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 138 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 139 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 140 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 141 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 142 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 143 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 144 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 145 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 146 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -합계: **136/136**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다. +합계: **146/146**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다. diff --git a/docs/styling/design-system-platform.md b/docs/styling/design-system-platform.md index d7f48f38..48f16cfd 100644 --- a/docs/styling/design-system-platform.md +++ b/docs/styling/design-system-platform.md @@ -57,7 +57,9 @@ RP-07 구현 이후 이 기반은 저장소 내부 디자인 시스템 플랫폼 3. 앱 셸, 예제와 reference feature는 public design-system barrel을 소비한다. 4. 문자 glyph는 semantic Lucide facade로 교체됐다. 5. token은 세 CSS 파일로 분리됐고 `theme.css`는 layout/component styling만 - 소유한다. + 소유한다. `theme.css`는 import 순서만 정하는 진입점이고, 실제 규칙은 + `styles/theme/` 아래 파일(base, shell, primitives, templates, pages, + responsive)에 같은 순서로 있다. 6. runtime gallery는 있지만 격리된 story, interaction story, 시각 회귀 기준선이 없다. 7. 사용자 문구가 한국어 literal로 고정되어 locale과 RTL 계약이 없다. diff --git a/index.html b/index.html index 047e363e..0ac9c9cc 100644 --- a/index.html +++ b/index.html @@ -7,7 +7,18 @@ Clean Architecture Frontend -
+
+ +
+ 불러오는 중 +
+
diff --git a/scripts/check-adapter-inventory.ts b/scripts/check-adapter-inventory.ts index c520019b..a8f7a0bd 100644 --- a/scripts/check-adapter-inventory.ts +++ b/scripts/check-adapter-inventory.ts @@ -201,7 +201,11 @@ async function main(): Promise { // 23 → 22: `storage/indexeddb/indexeddb-maintenance.ts`가 같은 이유로 지웠다. // 22 → 21: `storage/indexeddb/indexeddb-runtime.ts`가 같은 이유로 지웠다. // 이것으로 IndexedDB 어댑터 4벌이 모두 커널을 쓴다. - const HAND_ROLLED_ABORT_CEILING = 21; + // 21 → 19: `browser-files/download-delivery-adapter.ts`와 + // `browser-files/browser-file-vault.ts`가 커널 race로 옮겨갔다(Q-6.2-7). + // 19 → 18: `browser-file-storage/storage-manager-adapter.ts`의 inspection + // 대기가 커널 race로 옮겨갔다(Q-B). + const HAND_ROLLED_ABORT_CEILING = 17; const handRolledScan = spawnSync( "git", ["grep", "-l", 'addEventListener("abort"', "--", "src/adapters"], diff --git a/scripts/check-bundle.ts b/scripts/check-bundle.ts index a3117630..64223b20 100644 --- a/scripts/check-bundle.ts +++ b/scripts/check-bundle.ts @@ -1,6 +1,6 @@ import { readFile } from "node:fs/promises"; -import { evaluateBundleBudget } from "../src/application/policies/performance-budgets.ts"; +import { evaluateBundleBudget } from "./lib/performance-budgets.ts"; import { bundleOutputInventoryArtifactSchema, bundlePerformanceArtifactSchema, diff --git a/scripts/check-ci-contract.ts b/scripts/check-ci-contract.ts index 23768272..9eacfd0b 100644 --- a/scripts/check-ci-contract.ts +++ b/scripts/check-ci-contract.ts @@ -5,7 +5,7 @@ import { evaluatePromotionReadiness, PROMOTION_FORMULA, type GateResult, -} from "../src/application/policies/promotion-readiness.ts"; +} from "./lib/promotion-readiness.ts"; import { loadCiGateContract, indexCiGateContract, diff --git a/scripts/check-design-system.ts b/scripts/check-design-system.ts index 22ce4a8e..f968faa9 100644 --- a/scripts/check-design-system.ts +++ b/scripts/check-design-system.ts @@ -28,8 +28,14 @@ for (const [layer, file, tokens] of tokenLayers) { } } +// theme.css only imports the files under styles/theme/, so check them all. +const styleFiles = ( + await readdir("src/presentation/styles", { recursive: true }) +) + .filter((file) => file.endsWith(".css")) + .map((file) => path.join("src/presentation/styles", file)); const cssSources = await Promise.all( - [...Object.values(tokenFiles), "src/presentation/styles/theme.css"].map( + [...Object.values(tokenFiles), ...styleFiles].map( async (file) => ({ file, source: await readFile(file, "utf8") }), ), ); diff --git a/scripts/collect-web-vitals-evidence.ts b/scripts/collect-web-vitals-evidence.ts index 1935e371..7f1a90b7 100644 --- a/scripts/collect-web-vitals-evidence.ts +++ b/scripts/collect-web-vitals-evidence.ts @@ -3,7 +3,7 @@ import { mkdir, readFile } from "node:fs/promises"; import { evaluateFieldBudget, percentile75, -} from "../src/application/policies/performance-budgets.ts"; +} from "./lib/performance-budgets.ts"; import { fieldWebVitalsArtifactSchema } from "./contracts/release-artifacts.ts"; import { validateFieldEvidenceInput } from "./lib/field-vitals-evidence.ts"; import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts"; diff --git a/scripts/contracts/ci-gates.ts b/scripts/contracts/ci-gates.ts index 3443ca9c..d5557b45 100644 --- a/scripts/contracts/ci-gates.ts +++ b/scripts/contracts/ci-gates.ts @@ -4,7 +4,7 @@ import path from "node:path"; import { z } from "zod"; -import { PROMOTION_FORMULA } from "../../src/application/policies/promotion-readiness.ts"; +import { PROMOTION_FORMULA } from "../lib/promotion-readiness.ts"; import { RELEASE_CANDIDATE_EVIDENCE_PATHS, RELEASE_CANDIDATE_MANIFEST_PATH, diff --git a/src/application/policies/performance-budgets.ts b/scripts/lib/performance-budgets.ts similarity index 100% rename from src/application/policies/performance-budgets.ts rename to scripts/lib/performance-budgets.ts diff --git a/src/application/policies/promotion-readiness.ts b/scripts/lib/promotion-readiness.ts similarity index 100% rename from src/application/policies/promotion-readiness.ts rename to scripts/lib/promotion-readiness.ts diff --git a/scripts/test-performance.ts b/scripts/test-performance.ts index 2eb3e7a5..00547c8a 100644 --- a/scripts/test-performance.ts +++ b/scripts/test-performance.ts @@ -5,7 +5,7 @@ import process from "node:process"; import { chromium } from "@playwright/test"; -import { evaluateLabBudget } from "../src/application/policies/performance-budgets.ts"; +import { evaluateLabBudget } from "./lib/performance-budgets.ts"; import { ROUTE_REGISTRY } from "../src/features/installed-feature-contracts.ts"; import { labPerformanceArtifactSchema } from "./contracts/release-artifacts.ts"; import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts"; diff --git a/src/adapters/browser-file-storage/storage-manager-adapter.ts b/src/adapters/browser-file-storage/storage-manager-adapter.ts index e2b034a4..c77735a3 100644 --- a/src/adapters/browser-file-storage/storage-manager-adapter.ts +++ b/src/adapters/browser-file-storage/storage-manager-adapter.ts @@ -8,6 +8,7 @@ import { browserDataSuccess, mapBrowserDataException, } from "./result.ts"; +import { createAbortableOperation } from "../platform/abortable-operation.ts"; export type StorageManagerFacade = Readonly<{ estimate(): Promise>; @@ -155,48 +156,22 @@ function snapshotPressurePolicy( return snapshot; } +/** + * The kernel race: a caller abort ends the wait, and a native call that settles + * afterwards — including one that rejects — is consumed rather than leaked. + */ async function awaitStorageInspection( inspection: Promise, signal: AbortSignal | undefined, ): Promise { - if (!signal) return await inspection; - if (signal.aborted) { - // The native calls have already been invoked. Consume a later rejection - // even though the caller no longer waits for their result. - void inspection.catch(() => undefined); - return STORAGE_INSPECTION_ABORTED; + const operation = createAbortableOperation({ signal }); + try { + const raced = await operation.race(inspection); + if (raced.kind === "REJECTED") throw raced.reason; + return raced.kind === "VALUE" ? raced.value : STORAGE_INSPECTION_ABORTED; + } finally { + operation.close(); } - - return await new Promise( - (resolve, reject) => { - let settled = false; - const finish = ( - outcome: - | Readonly<{ kind: "VALUE"; value: Value }> - | Readonly<{ kind: "ABORTED" }> - | Readonly<{ kind: "ERROR"; error: unknown }>, - ): void => { - if (settled) return; - settled = true; - signal.removeEventListener("abort", onAbort); - if (outcome.kind === "VALUE") { - resolve(outcome.value); - } else if (outcome.kind === "ABORTED") { - resolve(STORAGE_INSPECTION_ABORTED); - } else { - reject(outcome.error); - } - }; - const onAbort = (): void => finish({ kind: "ABORTED" }); - - signal.addEventListener("abort", onAbort, { once: true }); - inspection.then( - (value) => finish({ kind: "VALUE", value }), - (error: unknown) => finish({ kind: "ERROR", error }), - ); - if (signal.aborted) onAbort(); - }, - ); } async function inspectPersistenceState( diff --git a/src/adapters/browser-files/browser-file-picker.ts b/src/adapters/browser-files/browser-file-picker.ts index cfd74975..fae5c0d1 100644 --- a/src/adapters/browser-files/browser-file-picker.ts +++ b/src/adapters/browser-files/browser-file-picker.ts @@ -54,7 +54,8 @@ interface DisposableFilePicker extends FilePickerPort { /** * Focus can return before some engines dispatch the file input change event. * This grace keeps the fallback from misclassifying a real selection as a - * dismissal. The native cancel event remains authoritative and immediate. + * dismissal. The native cancel event remains authoritative and immediate, and + * once a picker has seen it the fallback is no longer installed. */ export const DEFAULT_NATIVE_PICKER_FOCUS_GRACE_MS = 1_000; @@ -97,6 +98,12 @@ export class NativeInputFilePicker implements DisposableFilePicker { #pending = false; #disposed = false; #abortPending: (() => void) | undefined; + /** + * Q-6.2-8. Once this engine has dispatched a native `cancel`, dismissal is + * reported natively, so the focus heuristic would only turn a slow `change` + * (a cloud provider still fetching the file) into a false dismissal. + */ + #nativeCancelObserved = false; constructor(options: NativeInputFilePickerOptions) { this.#input = options.input; @@ -200,23 +207,25 @@ export class NativeInputFilePicker implements DisposableFilePicker { try { request = snapshotSelectionRequest(input); } catch { - return this.#finishObservation( + return observeSelection( + this.#observer, browserDataFailure("INVALID_INPUT", "FILE_SELECT"), ); } if (this.#disposed) { - return this.#finishObservation( + return observeSelection( + this.#observer, browserDataFailure("UNAVAILABLE", "FILE_SELECT"), ); } const cancelled = abortedResult(request.signal, "FILE_SELECT"); - if (cancelled) return this.#finishObservation(cancelled); + if (cancelled) return observeSelection(this.#observer, cancelled); const resolvedPolicy = this.#resolveSelection( request.policy, request.limits, ); if (!resolvedPolicy.ok) { - return this.#finishObservation(resolvedPolicy); + return observeSelection(this.#observer, resolvedPolicy); } const policy = resolvedPolicy.value; if ( @@ -225,17 +234,20 @@ export class NativeInputFilePicker implements DisposableFilePicker { this.#inputEvents.getAttribute, ) ) { - return this.#finishObservation( + return observeSelection( + this.#observer, browserDataFailure("INVALID_INPUT", "FILE_SELECT"), ); } if (this.#pending) { - return this.#finishObservation( + return observeSelection( + this.#observer, browserDataFailure("BLOCKED", "FILE_SELECT"), ); } if (this.#userActivation && !this.#userActivation.isActive) { - return this.#finishObservation( + return observeSelection( + this.#observer, browserDataFailure("PERMISSION_DENIED", "FILE_SELECT"), ); } @@ -293,7 +305,10 @@ export class NativeInputFilePicker implements DisposableFilePicker { : captured, ); }; - const onCancel = (): void => dismiss(); + const onCancel = (): void => { + this.#nativeCancelObserved = true; + dismiss(); + }; const onAbort = (): void => finish(browserDataFailure("ABORTED", "FILE_SELECT")); const abortPending = (): void => @@ -319,7 +334,9 @@ export class NativeInputFilePicker implements DisposableFilePicker { this.#inputEvents.add("change", onChange, { once: true }); this.#inputEvents.add("cancel", onCancel, { once: true }); signal?.addEventListener("abort", onAbort, { once: true }); - this.#windowEvents?.add("focus", onWindowFocus); + if (!this.#nativeCancelObserved) { + this.#windowEvents?.add("focus", onWindowFocus); + } this.#abortPending = abortPending; try { this.#input.accept = pickerAcceptValue(policy); @@ -332,9 +349,10 @@ export class NativeInputFilePicker implements DisposableFilePicker { } }, ); - return this.#finishObservation(result); + return observeSelection(this.#observer, result); } catch (error) { - return this.#finishObservation( + return observeSelection( + this.#observer, mapBrowserDataException(error, "FILE_SELECT"), ); } finally { @@ -356,33 +374,6 @@ export class NativeInputFilePicker implements DisposableFilePicker { // Some test doubles or constrained DOM hosts expose a readonly value. } } - - #finishObservation( - result: BrowserDataResult, - ): BrowserDataResult { - if (result.ok) { - const dismissed = result.value.kind === "DISMISSED"; - const bytes = - result.value.kind === "SELECTED" - ? result.value.files.reduce( - (total, candidate) => total + candidate.sizeBytes, - 0, - ) - : null; - observeBrowserFile(this.#observer, { - operation: "FILE_SELECT", - outcome: dismissed ? "DISMISSED" : "SUCCESS", - byteBucket: byteBucket(bytes), - }); - } else { - observeBrowserFile(this.#observer, { - operation: "FILE_SELECT", - outcome: "FAILED", - failureCode: result.error.code, - }); - } - return result; - } } export type SystemOpenPickerAcceptType = Readonly<{ @@ -460,30 +451,36 @@ export class EnhancedFilePicker implements DisposableFilePicker { try { request = snapshotSelectionRequest(input); } catch { - return this.#observe( + return observeSelection( + this.#observer, browserDataFailure("INVALID_INPUT", "FILE_SELECT"), ); } if (this.#disposed) { - return this.#observe( + return observeSelection( + this.#observer, browserDataFailure("UNAVAILABLE", "FILE_SELECT"), ); } const cancelled = abortedResult(request.signal, "FILE_SELECT"); - if (cancelled) return this.#observe(cancelled); + if (cancelled) return observeSelection(this.#observer, cancelled); const resolvedPolicy = this.#resolveSelection( request.policy, request.limits, ); - if (!resolvedPolicy.ok) return this.#observe(resolvedPolicy); + if (!resolvedPolicy.ok) { + return observeSelection(this.#observer, resolvedPolicy); + } const policy = resolvedPolicy.value; if (this.#pending) { - return this.#observe( + return observeSelection( + this.#observer, browserDataFailure("BLOCKED", "FILE_SELECT"), ); } if (this.#userActivation && !this.#userActivation.isActive) { - return this.#observe( + return observeSelection( + this.#observer, browserDataFailure("PERMISSION_DENIED", "FILE_SELECT"), ); } @@ -499,9 +496,10 @@ export class EnhancedFilePicker implements DisposableFilePicker { request.signal, ); const aborted = abortedResult(request.signal, "FILE_SELECT"); - if (aborted) return this.#observe(aborted); + if (aborted) return observeSelection(this.#observer, aborted); if (handles.length === 0) { - return this.#observe( + return observeSelection( + this.#observer, browserDataSuccess( Object.freeze({ kind: "DISMISSED" as const }), ), @@ -512,7 +510,8 @@ export class EnhancedFilePicker implements DisposableFilePicker { policy, request.signal ?? new AbortController().signal, ); - return this.#observe( + return observeSelection( + this.#observer, captured.ok ? browserDataSuccess( Object.freeze({ @@ -524,20 +523,23 @@ export class EnhancedFilePicker implements DisposableFilePicker { ); } catch (error) { if (error instanceof PickerDisposedError) { - return this.#observe( + return observeSelection( + this.#observer, browserDataFailure("ABORTED", "FILE_SELECT"), ); } if (error instanceof DOMException && error.name === "AbortError") { const aborted = abortedResult(input.signal, "FILE_SELECT"); - if (aborted) return this.#observe(aborted); - return this.#observe( + if (aborted) return observeSelection(this.#observer, aborted); + return observeSelection( + this.#observer, browserDataSuccess( Object.freeze({ kind: "DISMISSED" as const }), ), ); } - return this.#observe( + return observeSelection( + this.#observer, mapBrowserDataException(error, "FILE_SELECT"), ); } finally { @@ -589,34 +591,36 @@ export class EnhancedFilePicker implements DisposableFilePicker { ); }); } +} - #observe( - result: BrowserDataResult, - ): BrowserDataResult { - if (!result.ok) { - observeBrowserFile(this.#observer, { - operation: "FILE_SELECT", - outcome: "FAILED", - failureCode: result.error.code, - }); - } else if (result.value.kind === "DISMISSED") { - observeBrowserFile(this.#observer, { - operation: "FILE_SELECT", - outcome: "DISMISSED", - }); - } else { - const bytes = result.value.files.reduce( - (total, file) => total + file.sizeBytes, - 0, - ); - observeBrowserFile(this.#observer, { - operation: "FILE_SELECT", - outcome: "SUCCESS", - byteBucket: byteBucket(bytes), - }); - } - return result; +/** One observation per terminal selection result, shared by both pickers. */ +function observeSelection( + observer: BrowserFileObserver | undefined, + result: BrowserDataResult, +): BrowserDataResult { + if (!result.ok) { + observeBrowserFile(observer, { + operation: "FILE_SELECT", + outcome: "FAILED", + failureCode: result.error.code, + }); + } else if (result.value.kind === "DISMISSED") { + observeBrowserFile(observer, { + operation: "FILE_SELECT", + outcome: "DISMISSED", + }); + } else { + const bytes = result.value.files.reduce( + (total, file) => total + file.sizeBytes, + 0, + ); + observeBrowserFile(observer, { + operation: "FILE_SELECT", + outcome: "SUCCESS", + byteBucket: byteBucket(bytes), + }); } + return result; } function pickerAcceptValue( diff --git a/src/adapters/browser-files/browser-file-policy-registry.ts b/src/adapters/browser-files/browser-file-policy-registry.ts index 4a45c461..a4f639f0 100644 --- a/src/adapters/browser-files/browser-file-policy-registry.ts +++ b/src/adapters/browser-files/browser-file-policy-registry.ts @@ -14,6 +14,8 @@ import { import { assertFileInspectionPolicy, assertFileSelectionPolicy, + EXACT_MEDIA_TYPE, + isPositiveSafeInteger, sanitizeSuggestedFileName, type RegisteredFileInspectionPolicy, type RegisteredFileSelectionPolicy, @@ -81,8 +83,6 @@ type SnapshotProfile = Readonly<{ }>; const POLICY_TOKEN = /^[a-z0-9][a-z0-9._:-]{0,127}$/i; -const MEDIA_TYPE = - /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i; const ISSUED_POLICY_REFERENCES = new WeakSet(); /** @@ -417,7 +417,7 @@ function snapshotPreview( hardMaxPreviewBytes: number, ): SnapshotProfile["preview"] { if ( - !positiveSafeInteger(input.maxPreviewBytes) || + !isPositiveSafeInteger(input.maxPreviewBytes) || input.maxPreviewBytes > hardMaxPreviewBytes || !Array.isArray(input.allowedMediaTypes) || input.allowedMediaTypes.length < 1 || @@ -428,7 +428,7 @@ function snapshotPreview( const allowedMediaTypes = new Set(); for (const inputMediaType of input.allowedMediaTypes) { const mediaType = inputMediaType.trim().toLowerCase(); - if (!MEDIA_TYPE.test(mediaType)) { + if (!EXACT_MEDIA_TYPE.test(mediaType)) { throw new TypeError("File preview media type is invalid."); } allowedMediaTypes.add(mediaType); @@ -451,9 +451,9 @@ function snapshotDownload( "PROMPT_AND_STREAM", "BOUNDED_OBJECT_URL", ].includes(input.strategy) || - !MEDIA_TYPE.test(mediaType) || - !positiveSafeInteger(input.maxTransferBytes) || - !positiveSafeInteger(input.maxBufferedBytes) || + !EXACT_MEDIA_TYPE.test(mediaType) || + !isPositiveSafeInteger(input.maxTransferBytes) || + !isPositiveSafeInteger(input.maxBufferedBytes) || input.maxTransferBytes > hardLimits.maxTransferBytes || input.maxBufferedBytes > input.maxTransferBytes || (input.strategy === "BOUNDED_OBJECT_URL" && @@ -478,11 +478,11 @@ function assertHardLimits( input: BrowserFilePolicyRegistryOptions["hardLimits"], ): void { if ( - !positiveSafeInteger(input.maxInspectionBytes) || - !positiveSafeInteger(input.maxRetainedFileBytes) || - !positiveSafeInteger(input.maxPreviewBytes) || - !positiveSafeInteger(input.maxObjectUrlBytes) || - !positiveSafeInteger(input.maxTransferBytes) || + !isPositiveSafeInteger(input.maxInspectionBytes) || + !isPositiveSafeInteger(input.maxRetainedFileBytes) || + !isPositiveSafeInteger(input.maxPreviewBytes) || + !isPositiveSafeInteger(input.maxObjectUrlBytes) || + !isPositiveSafeInteger(input.maxTransferBytes) || input.maxObjectUrlBytes > input.maxTransferBytes ) { throw new TypeError("Browser file policy hard limits are invalid."); @@ -497,7 +497,7 @@ function reducedLimit( if (requested === undefined) { return browserDataSuccess(configured); } - if (!positiveSafeInteger(requested)) { + if (!isPositiveSafeInteger(requested)) { return browserDataFailure("INVALID_INPUT", operation); } if (requested > configured) { @@ -520,7 +520,3 @@ function referenceKey(reference: FilePolicyReference): string { reference.intention, ]); } - -function positiveSafeInteger(value: number): boolean { - return Number.isSafeInteger(value) && value > 0; -} diff --git a/src/adapters/browser-files/browser-file-vault.ts b/src/adapters/browser-files/browser-file-vault.ts index defb4961..8d36b126 100644 --- a/src/adapters/browser-files/browser-file-vault.ts +++ b/src/adapters/browser-files/browser-file-vault.ts @@ -19,10 +19,16 @@ import { browserDataSuccess, mapBrowserDataException, } from "../browser-file-storage/result.ts"; +import { + createAbortableOperation, + type AbortableOperation, +} from "../platform/abortable-operation.ts"; import { assertFileInspectionPolicy, assertFileSelectionPolicy, findMatchingSignature, + isPositiveSafeInteger, + isSafeGeneratedToken, matchesSelectionHint, normalizedExtension, signatureMetadataMatches, @@ -119,7 +125,8 @@ export class BrowserFileVault readonly #observer: BrowserFileObserver | undefined; readonly #resolveInspection: BrowserFilePolicyRegistry["resolveInspection"]; - readonly #lifetime = new AbortController(); + /** Open streams; dispose() closes each, which ends its pending read. */ + readonly #streams = new Set(); #disposed = false; #retainedBytes = 0; @@ -504,15 +511,12 @@ export class BrowserFileVault signal: AbortSignal, ): AsyncIterable> { let transferred = 0; - const combined = combineAbortSignals( - signal, - vault.#lifetime.signal, - ); + // Q-6.2-7. The kernel owner joins the caller signal and dispose(). + const owner = createAbortableOperation({ signal }); + if (vault.#disposed) owner.close(); + else vault.#streams.add(owner); try { - for await (const chunk of streamNativeFile( - file, - combined.signal, - )) { + for await (const chunk of streamNativeFile(file, owner)) { transferred += chunk.byteLength; yield browserDataSuccess(chunk); } @@ -533,7 +537,8 @@ export class BrowserFileVault vault.#observeFailureResult(failure); yield failure; } finally { - combined.release(); + vault.#streams.delete(owner); + owner.close(); } }, }); @@ -620,7 +625,8 @@ export class BrowserFileVault dispose(): void { if (this.#disposed) return; this.#disposed = true; - this.#lifetime.abort(); + for (const stream of this.#streams) stream.close(); + this.#streams.clear(); this.#verifications.clear(); this.#verificationReceiptsByRef.clear(); this.#records.clear(); @@ -681,7 +687,7 @@ export class BrowserFileVault return browserDataFailure("LIMIT_EXCEEDED", "FILE_SELECT"); } const refValue = this.#createReference(); - if (!safeOpaqueValue(refValue)) { + if (!isSafeGeneratedToken(refValue)) { return browserDataFailure("UNAVAILABLE", "FILE_SELECT"); } const ref = refValue as LocalFileRef; @@ -716,7 +722,7 @@ export class BrowserFileVault #issueVerification(record: VerificationRecord): BrowserDataResult { const receiptValue = this.#createVerificationReceipt(); - if (!safeOpaqueValue(receiptValue)) { + if (!isSafeGeneratedToken(receiptValue)) { return browserDataFailure("UNAVAILABLE", "FILE_INSPECT"); } const receipt = receiptValue as FileVerificationReceipt; @@ -810,21 +816,20 @@ function snapshotSystemFileHandles( async function* streamNativeFile( file: File, - signal: AbortSignal, + owner: AbortableOperation, ): AsyncIterable { - if (signal.aborted) throw abortException(); + if (owner.signal.aborted) throw abortException(); const reader = file.stream().getReader(); - const abort = () => { - void reader.cancel(abortException()).catch(() => {}); - }; - signal.addEventListener("abort", abort, { once: true }); let transferred = 0; let completed = false; try { while (true) { - if (signal.aborted) throw abortException(); - const result = await reader.read(); - if (signal.aborted) throw abortException(); + const raced = await owner.race(reader.read()); + if (raced.kind === "REJECTED") throw raced.reason; + if (raced.kind === "TERMINAL" || owner.signal.aborted) { + throw abortException(); + } + const result = raced.value; if (result.done) break; const chunk = result.value; if (!(chunk instanceof Uint8Array)) { @@ -844,12 +849,16 @@ async function* streamNativeFile( } completed = true; } finally { - signal.removeEventListener("abort", abort); if (!completed) { try { - await reader.cancel(); + // An aborted read never waits on the source's own cancel algorithm. + if (owner.signal.aborted) { + void reader.cancel(abortException()).catch(() => {}); + } else { + await reader.cancel(); + } } catch { - // The stream may already be errored or cancelled by AbortSignal. + // The stream may already be errored. } } reader.releaseLock(); @@ -861,35 +870,6 @@ function normalizedMediaType(value: string): string | null { return normalized.length > 0 ? normalized : null; } -function isPositiveSafeInteger(value: number): boolean { - return Number.isSafeInteger(value) && value > 0; -} - -function safeOpaqueValue(value: string): boolean { - return /^[a-z0-9][a-z0-9:_-]{0,127}$/i.test(value); -} - -function combineAbortSignals( - caller: AbortSignal, - lifetime: AbortSignal, -): Readonly<{ signal: AbortSignal; release(): void }> { - const controller = new AbortController(); - const abort = (): void => controller.abort(); - if (caller.aborted || lifetime.aborted) { - controller.abort(); - } else { - caller.addEventListener("abort", abort, { once: true }); - lifetime.addEventListener("abort", abort, { once: true }); - } - return Object.freeze({ - signal: controller.signal, - release(): void { - caller.removeEventListener("abort", abort); - lifetime.removeEventListener("abort", abort); - }, - }); -} - function abortException(): DOMException { return new DOMException("Operation aborted", "AbortError"); } diff --git a/src/adapters/browser-files/create-browser-file-runtime.ts b/src/adapters/browser-files/create-browser-file-runtime.ts index a8d25c8a..56de54da 100644 --- a/src/adapters/browser-files/create-browser-file-runtime.ts +++ b/src/adapters/browser-files/create-browser-file-runtime.ts @@ -24,6 +24,7 @@ import { type DownloadDeliveryAdapterOptions, } from "./download-delivery-adapter.ts"; import type { BrowserFileObserver } from "./file-observer.ts"; +import { isPositiveSafeInteger } from "./file-policy.ts"; import { BrowserTransientPreview, ObjectUrlLeaseRegistry, @@ -239,7 +240,3 @@ function resolveRuntimeLimits( } return resolved; } - -function isPositiveSafeInteger(value: number): boolean { - return Number.isSafeInteger(value) && value > 0; -} diff --git a/src/adapters/browser-files/download-delivery-adapter.ts b/src/adapters/browser-files/download-delivery-adapter.ts index 6c3b1139..8e3eeed4 100644 --- a/src/adapters/browser-files/download-delivery-adapter.ts +++ b/src/adapters/browser-files/download-delivery-adapter.ts @@ -1,5 +1,4 @@ import type { - BrowserManagedDownloadCapability, BrowserManagedDownloadCapabilityResolver, DownloadDeliveryPort, DownloadOutcome, @@ -12,7 +11,6 @@ import type { TransferProgress, } from "../../application/ports/browser-file-storage/shared.ts"; import type { - PresignedDownloadCapability, PresignedDownloadByteSource, PresignedDownloadSourcePort, } from "../../application/ports/browser-transfer/presigned-transfer.ts"; @@ -22,23 +20,31 @@ import { browserDataSuccess, mapBrowserDataException, } from "../browser-file-storage/result.ts"; +import { + createAbortableOperation, + type AbortableOperation, +} from "../platform/abortable-operation.ts"; import { byteBucket, observeBrowserFile, type BrowserFileObserver, } from "./file-observer.ts"; -import { - sanitizeSuggestedFileName, - type SuggestedFileNamePolicy, -} from "./file-policy.ts"; import { ObjectUrlLeaseRegistry, type ObjectUrlLease, } from "./object-url-lease.ts"; +import { BrowserFilePolicyRegistry } from "./browser-file-policy-registry.ts"; +import { isPositiveSafeInteger, isSafeGeneratedToken } from "./file-policy.ts"; import { - BrowserFilePolicyRegistry, - type ResolvedDownloadPolicy, -} from "./browser-file-policy-registry.ts"; + activeDeliveryInput, + resolveBrowserManagedTarget, + validByteSource, + validPresignedByteSource, + validateBrowserManagedCapability, + validateDownloadInput, + type DeliveryInput, + type DeliveryRequest, +} from "./download-input-validation.ts"; export type BrowserDownloadHost = Readonly<{ handoff(href: string, suggestedFileName: string): void; @@ -134,9 +140,6 @@ export type DownloadDeliveryAdapterOptions = Readonly<{ observer?: BrowserFileObserver; }>; -const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i; -const SHA256 = /^[a-f0-9]{64}$/i; - /** * Keeps a one-shot Blob URL alive across browser download scheduling and * process handoff. Runtime dispose() still revokes every active lease @@ -170,7 +173,8 @@ export function createDownloadDeliveryAdapter( options.baseOrigin ?? globalThis.location?.origin ?? "https://localhost"; const userActivation = options.userActivation ?? globalThis.navigator?.userActivation; - const lifetime = new AbortController(); + // Every delivery in flight; dispose() closes each, which aborts its signal. + const liveOperations = new Set(); let disposed = false; if ( @@ -178,8 +182,8 @@ export function createDownloadDeliveryAdapter( progressMinIntervalMs < 0 || !Number.isSafeInteger(releaseDelayMs) || releaseDelayMs < 0 || - !isPositiveByteLimit(options.hardMaxObjectUrlBytes) || - !isPositiveByteLimit(options.hardMaxTransferBytes) || + !isPositiveSafeInteger(options.hardMaxObjectUrlBytes) || + !isPositiveSafeInteger(options.hardMaxTransferBytes) || options.hardMaxObjectUrlBytes > options.hardMaxTransferBytes || typeof options.host?.handoff !== "function" || typeof options.policies?.resolveDownload !== "function" || @@ -266,19 +270,23 @@ export function createDownloadDeliveryAdapter( dependencies.observer, ); } - const combined = combineAbortSignals( - input.signal, - lifetime.signal, - ); + // Q-6.2-7. One owner per delivery: caller abort and dispose() both end + // it, and a lease or writable that lands after that is compensated by the + // kernel race instead of a hand-written listener pair. + const owner = createAbortableOperation({ signal: input.signal }); + liveOperations.add(owner); try { - return await deliverActive({ ...input, signal: combined.signal }); + return await deliverActive({ ...input, signal: owner.signal }, owner); } finally { - combined.release(); + liveOperations.delete(owner); + owner.close(); } } - async function deliverActive(input: DeliveryRequest): - Promise> { + async function deliverActive( + input: DeliveryRequest, + owner: AbortableOperation, + ): Promise> { const resolvedPolicy = resolveDownloadPolicy( input.policy, { @@ -315,17 +323,10 @@ export function createDownloadDeliveryAdapter( dependencies.observer, ); } - let suggestedFileName: string; + // Q-6.2-10. Validation already sanitized the name; it is not redone. + const suggestedFileName = validation.value; let transferId: string; try { - suggestedFileName = sanitizeSuggestedFileName( - activeInput.suggestedFileName, - { - safeExtension: activeInput.safeExtension, - maxUtf8Bytes: - dependencies.filenameMaxUtf8Bytes, - } satisfies SuggestedFileNamePolicy, - ); transferId = createTransferId(); } catch { return observeResult( @@ -333,7 +334,7 @@ export function createDownloadDeliveryAdapter( dependencies.observer, ); } - if (!safeGeneratedToken(transferId)) { + if (!isSafeGeneratedToken(transferId)) { return observeResult( browserDataFailure("UNAVAILABLE", "DOWNLOAD"), dependencies.observer, @@ -358,6 +359,7 @@ export function createDownloadDeliveryAdapter( if (activeInput.strategy === "PROMPT_AND_STREAM") { return promptAndStream({ input: activeInput, + owner, suggestedFileName, transferId, options: dependencies, @@ -367,6 +369,7 @@ export function createDownloadDeliveryAdapter( return boundedObjectUrlHandoff({ input: activeInput, + owner, suggestedFileName, transferId, options: dependencies, @@ -382,7 +385,8 @@ export function createDownloadDeliveryAdapter( dispose(): void { if (disposed) return; disposed = true; - lifetime.abort(); + for (const operation of liveOperations) operation.close(); + liveOperations.clear(); objectUrls.dispose(); }, }); @@ -482,6 +486,7 @@ function browserManagedHandoff(context: Readonly<{ async function promptAndStream(context: Readonly<{ input: DeliveryInput; + owner: AbortableOperation; suggestedFileName: string; transferId: string; options: DownloadDeliveryAdapterOptions; @@ -542,10 +547,7 @@ async function promptAndStream(context: Readonly<{ let handle: SaveFileHandle; try { - handle = await awaitWithSignal( - handlePromise, - context.input.signal, - ); + handle = await raceOwner(context.owner, handlePromise); } catch (error) { if ( error instanceof DOMException && @@ -576,7 +578,7 @@ async function promptAndStream(context: Readonly<{ try { const sourceResult = await resolveByteSource( context.input, - context.input.signal, + context.owner, context.options, sourceHolder, ); @@ -595,9 +597,14 @@ async function promptAndStream(context: Readonly<{ ); } context.progress.report("PREPARING", 0, source.byteLength, true); - const writable = await awaitWithSignal( + const writable = await raceOwner( + context.owner, handle.createWritable(), - context.input.signal, + // A writable that opens after the abort keeps a browser swap file + // until it is aborted. + (late) => { + void late.abort().catch(() => undefined); + }, ); const writer = writable.getWriter(); let committed = false; @@ -606,7 +613,7 @@ async function promptAndStream(context: Readonly<{ try { for await (const chunkResult of abortableFileChunks( source, - context.input.signal, + context.owner, )) { if (!chunkResult.ok) { throw new ClosedFileStreamError(chunkResult.error); @@ -622,15 +629,12 @@ async function promptAndStream(context: Readonly<{ throw limitException(); } if (verifier) { - await awaitWithSignal( + await raceOwner( + context.owner, Promise.resolve(verifier.update(chunk)), - context.input.signal, ); } - await awaitWithSignal( - writer.write(chunk), - context.input.signal, - ); + await raceOwner(context.owner, writer.write(chunk)); transferred = next; context.progress.report( "TRANSFERRING", @@ -647,9 +651,9 @@ async function promptAndStream(context: Readonly<{ true, ); if (verifier) { - const verified = await awaitWithSignal( + const verified = await raceOwner( + context.owner, Promise.resolve(verifier.verify()), - context.input.signal, ); if (!verified) throw integrityException(); } @@ -716,6 +720,7 @@ async function promptAndStream(context: Readonly<{ async function boundedObjectUrlHandoff(context: Readonly<{ input: DeliveryInput; + owner: AbortableOperation; suggestedFileName: string; transferId: string; options: DownloadDeliveryAdapterOptions; @@ -739,10 +744,10 @@ async function boundedObjectUrlHandoff(context: Readonly<{ let lease: ObjectUrlLease | undefined; try { // Inside the try: an open that throws or is aborted must still resolve to - // a Result and reach the finally that latches the holder for late leases. + // a Result and reach the finally that closes the held lease. const sourceResult = await resolveByteSource( context.input, - context.input.signal, + context.owner, context.options, sourceHolder, ); @@ -765,7 +770,7 @@ async function boundedObjectUrlHandoff(context: Readonly<{ context.progress.report("PREPARING", 0, source.byteLength, true); for await (const chunkResult of abortableFileChunks( source, - context.input.signal, + context.owner, )) { if (!chunkResult.ok) { throw new ClosedFileStreamError(chunkResult.error); @@ -782,9 +787,9 @@ async function boundedObjectUrlHandoff(context: Readonly<{ throw limitException(); } if (verifier) { - await awaitWithSignal( + await raceOwner( + context.owner, Promise.resolve(verifier.update(chunk)), - context.input.signal, ); } const copy = chunk.slice(); @@ -804,9 +809,9 @@ async function boundedObjectUrlHandoff(context: Readonly<{ true, ); if (verifier) { - const verified = await awaitWithSignal( + const verified = await raceOwner( + context.owner, Promise.resolve(verifier.verify()), - context.input.signal, ); if (!verified) throw integrityException(); } @@ -857,168 +862,14 @@ async function boundedObjectUrlHandoff(context: Readonly<{ } } -type DeliveryRequest = - Parameters[0]; - -type DeliveryInput = Readonly< - Omit< - DeliveryRequest, - "maxTransferBytes" | "maxBufferedBytes" - > & - ResolvedDownloadPolicy & { - expectedSha256?: string; - } ->; - -function activeDeliveryInput( - input: DeliveryRequest, - policy: ResolvedDownloadPolicy, -): DeliveryInput { - const source = snapshotDownloadSource(input.source); - const expectedSha256 = - source.kind === "GENERATED" - ? source.expectedSha256 - : undefined; - return Object.freeze({ - policy: input.policy, - source, - suggestedFileName: input.suggestedFileName, - signal: input.signal, - onProgress: input.onProgress, - ...policy, - ...(expectedSha256 !== undefined ? { expectedSha256 } : {}), - }); -} - -function snapshotDownloadSource( - source: DownloadSource, -): DownloadSource { - const kind = source.kind; - if (kind === "BROWSER_MANAGED_RESOURCE") { - return Object.freeze({ - kind, - resourceId: source.resourceId, - capabilityReceipt: source.capabilityReceipt, - }); - } - if (kind === "AUTHORIZED_STREAM_RESOURCE") { - return Object.freeze({ - kind, - resourceId: source.resourceId, - capability: source.capability, - }); - } - if (kind !== "GENERATED") { - throw new TypeError("Download source kind is invalid."); - } - const sourceBytes = source.bytes; - const stream = sourceBytes.stream; - const byteLength = sourceBytes.byteLength; - if (typeof stream !== "function") { - throw new TypeError("Download byte source is invalid."); - } - const bytes: FileByteSource = Object.freeze({ - byteLength, - stream: stream.bind(sourceBytes), - }); - const expectedSha256 = source.expectedSha256; - return Object.freeze({ - kind, - bytes, - ...(expectedSha256 !== undefined ? { expectedSha256 } : {}), - }); -} - -function validateDownloadInput( - input: DeliveryInput, - options: DownloadDeliveryAdapterOptions, - userActivation: Readonly<{ isActive: boolean }> | undefined, -): BrowserDataResult { - if ( - input.signal.aborted || - input.suggestedFileName.length === 0 || - !MEDIA_TYPE.test(input.mediaType) || - !isValidByteLength(input.maxTransferBytes) || - input.maxTransferBytes === 0 || - !isValidByteLength(input.maxBufferedBytes) || - input.maxBufferedBytes === 0 || - (input.expectedSha256 !== undefined && - !SHA256.test(input.expectedSha256)) || - (input.source.kind === "AUTHORIZED_STREAM_RESOURCE" && - (!safeOpaqueId(input.source.resourceId) || - !validPresignedCapabilityForInput( - input.source.capability, - input.source.resourceId, - input.mediaType, - input.maxTransferBytes, - options.now?.() ?? Date.now(), - ) || - options.openAuthorizedSource === undefined)) || - (input.source.kind === "BROWSER_MANAGED_RESOURCE" && - (!safeOpaqueId(input.source.resourceId) || - !safeOpaqueId(input.source.capabilityReceipt))) || - (input.strategy === "PROMPT_AND_STREAM" && - options.showSaveFilePicker === undefined) - ) { - return browserDataFailure( - input.signal.aborted ? "ABORTED" : "INVALID_INPUT", - "DOWNLOAD", - ); - } - if ( - input.maxTransferBytes > options.hardMaxTransferBytes || - (input.strategy === "BOUNDED_OBJECT_URL" && - (input.maxBufferedBytes > options.hardMaxObjectUrlBytes || - input.maxBufferedBytes > input.maxTransferBytes)) - ) { - return browserDataFailure("LIMIT_EXCEEDED", "DOWNLOAD"); - } - if ( - (input.strategy === "BROWSER_MANAGED" && - input.source.kind !== "BROWSER_MANAGED_RESOURCE") || - (input.strategy !== "BROWSER_MANAGED" && - input.source.kind === "BROWSER_MANAGED_RESOURCE") || - (input.integrity === "REQUIRED" && - input.source.kind === "GENERATED" && - input.expectedSha256 === undefined) - ) { - return browserDataFailure("POLICY_REJECTED", "DOWNLOAD"); - } - if (input.source.kind === "GENERATED") { - try { - if (!validByteSource(input.source.bytes)) { - return browserDataFailure("INTEGRITY_FAILED", "DOWNLOAD"); - } - if ( - input.source.bytes.byteLength !== null && - input.source.bytes.byteLength > input.maxTransferBytes - ) { - return browserDataFailure("LIMIT_EXCEEDED", "DOWNLOAD"); - } - } catch { - return browserDataFailure("INVALID_INPUT", "DOWNLOAD"); - } - } - if (userActivation && !userActivation.isActive) { - return browserDataFailure("PERMISSION_DENIED", "DOWNLOAD"); - } - try { - sanitizeSuggestedFileName(input.suggestedFileName, { - safeExtension: input.safeExtension, - maxUtf8Bytes: options.filenameMaxUtf8Bytes, - }); - } catch { - return browserDataFailure("INVALID_INPUT", "DOWNLOAD"); - } - return browserDataSuccess(true); -} - /** * TR-RR-04. A presigned byte source owns a fetch reader and a capability lease, * and its port requires `close()`. The delivery consumer never called it, so * every success, validation failure, writer failure and abort leaked both. The * closeable subtype is lost in the `FileByteSource` projection, so the holder - * keeps it and the outermost boundary closes it exactly once. + * keeps it and the outermost boundary closes it exactly once. A lease that + * lands after the owner ended never reaches the holder; the owner's race + * compensates it instead. */ type CloseableSourceHolder = { source: FileByteSource | null; closed: boolean }; @@ -1026,32 +877,6 @@ function createSourceHolder(): CloseableSourceHolder { return { source: null, closed: false }; } -/** - * TR-02. Closes a lease that fulfilled after the delivery already ended. The - * holder's own `closed` latch is the single close-once authority, so a lease - * the holder did adopt is never closed twice and a lease it never saw is still - * closed exactly once. A late rejection is observed and discarded. - */ -function compensateLateSource( - pending: Promise>, - holder: CloseableSourceHolder | undefined, -): void { - if (!holder) return; - void pending.then( - (result) => { - if (!result.ok || !holder.closed) return; - // The holder was already closed, so this lease was never adopted. - if (!isVerifiedPresignedSource(result.value)) return; - try { - result.value.close(); - } catch { - // Compensation is best effort and never changes the outcome. - } - }, - () => undefined, - ); -} - function closeHeldSource(holder: CloseableSourceHolder): void { if (holder.closed) return; holder.closed = true; @@ -1067,12 +892,12 @@ function closeHeldSource(holder: CloseableSourceHolder): void { async function resolveByteSource( input: DeliveryInput, - signal: AbortSignal, + owner: AbortableOperation, options: DownloadDeliveryAdapterOptions, holder?: CloseableSourceHolder, ): Promise> { const source = input.source; - if (signal.aborted) { + if (owner.signal.aborted) { return browserDataFailure("ABORTED", "DOWNLOAD"); } if (source.kind === "GENERATED") { @@ -1085,17 +910,22 @@ async function resolveByteSource( } const open = options.openAuthorizedSource; if (!open) return browserDataFailure("UNSUPPORTED", "DOWNLOAD"); - const pendingOpen = open({ - resourceId: source.resourceId, - capability: source.capability, - signal, - }); - // TR-02. A lease that arrives after the abort already ended the delivery - // never reaches the holder, so nothing would ever close it: the fetch reader - // and the capability lease outlived the terminal result. The compensator and - // the holder share one close-once latch, so exactly one of them closes it. - compensateLateSource(pendingOpen, holder); - const result = await awaitWithSignal(pendingOpen, signal); + // TR-02 / Q-6.2-7. A lease that arrives after the owner ended never reaches + // the holder, so the race closes it: exactly one of the two ever sees it, + // with no gap between the abort and the holder's own cleanup. + const result = await raceOwner( + owner, + open({ + resourceId: source.resourceId, + capability: source.capability, + signal: owner.signal, + }), + (late) => { + if (late.ok && isVerifiedPresignedSource(late.value)) { + late.value.close(); + } + }, + ); if (!result.ok) { return browserDataFailure(result.error.code, "DOWNLOAD", { retryable: result.error.retryable, @@ -1117,14 +947,6 @@ async function resolveByteSource( : browserDataFailure("INTEGRITY_FAILED", "DOWNLOAD"); } -function validByteSource(source: FileByteSource): boolean { - return ( - typeof source.stream === "function" && - (source.byteLength === null || - isValidByteLength(source.byteLength)) - ); -} - function isVerifiedPresignedSource( source: FileByteSource, ): source is PresignedDownloadByteSource { @@ -1134,70 +956,16 @@ function isVerifiedPresignedSource( ); } -function validPresignedByteSource( - source: PresignedDownloadByteSource, - capability: PresignedDownloadCapability, - resourceId: string, - mediaType: string, - maxTransferBytes: number, - nowEpochMs: number, -): boolean { - return ( - validByteSource(source) && - source.capability === capability && - source.integrity === "VERIFIED_ON_SUCCESSFUL_EXHAUSTION" && - source.byteLength === capability.byteLength && - capability.method === "GET" && - capability.binding.kind === "DOWNLOAD" && - capability.binding.resourceId === resourceId && - capability.mediaType === mediaType && - capability.byteLength <= capability.maxBytes && - capability.maxBytes <= maxTransferBytes && - SHA256.test(capability.expectedSha256) && - Number.isSafeInteger(nowEpochMs) && - capability.expiresAtEpochMs > nowEpochMs - ); -} - -function validPresignedCapabilityForInput( - capability: PresignedDownloadCapability, - resourceId: string, - mediaType: string, - maxTransferBytes: number, - nowEpochMs: number, -): boolean { - try { - return ( - Boolean(capability) && - typeof capability === "object" && - Object.isFrozen(capability) && - capability.method === "GET" && - capability.binding.kind === "DOWNLOAD" && - capability.binding.resourceId === resourceId && - capability.mediaType === mediaType && - isValidByteLength(capability.byteLength) && - isPositiveByteLimit(capability.maxBytes) && - capability.byteLength <= capability.maxBytes && - capability.maxBytes <= maxTransferBytes && - SHA256.test(capability.expectedSha256) && - Number.isSafeInteger(capability.expiresAtEpochMs) && - Number.isSafeInteger(nowEpochMs) && - capability.expiresAtEpochMs > nowEpochMs - ); - } catch { - return false; - } -} - async function* abortableFileChunks( source: FileByteSource, - signal: AbortSignal, + owner: AbortableOperation, ): AsyncIterable> { + const signal = owner.signal; const iterator = source.stream(signal)[Symbol.asyncIterator](); let completed = false; try { while (true) { - const next = await awaitWithSignal(iterator.next(), signal); + const next = await raceOwner(owner, iterator.next()); if (next.done) { completed = true; return; @@ -1270,116 +1038,6 @@ function mapDownloadException( return mapBrowserDataException(error, "DOWNLOAD"); } -function validateBrowserManagedCapability( - capability: BrowserManagedDownloadCapability, - input: DeliveryInput, - nowEpochMs: number, -): BrowserDataResult { - if ( - input.source.kind !== "BROWSER_MANAGED_RESOURCE" || - !capability || - typeof capability !== "object" || - typeof capability.href !== "string" || - capability.href.length === 0 || - capability.capabilityReceipt !== - input.source.capabilityReceipt || - capability.resourceId !== input.source.resourceId || - capability.mediaType.trim().toLowerCase() !== - input.mediaType || - capability.safeExtension.trim().toLowerCase() !== - input.safeExtension || - !isPositiveByteLimit(capability.maxBytes) || - capability.maxBytes > input.maxTransferBytes || - !Number.isSafeInteger(capability.expiresAtEpochMs) || - !Number.isSafeInteger(nowEpochMs) || - (capability.expectedSha256 !== undefined && - !SHA256.test(capability.expectedSha256)) || - (input.integrity === "REQUIRED" && - capability.expectedSha256 === undefined) - ) { - return browserDataFailure("POLICY_REJECTED", "DOWNLOAD"); - } - if (capability.expiresAtEpochMs <= nowEpochMs) { - return browserDataFailure("EXPIRED_RESOURCE", "DOWNLOAD", { - recovery: "RETRY", - }); - } - return browserDataSuccess( - Object.freeze({ - capabilityReceipt: capability.capabilityReceipt, - href: capability.href, - resourceId: capability.resourceId, - mediaType: input.mediaType, - safeExtension: input.safeExtension, - maxBytes: capability.maxBytes, - ...(capability.expectedSha256 - ? { - expectedSha256: - capability.expectedSha256.toLowerCase(), - } - : {}), - expiresAtEpochMs: capability.expiresAtEpochMs, - }), - ); -} - -type ResolvedBrowserManagedTarget = Readonly<{ absoluteHref: string }>; - -/** - * STO-02. Parse once, canonicalize, then execute the canonical value. - * - * Returning a boolean and handing the raw href to the host let the browser - * re-resolve a relative target against `document.baseURI`, so a hostile - * `` could send the navigation to a different origin than the one this - * policy just approved. - */ -function resolveBrowserManagedTarget( - href: string, - baseOrigin: string, - policy: Readonly<{ - allowCrossOrigin: boolean; - allowQuery: boolean; - }>, -): BrowserDataResult { - let base: URL; - let target: URL; - try { - base = new URL(baseOrigin); - target = new URL(href, base); - } catch { - return browserDataFailure("POLICY_REJECTED", "DOWNLOAD"); - } - if ( - !["http:", "https:"].includes(target.protocol) || - target.username.length > 0 || - target.password.length > 0 || - (!policy.allowCrossOrigin && target.origin !== base.origin) || - (!policy.allowQuery && target.search.length > 0) || - target.hash.length > 0 - ) { - return browserDataFailure("POLICY_REJECTED", "DOWNLOAD"); - } - return browserDataSuccess( - Object.freeze({ absoluteHref: target.href }), - ); -} - -function safeOpaqueId(value: unknown): value is string { - if (typeof value !== "string") return false; - if (value.length === 0 || value.length > 256) return false; - for (const character of value) { - const code = character.codePointAt(0); - if (code === undefined || code <= 0x20 || code === 0x7f) { - return false; - } - } - return true; -} - -function safeGeneratedToken(value: string): boolean { - return /^[a-z0-9][a-z0-9:_-]{0,127}$/i.test(value); -} - type ProgressReporter = Readonly<{ report( phase: TransferProgress["phase"], @@ -1482,50 +1140,17 @@ class ClosedFileStreamError extends Error { } } -function combineAbortSignals( - caller: AbortSignal, - lifetime: AbortSignal, -): Readonly<{ signal: AbortSignal; release(): void }> { - const controller = new AbortController(); - const abort = (): void => controller.abort(); - if (caller.aborted || lifetime.aborted) { - controller.abort(); - } else { - caller.addEventListener("abort", abort, { once: true }); - lifetime.addEventListener("abort", abort, { once: true }); - } - return Object.freeze({ - signal: controller.signal, - release(): void { - caller.removeEventListener("abort", abort); - lifetime.removeEventListener("abort", abort); - }, - }); -} - -async function awaitWithSignal( +/** + * The owner's value, the task's own rejection, or an AbortError once the owner + * ended. `compensate` receives a value that lands after that. + */ +async function raceOwner( + owner: AbortableOperation, pending: Promise, - signal: AbortSignal, + compensate?: (value: Value) => void, ): Promise { - if (signal.aborted) throw abortException(); - return new Promise((resolve, reject) => { - let settled = false; - const finish = (callback: () => void): void => { - if (settled) return; - settled = true; - signal.removeEventListener("abort", onAbort); - callback(); - }; - const onAbort = (): void => - finish(() => reject(abortException())); - signal.addEventListener("abort", onAbort, { once: true }); - pending.then( - (value) => finish(() => resolve(value)), - (error: unknown) => finish(() => reject(error)), - ); - }); -} - -function isPositiveByteLimit(value: number): boolean { - return isValidByteLength(value) && value > 0; + const raced = await owner.race(pending, compensate); + if (raced.kind === "VALUE") return raced.value; + if (raced.kind === "REJECTED") throw raced.reason; + throw abortException(); } diff --git a/src/adapters/browser-files/download-input-validation.ts b/src/adapters/browser-files/download-input-validation.ts new file mode 100644 index 00000000..5556f6ac --- /dev/null +++ b/src/adapters/browser-files/download-input-validation.ts @@ -0,0 +1,367 @@ +import type { + BrowserManagedDownloadCapability, + DownloadDeliveryPort, + DownloadSource, + FileByteSource, +} from "../../application/ports/browser-file-storage/file.ts"; +import type { BrowserDataResult } from "../../application/ports/browser-file-storage/shared.ts"; +import type { + PresignedDownloadCapability, + PresignedDownloadByteSource, +} from "../../application/ports/browser-transfer/presigned-transfer.ts"; +import { isValidByteLength } from "../../application/ports/browser-file-storage/shared.ts"; +import { + browserDataFailure, + browserDataSuccess, +} from "../browser-file-storage/result.ts"; +import { + EXACT_MEDIA_TYPE, + isPositiveSafeInteger, + sanitizeSuggestedFileName, + type SuggestedFileNamePolicy, +} from "./file-policy.ts"; +import type { ResolvedDownloadPolicy } from "./browser-file-policy-registry.ts"; + +/** + * Q-6.2-11. Input admission for download delivery: request snapshot, policy + * and limit checks, presigned and browser-managed capability validation, and + * canonical handoff target resolution. Moved verbatim out of the adapter. + */ + +/** The adapter options that input validation reads. */ +export type DownloadInputValidationOptions = Readonly<{ + hardMaxObjectUrlBytes: number; + hardMaxTransferBytes: number; + openAuthorizedSource?: unknown; + showSaveFilePicker?: unknown; + filenameMaxUtf8Bytes?: number; + now?: () => number; +}>; + +const SHA256 = /^[a-f0-9]{64}$/i; + +export type DeliveryRequest = + Parameters[0]; + +export type DeliveryInput = Readonly< + Omit< + DeliveryRequest, + "maxTransferBytes" | "maxBufferedBytes" + > & + ResolvedDownloadPolicy & { + expectedSha256?: string; + } +>; + +export function activeDeliveryInput( + input: DeliveryRequest, + policy: ResolvedDownloadPolicy, +): DeliveryInput { + const source = snapshotDownloadSource(input.source); + const expectedSha256 = + source.kind === "GENERATED" + ? source.expectedSha256 + : undefined; + return Object.freeze({ + policy: input.policy, + source, + suggestedFileName: input.suggestedFileName, + signal: input.signal, + onProgress: input.onProgress, + ...policy, + ...(expectedSha256 !== undefined ? { expectedSha256 } : {}), + }); +} + +function snapshotDownloadSource( + source: DownloadSource, +): DownloadSource { + const kind = source.kind; + if (kind === "BROWSER_MANAGED_RESOURCE") { + return Object.freeze({ + kind, + resourceId: source.resourceId, + capabilityReceipt: source.capabilityReceipt, + }); + } + if (kind === "AUTHORIZED_STREAM_RESOURCE") { + return Object.freeze({ + kind, + resourceId: source.resourceId, + capability: source.capability, + }); + } + if (kind !== "GENERATED") { + throw new TypeError("Download source kind is invalid."); + } + const sourceBytes = source.bytes; + const stream = sourceBytes.stream; + const byteLength = sourceBytes.byteLength; + if (typeof stream !== "function") { + throw new TypeError("Download byte source is invalid."); + } + const bytes: FileByteSource = Object.freeze({ + byteLength, + stream: stream.bind(sourceBytes), + }); + const expectedSha256 = source.expectedSha256; + return Object.freeze({ + kind, + bytes, + ...(expectedSha256 !== undefined ? { expectedSha256 } : {}), + }); +} + +export function validateDownloadInput( + input: DeliveryInput, + options: DownloadInputValidationOptions, + userActivation: Readonly<{ isActive: boolean }> | undefined, +): BrowserDataResult { + if ( + input.signal.aborted || + input.suggestedFileName.length === 0 || + !EXACT_MEDIA_TYPE.test(input.mediaType) || + !isValidByteLength(input.maxTransferBytes) || + input.maxTransferBytes === 0 || + !isValidByteLength(input.maxBufferedBytes) || + input.maxBufferedBytes === 0 || + (input.expectedSha256 !== undefined && + !SHA256.test(input.expectedSha256)) || + (input.source.kind === "AUTHORIZED_STREAM_RESOURCE" && + (!safeOpaqueId(input.source.resourceId) || + !validPresignedCapabilityForInput( + input.source.capability, + input.source.resourceId, + input.mediaType, + input.maxTransferBytes, + options.now?.() ?? Date.now(), + ) || + options.openAuthorizedSource === undefined)) || + (input.source.kind === "BROWSER_MANAGED_RESOURCE" && + (!safeOpaqueId(input.source.resourceId) || + !safeOpaqueId(input.source.capabilityReceipt))) || + (input.strategy === "PROMPT_AND_STREAM" && + options.showSaveFilePicker === undefined) + ) { + return browserDataFailure( + input.signal.aborted ? "ABORTED" : "INVALID_INPUT", + "DOWNLOAD", + ); + } + if ( + input.maxTransferBytes > options.hardMaxTransferBytes || + (input.strategy === "BOUNDED_OBJECT_URL" && + (input.maxBufferedBytes > options.hardMaxObjectUrlBytes || + input.maxBufferedBytes > input.maxTransferBytes)) + ) { + return browserDataFailure("LIMIT_EXCEEDED", "DOWNLOAD"); + } + if ( + (input.strategy === "BROWSER_MANAGED" && + input.source.kind !== "BROWSER_MANAGED_RESOURCE") || + (input.strategy !== "BROWSER_MANAGED" && + input.source.kind === "BROWSER_MANAGED_RESOURCE") || + (input.integrity === "REQUIRED" && + input.source.kind === "GENERATED" && + input.expectedSha256 === undefined) + ) { + return browserDataFailure("POLICY_REJECTED", "DOWNLOAD"); + } + if (input.source.kind === "GENERATED") { + try { + if (!validByteSource(input.source.bytes)) { + return browserDataFailure("INTEGRITY_FAILED", "DOWNLOAD"); + } + if ( + input.source.bytes.byteLength !== null && + input.source.bytes.byteLength > input.maxTransferBytes + ) { + return browserDataFailure("LIMIT_EXCEEDED", "DOWNLOAD"); + } + } catch { + return browserDataFailure("INVALID_INPUT", "DOWNLOAD"); + } + } + if (userActivation && !userActivation.isActive) { + return browserDataFailure("PERMISSION_DENIED", "DOWNLOAD"); + } + try { + return browserDataSuccess( + sanitizeSuggestedFileName(input.suggestedFileName, { + safeExtension: input.safeExtension, + maxUtf8Bytes: options.filenameMaxUtf8Bytes, + } satisfies SuggestedFileNamePolicy), + ); + } catch { + return browserDataFailure("INVALID_INPUT", "DOWNLOAD"); + } +} + +export function validByteSource(source: FileByteSource): boolean { + return ( + typeof source.stream === "function" && + (source.byteLength === null || + isValidByteLength(source.byteLength)) + ); +} + +export function validPresignedByteSource( + source: PresignedDownloadByteSource, + capability: PresignedDownloadCapability, + resourceId: string, + mediaType: string, + maxTransferBytes: number, + nowEpochMs: number, +): boolean { + return ( + validByteSource(source) && + source.capability === capability && + source.integrity === "VERIFIED_ON_SUCCESSFUL_EXHAUSTION" && + source.byteLength === capability.byteLength && + capability.method === "GET" && + capability.binding.kind === "DOWNLOAD" && + capability.binding.resourceId === resourceId && + capability.mediaType === mediaType && + capability.byteLength <= capability.maxBytes && + capability.maxBytes <= maxTransferBytes && + SHA256.test(capability.expectedSha256) && + Number.isSafeInteger(nowEpochMs) && + capability.expiresAtEpochMs > nowEpochMs + ); +} + +function validPresignedCapabilityForInput( + capability: PresignedDownloadCapability, + resourceId: string, + mediaType: string, + maxTransferBytes: number, + nowEpochMs: number, +): boolean { + try { + return ( + Boolean(capability) && + typeof capability === "object" && + Object.isFrozen(capability) && + capability.method === "GET" && + capability.binding.kind === "DOWNLOAD" && + capability.binding.resourceId === resourceId && + capability.mediaType === mediaType && + isValidByteLength(capability.byteLength) && + isPositiveSafeInteger(capability.maxBytes) && + capability.byteLength <= capability.maxBytes && + capability.maxBytes <= maxTransferBytes && + SHA256.test(capability.expectedSha256) && + Number.isSafeInteger(capability.expiresAtEpochMs) && + Number.isSafeInteger(nowEpochMs) && + capability.expiresAtEpochMs > nowEpochMs + ); + } catch { + return false; + } +} + +export function validateBrowserManagedCapability( + capability: BrowserManagedDownloadCapability, + input: DeliveryInput, + nowEpochMs: number, +): BrowserDataResult { + if ( + input.source.kind !== "BROWSER_MANAGED_RESOURCE" || + !capability || + typeof capability !== "object" || + typeof capability.href !== "string" || + capability.href.length === 0 || + capability.capabilityReceipt !== + input.source.capabilityReceipt || + capability.resourceId !== input.source.resourceId || + capability.mediaType.trim().toLowerCase() !== + input.mediaType || + capability.safeExtension.trim().toLowerCase() !== + input.safeExtension || + !isPositiveSafeInteger(capability.maxBytes) || + capability.maxBytes > input.maxTransferBytes || + !Number.isSafeInteger(capability.expiresAtEpochMs) || + !Number.isSafeInteger(nowEpochMs) || + (capability.expectedSha256 !== undefined && + !SHA256.test(capability.expectedSha256)) || + (input.integrity === "REQUIRED" && + capability.expectedSha256 === undefined) + ) { + return browserDataFailure("POLICY_REJECTED", "DOWNLOAD"); + } + if (capability.expiresAtEpochMs <= nowEpochMs) { + return browserDataFailure("EXPIRED_RESOURCE", "DOWNLOAD", { + recovery: "RETRY", + }); + } + return browserDataSuccess( + Object.freeze({ + capabilityReceipt: capability.capabilityReceipt, + href: capability.href, + resourceId: capability.resourceId, + mediaType: input.mediaType, + safeExtension: input.safeExtension, + maxBytes: capability.maxBytes, + ...(capability.expectedSha256 + ? { + expectedSha256: + capability.expectedSha256.toLowerCase(), + } + : {}), + expiresAtEpochMs: capability.expiresAtEpochMs, + }), + ); +} + +export type ResolvedBrowserManagedTarget = Readonly<{ absoluteHref: string }>; + +/** + * STO-02. Parse once, canonicalize, then execute the canonical value. + * + * Returning a boolean and handing the raw href to the host let the browser + * re-resolve a relative target against `document.baseURI`, so a hostile + * `` could send the navigation to a different origin than the one this + * policy just approved. + */ +export function resolveBrowserManagedTarget( + href: string, + baseOrigin: string, + policy: Readonly<{ + allowCrossOrigin: boolean; + allowQuery: boolean; + }>, +): BrowserDataResult { + let base: URL; + let target: URL; + try { + base = new URL(baseOrigin); + target = new URL(href, base); + } catch { + return browserDataFailure("POLICY_REJECTED", "DOWNLOAD"); + } + if ( + !["http:", "https:"].includes(target.protocol) || + target.username.length > 0 || + target.password.length > 0 || + (!policy.allowCrossOrigin && target.origin !== base.origin) || + (!policy.allowQuery && target.search.length > 0) || + target.hash.length > 0 + ) { + return browserDataFailure("POLICY_REJECTED", "DOWNLOAD"); + } + return browserDataSuccess( + Object.freeze({ absoluteHref: target.href }), + ); +} + +function safeOpaqueId(value: unknown): value is string { + if (typeof value !== "string") return false; + if (value.length === 0 || value.length > 256) return false; + for (const character of value) { + const code = character.codePointAt(0); + if (code === undefined || code <= 0x20 || code === 0x7f) { + return false; + } + } + return true; +} diff --git a/src/adapters/browser-files/file-observer.ts b/src/adapters/browser-files/file-observer.ts index d03ac2d5..e2026aa0 100644 --- a/src/adapters/browser-files/file-observer.ts +++ b/src/adapters/browser-files/file-observer.ts @@ -6,6 +6,8 @@ import type { } from "../../application/ports/browser-file-storage/shared.ts"; import { observeBrowserData } from "../browser-file-storage/result.ts"; +export { browserDataByteBucket as byteBucket } from "../../application/ports/browser-file-storage/shared.ts"; + type BrowserFileObservation = Readonly<{ operation: BrowserDataOperation; outcome: "SUCCESS" | "DISMISSED" | "FAILED"; @@ -19,19 +21,6 @@ type BrowserFileObservation = Readonly<{ */ export type BrowserFileObserver = BrowserDataObserver; -export function byteBucket( - byteLength: number | null, -): BrowserFileObservation["byteBucket"] | undefined { - if (byteLength === null || !Number.isSafeInteger(byteLength) || byteLength < 0) { - return undefined; - } - if (byteLength === 0) return "ZERO"; - if (byteLength < 1_048_576) return "LT1MIB"; - if (byteLength < 10_485_760) return "1_TO_9MIB"; - if (byteLength < 104_857_600) return "10_TO_99MIB"; - return "GTE100MIB"; -} - export function observeBrowserFile( observer: BrowserFileObserver | undefined, observation: BrowserFileObservation, diff --git a/src/adapters/browser-files/file-policy.ts b/src/adapters/browser-files/file-policy.ts index 455a4f57..988fc285 100644 --- a/src/adapters/browser-files/file-policy.ts +++ b/src/adapters/browser-files/file-policy.ts @@ -40,6 +40,20 @@ export type RegisteredFileInspectionPolicy = Readonly<{ }>; const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/(?:[a-z0-9!#$&^_.+-]+|\*)$/i; +/** + * Q-6.2-12. The shared browser-file copies of three checks that used to be + * redefined per module: an exact `type/subtype` media type (no wildcard), a + * generated opaque token (file reference, receipt or transfer ID) and a + * positive safe integer limit. + */ +export const EXACT_MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i; + +export function isSafeGeneratedToken(value: string): boolean { + return /^[a-z0-9][a-z0-9:_-]{0,127}$/i.test(value); +} + +export { isPositiveSafeInteger } from "../../application/ports/browser-file-storage/shared.ts"; + const EXTENSION = /^\.[a-z0-9][a-z0-9+_-]{0,15}(?:\.[a-z0-9][a-z0-9+_-]{0,15})?$/i; const POLICY_TOKEN = /^[a-z0-9][a-z0-9._:-]{0,127}$/i; @@ -354,12 +368,7 @@ export function sanitizeSuggestedFileName( base = fallbackBase.length > 0 ? fallbackBase : "download"; } - while ( - base.length > 0 && - utf8Length(`${base}${safeExtension}`) > maxUtf8Bytes - ) { - base = Array.from(base).slice(0, -1).join("").trimEnd(); - } + base = truncateUtf8(base, maxUtf8Bytes - utf8Length(safeExtension)); if (base.length === 0 || WINDOWS_RESERVED.test(base)) { base = fallbackBase; } @@ -401,21 +410,36 @@ function utf8Length(value: string): number { return new TextEncoder().encode(value).byteLength; } +/** + * Q-6.2-10. The longest code-point prefix within `maxBytes` UTF-8 bytes, with + * trailing whitespace removed once it was cut; `value` itself when it fits. + * One pass: re-encoding the whole name per dropped code point was O(n^2). + */ +function truncateUtf8(value: string, maxBytes: number): string { + let bytes = 0; + let end = 0; + for (const character of value) { + const codePoint = character.codePointAt(0) ?? 0; + // A lone surrogate encodes as U+FFFD, three bytes, like any BMP point. + bytes += + codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4; + if (bytes > maxBytes) return value.slice(0, end).trimEnd(); + end += character.length; + } + return value; +} + function fitFallbackBaseName( configured: string, extension: string, maxUtf8Bytes: number, ): string { - let fallback = + const fallback = truncateUtf8( configured.length > 0 && !WINDOWS_RESERVED.test(configured) ? configured - : "download"; - while ( - fallback.length > 0 && - utf8Length(`${fallback}${extension}`) > maxUtf8Bytes - ) { - fallback = Array.from(fallback).slice(0, -1).join("").trimEnd(); - } + : "download", + maxUtf8Bytes - utf8Length(extension), + ); return fallback.length > 0 && !WINDOWS_RESERVED.test(fallback) ? fallback : "a"; diff --git a/src/adapters/browser-files/object-url-lease.ts b/src/adapters/browser-files/object-url-lease.ts index d5c71aef..c1d82060 100644 --- a/src/adapters/browser-files/object-url-lease.ts +++ b/src/adapters/browser-files/object-url-lease.ts @@ -20,6 +20,7 @@ import { type BrowserFileObserver, } from "./file-observer.ts"; import { BrowserFilePolicyRegistry } from "./browser-file-policy-registry.ts"; +import { EXACT_MEDIA_TYPE, isPositiveSafeInteger } from "./file-policy.ts"; export type ObjectUrlApi = Readonly<{ createObjectURL(blob: Blob): string; @@ -109,13 +110,6 @@ export class ObjectUrlLeaseRegistry { } const url = this.#createObjectURL(blob); if (typeof url !== "string" || url.length === 0) { - if (typeof url === "string" && url.length > 0) { - try { - this.#revokeObjectURL(url); - } catch { - // The invalid lease is rejected regardless of cleanup support. - } - } throw new DOMException( "Object URL allocation failed", "InvalidStateError", @@ -184,7 +178,6 @@ const DEFAULT_ACTIVE_CONTENT = new Set([ "text/html", "text/xml", ]); -const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i; export class BrowserTransientPreview implements TransientPreviewPort { readonly #resolveVerifiedFile: @@ -269,7 +262,7 @@ export class BrowserTransientPreview implements TransientPreviewPort { } const mediaType = resolved.value.mediaType.trim().toLowerCase(); if ( - !MEDIA_TYPE.test(mediaType) || + !EXACT_MEDIA_TYPE.test(mediaType) || !policy.allowedMediaTypes.has(mediaType) || this.#hardForbiddenMediaTypes.has(mediaType) ) { @@ -333,7 +326,3 @@ export class BrowserTransientPreview implements TransientPreviewPort { return result; } } - -function isPositiveSafeInteger(value: number): boolean { - return Number.isSafeInteger(value) && value > 0; -} diff --git a/src/adapters/browser-rpc/browser-rpc-runtime.ts b/src/adapters/browser-rpc/browser-rpc-runtime.ts index 1341c1df..5842a154 100644 --- a/src/adapters/browser-rpc/browser-rpc-runtime.ts +++ b/src/adapters/browser-rpc/browser-rpc-runtime.ts @@ -22,6 +22,7 @@ import { import type { InstalledBoundaryMapper } from "../../contracts/boundary-mapper.ts"; import { createFailure, + withFailureEffect, type AppFailure, type FailureKind, } from "../../contracts/errors.ts"; @@ -292,6 +293,7 @@ async function executeUnary( const { operation, profile, encoder, transport } = bound; const linked = linkedAbortController(context.signal); let attemptCount = 0; + let sent = false; const finish = ( result: Result, @@ -300,7 +302,11 @@ async function executeUnary( // R-06. Listener and timer cleanup happens exactly once, on every exit. linked.cleanup(); observe(dependencies, operation, outcome, attemptCount, result.ok ? 1 : 0); - return result; + // Q-6.3-9. Once a command reached the transport, no failure proves the + // server did not apply it, so it is never offered as a plain retry. + return !result.ok && sent && operation.semantics === "COMMAND" + ? failureResult(withFailureEffect(result.error, "MAYBE_APPLIED")) + : result; }; const generation = safeCapture(generationFence); @@ -350,6 +356,21 @@ async function executeUnary( } for (let attempt = 0; attempt < profile.maxAttempts; attempt += 1) { + // Q-6.3-9. A retry never outlives the scope generation that started it, + // so a previous user's request is not sent again after a logout. + if (attempt > 0 && !safeIsCurrent(generationFence, generation)) { + return finish( + failureResult( + callFailure( + operation, + attempt - 1, + "SCOPE_GENERATION_CHANGED", + "RPC_SCOPE_GENERATION_CHANGED", + ), + ), + "ABORTED", + ); + } attemptCount = attempt + 1; const attemptNow = safeNow(clock); if (attemptNow === CLOCK_FAILURE) { @@ -393,6 +414,7 @@ async function executeUnary( ? { idempotencyKey: context.idempotencyKey } : {}), }); + sent = true; const timed = await raceWithin( Promise.resolve().then(() => transport.invokeUnary!(call)), remainingMs, @@ -549,10 +571,30 @@ async function* executeServerStream( const deadlineAt = safeNowOrDeadline(clock, 0) + operation.totalDeadlineMs; const linked = linkedAbortController(context.signal); let iterator: AsyncIterator | null = null; - let lease: BrowserRpcServerStreamLease | null = null; + let registered: ActiveStreamLease | null = null; let observed = false; let messageCount = 0; + // R-01 / RPC-RR-01. Runs once, when the stream's own signal aborts. The + // lease's `cancel` is what actually stops the physical stream, and the entry + // is removed only once the transport confirms the physical stream closed. + // Until then the operation stays DRAINING and admits nothing new — a bounded + // wait here would re-open the very hole this registry exists to close. + const releaseRegistered = () => { + const entry = registered; + if (!entry) return; + try { + entry.cancel("stream-closed"); + } catch { + // A transport that refuses to cancel stays DRAINING below. + } + void entry.closed.then((confirmed) => { + if (confirmed && activeStreams.get(operation.operationId) === entry) { + activeStreams.delete(operation.operationId); + } + }); + }; + const finish = (outcome: BrowserRpcObservationOutcome) => { if (observed) return; observed = true; @@ -662,21 +704,28 @@ async function* executeServerStream( yield failureResult(protocolFailure(operation, 0)); return; } - lease = decodedLease; + const lease = decodedLease; // Registered at the moment the physical stream exists, not after a timeout. - activeStreams.set( - operation.operationId, - Object.freeze({ - streamId: lease.streamId, - cancel: lease.cancel, - // RPC-01. Only a fulfilled, contract-shaped receipt is evidence that the - // physical stream closed. Absorbing a rejection, a synchronous throw or - // a non-promise into `undefined` forged that evidence, and the registry - // then admitted a second stream for the same operation while the first - // was still running against the server. - closed: confirmPhysicalClosure(lease), - }), - ); + registered = Object.freeze({ + streamId: lease.streamId, + cancel: lease.cancel, + // RPC-01. Only a fulfilled, contract-shaped receipt is evidence that the + // physical stream closed. Absorbing a rejection, a synchronous throw or + // a non-promise into `undefined` forged that evidence, and the registry + // then admitted a second stream for the same operation while the first + // was still running against the server. + closed: confirmPhysicalClosure(lease), + }); + activeStreams.set(operation.operationId, registered); + // Q-6.3-9. A consumer that aborts and walks away without `return()` leaves + // this generator suspended at a `yield`, so `finally` never runs. The + // abort itself releases the physical stream. + if (linked.controller.signal.aborted) releaseRegistered(); + else { + linked.controller.signal.addEventListener("abort", releaseRegistered, { + once: true, + }); + } try { iterator = lease.frames[Symbol.asyncIterator](); } catch { @@ -842,38 +891,13 @@ async function* executeServerStream( } } finally { // R-01 / RPC-RR-01. The commit/admission generation is fenced immediately - // and listeners are released without waiting for the transport. - // `iterator.return()` is a cleanup request, not a lifecycle authority, so - // the lease's own `cancel` is what actually stops the physical stream. + // and listeners are released without waiting for the transport. The abort + // runs `releaseRegistered` (cancel + positive-close subscription) unless + // an earlier abort already did. RPC-02: that happens before any fallible + // cleanup, so a throwing `return` accessor cannot strand the entry. + // `iterator.return()` is a cleanup request, not a lifecycle authority. linked.controller.abort("stream-closed"); linked.cleanup(); - const registered = lease - ? activeStreams.get(operation.operationId) - : undefined; - if (registered && registered.streamId === lease?.streamId) { - try { - registered.cancel("stream-closed"); - } catch { - // A transport that refuses to cancel stays DRAINING below. - } - } - if (registered && registered.streamId === lease?.streamId) { - // RPC-02. The positive-close subscription is installed before any - // fallible cleanup. Running cleanup first meant a throwing `return` - // accessor could skip it entirely and strand the registry entry. - // The entry is removed only once the transport confirms the physical - // stream closed. Until then the operation stays DRAINING and admits - // nothing new — a bounded wait here would re-open the very hole this - // registry exists to close. - void registered.closed.then((confirmed) => { - if ( - confirmed && - activeStreams.get(operation.operationId) === registered - ) { - activeStreams.delete(operation.operationId); - } - }); - } const returnIterator = safeIteratorReturn(iterator); if (returnIterator) { const cleanup = Promise.resolve() @@ -882,7 +906,7 @@ async function* executeServerStream( .catch(() => undefined); await boundedStreamCleanup(cleanup, clock, STREAM_CLEANUP_BOUND_MS); } - if (registered && registered.streamId === lease?.streamId) { + if (registered) { await boundedStreamCleanup( registered.closed.then(() => undefined), clock, @@ -1465,22 +1489,6 @@ function decodeTransportFailure( }); } -function validTransportFailure( - failure: unknown, -): failure is BrowserRpcTransportFailure { - if (!failure || typeof failure !== "object" || !("code" in failure)) { - return false; - } - const candidate = failure as BrowserRpcTransportFailure; - return ( - TRANSPORT_FAILURE_CODES.has(candidate.code) && - (candidate.retryAfterMs === undefined || - (Number.isSafeInteger(candidate.retryAfterMs) && - candidate.retryAfterMs >= 0 && - candidate.retryAfterMs <= BROWSER_RPC_HARD_LIMITS.maxRetryAfterMs)) - ); -} - const TRANSPORT_FAILURE_CODES = new Set([ "NETWORK_UNREACHABLE", diff --git a/src/adapters/browser-transfer/image-cdn/README.md b/src/adapters/browser-transfer/image-cdn/README.md index fcb38ef5..eb7dc932 100644 --- a/src/adapters/browser-transfer/image-cdn/README.md +++ b/src/adapters/browser-transfer/image-cdn/README.md @@ -133,7 +133,10 @@ and every CDN origin must differ from it. This is required because an `anonymous` image request omits credentials only when it is cross-origin. Private descriptors must be backend-signed, remain above the configured minimum TTL at every resolve, and use an eager, non-low-priority -`PRIMARY_REQUIRED` preset. Digest and signature verification share one +`PRIMARY_REQUIRED` preset. A `PRIMARY_REQUIRED` preset must use `fit` +`cover`, `contain` or `fill`: the probe expects the exact primary pixel size, +and `inside`/`outside` keep the source ratio, so the registry rejects that +combination at composition time. Digest and signature verification share one composition-owned deadline and race the caller's abort signal. The probe sends no credentials, rejects any final URL other than the exact signed URL, and requires the private response to declare the flag-only directive diff --git a/src/adapters/browser-transfer/image-cdn/browser-image-probe.ts b/src/adapters/browser-transfer/image-cdn/browser-image-probe.ts index 99fd66e9..2c22434c 100644 --- a/src/adapters/browser-transfer/image-cdn/browser-image-probe.ts +++ b/src/adapters/browser-transfer/image-cdn/browser-image-probe.ts @@ -7,11 +7,16 @@ import { browserDataSuccess, } from "../../browser-file-storage/result.ts"; import { + cancelBody, + cancelReader, createAbortableOperation, snapshotAbortTimers, - type AbortTimerSnapshot, + type AbortableOperation, } from "../../platform/abortable-operation.ts"; import { parseStaticImageHeaderMetadata } from "./image-header-metadata.ts"; +import { + isPositiveSafeInteger as positiveSafeInteger, +} from "../../../application/ports/browser-file-storage/shared.ts"; export type DecodedImageFacade = Readonly<{ width: number; @@ -49,7 +54,10 @@ export function createBrowserImageProbe( const createBitmap = dependencies.createBitmap ?? (typeof createImageBitmap === "function" - ? async (image: Blob) => createImageBitmap(image) + ? // Q-6.1-8. The header parser reads pre-rotation dimensions, so the + // decode must not apply EXIF/irot orientation and swap them. + async (image: Blob) => + createImageBitmap(image, { imageOrientation: "none" }) : undefined); const timeoutMs = dependencies.timeoutMs ?? DEFAULT_TIMEOUT_MS; const timers = snapshotAbortTimers( @@ -100,11 +108,15 @@ export function createBrowserImageProbe( return browserDataFailure("UNSUPPORTED", "IMAGE_RESOLVE"); } - const scope = createProbeAbortScope( - request.signal, + // X-AUDIT-02 / TR-RR-05. The probe is owned by the shared abort + // primitive: the caller listener and the deadline are installed + // together, so a throwing scheduler closes the probe instead of + // rejecting `probe()`. + const scope = createAbortableOperation({ + signal: request.signal, timeoutMs, - timers, - ); + ...timers, + }); let response: Response | undefined; try { if (scope.signal.aborted) { @@ -124,8 +136,8 @@ export function createBrowserImageProbe( signal: scope.signal, }), ); - response = await scope.await(fetchTask, (lateResponse) => { - cancelResponseBody(lateResponse); + response = await awaitOwned(scope, fetchTask, (lateResponse) => { + cancelBody(lateResponse); }); } catch { return signalFailure(request.signal); @@ -140,7 +152,7 @@ export function createBrowserImageProbe( response.url !== url.href || !validResponseHeaders(response, request) ) { - cancelResponseBody(response); + cancelBody(response); return browserDataFailure( "POLICY_REJECTED", "IMAGE_RESOLVE", @@ -152,10 +164,10 @@ export function createBrowserImageProbe( bytes = await readBoundedBody( response, request.maxEncodedBytes, - scope.signal, + scope, ); } catch (error) { - if (request.signal.aborted || scope.timedOut()) { + if (request.signal.aborted || unanswered(scope)) { return signalFailure(request.signal); } return error instanceof EncodedBodyLimitError @@ -227,18 +239,12 @@ export function createBrowserImageProbe( type: request.expectedMediaType, }), ); - bitmap = await scope.await(decodeTask, closeBitmap); + bitmap = await awaitOwned(scope, decodeTask, closeBitmap); if ( - !positiveSafeInteger(bitmap.width) || - !positiveSafeInteger(bitmap.height) || + // The header dimensions are positive and already within the + // decode budget, so an exact match is the whole check. bitmap.width !== metadata.width || - bitmap.height !== metadata.height || - !withinDecodeBudget( - bitmap.width, - bitmap.height, - request.maxDecodedPixels, - request.maxDecodedBytes, - ) + bitmap.height !== metadata.height ) { return browserDataFailure( "INTEGRITY_FAILED", @@ -255,7 +261,7 @@ export function createBrowserImageProbe( }), ); } catch { - return request.signal.aborted || scope.timedOut() + return request.signal.aborted || unanswered(scope) ? signalFailure(request.signal) : browserDataFailure( "INTEGRITY_FAILED", @@ -265,7 +271,7 @@ export function createBrowserImageProbe( if (bitmap) closeBitmap(bitmap); } } finally { - scope.release(); + scope.close(); } }, }); @@ -474,7 +480,7 @@ class EncodedBodyLimitError extends Error {} async function readBoundedBody( response: Response, maximumBytes: number, - signal: AbortSignal, + scope: AbortableOperation, ): Promise { if (!response.body) { throw new TypeError("Image response body is unavailable."); @@ -484,8 +490,9 @@ async function readBoundedBody( let total = 0; try { while (true) { - if (signal.aborted) throw abortException(); - const next = await readOrAbort(reader.read(), signal); + if (scope.signal.aborted) throw abortException(); + // A late chunk is dropped: the bytes are only accumulated below. + const next = await awaitOwned(scope, reader.read(), () => undefined); if (next.done) break; if (!(next.value instanceof Uint8Array)) { throw new TypeError("Image response chunk is invalid."); @@ -515,90 +522,28 @@ async function readBoundedBody( return bytes; } -type ProbeAbortScope = Readonly<{ - signal: AbortSignal; - /** True once a deadline, or a deadline that could not be installed, ended it. */ - timedOut(): boolean; - /** - * Awaits `task` under this scope's ownership. A late value is compensated - * exactly once; a terminal owner raises the scope's abort exception. - */ - await( - task: Promise, - onLateValue: (value: Value) => void, - ): Promise; - release(): void; -}>; - /** - * X-AUDIT-02 / TR-RR-05. The probe scope is the shared abort primitive with - * this subsystem's vocabulary on top. Owning a private copy meant the caller - * listener was attached before the timer was installed, so a scheduler that - * threw rejected the public `probe()` promise and left the listener behind. + * `CLOSED` here means the deadline could never be installed, so the probe was + * never bounded: operationally the same unanswered host as a deadline. */ -function createProbeAbortScope( - externalSignal: AbortSignal, - timeoutMs: number, - timers: AbortTimerSnapshot, -): ProbeAbortScope { - const operation = createAbortableOperation({ - signal: externalSignal, - timeoutMs, - setTimer: timers.setTimer, - clearTimer: timers.clearTimer, - }); - return Object.freeze({ - signal: operation.signal, - // `CLOSED` here means the deadline could never be installed, so the probe - // was never bounded: operationally the same unanswered host as a deadline. - timedOut: () => - operation.terminal() !== "CALLER_ABORT" && operation.terminal() !== null, - async await( - task: Promise, - onLateValue: (value: Value) => void, - ): Promise { - const raced = await operation.race(task, onLateValue); - if (raced.kind === "VALUE") return raced.value; - if (raced.kind === "REJECTED") throw raced.reason; - throw abortException(); - }, - release: () => operation.close(), - }); +function unanswered(scope: AbortableOperation): boolean { + const terminal = scope.terminal(); + return terminal !== null && terminal !== "CALLER_ABORT"; } /** - * A single read raced against the probe's ownership. A late chunk is dropped: - * the bytes are only ever accumulated by the caller below. + * Awaits `task` under the probe's ownership. A late value is compensated + * exactly once; a terminal owner raises the probe's abort exception. */ -function readOrAbort( +async function awaitOwned( + scope: AbortableOperation, task: Promise, - signal: AbortSignal, + onLateValue: (value: Value) => void, ): Promise { - return new Promise((resolve, reject) => { - let settled = false; - const onAbort = () => { - if (settled) return; - settled = true; - reject(abortException()); - }; - signal.addEventListener("abort", onAbort, { once: true }); - void task.then( - (value) => { - signal.removeEventListener("abort", onAbort); - if (!settled) { - settled = true; - resolve(value); - } - }, - (error: unknown) => { - signal.removeEventListener("abort", onAbort); - if (!settled) { - settled = true; - reject(error); - } - }, - ); - }); + const raced = await scope.race(task, onLateValue); + if (raced.kind === "VALUE") return raced.value; + if (raced.kind === "REJECTED") throw raced.reason; + throw abortException(); } function signalFailure(externalSignal: AbortSignal) { @@ -612,25 +557,6 @@ function signalFailure(externalSignal: AbortSignal) { }); } -function cancelResponseBody(response: Response): void { - try { - const cancellation = response.body?.cancel(); - void cancellation?.catch(() => undefined); - } catch { - // Best-effort release cannot change the closed probe result. - } -} - -function cancelReader( - reader: ReadableStreamDefaultReader, -): void { - try { - void reader.cancel().catch(() => undefined); - } catch { - // Best-effort release cannot change the closed probe result. - } -} - function closeBitmap(bitmap: DecodedImageFacade): void { try { bitmap.close(); @@ -682,7 +608,3 @@ function isRasterMediaType( "image/webp", ].includes(value); } - -function positiveSafeInteger(value: number): boolean { - return Number.isSafeInteger(value) && value > 0; -} diff --git a/src/adapters/browser-transfer/image-cdn/image-cdn-policy.ts b/src/adapters/browser-transfer/image-cdn/image-cdn-policy.ts index 17e7853b..25f1634d 100644 --- a/src/adapters/browser-transfer/image-cdn/image-cdn-policy.ts +++ b/src/adapters/browser-transfer/image-cdn/image-cdn-policy.ts @@ -4,6 +4,11 @@ import type { ImagePresetReference, ImageRasterMediaType, } from "../../../application/ports/browser-transfer/image-cdn.ts"; +import { + isPositiveSafeInteger as positiveSafeInteger, + isNonNegativeSafeInteger as nonNegativeSafeInteger, + hasControlCharacter, +} from "../../../application/ports/browser-file-storage/shared.ts"; export type ImageCdnOriginPolicy = Readonly<{ originKey: string; @@ -476,7 +481,7 @@ function snapshotPreset( !positiveSafeInteger(input.quality) || input.quality > hardLimits.maxQuality || !SAFE_SIZES.test(input.sizes) || - hasControlCharacters(input.sizes) || + hasControlCharacter(input.sizes) || !["eager", "lazy"].includes(input.loading) || !["async", "sync"].includes(input.decoding) || !["high", "low", "auto"].includes(input.fetchPriority) || @@ -485,6 +490,10 @@ function snapshotPreset( "strict-origin-when-cross-origin", ].includes(input.referrerPolicy) || !["NONE", "PRIMARY_REQUIRED"].includes(input.probeMode) || + // Q-6.1-7 / D-12. The probe expects the exact primary pixel size, which + // only these fits produce; inside/outside keep the source ratio. + (input.probeMode === "PRIMARY_REQUIRED" && + !["cover", "contain", "fill"].includes(input.fit)) || typeof input.allowUpscale !== "boolean" || !positiveSafeInteger(input.maxTransformedPixels) || input.maxTransformedPixels > hardLimits.maxTransformedPixels || @@ -722,14 +731,6 @@ function positiveDpr(value: number): boolean { ); } -function positiveSafeInteger(value: number): boolean { - return Number.isSafeInteger(value) && value > 0; -} - -function nonNegativeSafeInteger(value: number): boolean { - return Number.isSafeInteger(value) && value >= 0; -} - function hasExactOwnKeys( input: unknown, keys: readonly string[], @@ -744,10 +745,3 @@ function hasExactOwnKeys( actual.every((key, index) => key === expected[index]) ); } - -function hasControlCharacters(value: string): boolean { - return [...value].some((character) => { - const codePoint = character.codePointAt(0) ?? 0; - return codePoint < 0x20 || codePoint === 0x7f; - }); -} diff --git a/src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts b/src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts index 33b297db..6f598ad1 100644 --- a/src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts +++ b/src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts @@ -71,6 +71,7 @@ type IssuedDescriptorSnapshot = BackendIssuedImageAsset; const OPAQUE_TOKEN = /^[A-Za-z0-9_-]{8,128}$/u; const SIGNATURE = /^[A-Za-z0-9_-]{16,512}$/u; const SHA256_HEX = /^[a-f0-9]{64}$/u; +const REGISTRY_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; const PUBLIC_DESCRIPTOR_KEYS = Object.freeze([ "kind", "originKey", @@ -145,19 +146,18 @@ export function createImageCdnRuntime( dependencies.capabilityVerifier, ); if (dependencies.capabilityVerifier) { + let covered = false; try { - if ( - !verifyCapability || - !acceptsCapabilityKey || - [...capabilityPolicy.acceptedKeyIds].some( - (keyId) => acceptsCapabilityKey(keyId) !== true, - ) - ) { - throw new TypeError( - "Image capability verifier registry does not cover policy keys.", + covered = + !!verifyCapability && + !!acceptsCapabilityKey && + [...capabilityPolicy.acceptedKeyIds].every( + (keyId) => acceptsCapabilityKey(keyId) === true, ); - } } catch { + // A throwing registry covers nothing. + } + if (!covered) { throw new TypeError( "Image capability verifier registry does not cover policy keys.", ); @@ -943,17 +943,11 @@ function snapshotIssuedDescriptor( allowedPresetBindingIds.some( (bindingId) => typeof bindingId !== "string" || - !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test( - bindingId, - ), + !REGISTRY_ID.test(bindingId), ) || snapshot.signature.algorithm !== "ECDSA_P256_SHA256" || - !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test( - snapshot.issuer, - ) || - !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test( - snapshot.signature.keyId, - ) || + !REGISTRY_ID.test(snapshot.issuer) || + !REGISTRY_ID.test(snapshot.signature.keyId) || !SHA256_HEX.test( snapshot.signature.capabilityBindingDigestHex, ) || @@ -1062,34 +1056,25 @@ function createCapabilityVerificationDeadline( timeoutMs: number, scheduler: ImageCapabilityVerificationScheduler, ): ImageCapabilityVerificationDeadline { - const controller = new AbortController(); - let released = false; - const abortListeners = new Map void>(); - const activeSignals = signals.filter( - (signal): signal is AbortSignal => signal !== undefined, + const scope = combineImageRuntimeAbortSignals( + signals.filter( + (signal): signal is AbortSignal => signal !== undefined, + ), ); - for (const signal of new Set(activeSignals)) { - const onAbort = () => controller.abort(signal.reason); - abortListeners.set(signal, onAbort); - signal.addEventListener("abort", onAbort, { once: true }); - if (signal.aborted) onAbort(); - } - + let released = false; let timeoutHandle: unknown; try { timeoutHandle = scheduler.setTimeout(() => { if (released) return; - controller.abort(capabilityVerificationAbortException()); + scope.abort(capabilityVerificationAbortException()); }, timeoutMs); } catch (error) { - for (const [signal, onAbort] of abortListeners) { - signal.removeEventListener("abort", onAbort); - } + scope.release(); throw error; } return Object.freeze({ - signal: controller.signal, + signal: scope.signal, release() { if (released) return; released = true; @@ -1098,10 +1083,7 @@ function createCapabilityVerificationDeadline( } catch { // Scheduler cleanup cannot alter an already closed adapter result. } - for (const [signal, onAbort] of abortListeners) { - signal.removeEventListener("abort", onAbort); - } - abortListeners.clear(); + scope.release(); }, }); } @@ -1139,7 +1121,11 @@ function awaitImageRuntimeAbort( function combineImageRuntimeAbortSignals( signals: readonly AbortSignal[], -): Readonly<{ signal: AbortSignal; release(): void }> { +): Readonly<{ + signal: AbortSignal; + abort(reason: unknown): void; + release(): void; +}> { const controller = new AbortController(); const abortListeners = new Map void>(); for (const signal of new Set(signals)) { @@ -1151,6 +1137,7 @@ function combineImageRuntimeAbortSignals( let released = false; return Object.freeze({ signal: controller.signal, + abort: (reason: unknown) => controller.abort(reason), release() { if (released) return; released = true; diff --git a/src/adapters/browser-transfer/image-cdn/image-header-metadata.ts b/src/adapters/browser-transfer/image-cdn/image-header-metadata.ts index 2e5353e8..d50fab37 100644 --- a/src/adapters/browser-transfer/image-cdn/image-header-metadata.ts +++ b/src/adapters/browser-transfer/image-cdn/image-header-metadata.ts @@ -73,8 +73,6 @@ function parsePng( const interlace = bytes[payloadStart + 12]; if ( !dimensions || - bitDepth === undefined || - colorType === undefined || !validPngColorDepth(colorType, bitDepth) || compression !== 0 || filter !== 0 || @@ -144,7 +142,7 @@ function parseJpeg( if (offset >= bytes.byteLength) return null; const marker = bytes[offset]; offset += 1; - if (marker === undefined || marker === 0x00) return null; + if (marker === 0x00) return null; if (marker === 0xd9) return null; if (marker === 0xda) return dimensions; if ( @@ -227,7 +225,6 @@ function parseWebp( chunkIndex !== 0 || extendedHeaderSeen || length !== 10 || - bytes[payloadStart] === undefined || (bytes[payloadStart] & 0xc3) !== 0 ) { return null; @@ -260,15 +257,7 @@ function parseWebp( const byte2 = bytes[payloadStart + 2]; const byte3 = bytes[payloadStart + 3]; const byte4 = bytes[payloadStart + 4]; - if ( - byte1 === undefined || - byte2 === undefined || - byte3 === undefined || - byte4 === undefined || - (byte4 & 0xe0) !== 0 - ) { - return null; - } + if ((byte4 & 0xe0) !== 0) return null; candidate = validDimensions( 1 + byte1 + ((byte2 & 0x3f) << 8), 1 + @@ -306,14 +295,8 @@ function parseAvif( return null; } const fileType = boxes[0]; - const fileTypeLength = fileType - ? fileType.payloadEnd - fileType.payloadStart - : 0; - if ( - !fileType || - fileTypeLength < 8 || - (fileTypeLength - 8) % 4 !== 0 - ) { + const fileTypeLength = fileType.payloadEnd - fileType.payloadStart; + if (fileTypeLength < 8 || (fileTypeLength - 8) % 4 !== 0) { return null; } const brands: string[] = [ @@ -343,7 +326,6 @@ function parseAvif( const metadataBox = metadataBoxes[0]; if ( metadataBoxes.length !== 1 || - !metadataBox || metadataBox.payloadStart + 4 > metadataBox.payloadEnd || !zeroFullBoxFlags(bytes, metadataBox.payloadStart) ) { @@ -413,9 +395,7 @@ function parseAvif( const dimensions = state.properties.get(propertyIndex); if (dimensions) associatedExtents.push(dimensions); } - return associatedExtents.length === 1 - ? (associatedExtents[0] ?? null) - : null; + return associatedExtents.length === 1 ? associatedExtents[0] : null; } type IsoBox = Readonly<{ @@ -532,11 +512,7 @@ function parseAvifItemProperties( (child) => child.type === "ipma", ); const propertyContainer = propertyContainers[0]; - if ( - propertyContainers.length !== 1 || - associationBoxes.length < 1 || - !propertyContainer - ) { + if (propertyContainers.length !== 1 || associationBoxes.length < 1) { return false; } const properties = parseBoxes( @@ -581,9 +557,7 @@ function parseAvifPropertyAssociations( const version = bytes[start]; if (version !== 0 && version !== 1) return false; const flags = - ((bytes[start + 1] ?? 0) << 16) | - ((bytes[start + 2] ?? 0) << 8) | - (bytes[start + 3] ?? 0); + (bytes[start + 1] << 16) | (bytes[start + 2] << 8) | bytes[start + 3]; if ((flags & ~1) !== 0) return false; const wideAssociation = (flags & 1) === 1; const view = dataView(bytes); @@ -598,7 +572,6 @@ function parseAvifPropertyAssociations( : view.getUint32(offset); offset += itemIdBytes; const associationCount = bytes[offset]; - if (associationCount === undefined) return false; offset += 1; const propertyIndices: number[] = []; for ( @@ -609,9 +582,7 @@ function parseAvifPropertyAssociations( const associationBytes = wideAssociation ? 2 : 1; if (offset + associationBytes > end) return false; const encoded = - associationBytes === 2 - ? view.getUint16(offset) - : (bytes[offset] ?? 0); + associationBytes === 2 ? view.getUint16(offset) : bytes[offset]; const propertyIndex = encoded & (wideAssociation ? 0x7fff : 0x7f); offset += associationBytes; @@ -694,35 +665,23 @@ function validDimensions( : null; } +/** Callers pass an offset whose three bytes lie inside a checked chunk. */ function readUint24LittleEndian( bytes: Uint8Array, offset: number, ): number { - const byte0 = bytes[offset]; - const byte1 = bytes[offset + 1]; - const byte2 = bytes[offset + 2]; - if ( - byte0 === undefined || - byte1 === undefined || - byte2 === undefined - ) { - return Number.NaN; - } - return byte0 | (byte1 << 8) | (byte2 << 16); + return ( + bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) + ); } +/** Callers pass a range that the surrounding length checks keep in bounds. */ function ascii( bytes: Uint8Array, start: number, end: number, ): string { - let value = ""; - for (let offset = start; offset < end; offset += 1) { - const byte = bytes[offset]; - if (byte === undefined) return ""; - value += String.fromCharCode(byte); - } - return value; + return String.fromCharCode(...bytes.subarray(start, end)); } function dataView(bytes: Uint8Array): DataView { diff --git a/src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts b/src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts index 86582cf1..e984e61c 100644 --- a/src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts +++ b/src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts @@ -87,8 +87,7 @@ export function createP256ImageCapabilityVerifier( return false; } try { - const signatureBytes = new Uint8Array(signature.byteLength); - signatureBytes.set(signature); + // `decodeBase64Url` already returns an owned, exactly sized buffer. const payloadBytes = new Uint8Array( request.canonicalPayload.byteLength, ); @@ -96,7 +95,7 @@ export function createP256ImageCapabilityVerifier( return await verify( { name: "ECDSA", hash: "SHA-256" }, key, - signatureBytes.buffer, + signature.buffer, payloadBytes.buffer, ); } catch { @@ -106,7 +105,7 @@ export function createP256ImageCapabilityVerifier( }); } -function decodeBase64Url(value: string): Uint8Array | null { +function decodeBase64Url(value: string): Uint8Array | null { if ( !/^[A-Za-z0-9_-]+$/u.test(value) || value.length % 4 === 1 @@ -119,9 +118,8 @@ function decodeBase64Url(value: string): Uint8Array | null { let accumulator = 0; let bitCount = 0; for (const character of value) { - const index = alphabet.indexOf(character); - if (index < 0) return null; - accumulator = (accumulator << 6) | index; + // The pattern above admits only alphabet characters. + accumulator = (accumulator << 6) | alphabet.indexOf(character); bitCount += 6; if (bitCount >= 8) { bitCount -= 8; diff --git a/src/adapters/browser-transfer/presigned/http-common.ts b/src/adapters/browser-transfer/presigned/http-common.ts new file mode 100644 index 00000000..8cbe3841 --- /dev/null +++ b/src/adapters/browser-transfer/presigned/http-common.ts @@ -0,0 +1,236 @@ +import { + createAbortableOperation, + type AbortTimerSnapshot, +} from "../../platform/abortable-operation.ts"; +import type { + BrowserDataFailureCode, + BrowserDataObserver, + BrowserDataOperation, + BrowserDataRecovery, + BrowserDataResult, +} from "../../../application/ports/browser-file-storage/shared.ts"; +import { browserDataByteBucket as byteBucket } from "../../../application/ports/browser-file-storage/shared.ts"; +import type { Result } from "../../../contracts/result.ts"; +import { + browserDataFailure, + observeBrowserData, +} from "../../browser-file-storage/result.ts"; + +/** + * Q-6.1-9. HTTP mechanics shared by the presigned executor (object-store + * GET/PUT) and the capability provider (BFF issuance). They were two + * near-identical copies whose status table had already drifted apart. + */ + +export { byteBucket }; + +/** BT-PRE-03. The scope ended before the task settled. */ +export const SCOPE_ENDED = Symbol("presigned-scope-ended"); + +export type PresignedAbortScope = ReturnType; + +/** + * TR-RR-01 / TR-RR-05. A thin projection of the shared + * `createAbortableOperation` primitive into this subsystem's vocabulary. + * + * `abort()` exists, so `close()` on a download can actually stop a pending + * fetch instead of only dropping listeners; and additional ownership signals — + * a consumer's stream signal — are composed into the same operation *before* + * any I/O starts, so an already-aborted consumer never causes a fetch. + */ +export function createAbortScope( + external: AbortSignal, + timeoutMs: number, + timers: AbortTimerSnapshot, + additionalSignals: readonly AbortSignal[] = [], +) { + const operation = createAbortableOperation({ + signal: external, + timeoutMs, + setTimer: timers.setTimer, + clearTimer: timers.clearTimer, + }); + const releases: (() => void)[] = []; + for (const extra of additionalSignals) { + if (!extra) continue; + if (extra.aborted) { + operation.close(); + continue; + } + const onAbort = () => operation.close(); + try { + extra.addEventListener("abort", onAbort, { once: true }); + releases.push(() => { + try { + extra.removeEventListener("abort", onAbort); + } catch { + // A hostile signal facade cannot block the rest of cleanup. + } + }); + } catch { + // A signal that refuses a listener cannot bound this operation, so the + // operation closes rather than running unbounded. + operation.close(); + } + } + const end = () => { + operation.close(); + for (const release of releases.splice(0)) release(); + }; + return Object.freeze({ + signal: operation.signal, + timedOut: () => operation.terminal() === "DEADLINE", + /** Bounds a fetch that ignores its signal; a late response is cancelled. */ + async race(task: Promise): Promise { + const outcome = await operation.race(task, (value) => { + const body = ( + value as { body?: { cancel(): Promise } | null } | null + )?.body; + void body?.cancel().catch(() => undefined); + }); + if (outcome.kind === "VALUE") return outcome.value; + // A collaborator's own rejection stays a rejection: the caller's existing + // catch classifies it, and it is never forged into a cancellation. + if (outcome.kind === "REJECTED") throw outcome.reason; + return SCOPE_ENDED; + }, + /** TR-RR-01. Ends the physical work, not just the bookkeeping. */ + abort: end, + release: end, + }); +} + +export function readWithSignal( + reader: ReadableStreamDefaultReader, + signal: AbortSignal, +): Promise> { + if (signal.aborted) { + return Promise.reject(new DOMException("Aborted", "AbortError")); + } + return new Promise((resolve, reject) => { + const onAbort = () => { + reject(new DOMException("Aborted", "AbortError")); + }; + signal.addEventListener("abort", onAbort, { once: true }); + reader.read().then( + (result) => { + signal.removeEventListener("abort", onAbort); + resolve(result); + }, + (error: unknown) => { + signal.removeEventListener("abort", onAbort); + reject(error); + }, + ); + }); +} + +/** + * A plain decimal `Content-Length`. `Number()` alone accepted `"5e0"`, + * `"0x5"`, `"+5"` and `""`. An absent header is `null` unless the caller's + * binding allows an implicit zero. + */ +export function normalizedContentLength( + value: string | null, + allowImplicitZero = false, +): number | null { + if (value === null) return allowImplicitZero ? 0 : null; + const trimmed = value.trim(); + if (!/^(?:0|[1-9][0-9]{0,15})$/.test(trimmed)) return null; + const length = Number(trimmed); + return Number.isSafeInteger(length) ? length : null; +} + +/** + * One status table for both HTTP exchanges. Presigned capabilities are + * single-use, so every recoverable refusal — an expired or rejected signature + * (401/403), a conflict, a gone resource or a transient 429/5xx — is recovered + * by issuing a new capability, never by replaying the same one. + */ +export function statusFailure( + status: number, +): BrowserDataResult { + let code: BrowserDataFailureCode = "UNAVAILABLE"; + let recovery: BrowserDataRecovery = "REISSUE_CAPABILITY"; + let retryable = status === 429 || status >= 500; + if (status === 401 || status === 403) { + code = "PERMISSION_DENIED"; + retryable = false; + } else if (status === 404) { + code = "NOT_FOUND"; + recovery = "NONE"; + retryable = false; + } else if (status === 409) { + code = "CONFLICT"; + retryable = false; + } else if (status === 410) { + code = "EXPIRED_RESOURCE"; + retryable = false; + } else if (status === 413) { + code = "LIMIT_EXCEEDED"; + recovery = "NONE"; + retryable = false; + } else if (status >= 400 && status < 500 && status !== 429) { + code = "POLICY_REJECTED"; + recovery = "NONE"; + retryable = false; + } + return browserDataFailure(code, "PRESIGNED_TRANSFER", { + retryable, + recovery, + }); +} + +export function transferFailure( + externalSignal: AbortSignal, + timedOut: boolean, +): BrowserDataResult { + if (externalSignal.aborted) { + return browserDataFailure("ABORTED", "PRESIGNED_TRANSFER"); + } + return browserDataFailure( + timedOut ? "UNAVAILABLE" : "NOT_READABLE", + "PRESIGNED_TRANSFER", + { + retryable: true, + recovery: "REISSUE_CAPABILITY", + }, + ); +} + +export function isAbortSignal(value: unknown): value is AbortSignal { + try { + if (!value || typeof value !== "object") return false; + const abortedGetter = Object.getOwnPropertyDescriptor( + AbortSignal.prototype, + "aborted", + )?.get; + return Boolean( + abortedGetter && + typeof abortedGetter.call(value) === "boolean" && + typeof (value as AbortSignal).addEventListener === "function" && + typeof (value as AbortSignal).removeEventListener === "function", + ); + } catch { + return false; + } +} + +/** + * One terminal observation for presigned and resumable transfers. An absent or + * invalid byte length leaves `byteBucket` out rather than guessing one. + */ +export function observeTransferResult( + observer: BrowserDataObserver | undefined, + operation: BrowserDataOperation, + result: Result>, + byteLength?: number, +): void { + const bucket = byteBucket(byteLength); + observeBrowserData(observer, { + operation, + outcome: result.ok ? "SUCCEEDED" : "FAILED", + ...(!result.ok ? { failureCode: result.error.code } : {}), + ...(bucket !== undefined ? { byteBucket: bucket } : {}), + }); +} diff --git a/src/adapters/browser-transfer/presigned/incremental-sha256.ts b/src/adapters/browser-transfer/presigned/incremental-sha256.ts index bcc1c1ec..132d303b 100644 --- a/src/adapters/browser-transfer/presigned/incremental-sha256.ts +++ b/src/adapters/browser-transfer/presigned/incremental-sha256.ts @@ -126,8 +126,8 @@ class Sha256Accumulator { words[index] = view.getUint32(index * 4, false); } for (let index = 16; index < 64; index += 1) { - const previous15 = words[index - 15] ?? 0; - const previous2 = words[index - 2] ?? 0; + const previous15 = words[index - 15]; + const previous2 = words[index - 2]; const sigma0 = rotateRight(previous15, 7) ^ rotateRight(previous15, 18) ^ @@ -136,22 +136,18 @@ class Sha256Accumulator { rotateRight(previous2, 17) ^ rotateRight(previous2, 19) ^ (previous2 >>> 10); - words[index] = - ((words[index - 16] ?? 0) + - sigma0 + - (words[index - 7] ?? 0) + - sigma1) >>> - 0; + // A Uint32Array store already reduces modulo 2^32. + words[index] = words[index - 16] + sigma0 + words[index - 7] + sigma1; } - let a = this.#state[0] ?? 0; - let b = this.#state[1] ?? 0; - let c = this.#state[2] ?? 0; - let d = this.#state[3] ?? 0; - let e = this.#state[4] ?? 0; - let f = this.#state[5] ?? 0; - let g = this.#state[6] ?? 0; - let h = this.#state[7] ?? 0; + let a = this.#state[0]; + let b = this.#state[1]; + let c = this.#state[2]; + let d = this.#state[3]; + let e = this.#state[4]; + let f = this.#state[5]; + let g = this.#state[6]; + let h = this.#state[7]; for (let index = 0; index < 64; index += 1) { const sum1 = @@ -161,8 +157,8 @@ class Sha256Accumulator { (h + sum1 + choice + - (ROUND_CONSTANTS[index] ?? 0) + - (words[index] ?? 0)) >>> + ROUND_CONSTANTS[index] + + words[index]) >>> 0; const sum0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22); @@ -178,14 +174,15 @@ class Sha256Accumulator { a = (temporary1 + temporary2) >>> 0; } - this.#state[0] = ((this.#state[0] ?? 0) + a) >>> 0; - this.#state[1] = ((this.#state[1] ?? 0) + b) >>> 0; - this.#state[2] = ((this.#state[2] ?? 0) + c) >>> 0; - this.#state[3] = ((this.#state[3] ?? 0) + d) >>> 0; - this.#state[4] = ((this.#state[4] ?? 0) + e) >>> 0; - this.#state[5] = ((this.#state[5] ?? 0) + f) >>> 0; - this.#state[6] = ((this.#state[6] ?? 0) + g) >>> 0; - this.#state[7] = ((this.#state[7] ?? 0) + h) >>> 0; + const state = this.#state; + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + state[4] += e; + state[5] += f; + state[6] += g; + state[7] += h; } } diff --git a/src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts b/src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts index 1f62832b..d84343cb 100644 --- a/src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts +++ b/src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts @@ -11,30 +11,39 @@ import type { PresignedUploadPartCapabilityProvider, } from "../../../application/ports/browser-transfer/presigned-transfer.ts"; import { - createAbortableOperation, + cancelBody, + cancelReader, snapshotAbortTimers, - type AbortTimerSnapshot, } from "../../platform/abortable-operation.ts"; import { RESUMABLE_UPLOAD_PROTOCOL } from "../../../application/ports/browser-transfer/resumable-upload.ts"; import type { - BrowserDataFailureCode, BrowserDataObserver, - BrowserDataRecovery, BrowserDataResult, } from "../../../application/ports/browser-file-storage/shared.ts"; import { browserDataFailure, browserDataSuccess, - observeBrowserData, } from "../../browser-file-storage/result.ts"; import type { PresignedCapabilityRegistration, PresignedCapabilityVault, PresignedHeaderBinding, } from "./presigned-capability-vault.ts"; -import { SAFE_TRANSFER_ID } from "../resumable-upload/checkpoint-schema.ts"; +import { + createAbortScope, + isAbortSignal, + normalizedContentLength, + observeTransferResult, + readWithSignal, + SCOPE_ENDED, + statusFailure, + transferFailure, +} from "./http-common.ts"; +import { + SAFE_TRANSFER_ID, + SHA256_HEX as SHA256, +} from "../resumable-upload/checkpoint-schema.ts"; -const SHA256 = /^[a-f0-9]{64}$/; const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/; const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; const QUERY_NAME = /^[A-Za-z0-9_.~-]{1,128}$/; @@ -170,15 +179,12 @@ export function createPresignedCapabilityHttpProvider( result: BrowserDataResult, byteLength?: number, ): BrowserDataResult { - const bucket = byteBucket( + observeTransferResult( + observer, + "PRESIGNED_TRANSFER", + result, result.ok ? result.value.byteLength : byteLength, ); - observeBrowserData(observer, { - operation: "PRESIGNED_TRANSFER", - outcome: result.ok ? "SUCCEEDED" : "FAILED", - ...(!result.ok ? { failureCode: result.error.code } : {}), - ...(bucket !== undefined ? { byteBucket: bucket } : {}), - }); return result; } @@ -237,11 +243,11 @@ export function createPresignedCapabilityHttpProvider( response.type === "opaqueredirect" || response.url !== endpoint ) { - cancelResponseBody(response); + cancelBody(response); return browserDataFailure("POLICY_REJECTED", "PRESIGNED_TRANSFER"); } if (!response.ok || response.status !== 200) { - cancelResponseBody(response); + cancelBody(response); return statusFailure(response.status); } const contentType = response.headers.get("content-type") ?? ""; @@ -249,7 +255,7 @@ export function createPresignedCapabilityHttpProvider( contentType.split(";", 1)[0]?.trim().toLowerCase() !== "application/json" ) { - cancelResponseBody(response); + cancelBody(response); return browserDataFailure("POLICY_REJECTED", "PRESIGNED_TRANSFER"); } const payload = await readBoundedJson( @@ -762,11 +768,11 @@ async function readBoundedJson( if (declared !== null) { declaredLength = normalizedContentLength(declared); if (declaredLength === null) { - cancelResponseBody(response); + cancelBody(response); throw new ResponseIntegrityError(); } if (declaredLength > maxBytes) { - cancelResponseBody(response); + cancelBody(response); throw new ResponseLimitError(); } } @@ -797,15 +803,7 @@ async function readBoundedJson( text += decoder.decode(); return JSON.parse(text) as unknown; } finally { - if (!completed) { - try { - void reader.cancel().catch(() => { - // Response cancellation is best effort after classification. - }); - } catch { - // Response cleanup cannot alter the closed result. - } - } + if (!completed) cancelReader(reader); try { reader.releaseLock(); } catch { @@ -814,223 +812,6 @@ async function readBoundedJson( } } -function cancelResponseBody(response: Response): void { - try { - void response.body?.cancel().catch(() => { - // Cancellation is best effort after the response is classified. - }); - } catch { - // Response cleanup cannot alter the closed result. - } -} - -function normalizedContentLength(value: string): number | null { - const trimmed = value.trim(); - if (!/^(?:0|[1-9][0-9]{0,15})$/.test(trimmed)) return null; - const length = Number(trimmed); - return Number.isSafeInteger(length) ? length : null; -} - -function readWithSignal( - reader: ReadableStreamDefaultReader, - signal: AbortSignal, -): Promise> { - if (signal.aborted) { - return Promise.reject(new DOMException("Aborted", "AbortError")); - } - return new Promise((resolve, reject) => { - const onAbort = () => - reject(new DOMException("Aborted", "AbortError")); - signal.addEventListener("abort", onAbort, { once: true }); - reader.read().then( - (result) => { - signal.removeEventListener("abort", onAbort); - resolve(result); - }, - (error: unknown) => { - signal.removeEventListener("abort", onAbort); - reject(error); - }, - ); - }); -} - -function statusFailure( - status: number, -): BrowserDataResult { - let code: BrowserDataFailureCode = "UNAVAILABLE"; - let recovery: BrowserDataRecovery = "RETRY"; - let retryable = status === 429 || status >= 500; - if (status === 401 || status === 403) { - code = "PERMISSION_DENIED"; - recovery = "NONE"; - retryable = false; - } else if (status === 404) { - code = "NOT_FOUND"; - recovery = "NONE"; - retryable = false; - } else if (status === 409) { - code = "CONFLICT"; - recovery = "REISSUE_CAPABILITY"; - retryable = false; - } else if (status === 410) { - code = "EXPIRED_RESOURCE"; - recovery = "REISSUE_CAPABILITY"; - retryable = false; - } else if (status === 413) { - code = "LIMIT_EXCEEDED"; - recovery = "NONE"; - retryable = false; - } else if (status >= 400 && status < 500 && status !== 429) { - code = "POLICY_REJECTED"; - recovery = "NONE"; - retryable = false; - } - return browserDataFailure(code, "PRESIGNED_TRANSFER", { - retryable, - recovery, - }); -} - -/** BT-PRE-03. The scope ended before the task settled. */ -const SCOPE_ENDED = Symbol("presigned-capability-scope-ended"); - -/** - * TR-RR-01 / TR-RR-05. The abort scope is a thin projection of the shared - * `createAbortableOperation` primitive into this subsystem's vocabulary. - * - * Two things changed with the migration. `abort()` exists, so `close()` on a - * download can actually stop a pending fetch instead of only dropping - * listeners; and additional ownership signals — a consumer's stream signal — - * are composed into the same operation *before* any I/O starts, so an - * already-aborted consumer never causes a fetch. - */ -function createAbortScope( - external: AbortSignal, - timeoutMs: number, - timers: AbortTimerSnapshot, - additionalSignals: readonly AbortSignal[] = [], -) { - const operation = createAbortableOperation({ - signal: external, - timeoutMs, - setTimer: timers.setTimer, - clearTimer: timers.clearTimer, - }); - const releases: (() => void)[] = []; - for (const extra of additionalSignals) { - if (!extra) continue; - if (extra.aborted) { - operation.close(); - continue; - } - const onAbort = () => operation.close(); - try { - extra.addEventListener("abort", onAbort, { once: true }); - releases.push(() => { - try { - extra.removeEventListener("abort", onAbort); - } catch { - // A hostile signal facade cannot block the rest of cleanup. - } - }); - } catch { - // A signal that refuses a listener cannot bound this operation, so the - // operation closes rather than running unbounded. - operation.close(); - } - } - const releaseExtras = () => { - for (const release of releases.splice(0)) release(); - }; - return Object.freeze({ - signal: operation.signal, - timedOut: () => operation.terminal() === "DEADLINE", - /** Bounds a fetch that ignores its signal. */ - async race(task: Promise): Promise { - const outcome = await operation.race( - task, - (value) => compensateLateResponseValue(value), - ); - if (outcome.kind === "VALUE") return outcome.value; - // A collaborator's own rejection stays a rejection: the caller's existing - // catch classifies it, and it is never forged into a cancellation. - if (outcome.kind === "REJECTED") throw outcome.reason; - return SCOPE_ENDED; - }, - /** TR-RR-01. Ends the physical work, not just the bookkeeping. */ - abort() { - operation.close(); - releaseExtras(); - }, - release() { - operation.close(); - releaseExtras(); - }, - }); -} - -function compensateLateResponseValue(value: unknown): void { - const body = (value as { body?: { cancel(): Promise } | null } | null) - ?.body; - void body?.cancel().catch(() => undefined); -} - -function transferFailure( - signal: AbortSignal, - timedOut: boolean, -): BrowserDataResult { - if (signal.aborted) { - return browserDataFailure("ABORTED", "PRESIGNED_TRANSFER"); - } - return browserDataFailure( - timedOut ? "UNAVAILABLE" : "NOT_READABLE", - "PRESIGNED_TRANSFER", - { retryable: true, recovery: "REISSUE_CAPABILITY" }, - ); -} - -function isAbortSignal(value: unknown): value is AbortSignal { - try { - if (!value || typeof value !== "object") return false; - const abortedGetter = Object.getOwnPropertyDescriptor( - AbortSignal.prototype, - "aborted", - )?.get; - return Boolean( - abortedGetter && - typeof abortedGetter.call(value) === "boolean" && - typeof (value as AbortSignal).addEventListener === "function" && - typeof (value as AbortSignal).removeEventListener === "function", - ); - } catch { - return false; - } -} - -function byteBucket( - byteLength: number | undefined, -): - | "ZERO" - | "LT1MIB" - | "1_TO_9MIB" - | "10_TO_99MIB" - | "GTE100MIB" - | undefined { - if ( - byteLength === undefined || - !Number.isSafeInteger(byteLength) || - byteLength < 0 - ) { - return undefined; - } - if (byteLength === 0) return "ZERO"; - if (byteLength < 1_048_576) return "LT1MIB"; - if (byteLength < 10_485_760) return "1_TO_9MIB"; - if (byteLength < 104_857_600) return "10_TO_99MIB"; - return "GTE100MIB"; -} - function strictRecord( value: unknown, keys: readonly string[], diff --git a/src/adapters/browser-transfer/presigned/presigned-capability-vault.ts b/src/adapters/browser-transfer/presigned/presigned-capability-vault.ts index 1bba8d98..4f554b27 100644 --- a/src/adapters/browser-transfer/presigned/presigned-capability-vault.ts +++ b/src/adapters/browser-transfer/presigned/presigned-capability-vault.ts @@ -275,18 +275,14 @@ export function createPresignedCapabilityVault(options: Readonly<{ const invalid = validatePresignedCapabilityRegistration(snapshot); if (invalid) return invalid; pruneExpired(); - if ( - byReceipt.has(registration.capabilityReceipt) || - byReceipt.size >= maxActiveCapabilities - ) { + // Q-6.1-11. The duplicate check reads the snapshot too; the issuer's + // object is never read again once the snapshot exists. + const duplicate = byReceipt.has(snapshot.capabilityReceipt); + if (duplicate || byReceipt.size >= maxActiveCapabilities) { return browserDataFailure( - byReceipt.has(registration.capabilityReceipt) - ? "CONFLICT" - : "LIMIT_EXCEEDED", + duplicate ? "CONFLICT" : "LIMIT_EXCEEDED", "PRESIGNED_TRANSFER", - byReceipt.has(registration.capabilityReceipt) - ? { recovery: "REISSUE_CAPABILITY" } - : undefined, + duplicate ? { recovery: "REISSUE_CAPABILITY" } : undefined, ); } diff --git a/src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts b/src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts index 2ddfdd34..7002cc8d 100644 --- a/src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts +++ b/src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts @@ -9,9 +9,9 @@ import type { PresignedUploadPartPort, } from "../../../application/ports/browser-transfer/presigned-transfer.ts"; import { - createAbortableOperation, + cancelBody, + cancelReader, snapshotAbortTimers, - type AbortTimerSnapshot, } from "../../platform/abortable-operation.ts"; import { RESUMABLE_UPLOAD_PROTOCOL } from "../../../application/ports/browser-transfer/resumable-upload.ts"; import type { @@ -34,10 +34,23 @@ import type { PresignedCapabilityBinding, PresignedCapabilityVault, } from "./presigned-capability-vault.ts"; -import { SAFE_TRANSFER_ID } from "../resumable-upload/checkpoint-schema.ts"; - -const SHA256 = /^[a-f0-9]{64}$/; -const RECEIPT_TOKEN = /^[A-Za-z0-9][A-Za-z0-9._~:+/=-]{0,511}$/; +import { + byteBucket, + createAbortScope, + isAbortSignal, + normalizedContentLength, + observeTransferResult, + readWithSignal, + SCOPE_ENDED, + statusFailure, + transferFailure, + type PresignedAbortScope, +} from "./http-common.ts"; +import { + isSafeUploadReceiptToken, + SAFE_TRANSFER_ID, + SHA256_HEX as SHA256, +} from "../resumable-upload/checkpoint-schema.ts"; type Scheduler = Readonly<{ setTimeout(callback: () => void, milliseconds: number): unknown; @@ -436,12 +449,12 @@ export function createPresignedTransferExecutor( function createDownloadSource(input: Readonly<{ start: ( - scope: ReturnType, + scope: PresignedAbortScope, ) => Promise; validateResponse: (response: Response) => BrowserDataResult; createScope: ( consumerSignal?: AbortSignal, - ) => ReturnType; + ) => PresignedAbortScope; recheckExpiry: () => BrowserDataResult; binding: PresignedCapabilityBinding; capability: PresignedDownloadCapability; @@ -454,7 +467,7 @@ function createDownloadSource(input: Readonly<{ }>): PresignedDownloadByteSource { /** BT-PRE-01. One state machine shared by `stream()` and `close()`. */ let state: "READY" | "STREAMING" | "CLOSED" = "READY"; - let activeScope: ReturnType | undefined; + let activeScope: PresignedAbortScope | undefined; let activeResponse: Response | undefined; // TR-RR-01. Releasing the scope only dropped listeners and the timer, so a @@ -784,8 +797,7 @@ function validateDownloadResponse( const contentEncoding = response.headers.get("content-encoding"); if ( mediaType !== binding.mediaType || - declaredLength === null || - Number(declaredLength) !== binding.byteLength || + normalizedContentLength(declaredLength) !== binding.byteLength || digestHeader === null || response.headers.get(digestHeader)?.trim().toLowerCase() !== binding.expectedSha256 || @@ -929,17 +941,6 @@ function validateRequiredHeaders( ); } -function normalizedContentLength( - value: string | null, - allowImplicitZero: boolean, -): number | null { - if (value === null) return allowImplicitZero ? 0 : null; - const trimmed = value.trim(); - if (!/^(?:0|[1-9][0-9]{0,15})$/.test(trimmed)) return null; - const length = Number(trimmed); - return Number.isSafeInteger(length) ? length : null; -} - function headersFor(binding: PresignedCapabilityBinding): Headers { const headers = new Headers(); for (const header of binding.requestHeaders) { @@ -995,189 +996,6 @@ function validateExpiry( ); } -function statusFailure( - status: number, -): BrowserDataResult { - let code: BrowserDataFailureCode = "UNAVAILABLE"; - let recovery: BrowserDataRecovery = "REISSUE_CAPABILITY"; - let retryable = status === 429 || status >= 500; - if (status === 401 || status === 403) { - code = "PERMISSION_DENIED"; - recovery = "REISSUE_CAPABILITY"; - retryable = false; - } else if (status === 404) { - code = "NOT_FOUND"; - recovery = "NONE"; - retryable = false; - } else if (status === 409) { - code = "CONFLICT"; - retryable = false; - } else if (status === 410) { - code = "EXPIRED_RESOURCE"; - retryable = false; - } else if (status === 413) { - code = "LIMIT_EXCEEDED"; - recovery = "NONE"; - retryable = false; - } else if (status >= 400 && status < 500 && status !== 429) { - code = "POLICY_REJECTED"; - recovery = "NONE"; - retryable = false; - } - return browserDataFailure(code, "PRESIGNED_TRANSFER", { - retryable, - recovery, - }); -} - -function transferFailure( - externalSignal: AbortSignal, - timedOut: boolean, -): BrowserDataResult { - if (externalSignal.aborted) { - return browserDataFailure("ABORTED", "PRESIGNED_TRANSFER"); - } - return browserDataFailure( - timedOut ? "UNAVAILABLE" : "NOT_READABLE", - "PRESIGNED_TRANSFER", - { - retryable: true, - recovery: "REISSUE_CAPABILITY", - }, - ); -} - -/** BT-PRE-03. The scope ended before the task settled. */ -const SCOPE_ENDED = Symbol("presigned-scope-ended"); - -function compensateLateResponse(task: Promise): void { - void task - .then(async (value) => { - const body = (value as { body?: { cancel(): Promise } | null }) - ?.body; - await body?.cancel(); - }) - .catch(() => undefined); -} - -/** - * TR-RR-01 / TR-RR-05. A projection of the shared `createAbortableOperation` - * primitive into this subsystem's vocabulary, replacing a second hand-written - * copy of the same mechanics. - * - * `additionalSignals` lets a consumer's stream signal join the operation's - * ownership before any I/O begins, and `abort()` ends the physical work rather - * than only releasing bookkeeping. - */ -function createAbortScope( - external: AbortSignal, - timeoutMs: number, - timers: AbortTimerSnapshot, - additionalSignals: readonly AbortSignal[] = [], -) { - const operation = createAbortableOperation({ - signal: external, - timeoutMs, - setTimer: timers.setTimer, - clearTimer: timers.clearTimer, - }); - const releases: (() => void)[] = []; - for (const extra of additionalSignals) { - if (!extra) continue; - if (extra.aborted) { - operation.close(); - continue; - } - const onAbort = () => operation.close(); - try { - extra.addEventListener("abort", onAbort, { once: true }); - releases.push(() => { - try { - extra.removeEventListener("abort", onAbort); - } catch { - // A hostile signal facade cannot block the rest of cleanup. - } - }); - } catch { - operation.close(); - } - } - const releaseExtras = () => { - for (const release of releases.splice(0)) release(); - }; - return Object.freeze({ - signal: operation.signal, - timedOut: () => operation.terminal() === "DEADLINE", - async race(task: Promise): Promise { - const outcome = await operation.race(task, (value) => { - const body = ( - value as { body?: { cancel(): Promise } | null } | null - )?.body; - void body?.cancel().catch(() => undefined); - }); - if (outcome.kind === "VALUE") return outcome.value; - if (outcome.kind === "REJECTED") throw outcome.reason; - return SCOPE_ENDED; - }, - abort() { - operation.close(); - releaseExtras(); - }, - release() { - operation.close(); - releaseExtras(); - }, - }); -} - -function cancelBody(response: Response): void { - try { - void response.body?.cancel().catch(() => { - // Cancellation is best effort after the result is classified. - }); - } catch { - // A response already classified as failure/success is not reclassified by - // best-effort body cancellation. - } -} - -function cancelReader( - reader: ReadableStreamDefaultReader, -): void { - try { - void reader.cancel().catch(() => { - // Cancellation is best effort after the result is classified. - }); - } catch { - // Reader cancellation cannot alter the terminal closed result. - } -} - -function readWithSignal( - reader: ReadableStreamDefaultReader, - signal: AbortSignal, -): Promise> { - if (signal.aborted) { - return Promise.reject(new DOMException("Aborted", "AbortError")); - } - return new Promise((resolve, reject) => { - const onAbort = () => { - reject(new DOMException("Aborted", "AbortError")); - }; - signal.addEventListener("abort", onAbort, { once: true }); - reader.read().then( - (result) => { - signal.removeEventListener("abort", onAbort); - resolve(result); - }, - (error: unknown) => { - signal.removeEventListener("abort", onAbort); - reject(error); - }, - ); - }); -} - function normalizeReceiptToken(value: string | null): string | null { if (!value) return null; const trimmed = value.trim(); @@ -1187,9 +1005,7 @@ function normalizeReceiptToken(value: string | null): string | null { trimmed.endsWith("\"") ? trimmed.slice(1, -1) : trimmed; - return RECEIPT_TOKEN.test(unquoted) && !unquoted.includes("://") - ? unquoted - : null; + return isSafeUploadReceiptToken(unquoted) ? unquoted : null; } function responseUrlMatches( @@ -1247,24 +1063,6 @@ async function digestSha256WithWebCrypto( ).join(""); } -function isAbortSignal(value: unknown): value is AbortSignal { - try { - if (!value || typeof value !== "object") return false; - const abortedGetter = Object.getOwnPropertyDescriptor( - AbortSignal.prototype, - "aborted", - )?.get; - return Boolean( - abortedGetter && - typeof abortedGetter.call(value) === "boolean" && - typeof (value as AbortSignal).addEventListener === "function" && - typeof (value as AbortSignal).removeEventListener === "function", - ); - } catch { - return false; - } -} - function safeInputByteLength(value: unknown): number | undefined { try { if (!value || typeof value !== "object") return undefined; @@ -1300,41 +1098,3 @@ function safeInputByteLength(value: unknown): number | undefined { } return undefined; } - -function observeTransferResult( - observer: BrowserDataObserver | undefined, - operation: BrowserDataOperation, - result: BrowserDataResult, - byteLength?: number, -): void { - const bucket = byteBucket(byteLength); - observeBrowserData(observer, { - operation, - outcome: result.ok ? "SUCCEEDED" : "FAILED", - ...(!result.ok ? { failureCode: result.error.code } : {}), - ...(bucket !== undefined ? { byteBucket: bucket } : {}), - }); -} - -function byteBucket( - byteLength: number | undefined, -): - | "ZERO" - | "LT1MIB" - | "1_TO_9MIB" - | "10_TO_99MIB" - | "GTE100MIB" - | undefined { - if ( - byteLength === undefined || - !Number.isSafeInteger(byteLength) || - byteLength < 0 - ) { - return undefined; - } - if (byteLength === 0) return "ZERO"; - if (byteLength < 1_048_576) return "LT1MIB"; - if (byteLength < 10_485_760) return "1_TO_9MIB"; - if (byteLength < 104_857_600) return "10_TO_99MIB"; - return "GTE100MIB"; -} diff --git a/src/adapters/browser-transfer/resumable-upload/checkpoint-schema.ts b/src/adapters/browser-transfer/resumable-upload/checkpoint-schema.ts index 14b1e82d..89ee3d40 100644 --- a/src/adapters/browser-transfer/resumable-upload/checkpoint-schema.ts +++ b/src/adapters/browser-transfer/resumable-upload/checkpoint-schema.ts @@ -5,6 +5,10 @@ import type { UploadPartReceipt, } from "../../../application/ports/browser-transfer/resumable-upload.ts"; import { RESUMABLE_UPLOAD_PROTOCOL } from "../../../application/ports/browser-transfer/resumable-upload.ts"; +import { + isPositiveSafeInteger as positiveSafeInteger, + isNonNegativeSafeInteger as nonNegativeSafeInteger, +} from "../../../application/ports/browser-file-storage/shared.ts"; export const SAFE_UPLOAD_KEY = /^[A-Za-z0-9][A-Za-z0-9._~:-]{7,127}$/u; export const SAFE_REGISTRY_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; @@ -17,7 +21,7 @@ export const SAFE_OPAQUE_ID = /^[A-Za-z0-9_-]{8,512}$/u; */ export const SAFE_TRANSFER_ID = /^[A-Za-z0-9_-][A-Za-z0-9._:-]{0,511}$/u; export const SHA256_HEX = /^[a-f0-9]{64}$/u; -export const RECEIPT_TOKEN = +const RECEIPT_TOKEN = /^[A-Za-z0-9][A-Za-z0-9._~:+/=-]{0,511}$/u; export const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]{1,63}\/[a-z0-9!#$&^_.+-]{1,63}$/u; @@ -67,7 +71,7 @@ export function isUploadFileFingerprint( ); } -export function isUploadPartDescriptor( +function isUploadPartDescriptor( value: unknown, ): value is UploadPartDescriptor { if (!exactRecord(value, PART_KEYS)) return false; @@ -138,7 +142,7 @@ export function isResumableUploadCheckpoint( return true; } -export function partMatchesFingerprint( +function partMatchesFingerprint( part: UploadPartDescriptor, fingerprint: UploadFileFingerprint, ): boolean { @@ -168,7 +172,7 @@ export function samePart( ); } -function exactRecord( +export function exactRecord( value: unknown, keys: Keys, ): value is Record { @@ -183,10 +187,17 @@ function exactRecord( ); } -function positiveSafeInteger(value: unknown): value is number { - return Number.isSafeInteger(value) && (value as number) > 0; -} - -function nonNegativeSafeInteger(value: unknown): value is number { - return Number.isSafeInteger(value) && (value as number) >= 0; +/** + * BT-UP-01. The structural guard must cover every method cleanup will call. + * Admitting a signal without `removeEventListener` turned a `finally` into a + * Promise rejection instead of the typed terminal result. + */ +export function isAbortSignal(value: unknown): value is AbortSignal { + return Boolean( + value && + typeof value === "object" && + typeof (value as AbortSignal).aborted === "boolean" && + typeof (value as AbortSignal).addEventListener === "function" && + typeof (value as AbortSignal).removeEventListener === "function", + ); } diff --git a/src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts b/src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts index 8dd4a5d1..a943007f 100644 --- a/src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts +++ b/src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts @@ -2,23 +2,26 @@ import type { UploadProviderFailure, UploadProviderResult, } from "../../../application/ports/browser-transfer/resumable-upload.ts"; -import type { - BrowserDataFailureCode, - BrowserDataRecovery, +import { + hasControlCharacter, + type BrowserDataFailureCode, + type BrowserDataRecovery, } from "../../../application/ports/browser-file-storage/shared.ts"; import { browserDataFailure, browserDataSuccess, } from "../../browser-file-storage/result.ts"; import { + cancelBody, + cancelReader, createAbortableOperation, - type AbortRace, - type AbortTerminalReason, + type AbortableOperation, } from "../../platform/abortable-operation.ts"; import type { ResumableUploadControlOperation, ResumableUploadJsonTransport, } from "./http-control-plane-adapter.ts"; +import { isAbortSignal } from "./checkpoint-schema.ts"; export type ResumableUploadEndpointMap = Readonly< Record @@ -182,14 +185,17 @@ export function createResumableUploadFetchJsonTransport( "NONE", ); } - const attempt = createFetchAttempt( + // X-AUDIT-02 / TR-RR-05. The attempt is the shared abort primitive: + // the listener and the timer are installed together, so a throwing + // scheduler closes the attempt instead of rejecting `execute()`. + const attempt = createAbortableOperation({ signal, timeoutMs, setTimer, clearTimer, - ); + }); try { - if (attempt.terminalKind() !== null) { + if (attempt.terminal() !== null) { // The attempt was closed before it could be bounded, so no request is // ever put on the wire. return attemptFailure(attempt, operation); @@ -210,7 +216,7 @@ export function createResumableUploadFetchJsonTransport( const raced = await attempt.race( Promise.resolve(fetchPromise), (late) => { - cancelResponseBody(late); + cancelBody(late); }, ); if (raced.kind !== "VALUE") { @@ -222,7 +228,7 @@ export function createResumableUploadFetchJsonTransport( response.type === "opaqueredirect" || !sameUrl(response.url, endpoint) ) { - cancelResponseBody(response); + cancelBody(response); return failure( "POLICY_REJECTED", operation, @@ -237,11 +243,11 @@ export function createResumableUploadFetchJsonTransport( maxRetryAfterMs, safeNowEpochMs(), ); - cancelResponseBody(response); + cancelBody(response); return failed; } if (!jsonContentType(response.headers.get("content-type"))) { - cancelResponseBody(response); + cancelBody(response); return failure( "CORRUPT_DATA", operation, @@ -261,7 +267,9 @@ export function createResumableUploadFetchJsonTransport( } catch { return attemptFailure(attempt, operation); } finally { - attempt.release(); + // BT-UP-01. Cleanup is best effort and never replaces the classified + // terminal result with a rejection. + attempt.close(); } }, }; @@ -341,7 +349,7 @@ function snapshotHeaders( seen.has(name) || typeof header.value !== "string" || header.value.length > 2048 || - hasForbiddenHeaderValueCharacter(header.value) + hasControlCharacter(header.value) ) { throw new TypeError("Upload request header is invalid."); } @@ -405,7 +413,7 @@ async function readBoundedJson( response: Response, maxBytes: number, operation: ResumableUploadControlOperation, - attempt: FetchAttempt, + attempt: AbortableOperation, ): Promise> { const contentLength = response.headers.get("content-length"); let declaredLength: number | null = null; @@ -414,7 +422,7 @@ async function readBoundedJson( (!/^(0|[1-9][0-9]*)$/u.test(contentLength) || Number(contentLength) > maxBytes) ) { - cancelResponseBody(response); + cancelBody(response); return failure( "LIMIT_EXCEEDED", operation, @@ -574,89 +582,15 @@ function failure( return Object.freeze({ ok: false, error }); } -type FetchAttemptTerminalKind = "ABORT" | "TIMEOUT" | "CLOSED"; - -type FetchAttempt = Readonly<{ - signal: AbortSignal; - terminalKind(): FetchAttemptTerminalKind | null; - race( - task: Promise, - compensate?: (value: Value) => void, - ): Promise>; - release(): void; -}>; - -/** - * X-AUDIT-02 / TR-RR-05. The attempt is the shared abort primitive with this - * subsystem's vocabulary on top. Owning a private copy meant the listener was - * attached before the timer was installed, so a scheduler that threw rejected - * the public `execute()` promise and left the listener on the caller's signal. - */ -function createFetchAttempt( - parent: AbortSignal, - timeoutMs: number, - setTimer: (callback: () => void, delayMs: number) => unknown, - clearTimer: (handle: unknown) => void, -): FetchAttempt { - const operation = createAbortableOperation({ - signal: parent, - timeoutMs, - setTimer, - clearTimer, - }); - const kindOf = ( - reason: AbortTerminalReason | null, - ): FetchAttemptTerminalKind | null => { - if (reason === null) return null; - if (reason === "CALLER_ABORT") return "ABORT"; - return reason === "DEADLINE" ? "TIMEOUT" : "CLOSED"; - }; - return Object.freeze({ - signal: operation.signal, - terminalKind: () => kindOf(operation.terminal()), - race: ( - task: Promise, - compensate?: (value: Value) => void, - ) => operation.race(task, compensate), - release() { - // BT-UP-01. Cleanup is best effort and must never replace the already - // classified terminal result with a rejection. - operation.close(); - }, - }); -} - function attemptFailure( - attempt: FetchAttempt, + attempt: AbortableOperation, operation: ResumableUploadControlOperation, ): UploadProviderResult { - return attempt.terminalKind() === "ABORT" + return attempt.terminal() === "CALLER_ABORT" ? failure("ABORTED", operation, false, "NONE") : failure("UNAVAILABLE", operation, true, "RESUME"); } -function cancelResponseBody(response: Response): void { - try { - void response.body?.cancel().catch(() => { - // Response cancellation is best effort after closed classification. - }); - } catch { - // A cancellation failure cannot change the already classified result. - } -} - -function cancelReader( - reader: ReadableStreamDefaultReader, -): void { - try { - void reader.cancel().catch(() => { - // Reader cancellation is best effort after closed classification. - }); - } catch { - // A cancellation failure cannot change the already classified result. - } -} - function releaseReader( reader: ReadableStreamDefaultReader, ): void { @@ -721,21 +655,6 @@ function boundedPositiveInteger( return value; } -/** - * BT-UP-01. The structural guard must cover every method cleanup will call. - * Admitting a signal without `removeEventListener` turned a `finally` into a - * Promise rejection instead of the typed terminal result. - */ -function isAbortSignal(value: unknown): value is AbortSignal { - return Boolean( - value && - typeof value === "object" && - typeof (value as AbortSignal).aborted === "boolean" && - typeof (value as AbortSignal).addEventListener === "function" && - typeof (value as AbortSignal).removeEventListener === "function", - ); -} - function isControlOperation( value: unknown, ): value is ResumableUploadControlOperation { @@ -766,13 +685,6 @@ function snapshotTransportRequest( } } -function hasForbiddenHeaderValueCharacter(value: string): boolean { - return [...value].some((character) => { - const codePoint = character.codePointAt(0); - return codePoint !== undefined && (codePoint <= 31 || codePoint === 127); - }); -} - function isPlainRecord( value: unknown, ): value is Readonly> { diff --git a/src/adapters/browser-transfer/resumable-upload/http-control-plane-adapter.ts b/src/adapters/browser-transfer/resumable-upload/http-control-plane-adapter.ts index bfd942ef..c5d2dfd7 100644 --- a/src/adapters/browser-transfer/resumable-upload/http-control-plane-adapter.ts +++ b/src/adapters/browser-transfer/resumable-upload/http-control-plane-adapter.ts @@ -30,6 +30,10 @@ import { SAFE_UPLOAD_KEY, SHA256_HEX, } from "./checkpoint-schema.ts"; +import { + isPositiveSafeInteger as positiveSafeInteger, + isNonNegativeSafeInteger as nonNegativeSafeInteger, +} from "../../../application/ports/browser-file-storage/shared.ts"; export type ResumableUploadControlOperation = | "CREATE_SESSION" @@ -679,11 +683,3 @@ function safeIdempotencyKey(value: string): boolean { /^[A-Za-z0-9._~-]+$/u.test(value) ); } - -function positiveSafeInteger(value: unknown): value is number { - return Number.isSafeInteger(value) && (value as number) > 0; -} - -function nonNegativeSafeInteger(value: unknown): value is number { - return Number.isSafeInteger(value) && (value as number) >= 0; -} 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 1861697d..f17a62f1 100644 --- a/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts +++ b/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts @@ -285,6 +285,35 @@ export function createIndexedDbResumableUploadCheckpointRuntime( }), }); + /** + * Every store operation reads the row it guards inside the same transaction + * it may then write in, so the guard and the write cannot interleave with + * another context. + */ + async function withCheckpointRow( + uploadKey: string, + mode: "readonly" | "readwrite", + signal: AbortSignal | undefined, + onRow: ( + row: unknown, + store: IDBObjectStore, + context: CheckpointTransactionContext, + ) => void, + ): Promise> { + const opened = await connection.acquire(signal); + if (!opened.ok) return opened; + return await runCheckpointTransaction( + opened.value, + mode, + signal, + (nativeStore, context) => { + const request = nativeStore.get(uploadKey); + request.onerror = () => context.fail(mappedFailure(request.error)); + request.onsuccess = () => onRow(request.result, nativeStore, context); + }, + ); + } + const storeValue: ResumableUploadCheckpointStore = { async read( uploadKey: string, @@ -295,32 +324,22 @@ export function createIndexedDbResumableUploadCheckpointRuntime( if (!SAFE_UPLOAD_KEY.test(uploadKey)) { return browserDataFailure("INVALID_INPUT", OPERATION); } - const opened = await connection.acquire(signal); - if (!opened.ok) return opened; - return await runCheckpointTransaction< - ResumableUploadCheckpoint | null - >( - opened.value, + return await withCheckpointRow( + uploadKey, "readonly", signal, - (nativeStore, context) => { - const request = nativeStore.get(uploadKey); - request.onerror = () => context.fail(mappedFailure(request.error)); - request.onsuccess = () => { - if (request.result === undefined) { - context.succeed(null); - return; - } - if (!isResumableUploadCheckpoint(request.result)) { - context.fail( - checkpointFailure("CORRUPT_DATA", { recovery: "RECONCILE" }), - ); - return; - } - context.succeed( - snapshotCheckpoint(request.result), + (row, _nativeStore, context) => { + if (row === undefined) { + context.succeed(null); + return; + } + if (!isResumableUploadCheckpoint(row)) { + context.fail( + checkpointFailure("CORRUPT_DATA", { recovery: "RECONCILE" }), ); - }; + return; + } + context.succeed(snapshotCheckpoint(row)); }, ); }, @@ -345,32 +364,25 @@ export function createIndexedDbResumableUploadCheckpointRuntime( ) { return browserDataFailure("INVALID_INPUT", OPERATION); } - const opened = await connection.acquire(inputValue.signal); - if (!opened.ok) return opened; - return await runCheckpointTransaction( - opened.value, + return await withCheckpointRow( + checkpoint.uploadKey, "readwrite", inputValue.signal, - (nativeStore, context) => { - const request = nativeStore.get(checkpoint.uploadKey); - request.onerror = () => context.fail(mappedFailure(request.error)); - request.onsuccess = () => { - const current = request.result; - if ( - (expectedRevision === null && current !== undefined) || - (expectedRevision !== null && - (!isResumableUploadCheckpoint(current) || - current.revision !== expectedRevision)) - ) { - context.fail( - checkpointFailure("CONFLICT", { recovery: "RECONCILE" }), - ); - return; - } - const put = nativeStore.put(checkpoint); - put.onerror = () => context.fail(mappedFailure(put.error)); - put.onsuccess = () => context.succeed(checkpoint); - }; + (current, nativeStore, context) => { + if ( + (expectedRevision === null && current !== undefined) || + (expectedRevision !== null && + (!isResumableUploadCheckpoint(current) || + current.revision !== expectedRevision)) + ) { + context.fail( + checkpointFailure("CONFLICT", { recovery: "RECONCILE" }), + ); + return; + } + const put = nativeStore.put(checkpoint); + put.onerror = () => context.fail(mappedFailure(put.error)); + put.onsuccess = () => context.succeed(checkpoint); }, ); }, @@ -387,30 +399,51 @@ export function createIndexedDbResumableUploadCheckpointRuntime( ) { return browserDataFailure("INVALID_INPUT", OPERATION); } - const opened = await connection.acquire(inputValue.signal); - if (!opened.ok) return opened; - return await runCheckpointTransaction( - opened.value, + return await withCheckpointRow( + inputValue.uploadKey, "readwrite", inputValue.signal, - (nativeStore, context) => { - const request = nativeStore.get(inputValue.uploadKey); - request.onerror = () => context.fail(mappedFailure(request.error)); - request.onsuccess = () => { - if ( - !isResumableUploadCheckpoint(request.result) || - request.result.revision !== inputValue.expectedRevision - ) { - context.fail( - checkpointFailure("CONFLICT", { recovery: "RECONCILE" }), - ); - return; - } - const deletion = nativeStore.delete(inputValue.uploadKey); - deletion.onerror = () => - context.fail(mappedFailure(deletion.error)); - deletion.onsuccess = () => context.succeed(undefined); - }; + (row, nativeStore, context) => { + if ( + !isResumableUploadCheckpoint(row) || + row.revision !== inputValue.expectedRevision + ) { + context.fail( + checkpointFailure("CONFLICT", { recovery: "RECONCILE" }), + ); + return; + } + deleteCheckpointRow(nativeStore, inputValue.uploadKey, context); + }, + ); + }, + + async removeUnreadable( + inputValue: Parameters< + NonNullable + >[0], + ): Promise> { + if (!SAFE_UPLOAD_KEY.test(inputValue.uploadKey)) { + return browserDataFailure("INVALID_INPUT", OPERATION); + } + return await withCheckpointRow( + inputValue.uploadKey, + "readwrite", + inputValue.signal, + (row, nativeStore, context) => { + // Checked in the same transaction as the delete, so a row another + // context rewrote as a valid checkpoint is never dropped. + if (row === undefined) { + context.succeed(undefined); + return; + } + if (isResumableUploadCheckpoint(row)) { + context.fail( + checkpointFailure("CONFLICT", { recovery: "RECONCILE" }), + ); + return; + } + deleteCheckpointRow(nativeStore, inputValue.uploadKey, context); }, ); }, @@ -477,6 +510,21 @@ export function createIndexedDbResumableUploadCheckpointRuntime( return Object.freeze({ store, admin }); } +type CheckpointTransactionContext = Readonly<{ + succeed(value: Value): void; + fail(failure: BrowserDataFailure): void; +}>; + +function deleteCheckpointRow( + store: IDBObjectStore, + uploadKey: string, + context: CheckpointTransactionContext, +): void { + const deletion = store.delete(uploadKey); + deletion.onerror = () => context.fail(mappedFailure(deletion.error)); + deletion.onsuccess = () => context.succeed(undefined); +} + /** * `durability` is deliberately `undefined` rather than `"default"`: that opens * the transaction with no options bag at all, which is what checkpoint writes @@ -494,10 +542,7 @@ async function runCheckpointTransaction( signal: AbortSignal | undefined, execute: ( store: IDBObjectStore, - context: Readonly<{ - succeed(value: Value): void; - fail(failure: BrowserDataFailure): void; - }>, + context: CheckpointTransactionContext, ) => void, ): Promise> { return await runIndexedDbTransaction({ diff --git a/src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts b/src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts index 08713993..e2bc849b 100644 --- a/src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts +++ b/src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts @@ -91,7 +91,9 @@ export function createPresignedUploadPartExecutor( byteLength: input.part.byteLength, checksumSha256: input.part.checksumSha256, idempotencyKey: input.idempotencyKey, - bytes: Uint8Array.from(input.bytes), + // Q-6.1-3b. The presigned port snapshots `bytes` before any await, + // so a second copy here only doubled the per-part buffer. + bytes: input.bytes, signal: input.signal, }); } catch { diff --git a/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts b/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts index 43ee9a68..efe2ffff 100644 --- a/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts +++ b/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts @@ -1,45 +1,41 @@ import type { - ActiveUploadStatus, QuarantinedUpload, ResumableUploadCheckpoint, - ResumableUploadCheckpointStore, - ResumableUploadControlPlane, ResumableUploadPort, ResumableUploadRequest, UploadAbortOutcome, UploadFileFingerprint, - UploadPartCapability, UploadPartDescriptor, - UploadPartExecutor, UploadPartReceipt, UploadProviderFailure, UploadProviderResult, UploadSession, - UploadSessionStatus, } from "../../../application/ports/browser-transfer/resumable-upload.ts"; import { RESUMABLE_UPLOAD_PROTOCOL } from "../../../application/ports/browser-transfer/resumable-upload.ts"; import type { BrowserDataFailureCode, - BrowserDataObserver, BrowserDataOperation, BrowserDataRecovery, BrowserDataResult, TransferProgress, } from "../../../application/ports/browser-file-storage/shared.ts"; +import { isBrowserDataFailureCode } from "../../../application/ports/browser-file-storage/shared.ts"; import { browserDataFailure, browserDataSuccess, } from "../../browser-file-storage/result.ts"; +import { createAbortableOperation } from "../../platform/abortable-operation.ts"; +import { observeTransferResult } from "../presigned/http-common.ts"; import { + exactRecord, + isAbortSignal, isResumableUploadCheckpoint, - isUploadFileFingerprint, isUploadPartReceipt, MEDIA_TYPE, SAFE_OPAQUE_ID, SAFE_REGISTRY_ID, SAFE_UPLOAD_KEY, samePart, - SHA256_HEX, } from "./checkpoint-schema.ts"; import { buildUploadPartManifest, @@ -49,20 +45,28 @@ import { findManifestPart, iterateUploadParts, readAndVerifyRangePart, - snapshotUploadCrypto, snapshotUploadSource, - verifyPartAgainstManifest, verifyUploadPartBytes, - type UploadCrypto, type UploadPartManifest, type UploadSourceSnapshot, } from "./upload-byte-source.ts"; +import type { ResumableUploadRuntimePolicy } from "./runtime-policy.ts"; import { - resolveResumableUploadRuntimePolicy, - type ResumableUploadRuntimePolicy, -} from "./runtime-policy.ts"; -import type { UploadCancellationChannel } from "./upload-cancellation-channel.ts"; -import type { UploadMutationLock } from "./upload-mutation-lock.ts"; + safeNow, + safeRandom, + snapshotDependencies, + type ResumableUploadRuntimeDependencies, + type RuntimeDependencies, +} from "./runtime-dependencies.ts"; +import { + sameFingerprint, + snapshotReceipts, + validatePartCapability, + validateSession, + validateStatus, +} from "./upload-response-validation.ts"; + +export type { ResumableUploadRuntimeDependencies } from "./runtime-dependencies.ts"; export type ResumableUploadRuntime = ResumableUploadPort & Readonly<{ @@ -86,24 +90,6 @@ export type ResumableUploadRuntime = ResumableUploadPort & lifecycle(): "OPEN" | "CLOSING" | "CLOSED"; }>; -export type ResumableUploadRuntimeDependencies = Readonly<{ - controlPlane: ResumableUploadControlPlane; - partExecutor: UploadPartExecutor; - checkpoints: ResumableUploadCheckpointStore; - mutationLock: UploadMutationLock; - /** - * Runtime-owned ephemeral BroadcastChannel coordination. When omitted, - * explicit abort is still correct but may wait for another context's lock. - */ - crossContextCancellation?: UploadCancellationChannel; - crypto: Crypto; - policy?: Partial; - now?: () => number; - random?: () => number; - sleep?: (delayMs: number, signal: AbortSignal) => Promise; - observer?: BrowserDataObserver; -}>; - type UploadRequestSnapshot = Readonly<{ uploadKey: string; purpose: string; @@ -113,27 +99,6 @@ type UploadRequestSnapshot = Readonly<{ onProgress?: (progress: TransferProgress) => void; }>; -type RuntimeDependencies = Readonly<{ - controlPlane: ResumableUploadControlPlane; - partExecutor: UploadPartExecutor; - checkpoints: ResumableUploadCheckpointStore; - mutationLock: UploadMutationLock; - crossContextCancellation?: UploadCancellationChannel; - crypto: UploadCrypto; - policy: ResumableUploadRuntimePolicy; - now(): number; - random(): number; - sleep(delayMs: number, signal: AbortSignal): Promise; - observer?: BrowserDataObserver; - /** - * TR-04. Every raw provider promise, from the moment the collaborator is - * called until it actually settles. The wrapper that bounds the attempt can - * settle long before the provider does, so the wrapper registry alone could - * report an empty set while physical work was still running. - */ - physicalTasks: Set>; -}>; - type ActiveResolution = | Readonly<{ kind: "ACTIVE"; @@ -144,26 +109,6 @@ type ActiveResolution = upload: QuarantinedUpload; }>; -const FAILURE_CODES: ReadonlySet = new Set([ - "ABORTED", - "BLOCKED", - "CONFLICT", - "CORRUPT_DATA", - "EXPIRED_RESOURCE", - "INTEGRITY_FAILED", - "INVALID_INPUT", - "LIMIT_EXCEEDED", - "MIGRATION_FAILED", - "NOT_FOUND", - "NOT_READABLE", - "PERMISSION_DENIED", - "POLICY_REJECTED", - "QUOTA_EXCEEDED", - "STALE_RESULT", - "STORAGE_EVICTED", - "UNAVAILABLE", - "UNSUPPORTED", -]); const RECOVERIES: ReadonlySet = new Set([ "NONE", "RETRY", @@ -479,14 +424,12 @@ async function executeUpload( return browserDataSuccess(reconciled.value.upload); } if (reconciled.value.kind !== "ACTIVE") { - const removed = await dependencies.checkpoints.remove({ - uploadKey: transferred.value.uploadKey, - expectedRevision: transferred.value.revision, - signal: request.signal, - }); - if (!removed.ok) { - return remapResult(removed, "UPLOAD_RECONCILE"); - } + const removed = await removeCheckpoint( + dependencies, + transferred.value, + request.signal, + ); + if (!removed.ok) return removed; return browserDataFailure("EXPIRED_RESOURCE", "UPLOAD_SESSION", { recovery: "RESTART", }); @@ -547,14 +490,12 @@ async function resolveActiveSession( return browserDataSuccess(reconciled.value); } if (restartIndex === 1) { - const removed = await dependencies.checkpoints.remove({ - uploadKey: checkpoint.uploadKey, - expectedRevision: checkpoint.revision, - signal: request.signal, - }); - if (!removed.ok) { - return remapResult(removed, "UPLOAD_RECONCILE"); - } + const removed = await removeCheckpoint( + dependencies, + checkpoint, + request.signal, + ); + if (!removed.ok) return removed; break; } const replaced = await createUploadSession( @@ -614,12 +555,12 @@ async function reconcileActiveCheckpoint( ); if (!status.ok) return status; if (status.value.state === "QUARANTINED") { - const removed = await dependencies.checkpoints.remove({ - uploadKey: checkpoint.uploadKey, - expectedRevision: checkpoint.revision, - signal: request.signal, - }); - if (!removed.ok) return remapResult(removed, "UPLOAD_RECONCILE"); + const removed = await removeCheckpoint( + dependencies, + checkpoint, + request.signal, + ); + if (!removed.ok) return removed; return browserDataSuccess( Object.freeze({ kind: "COMPLETED" as const, @@ -811,6 +752,22 @@ async function transferMissingParts( ); let nextIndex = 0; let firstFailure: BrowserDataResult | null = null; + // Q-6.1-5. The first failure aborts every sibling worker at once, so an + // in-flight part does not keep retrying until its own attempt deadline. + // The sibling's resulting ABORTED never replaces the failure that won. + const failFast = new AbortController(); + const transferScope = combineAbortSignals( + request.signal, + failFast.signal, + ); + const transferRequest = Object.freeze({ + ...request, + signal: transferScope.signal, + }); + const fail = (failure: BrowserDataResult): void => { + firstFailure ??= failure; + failFast.abort(); + }; // R-1.3. The resolved policy already fits maxConcurrency parts in // maxInFlightBytes, so the concurrency createSession requested is real. const workerCount = Math.min( @@ -831,38 +788,42 @@ async function transferMissingParts( >, part, crypto: dependencies.crypto, - signal: request.signal, + signal: transferRequest.signal, }); if (!bytes.ok) { - firstFailure = bytes; + fail(bytes); return; } const uploaded = await uploadPartWithRetry( dependencies, - request, + transferRequest, manifest, checkpoint, part, bytes.value, ); - observeTerminal( + observeTransferResult( dependencies.observer, "UPLOAD_PART", uploaded, part.byteLength, ); if (!uploaded.ok) { - firstFailure = uploaded; + fail(uploaded); return; } const persisted = await persistReceipt(uploaded.value); if (!persisted.ok) { - firstFailure = persisted; + fail(persisted); return; } } }); - await Promise.all(workers); + try { + await Promise.all(workers); + } finally { + transferScope.release(); + } if (firstFailure) return firstFailure; } else { for await (const partResult of iterateUploadParts({ @@ -904,7 +865,7 @@ async function transferMissingParts( part, verified.value, ); - observeTerminal( + observeTransferResult( dependencies.observer, "UPLOAD_PART", uploaded, @@ -1110,7 +1071,7 @@ async function completeUpload( if (!completed.ok) return stripProviderFailure(completed); const value = completed.value; if ( - !exactKeys(value, [ + !exactRecord(value, [ "state", "protocol", "sessionId", @@ -1131,12 +1092,12 @@ async function completeUpload( { recovery: "RECONCILE" }, ); } - const removed = await dependencies.checkpoints.remove({ - uploadKey: checkpoint.uploadKey, - expectedRevision: checkpoint.revision, - signal: request.signal, - }); - if (!removed.ok) return remapResult(removed, "UPLOAD_RECONCILE"); + const removed = await removeCheckpoint( + dependencies, + checkpoint, + request.signal, + ); + if (!removed.ok) return removed; return browserDataSuccess( quarantinedOutcome(value.resourceId, sessionFromCheckpoint(checkpoint), false), ); @@ -1148,6 +1109,21 @@ async function executeAbort( signal: AbortSignal, ): Promise> { const found = await dependencies.checkpoints.read(uploadKey, signal); + if ( + !found.ok && + found.error.code === "CORRUPT_DATA" && + dependencies.checkpoints.removeUnreadable + ) { + // Q-6.1-6. A row this build cannot read names no session to abort, so + // explicit abort drops it and leaves the server session to expire. + const removed = await dependencies.checkpoints.removeUnreadable({ + uploadKey, + signal, + }); + return removed.ok + ? browserDataSuccess(Object.freeze({ state: "ORPHANED" as const })) + : remapResult(removed, "UPLOAD_ABORT"); + } if (!found.ok) return remapResult(found, "UPLOAD_ABORT"); if (!found.value) { return browserDataSuccess(Object.freeze({ state: "NOT_FOUND" })); @@ -1210,7 +1186,7 @@ async function executeAbort( return stripProviderFailure(aborted); } if ( - !exactKeys(aborted.value, ["state"]) || + !exactRecord(aborted.value, ["state"]) || ![ "ABORTED", "NOT_FOUND", @@ -1237,6 +1213,22 @@ async function executeAbort( return browserDataSuccess(Object.freeze({ state })); } +/** Drops the durable checkpoint a finished or dead session no longer needs. */ +async function removeCheckpoint( + dependencies: RuntimeDependencies, + checkpoint: ResumableUploadCheckpoint, + signal: AbortSignal, +): Promise> { + return remapResult( + await dependencies.checkpoints.remove({ + uploadKey: checkpoint.uploadKey, + expectedRevision: checkpoint.revision, + signal, + }), + "UPLOAD_RECONCILE", + ); +} + async function callWithRetry( dependencies: RuntimeDependencies, operation: BrowserDataOperation, @@ -1273,12 +1265,12 @@ async function callWithRetry( action, ); if (result.ok) { - observeTerminal(dependencies.observer, operation, result); + observeTransferResult(dependencies.observer, operation, result); return result; } lastFailure = result.error; if (!canRetry(result.error, attempt, dependencies.policy)) { - observeTerminal(dependencies.observer, operation, result); + observeTransferResult(dependencies.observer, operation, result); return result; } } @@ -1293,7 +1285,7 @@ async function callWithRetry( "RESUME", ), }) as UploadProviderResult; - observeTerminal(dependencies.observer, operation, exhausted); + observeTransferResult(dependencies.observer, operation, exhausted); return exhausted; } @@ -1308,23 +1300,11 @@ async function invokeProviderAttempt( if (parentSignal.aborted) { return providerFailure("ABORTED", operation, false, "NONE"); } - const controller = new AbortController(); - let timer: ReturnType | undefined; - let releaseAbort = () => {}; - const deadline = new Promise>((resolve) => { - const abort = () => { - controller.abort(); - resolve(providerFailure("ABORTED", operation, false, "NONE")); - }; - parentSignal.addEventListener("abort", abort, { once: true }); - releaseAbort = () => - parentSignal.removeEventListener("abort", abort); - timer = setTimeout(() => { - controller.abort(); - resolve( - providerFailure("UNAVAILABLE", operation, true, "RESUME"), - ); - }, dependencies.policy.providerAttemptTimeoutMs); + // Q-6.1-9. The caller signal and the attempt deadline are the kernel's + // abortable operation, not a second hand-written race. + const attempt = createAbortableOperation({ + signal: parentSignal, + timeoutMs: dependencies.policy.providerAttemptTimeoutMs, }); try { // TR-04. The raw promise enters the physical registry the moment the @@ -1332,20 +1312,20 @@ async function invokeProviderAttempt( // against a deadline let the bounded wrapper settle first and leave the // set empty, so `dispose()` reported a drained runtime while the provider // was still running. - const raw = action(controller.signal); + const raw = action(attempt.signal); const tracked = Promise.resolve(raw).then( () => undefined, () => undefined, ); dependencies.physicalTasks.add(tracked); void tracked.finally(() => dependencies.physicalTasks.delete(tracked)); - return await Promise.race([ - invokeProvider(operation, () => raw), - deadline, - ]); + const outcome = await attempt.race(invokeProvider(operation, () => raw)); + if (outcome.kind === "VALUE") return outcome.value; + return outcome.kind === "TERMINAL" && outcome.terminal === "CALLER_ABORT" + ? providerFailure("ABORTED", operation, false, "NONE") + : providerFailure("UNAVAILABLE", operation, true, "RESUME"); } finally { - if (timer) clearTimeout(timer); - releaseAbort(); + attempt.close(); } } @@ -1420,245 +1400,6 @@ function canRetry( ); } -function validatePartCapability( - value: UploadPartCapability, - checkpoint: ResumableUploadCheckpoint, - uploadBindingSha256: string, - dependencies: RuntimeDependencies, -): BrowserDataResult> { - if ( - !exactKeys(value, [ - "capability", - "uploadBindingSha256", - "expiresAtEpochMs", - ]) || - value.uploadBindingSha256 !== uploadBindingSha256 || - !SHA256_HEX.test(value.uploadBindingSha256) || - !Number.isSafeInteger(value.expiresAtEpochMs) - ) { - return browserDataFailure("CORRUPT_DATA", "UPLOAD_PART", { - recovery: "REISSUE_CAPABILITY", - }); - } - const now = safeNow(dependencies, "UPLOAD_PART"); - if (!now.ok) return now; - if ( - value.expiresAtEpochMs <= - now.value + dependencies.policy.capabilityRefreshSkewMs - ) { - return browserDataFailure("EXPIRED_RESOURCE", "UPLOAD_PART", { - retryable: true, - recovery: "REISSUE_CAPABILITY", - }); - } - if (value.expiresAtEpochMs > checkpoint.sessionExpiresAtEpochMs) { - return browserDataFailure("POLICY_REJECTED", "UPLOAD_PART", { - recovery: "REISSUE_CAPABILITY", - }); - } - return browserDataSuccess(value); -} - -function validateStatus( - value: UploadSessionStatus, - checkpoint: ResumableUploadCheckpoint, - manifest: UploadPartManifest, - dependencies: RuntimeDependencies, -): BrowserDataResult { - if (!value || typeof value !== "object" || Array.isArray(value)) { - return browserDataFailure("CORRUPT_DATA", "UPLOAD_RECONCILE", { - recovery: "RECONCILE", - }); - } - if (value.state === "ACTIVE") { - if (!exactKeys(value, ["state", "session", "acceptedParts"])) { - return browserDataFailure( - "CORRUPT_DATA", - "UPLOAD_RECONCILE", - { recovery: "RECONCILE" }, - ); - } - const session = validateSession( - value.session, - checkpoint.requestBindingSha256, - manifest.fingerprint, - dependencies, - true, - ); - if ( - !session.ok || - session.value.sessionId !== checkpoint.sessionId || - session.value.maxConcurrency !== checkpoint.sessionMaxConcurrency || - session.value.expiresAtEpochMs !== - checkpoint.sessionExpiresAtEpochMs - ) { - return browserDataFailure( - "INTEGRITY_FAILED", - "UPLOAD_RECONCILE", - { recovery: "RECONCILE" }, - ); - } - const receipts = validateServerReceipts( - value, - manifest, - "UPLOAD_RECONCILE", - ); - if (!receipts.ok) return receipts; - return browserDataSuccess( - Object.freeze({ - state: "ACTIVE" as const, - session: session.value, - acceptedParts: receipts.value, - }), - ); - } - if (value.state === "QUARANTINED") { - if (!exactKeys(value, ["state", "session", "resourceId"])) { - return browserDataFailure( - "CORRUPT_DATA", - "UPLOAD_RECONCILE", - { recovery: "RECONCILE" }, - ); - } - const session = validateSession( - value.session, - checkpoint.requestBindingSha256, - manifest.fingerprint, - dependencies, - false, - ); - if ( - !session.ok || - session.value.sessionId !== checkpoint.sessionId || - session.value.maxConcurrency !== checkpoint.sessionMaxConcurrency || - session.value.expiresAtEpochMs !== - checkpoint.sessionExpiresAtEpochMs || - !SAFE_OPAQUE_ID.test(value.resourceId) - ) { - return browserDataFailure( - "INTEGRITY_FAILED", - "UPLOAD_RECONCILE", - { recovery: "RECONCILE" }, - ); - } - return browserDataSuccess( - Object.freeze({ - state: "QUARANTINED" as const, - session: session.value, - resourceId: value.resourceId, - }), - ); - } - if ( - !["ABORTED", "EXPIRED", "NOT_FOUND"].includes(value.state) || - !exactKeys(value, [ - "state", - "protocol", - "sessionId", - "requestBindingSha256", - ]) || - value.protocol !== RESUMABLE_UPLOAD_PROTOCOL || - value.sessionId !== checkpoint.sessionId || - value.requestBindingSha256 !== checkpoint.requestBindingSha256 - ) { - return browserDataFailure("INTEGRITY_FAILED", "UPLOAD_RECONCILE", { - recovery: "RECONCILE", - }); - } - return browserDataSuccess( - Object.freeze({ - state: value.state, - protocol: RESUMABLE_UPLOAD_PROTOCOL, - sessionId: value.sessionId, - requestBindingSha256: value.requestBindingSha256, - }), - ); -} - -function validateSession( - value: UploadSession, - requestBindingSha256: string, - fingerprint: UploadFileFingerprint, - dependencies: RuntimeDependencies, - requireActiveExpiry = true, -): BrowserDataResult { - if ( - !exactKeys(value, [ - "protocol", - "sessionId", - "requestBindingSha256", - "fingerprint", - "partSizeBytes", - "partCount", - "maxConcurrency", - "expiresAtEpochMs", - ]) || - value.protocol !== RESUMABLE_UPLOAD_PROTOCOL || - !SAFE_OPAQUE_ID.test(value.sessionId) || - value.requestBindingSha256 !== requestBindingSha256 || - !SHA256_HEX.test(value.requestBindingSha256) || - !isUploadFileFingerprint(value.fingerprint) || - !sameFingerprint(value.fingerprint, fingerprint) || - value.partSizeBytes !== fingerprint.partSizeBytes || - value.partCount !== fingerprint.partCount || - !Number.isSafeInteger(value.maxConcurrency) || - value.maxConcurrency < 1 || - value.maxConcurrency > dependencies.policy.maxConcurrency || - !Number.isSafeInteger(value.expiresAtEpochMs) - ) { - return browserDataFailure("INTEGRITY_FAILED", "UPLOAD_SESSION", { - recovery: "RECONCILE", - }); - } - const now = safeNow(dependencies, "UPLOAD_SESSION"); - if (!now.ok) return now; - if ( - requireActiveExpiry && - (value.expiresAtEpochMs <= now.value || - value.expiresAtEpochMs - now.value > - dependencies.policy.maxSessionLifetimeMs) - ) { - return browserDataFailure("EXPIRED_RESOURCE", "UPLOAD_SESSION", { - recovery: "RESTART", - }); - } - return browserDataSuccess( - Object.freeze({ - ...value, - fingerprint: Object.freeze({ ...value.fingerprint }), - }), - ); -} - -function validateServerReceipts( - status: ActiveUploadStatus, - manifest: UploadPartManifest, - operation: BrowserDataOperation, -): BrowserDataResult { - if ( - !Array.isArray(status.acceptedParts) || - status.acceptedParts.length > manifest.parts.length - ) { - return browserDataFailure("CORRUPT_DATA", operation, { - recovery: "RECONCILE", - }); - } - let previousPart = 0; - for (const receipt of status.acceptedParts) { - if ( - !isUploadPartReceipt(receipt) || - receipt.partNumber <= previousPart || - !verifyPartAgainstManifest(receipt, manifest) - ) { - return browserDataFailure("INTEGRITY_FAILED", operation, { - recovery: "RECONCILE", - }); - } - previousPart = receipt.partNumber; - } - return browserDataSuccess(snapshotReceipts(status.acceptedParts)); -} - function checkpointFrom( input: | Readonly<{ @@ -1763,256 +1504,6 @@ function snapshotRequest( }); } -function snapshotDependencies( - input: ResumableUploadRuntimeDependencies, - physicalTasks: Set>, -): RuntimeDependencies { - const policy = resolveResumableUploadRuntimePolicy(input.policy); - const controlPlane = snapshotControlPlane(input.controlPlane); - const partExecutor = snapshotPartExecutor(input.partExecutor); - const checkpoints = snapshotCheckpointStore(input.checkpoints); - const mutationLock = snapshotMutationLock(input.mutationLock); - const crossContextCancellation = snapshotCancellationChannel( - input.crossContextCancellation, - ); - const crypto = snapshotUploadCrypto(input.crypto); - const nowSource = input.now ?? Date.now; - const randomSource = input.random ?? Math.random; - const sleepSource = input.sleep ?? abortableSleep; - const observer = snapshotObserver(input.observer); - if ( - typeof nowSource !== "function" || - typeof randomSource !== "function" || - typeof sleepSource !== "function" - ) { - throw new TypeError("Upload runtime dependency is invalid."); - } - return Object.freeze({ - physicalTasks, - controlPlane, - partExecutor, - checkpoints, - mutationLock, - ...(crossContextCancellation - ? { crossContextCancellation } - : {}), - crypto, - policy, - now: () => nowSource(), - random: () => randomSource(), - sleep: async (delayMs, signal) => - await sleepSource(delayMs, signal), - ...(observer ? { observer } : {}), - }); -} - -function snapshotCancellationChannel( - value: UploadCancellationChannel | undefined, -): UploadCancellationChannel | undefined { - if (!value) return undefined; - const publish = value.publish; - const subscribe = value.subscribe; - const close = value.close; - if ( - typeof publish !== "function" || - typeof subscribe !== "function" || - typeof close !== "function" - ) { - throw new TypeError( - "Upload cancellation channel is invalid.", - ); - } - return Object.freeze({ - publish(uploadKey: string): boolean { - try { - return publish.call(value, uploadKey) === true; - } catch { - return false; - } - }, - subscribe( - listener: (uploadKey: string) => void, - ): () => void { - const release = subscribe.call(value, listener); - if (typeof release !== "function") { - throw new TypeError( - "Upload cancellation subscription is invalid.", - ); - } - let active = true; - return () => { - if (!active) return; - active = false; - try { - release(); - } catch { - // Runtime close remains terminal. - } - }; - }, - close(): void { - try { - close.call(value); - } catch { - // Runtime close remains terminal. - } - }, - }); -} - -function snapshotObserver( - value: BrowserDataObserver | undefined, -): BrowserDataObserver | undefined { - if (!value) return undefined; - const record = value.record; - if (typeof record !== "function") { - throw new TypeError("Upload observer is invalid."); - } - return Object.freeze({ - record( - observation: Parameters[0], - ) { - record.call(value, Object.freeze({ ...observation })); - }, - }); -} - -function snapshotControlPlane( - value: ResumableUploadControlPlane, -): ResumableUploadControlPlane { - const createSession = value?.createSession; - const getStatus = value?.getStatus; - const issuePartCapability = value?.issuePartCapability; - const complete = value?.complete; - const abort = value?.abort; - if ( - typeof createSession !== "function" || - typeof getStatus !== "function" || - typeof issuePartCapability !== "function" || - typeof complete !== "function" || - typeof abort !== "function" - ) { - throw new TypeError("Upload control plane is invalid."); - } - const snapshot: ResumableUploadControlPlane = { - async createSession( - input: Parameters< - ResumableUploadControlPlane["createSession"] - >[0], - ) { - return await createSession.call(value, input); - }, - async getStatus( - input: Parameters< - ResumableUploadControlPlane["getStatus"] - >[0], - ) { - return await getStatus.call(value, input); - }, - async issuePartCapability( - input: Parameters< - ResumableUploadControlPlane["issuePartCapability"] - >[0], - ) { - return await issuePartCapability.call(value, input); - }, - async complete( - input: Parameters< - ResumableUploadControlPlane["complete"] - >[0], - ) { - return await complete.call(value, input); - }, - async abort( - input: Parameters< - ResumableUploadControlPlane["abort"] - >[0], - ) { - return await abort.call(value, input); - }, - }; - return Object.freeze(snapshot); -} - -function snapshotPartExecutor( - value: UploadPartExecutor, -): UploadPartExecutor { - const uploadPart = value?.uploadPart; - if (typeof uploadPart !== "function") { - throw new TypeError("Upload part executor is invalid."); - } - const snapshot: UploadPartExecutor = { - async uploadPart( - input: Parameters["uploadPart"]>[0], - ) { - return await uploadPart.call(value, input); - }, - }; - return Object.freeze(snapshot); -} - -function snapshotCheckpointStore( - value: ResumableUploadCheckpointStore, -): ResumableUploadCheckpointStore { - const read = value?.read; - const compareAndSwap = value?.compareAndSwap; - const remove = value?.remove; - const close = value?.close; - if ( - typeof read !== "function" || - typeof compareAndSwap !== "function" || - typeof remove !== "function" || - typeof close !== "function" - ) { - throw new TypeError("Upload checkpoint store is invalid."); - } - const snapshot: ResumableUploadCheckpointStore = { - async read( - uploadKey: string, - signal?: AbortSignal, - ) { - return await read.call(value, uploadKey, signal); - }, - async compareAndSwap( - input: Parameters< - ResumableUploadCheckpointStore["compareAndSwap"] - >[0], - ) { - return await compareAndSwap.call(value, input); - }, - async remove( - input: Parameters[0], - ) { - return await remove.call(value, input); - }, - close() { - close.call(value); - }, - }; - return Object.freeze(snapshot); -} - -function snapshotMutationLock(value: UploadMutationLock): UploadMutationLock { - const run = value?.run; - if (typeof run !== "function") { - throw new TypeError("Upload mutation lock is invalid."); - } - return Object.freeze({ - async run( - uploadKey: string, - signal: AbortSignal, - task: () => Promise, - ): Promise { - return await (run.call( - value, - uploadKey, - signal, - task, - ) as Promise); - }, - }); -} - function normalizeProviderFailure( input: UploadProviderFailure, operation: BrowserDataOperation, @@ -2020,7 +1511,7 @@ function normalizeProviderFailure( if ( !input || typeof input !== "object" || - !FAILURE_CODES.has(input.code) || + !isBrowserDataFailureCode(input.code) || typeof input.retryable !== "boolean" || !RECOVERIES.has(input.recovery) || (input.retryAfterMs !== undefined && @@ -2093,77 +1584,6 @@ function remapResult( }); } -function safeNow( - dependencies: RuntimeDependencies, - operation: BrowserDataOperation, -): BrowserDataResult { - try { - const value = dependencies.now(); - return Number.isSafeInteger(value) && value >= 0 - ? browserDataSuccess(value) - : browserDataFailure("UNAVAILABLE", operation, { - recovery: "RESUME", - }); - } catch { - return browserDataFailure("UNAVAILABLE", operation, { - recovery: "RESUME", - }); - } -} - -function safeRandom( - dependencies: RuntimeDependencies, -): BrowserDataResult { - try { - const value = dependencies.random(); - return Number.isFinite(value) && value >= 0 && value <= 1 - ? browserDataSuccess(value) - : browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", { - recovery: "RESUME", - }); - } catch { - return browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", { - recovery: "RESUME", - }); - } -} - -function sameFingerprint( - left: UploadFileFingerprint, - right: UploadFileFingerprint, -): boolean { - return ( - left.algorithm === right.algorithm && - left.digestHex === right.digestHex && - left.byteLength === right.byteLength && - left.partSizeBytes === right.partSizeBytes && - left.partCount === right.partCount - ); -} - -function snapshotReceipts( - parts: readonly UploadPartReceipt[], -): readonly UploadPartReceipt[] { - return Object.freeze( - parts.map((part) => Object.freeze({ ...part })), - ); -} - -function exactKeys( - value: unknown, - keys: readonly string[], -): value is Record { - if (!value || typeof value !== "object" || Array.isArray(value)) { - return false; - } - const actual = Object.keys(value).sort(); - const expected = [...keys].sort(); - return ( - actual.length === expected.length && - actual.every((key, index) => key === expected[index]) - ); -} - function reportProgress( request: UploadRequestSnapshot, phase: TransferProgress["phase"], @@ -2182,40 +1602,6 @@ function reportProgress( } } -function observeTerminal( - observer: BrowserDataObserver | undefined, - operation: BrowserDataOperation, - result: BrowserDataResult | UploadProviderResult, - byteLength?: number, -): void { - try { - observer?.record( - Object.freeze({ - operation, - outcome: result.ok ? "SUCCEEDED" : "FAILED", - ...(result.ok ? {} : { failureCode: result.error.code }), - ...(byteLength === undefined - ? {} - : { byteBucket: transferByteBucket(byteLength) }), - }), - ); - } catch { - // Upload correctness is independent from best-effort observation. - } -} - -function transferByteBucket( - byteLength: number, -): NonNullable< - Parameters[0]["byteBucket"] -> { - if (byteLength === 0) return "ZERO"; - if (byteLength < 1024 * 1024) return "LT1MIB"; - if (byteLength < 10 * 1024 * 1024) return "1_TO_9MIB"; - if (byteLength < 100 * 1024 * 1024) return "10_TO_99MIB"; - return "GTE100MIB"; -} - function mapLockFailure( error: unknown, operation: BrowserDataOperation, @@ -2258,35 +1644,3 @@ function combineAbortSignals( }, }); } - -function isAbortSignal(value: unknown): value is AbortSignal { - return Boolean( - value && - typeof value === "object" && - typeof (value as AbortSignal).aborted === "boolean" && - typeof (value as AbortSignal).addEventListener === "function" && - typeof (value as AbortSignal).removeEventListener === "function", - ); -} - -async function abortableSleep( - delayMs: number, - signal: AbortSignal, -): Promise { - if (signal.aborted) { - throw new DOMException("The operation was aborted.", "AbortError"); - } - await new Promise((resolve, reject) => { - const timer = setTimeout(finish, delayMs); - function finish() { - signal.removeEventListener("abort", abort); - resolve(); - } - function abort() { - clearTimeout(timer); - signal.removeEventListener("abort", abort); - reject(new DOMException("The operation was aborted.", "AbortError")); - } - signal.addEventListener("abort", abort, { once: true }); - }); -} diff --git a/src/adapters/browser-transfer/resumable-upload/runtime-dependencies.ts b/src/adapters/browser-transfer/resumable-upload/runtime-dependencies.ts new file mode 100644 index 00000000..5b1537e5 --- /dev/null +++ b/src/adapters/browser-transfer/resumable-upload/runtime-dependencies.ts @@ -0,0 +1,378 @@ +import type { + ResumableUploadCheckpointStore, + ResumableUploadControlPlane, + UploadPartExecutor, +} from "../../../application/ports/browser-transfer/resumable-upload.ts"; +import type { + BrowserDataObserver, + BrowserDataOperation, + BrowserDataResult, +} from "../../../application/ports/browser-file-storage/shared.ts"; +import { + browserDataFailure, + browserDataSuccess, +} from "../../browser-file-storage/result.ts"; +import { createAbortableOperation } from "../../platform/abortable-operation.ts"; +import { snapshotUploadCrypto, type UploadCrypto } from "./upload-byte-source.ts"; +import { + resolveResumableUploadRuntimePolicy, + type ResumableUploadRuntimePolicy, +} from "./runtime-policy.ts"; +import type { UploadCancellationChannel } from "./upload-cancellation-channel.ts"; +import type { UploadMutationLock } from "./upload-mutation-lock.ts"; + +/** + * Q-6.1-10. The resumable upload runtime's injected collaborators. Each one is + * validated and its methods captured once at composition, so replacing a + * method afterwards cannot change what an upload in flight calls. + */ + +export type ResumableUploadRuntimeDependencies = Readonly<{ + controlPlane: ResumableUploadControlPlane; + partExecutor: UploadPartExecutor; + checkpoints: ResumableUploadCheckpointStore; + mutationLock: UploadMutationLock; + /** + * Runtime-owned ephemeral BroadcastChannel coordination. When omitted, + * explicit abort is still correct but may wait for another context's lock. + */ + crossContextCancellation?: UploadCancellationChannel; + crypto: Crypto; + policy?: Partial; + now?: () => number; + random?: () => number; + sleep?: (delayMs: number, signal: AbortSignal) => Promise; + observer?: BrowserDataObserver; +}>; + +export type RuntimeDependencies = Readonly<{ + controlPlane: ResumableUploadControlPlane; + partExecutor: UploadPartExecutor; + checkpoints: ResumableUploadCheckpointStore; + mutationLock: UploadMutationLock; + crossContextCancellation?: UploadCancellationChannel; + crypto: UploadCrypto; + policy: ResumableUploadRuntimePolicy; + now(): number; + random(): number; + sleep(delayMs: number, signal: AbortSignal): Promise; + observer?: BrowserDataObserver; + /** + * TR-04. Every raw provider promise, from the moment the collaborator is + * called until it actually settles. The wrapper that bounds the attempt can + * settle long before the provider does, so the wrapper registry alone could + * report an empty set while physical work was still running. + */ + physicalTasks: Set>; +}>; + +export function snapshotDependencies( + input: ResumableUploadRuntimeDependencies, + physicalTasks: Set>, +): RuntimeDependencies { + const policy = resolveResumableUploadRuntimePolicy(input.policy); + const controlPlane = snapshotControlPlane(input.controlPlane); + const partExecutor = snapshotPartExecutor(input.partExecutor); + const checkpoints = snapshotCheckpointStore(input.checkpoints); + const mutationLock = snapshotMutationLock(input.mutationLock); + const crossContextCancellation = snapshotCancellationChannel( + input.crossContextCancellation, + ); + const crypto = snapshotUploadCrypto(input.crypto); + const nowSource = input.now ?? Date.now; + const randomSource = input.random ?? Math.random; + const sleepSource = input.sleep ?? abortableSleep; + const observer = snapshotObserver(input.observer); + if ( + typeof nowSource !== "function" || + typeof randomSource !== "function" || + typeof sleepSource !== "function" + ) { + throw new TypeError("Upload runtime dependency is invalid."); + } + return Object.freeze({ + physicalTasks, + controlPlane, + partExecutor, + checkpoints, + mutationLock, + ...(crossContextCancellation + ? { crossContextCancellation } + : {}), + crypto, + policy, + now: () => nowSource(), + random: () => randomSource(), + sleep: async (delayMs, signal) => + await sleepSource(delayMs, signal), + ...(observer ? { observer } : {}), + }); +} + +function snapshotCancellationChannel( + value: UploadCancellationChannel | undefined, +): UploadCancellationChannel | undefined { + if (!value) return undefined; + const publish = value.publish; + const subscribe = value.subscribe; + const close = value.close; + if ( + typeof publish !== "function" || + typeof subscribe !== "function" || + typeof close !== "function" + ) { + throw new TypeError( + "Upload cancellation channel is invalid.", + ); + } + return Object.freeze({ + publish(uploadKey: string): boolean { + try { + return publish.call(value, uploadKey) === true; + } catch { + return false; + } + }, + subscribe( + listener: (uploadKey: string) => void, + ): () => void { + const release = subscribe.call(value, listener); + if (typeof release !== "function") { + throw new TypeError( + "Upload cancellation subscription is invalid.", + ); + } + let active = true; + return () => { + if (!active) return; + active = false; + try { + release(); + } catch { + // Runtime close remains terminal. + } + }; + }, + close(): void { + try { + close.call(value); + } catch { + // Runtime close remains terminal. + } + }, + }); +} + +function snapshotObserver( + value: BrowserDataObserver | undefined, +): BrowserDataObserver | undefined { + if (!value) return undefined; + const record = value.record; + if (typeof record !== "function") { + throw new TypeError("Upload observer is invalid."); + } + return Object.freeze({ + record( + observation: Parameters[0], + ) { + record.call(value, Object.freeze({ ...observation })); + }, + }); +} + +function snapshotControlPlane( + value: ResumableUploadControlPlane, +): ResumableUploadControlPlane { + const createSession = value?.createSession; + const getStatus = value?.getStatus; + const issuePartCapability = value?.issuePartCapability; + const complete = value?.complete; + const abort = value?.abort; + if ( + typeof createSession !== "function" || + typeof getStatus !== "function" || + typeof issuePartCapability !== "function" || + typeof complete !== "function" || + typeof abort !== "function" + ) { + throw new TypeError("Upload control plane is invalid."); + } + const snapshot: ResumableUploadControlPlane = { + async createSession( + input: Parameters< + ResumableUploadControlPlane["createSession"] + >[0], + ) { + return await createSession.call(value, input); + }, + async getStatus( + input: Parameters< + ResumableUploadControlPlane["getStatus"] + >[0], + ) { + return await getStatus.call(value, input); + }, + async issuePartCapability( + input: Parameters< + ResumableUploadControlPlane["issuePartCapability"] + >[0], + ) { + return await issuePartCapability.call(value, input); + }, + async complete( + input: Parameters< + ResumableUploadControlPlane["complete"] + >[0], + ) { + return await complete.call(value, input); + }, + async abort( + input: Parameters< + ResumableUploadControlPlane["abort"] + >[0], + ) { + return await abort.call(value, input); + }, + }; + return Object.freeze(snapshot); +} + +function snapshotPartExecutor( + value: UploadPartExecutor, +): UploadPartExecutor { + const uploadPart = value?.uploadPart; + if (typeof uploadPart !== "function") { + throw new TypeError("Upload part executor is invalid."); + } + const snapshot: UploadPartExecutor = { + async uploadPart( + input: Parameters["uploadPart"]>[0], + ) { + return await uploadPart.call(value, input); + }, + }; + return Object.freeze(snapshot); +} + +function snapshotCheckpointStore( + value: ResumableUploadCheckpointStore, +): ResumableUploadCheckpointStore { + const read = value?.read; + const compareAndSwap = value?.compareAndSwap; + const remove = value?.remove; + const removeUnreadable = value?.removeUnreadable; + const close = value?.close; + if ( + typeof read !== "function" || + typeof compareAndSwap !== "function" || + typeof remove !== "function" || + (removeUnreadable !== undefined && + typeof removeUnreadable !== "function") || + typeof close !== "function" + ) { + throw new TypeError("Upload checkpoint store is invalid."); + } + const snapshot: ResumableUploadCheckpointStore = { + async read( + uploadKey: string, + signal?: AbortSignal, + ) { + return await read.call(value, uploadKey, signal); + }, + async compareAndSwap( + input: Parameters< + ResumableUploadCheckpointStore["compareAndSwap"] + >[0], + ) { + return await compareAndSwap.call(value, input); + }, + async remove( + input: Parameters[0], + ) { + return await remove.call(value, input); + }, + ...(removeUnreadable + ? { + async removeUnreadable( + input: Parameters[0], + ) { + return await removeUnreadable.call(value, input); + }, + } + : {}), + close() { + close.call(value); + }, + }; + return Object.freeze(snapshot); +} + +function snapshotMutationLock(value: UploadMutationLock): UploadMutationLock { + const run = value?.run; + if (typeof run !== "function") { + throw new TypeError("Upload mutation lock is invalid."); + } + return Object.freeze({ + async run( + uploadKey: string, + signal: AbortSignal, + task: () => Promise, + ): Promise { + return await (run.call( + value, + uploadKey, + signal, + task, + ) as Promise); + }, + }); +} + +export function safeNow( + dependencies: RuntimeDependencies, + operation: BrowserDataOperation, +): BrowserDataResult { + try { + const value = dependencies.now(); + return Number.isSafeInteger(value) && value >= 0 + ? browserDataSuccess(value) + : browserDataFailure("UNAVAILABLE", operation, { + recovery: "RESUME", + }); + } catch { + return browserDataFailure("UNAVAILABLE", operation, { + recovery: "RESUME", + }); + } +} + +export function safeRandom( + dependencies: RuntimeDependencies, +): BrowserDataResult { + try { + const value = dependencies.random(); + return Number.isFinite(value) && value >= 0 && value <= 1 + ? browserDataSuccess(value) + : browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", { + recovery: "RESUME", + }); + } catch { + return browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", { + recovery: "RESUME", + }); + } +} + +async function abortableSleep( + delayMs: number, + signal: AbortSignal, +): Promise { + // The kernel owns the timer and the abort listener; the sleep only waits + // for whichever of the two ends the operation first. + const sleep = createAbortableOperation({ signal, timeoutMs: delayMs }); + const ended = await sleep.race(new Promise(() => {})); + sleep.close(); + if (ended.kind !== "TERMINAL" || ended.terminal !== "DEADLINE") { + throw new DOMException("The operation was aborted.", "AbortError"); + } +} diff --git a/src/adapters/browser-transfer/resumable-upload/runtime-policy.ts b/src/adapters/browser-transfer/resumable-upload/runtime-policy.ts index 57838b75..9ced011a 100644 --- a/src/adapters/browser-transfer/resumable-upload/runtime-policy.ts +++ b/src/adapters/browser-transfer/resumable-upload/runtime-policy.ts @@ -1,3 +1,8 @@ +import { + isPositiveSafeInteger as positiveSafeInteger, + isNonNegativeSafeInteger as nonNegativeSafeInteger, +} from "../../../application/ports/browser-file-storage/shared.ts"; + export type ResumableUploadRuntimePolicy = Readonly<{ partSizeBytes: number; maxFileBytes: number; @@ -116,11 +121,3 @@ export function resolveResumableUploadRuntimePolicy( } return policy; } - -function positiveSafeInteger(value: number): boolean { - return Number.isSafeInteger(value) && value > 0; -} - -function nonNegativeSafeInteger(value: number): boolean { - return Number.isSafeInteger(value) && value >= 0; -} diff --git a/src/adapters/browser-transfer/resumable-upload/upload-byte-source.ts b/src/adapters/browser-transfer/resumable-upload/upload-byte-source.ts index e2cecfeb..852d4551 100644 --- a/src/adapters/browser-transfer/resumable-upload/upload-byte-source.ts +++ b/src/adapters/browser-transfer/resumable-upload/upload-byte-source.ts @@ -13,6 +13,9 @@ import { browserDataSuccess, } from "../../browser-file-storage/result.ts"; import { samePart } from "./checkpoint-schema.ts"; +import { + isPositiveSafeInteger as positiveSafeInteger, +} from "../../../application/ports/browser-file-storage/shared.ts"; export type UploadCrypto = Readonly<{ digestSha256(bytes: Uint8Array): Promise; @@ -594,7 +597,3 @@ function remapFailure( }), }); } - -function positiveSafeInteger(value: unknown): value is number { - return Number.isSafeInteger(value) && (value as number) > 0; -} diff --git a/src/adapters/browser-transfer/resumable-upload/upload-response-validation.ts b/src/adapters/browser-transfer/resumable-upload/upload-response-validation.ts new file mode 100644 index 00000000..8cd48536 --- /dev/null +++ b/src/adapters/browser-transfer/resumable-upload/upload-response-validation.ts @@ -0,0 +1,296 @@ +import type { + ActiveUploadStatus, + ResumableUploadCheckpoint, + UploadFileFingerprint, + UploadPartCapability, + UploadPartReceipt, + UploadSession, + UploadSessionStatus, +} from "../../../application/ports/browser-transfer/resumable-upload.ts"; +import { RESUMABLE_UPLOAD_PROTOCOL } from "../../../application/ports/browser-transfer/resumable-upload.ts"; +import type { + BrowserDataOperation, + BrowserDataResult, +} from "../../../application/ports/browser-file-storage/shared.ts"; +import { + browserDataFailure, + browserDataSuccess, +} from "../../browser-file-storage/result.ts"; +import { + exactRecord, + isUploadFileFingerprint, + isUploadPartReceipt, + SAFE_OPAQUE_ID, + SHA256_HEX, +} from "./checkpoint-schema.ts"; +import { safeNow, type RuntimeDependencies } from "./runtime-dependencies.ts"; +import { + verifyPartAgainstManifest, + type UploadPartManifest, +} from "./upload-byte-source.ts"; + +/** + * Q-6.1-10. Strict decoders for what the control plane returns: a session, a + * status, a part capability and the accepted receipts. Every failure is closed + * with the recovery the runtime reports unchanged. + */ + +export function validatePartCapability( + value: UploadPartCapability, + checkpoint: ResumableUploadCheckpoint, + uploadBindingSha256: string, + dependencies: RuntimeDependencies, +): BrowserDataResult> { + if ( + !exactRecord(value, [ + "capability", + "uploadBindingSha256", + "expiresAtEpochMs", + ]) || + value.uploadBindingSha256 !== uploadBindingSha256 || + !SHA256_HEX.test(value.uploadBindingSha256) || + !Number.isSafeInteger(value.expiresAtEpochMs) + ) { + return browserDataFailure("CORRUPT_DATA", "UPLOAD_PART", { + recovery: "REISSUE_CAPABILITY", + }); + } + const now = safeNow(dependencies, "UPLOAD_PART"); + if (!now.ok) return now; + if ( + value.expiresAtEpochMs <= + now.value + dependencies.policy.capabilityRefreshSkewMs + ) { + return browserDataFailure("EXPIRED_RESOURCE", "UPLOAD_PART", { + retryable: true, + recovery: "REISSUE_CAPABILITY", + }); + } + if (value.expiresAtEpochMs > checkpoint.sessionExpiresAtEpochMs) { + return browserDataFailure("POLICY_REJECTED", "UPLOAD_PART", { + recovery: "REISSUE_CAPABILITY", + }); + } + return browserDataSuccess(value); +} + +export function validateStatus( + value: UploadSessionStatus, + checkpoint: ResumableUploadCheckpoint, + manifest: UploadPartManifest, + dependencies: RuntimeDependencies, +): BrowserDataResult { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return browserDataFailure("CORRUPT_DATA", "UPLOAD_RECONCILE", { + recovery: "RECONCILE", + }); + } + if (value.state === "ACTIVE") { + if (!exactRecord(value, ["state", "session", "acceptedParts"])) { + return browserDataFailure( + "CORRUPT_DATA", + "UPLOAD_RECONCILE", + { recovery: "RECONCILE" }, + ); + } + const session = validateSession( + value.session, + checkpoint.requestBindingSha256, + manifest.fingerprint, + dependencies, + true, + ); + if ( + !session.ok || + session.value.sessionId !== checkpoint.sessionId || + session.value.maxConcurrency !== checkpoint.sessionMaxConcurrency || + session.value.expiresAtEpochMs !== + checkpoint.sessionExpiresAtEpochMs + ) { + return browserDataFailure( + "INTEGRITY_FAILED", + "UPLOAD_RECONCILE", + { recovery: "RECONCILE" }, + ); + } + const receipts = validateServerReceipts( + value, + manifest, + "UPLOAD_RECONCILE", + ); + if (!receipts.ok) return receipts; + return browserDataSuccess( + Object.freeze({ + state: "ACTIVE" as const, + session: session.value, + acceptedParts: receipts.value, + }), + ); + } + if (value.state === "QUARANTINED") { + if (!exactRecord(value, ["state", "session", "resourceId"])) { + return browserDataFailure( + "CORRUPT_DATA", + "UPLOAD_RECONCILE", + { recovery: "RECONCILE" }, + ); + } + const session = validateSession( + value.session, + checkpoint.requestBindingSha256, + manifest.fingerprint, + dependencies, + false, + ); + if ( + !session.ok || + session.value.sessionId !== checkpoint.sessionId || + session.value.maxConcurrency !== checkpoint.sessionMaxConcurrency || + session.value.expiresAtEpochMs !== + checkpoint.sessionExpiresAtEpochMs || + !SAFE_OPAQUE_ID.test(value.resourceId) + ) { + return browserDataFailure( + "INTEGRITY_FAILED", + "UPLOAD_RECONCILE", + { recovery: "RECONCILE" }, + ); + } + return browserDataSuccess( + Object.freeze({ + state: "QUARANTINED" as const, + session: session.value, + resourceId: value.resourceId, + }), + ); + } + if ( + !["ABORTED", "EXPIRED", "NOT_FOUND"].includes(value.state) || + !exactRecord(value, [ + "state", + "protocol", + "sessionId", + "requestBindingSha256", + ]) || + value.protocol !== RESUMABLE_UPLOAD_PROTOCOL || + value.sessionId !== checkpoint.sessionId || + value.requestBindingSha256 !== checkpoint.requestBindingSha256 + ) { + return browserDataFailure("INTEGRITY_FAILED", "UPLOAD_RECONCILE", { + recovery: "RECONCILE", + }); + } + return browserDataSuccess( + Object.freeze({ + state: value.state, + protocol: RESUMABLE_UPLOAD_PROTOCOL, + sessionId: value.sessionId, + requestBindingSha256: value.requestBindingSha256, + }), + ); +} + +export function validateSession( + value: UploadSession, + requestBindingSha256: string, + fingerprint: UploadFileFingerprint, + dependencies: RuntimeDependencies, + requireActiveExpiry = true, +): BrowserDataResult { + if ( + !exactRecord(value, [ + "protocol", + "sessionId", + "requestBindingSha256", + "fingerprint", + "partSizeBytes", + "partCount", + "maxConcurrency", + "expiresAtEpochMs", + ]) || + value.protocol !== RESUMABLE_UPLOAD_PROTOCOL || + !SAFE_OPAQUE_ID.test(value.sessionId) || + value.requestBindingSha256 !== requestBindingSha256 || + !SHA256_HEX.test(value.requestBindingSha256) || + !isUploadFileFingerprint(value.fingerprint) || + !sameFingerprint(value.fingerprint, fingerprint) || + value.partSizeBytes !== fingerprint.partSizeBytes || + value.partCount !== fingerprint.partCount || + !Number.isSafeInteger(value.maxConcurrency) || + value.maxConcurrency < 1 || + value.maxConcurrency > dependencies.policy.maxConcurrency || + !Number.isSafeInteger(value.expiresAtEpochMs) + ) { + return browserDataFailure("INTEGRITY_FAILED", "UPLOAD_SESSION", { + recovery: "RECONCILE", + }); + } + const now = safeNow(dependencies, "UPLOAD_SESSION"); + if (!now.ok) return now; + if ( + requireActiveExpiry && + (value.expiresAtEpochMs <= now.value || + value.expiresAtEpochMs - now.value > + dependencies.policy.maxSessionLifetimeMs) + ) { + return browserDataFailure("EXPIRED_RESOURCE", "UPLOAD_SESSION", { + recovery: "RESTART", + }); + } + return browserDataSuccess( + Object.freeze({ + ...value, + fingerprint: Object.freeze({ ...value.fingerprint }), + }), + ); +} + +function validateServerReceipts( + status: ActiveUploadStatus, + manifest: UploadPartManifest, + operation: BrowserDataOperation, +): BrowserDataResult { + if ( + !Array.isArray(status.acceptedParts) || + status.acceptedParts.length > manifest.parts.length + ) { + return browserDataFailure("CORRUPT_DATA", operation, { + recovery: "RECONCILE", + }); + } + let previousPart = 0; + for (const receipt of status.acceptedParts) { + if ( + !isUploadPartReceipt(receipt) || + receipt.partNumber <= previousPart || + !verifyPartAgainstManifest(receipt, manifest) + ) { + return browserDataFailure("INTEGRITY_FAILED", operation, { + recovery: "RECONCILE", + }); + } + previousPart = receipt.partNumber; + } + return browserDataSuccess(snapshotReceipts(status.acceptedParts)); +} + +export function sameFingerprint( + left: UploadFileFingerprint, + right: UploadFileFingerprint, +): boolean { + return ( + left.algorithm === right.algorithm && + left.digestHex === right.digestHex && + left.byteLength === right.byteLength && + left.partSizeBytes === right.partSizeBytes && + left.partCount === right.partCount + ); +} + +export function snapshotReceipts( + parts: readonly UploadPartReceipt[], +): readonly UploadPartReceipt[] { + return Object.freeze( + parts.map((part) => Object.freeze({ ...part })), + ); +} diff --git a/src/adapters/cache-storage/public-cache-codec.ts b/src/adapters/cache-storage/public-cache-codec.ts new file mode 100644 index 00000000..6482c0f3 --- /dev/null +++ b/src/adapters/cache-storage/public-cache-codec.ts @@ -0,0 +1,656 @@ +import type { + PublicCacheAsset, + PublicCacheHeader, + PublicCacheReleaseManifest, +} from "../../application/ports/browser-file-storage/cache-storage-ports.ts"; +import type { + BrowserDataFailure, + BrowserDataFailureCode, + BrowserDataOperation, + BrowserDataResult, +} from "../../application/ports/browser-file-storage/shared.ts"; +import { + browserDataFailure, + mapBrowserDataException, +} from "../browser-file-storage/result.ts"; +import { + isAllowedPublicCacheOrigin, + type PublicCacheRuntimePolicy, +} from "./public-cache-policy.ts"; + +/** + * Q-6.2-11. Release manifest, marker and active-pointer codec for the public + * response cache: normalization, canonical digest input, bounded control JSON + * decoding, owned cache naming, and the mapping of a validation failure to a + * browser-data Result. Moved verbatim out of the adapter. + */ + +export type PublicCacheCryptoFacade = Readonly<{ + digestSha256(bytes: Uint8Array): Promise; +}>; + +export type NormalizedAsset = Readonly<{ + absoluteUrl: string; + expectedByteLength: number; + expectedContentType: string; + digestHex: string; + requestHeaders: readonly PublicCacheHeader[]; +}>; + +export type NormalizedReleaseManifest = Readonly<{ + releaseRegistryId: string; + manifestDigestHex: string; + assets: readonly NormalizedAsset[]; +}>; + +export type ReleaseMarker = Readonly<{ + schemaVersion: 1; + verified: true; + releaseRegistryId: string; + manifestDigestHex: string; + entryCount: number; + totalBytes: number; + stagedAtEpochMs: number; + assets: readonly NormalizedAsset[]; +}>; + +export type ActiveReleasePointer = Readonly<{ + schemaVersion: 1; + releaseRegistryId: string; + manifestDigestHex: string; + candidateCacheName: string; + rollbackCandidateCacheNames: readonly string[]; + activatedAtEpochMs: number; +}>; + +export type BrowserFailureResult = Readonly<{ + ok: false; + error: BrowserDataFailure; +}>; + +export class CacheValidationFailure extends Error { + readonly code: BrowserDataFailureCode; + + constructor(code: BrowserDataFailureCode) { + super("Public cache validation failed."); + this.name = "CacheValidationFailure"; + this.code = code; + } +} + +export async function normalizeAndVerifyManifest( + manifest: PublicCacheReleaseManifest, + policy: PublicCacheRuntimePolicy, + crypto: PublicCacheCryptoFacade, +): Promise { + const snapshot = Object.freeze({ + releaseRegistryId: manifest.releaseRegistryId, + manifestDigestHex: manifest.manifestDigestHex, + assets: normalizeAssets(manifest.assets, policy), + }); + if ( + !policy.isReleaseRegistryIdAllowed(snapshot.releaseRegistryId) || + !SHA256_HEX.test(snapshot.manifestDigestHex) + ) { + throw new CacheValidationFailure("INVALID_INPUT"); + } + const actualDigest = await sha256Hex( + crypto, + new TextEncoder().encode( + canonicalManifest(snapshot.releaseRegistryId, snapshot.assets), + ), + ); + if (actualDigest !== snapshot.manifestDigestHex) { + throw new CacheValidationFailure("INTEGRITY_FAILED"); + } + return snapshot; +} + +export function normalizeAssets( + assets: readonly PublicCacheAsset[], + policy: PublicCacheRuntimePolicy, +): readonly NormalizedAsset[] { + if ( + !Array.isArray(assets) || + assets.length < 1 || + assets.length > policy.maxEntriesPerRelease + ) { + throw new CacheValidationFailure("LIMIT_EXCEEDED"); + } + const normalized = assets.map((asset) => + normalizeAsset(asset, policy), + ); + const keys = normalized.map(assetKey); + if (new Set(keys).size !== keys.length) { + throw new CacheValidationFailure("CONFLICT"); + } + const declaredTotal = normalized.reduce( + (total, asset) => total + asset.expectedByteLength, + 0, + ); + if ( + !Number.isSafeInteger(declaredTotal) || + declaredTotal > policy.maxReleaseBytes + ) { + throw new CacheValidationFailure("LIMIT_EXCEEDED"); + } + return Object.freeze(normalized); +} + +export function normalizeAsset( + asset: PublicCacheAsset, + policy: PublicCacheRuntimePolicy, +): NormalizedAsset { + if ( + !asset || + typeof asset !== "object" || + !Number.isSafeInteger(asset.expectedByteLength) || + asset.expectedByteLength < 0 || + asset.expectedByteLength > policy.maxEntryBytes || + asset.integrity?.algorithm !== "SHA-256" || + !SHA256_HEX.test(asset.integrity.digestHex) + ) { + throw new CacheValidationFailure("INVALID_INPUT"); + } + return Object.freeze({ + absoluteUrl: normalizePublicUrl(asset.absoluteUrl, policy), + expectedByteLength: asset.expectedByteLength, + expectedContentType: normalizeContentType( + asset.expectedContentType, + policy, + ), + digestHex: asset.integrity.digestHex, + requestHeaders: normalizeRequestHeaders( + asset.requestHeaders, + policy, + ), + }); +} + +export function normalizeLookupRequest( + absoluteUrl: string, + requestHeaders: readonly PublicCacheHeader[] | undefined, + policy: PublicCacheRuntimePolicy, +): NormalizedAsset { + return { + absoluteUrl: normalizePublicUrl(absoluteUrl, policy), + expectedByteLength: 0, + expectedContentType: "", + digestHex: ZERO_SHA256, + requestHeaders: normalizeRequestHeaders(requestHeaders, policy), + }; +} + +export function normalizeContentType( + input: string, + policy: PublicCacheRuntimePolicy, +): string { + if ( + typeof input !== "string" || + input.length < 1 || + input.length > 256 || + /[\r\n\0]/u.test(input) || + !policy.isContentTypeAllowed(input) + ) { + throw new CacheValidationFailure("POLICY_REJECTED"); + } + return input + .split(";") + .map((part) => part.trim()) + .filter((part) => part.length > 0) + .map((part, index) => + index === 0 ? part.toLowerCase() : part, + ) + .join("; "); +} + +export function normalizePublicUrl( + input: string, + policy: PublicCacheRuntimePolicy, +): string { + if (typeof input !== "string" || input.length > 2_048) { + throw new CacheValidationFailure("INVALID_INPUT"); + } + let url: URL; + try { + url = new URL(input); + } catch { + throw new CacheValidationFailure("INVALID_INPUT"); + } + if ( + url.origin !== policy.origin || + !isAllowedPublicCacheOrigin(url) || + url.username.length > 0 || + url.password.length > 0 || + url.hash.length > 0 || + url.href === markerRequestUrl(policy) || + url.href === activePointerRequestUrl(policy) + ) { + throw new CacheValidationFailure("POLICY_REJECTED"); + } + const forbidden = new Set(policy.forbiddenQueryParameterNames); + const allowed = new Set(policy.allowedQueryParameterNames); + const seenNames = new Set(); + for (const [rawName, value] of url.searchParams.entries()) { + const name = rawName.toLowerCase(); + if ( + forbidden.has(name) || + !allowed.has(name) || + seenNames.has(name) || + !policy.isQueryParameterValueAllowed(name, value) + ) { + throw new CacheValidationFailure("POLICY_REJECTED"); + } + seenNames.add(name); + } + return url.href; +} + +export function normalizeRequestHeaders( + input: readonly PublicCacheHeader[] | undefined, + policy: PublicCacheRuntimePolicy, +): readonly PublicCacheHeader[] { + const allowed = new Set(policy.allowedRequestHeaderNames); + const forbidden = new Set([ + "authorization", + "cookie", + "proxy-authorization", + "range", + ]); + const headers = new Headers(); + for (const pair of input ?? []) { + if ( + !Array.isArray(pair) || + pair.length !== 2 || + typeof pair[0] !== "string" || + typeof pair[1] !== "string" + ) { + throw new CacheValidationFailure("INVALID_INPUT"); + } + const name = pair[0].toLowerCase(); + if ( + forbidden.has(name) || + !allowed.has(name) || + pair[1].length > 1_024 || + /[\r\n\0]/u.test(pair[1]) + ) { + throw new CacheValidationFailure("POLICY_REJECTED"); + } + headers.append(name, pair[1].trim()); + } + return Object.freeze( + [...headers.entries()] + .sort(([left], [right]) => left.localeCompare(right)) + .map( + ([name, value]) => + Object.freeze([name, value]) as PublicCacheHeader, + ), + ); +} + +export async function readBoundedJson( + response: Response, + maximumBytes: number, +): Promise { + const contentLength = response.headers.get("content-length"); + if ( + !Number.isSafeInteger(maximumBytes) || + maximumBytes <= 0 || + (contentLength !== null && + (!/^\d+$/u.test(contentLength) || + Number(contentLength) > maximumBytes)) + ) { + throw new CacheValidationFailure("CORRUPT_DATA"); + } + if (!response.body) { + throw new CacheValidationFailure("CORRUPT_DATA"); + } + + const reader = response.body.getReader(); + // Q-6.2-6. Chunks are kept as read; the budget is enforced on their total, + // never by preallocating it. + const chunks: Uint8Array[] = []; + let byteLength = 0; + let completelyRead = false; + try { + while (true) { + const chunk = await reader.read(); + if (chunk.done) { + completelyRead = true; + break; + } + if (chunk.value.byteLength > maximumBytes - byteLength) { + throw new CacheValidationFailure("CORRUPT_DATA"); + } + chunks.push(chunk.value); + byteLength += chunk.value.byteLength; + } + } catch (error) { + if (!completelyRead) { + cancelReaderSafely( + reader, + "Cache control JSON exceeded its read budget.", + ); + } + throw error; + } finally { + reader.releaseLock(); + } + + const bytes = new Uint8Array(byteLength); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + let text: string; + try { + text = new TextDecoder("utf-8", { fatal: true }).decode(bytes); + } catch { + throw new CacheValidationFailure("CORRUPT_DATA"); + } + try { + return JSON.parse(text); + } catch { + throw new CacheValidationFailure("CORRUPT_DATA"); + } +} + +export function cancelReaderSafely( + reader: ReadableStreamDefaultReader, + reason: string, +): void { + try { + void reader.cancel(reason).catch(() => undefined); + } catch { + // Cancellation is best effort once the bounded consumer has stopped. + } +} + +export function isReleaseMarker( + value: unknown, + policy: PublicCacheRuntimePolicy, +): value is ReleaseMarker { + if ( + !value || + typeof value !== "object" || + !("schemaVersion" in value) || + value.schemaVersion !== 1 || + !("verified" in value) || + value.verified !== true || + !("releaseRegistryId" in value) || + typeof value.releaseRegistryId !== "string" || + !policy.isReleaseRegistryIdAllowed(value.releaseRegistryId) || + !("manifestDigestHex" in value) || + typeof value.manifestDigestHex !== "string" || + !SHA256_HEX.test(value.manifestDigestHex) || + !("entryCount" in value) || + typeof value.entryCount !== "number" || + !Number.isSafeInteger(value.entryCount) || + !("totalBytes" in value) || + typeof value.totalBytes !== "number" || + !Number.isSafeInteger(value.totalBytes) || + !("stagedAtEpochMs" in value) || + typeof value.stagedAtEpochMs !== "number" || + !Number.isSafeInteger(value.stagedAtEpochMs) || + !("assets" in value) || + !Array.isArray(value.assets) || + value.assets.length > policy.maxEntriesPerRelease + ) { + return false; + } + try { + const normalized = normalizeAssets( + value.assets.map((asset) => markerAssetToPublicAsset(asset)), + policy, + ); + return stableJson(normalized) === stableJson(value.assets); + } catch { + return false; + } +} + +export function markerAssetToPublicAsset(value: unknown): PublicCacheAsset { + if (!value || typeof value !== "object") { + throw new CacheValidationFailure("CORRUPT_DATA"); + } + const asset = value as Partial; + return { + absoluteUrl: asset.absoluteUrl ?? "", + expectedByteLength: asset.expectedByteLength ?? -1, + expectedContentType: asset.expectedContentType ?? "", + integrity: { + algorithm: "SHA-256", + digestHex: asset.digestHex ?? "", + }, + requestHeaders: asset.requestHeaders, + }; +} + +export function isActivePointer( + value: unknown, + policy: PublicCacheRuntimePolicy, +): value is ActiveReleasePointer { + return Boolean( + value && + typeof value === "object" && + "schemaVersion" in value && + value.schemaVersion === 1 && + "releaseRegistryId" in value && + typeof value.releaseRegistryId === "string" && + policy.isReleaseRegistryIdAllowed(value.releaseRegistryId) && + "manifestDigestHex" in value && + typeof value.manifestDigestHex === "string" && + SHA256_HEX.test(value.manifestDigestHex) && + "candidateCacheName" in value && + typeof value.candidateCacheName === "string" && + value.candidateCacheName === + releaseCacheName( + policy, + value.releaseRegistryId, + value.manifestDigestHex, + ) && + "rollbackCandidateCacheNames" in value && + Array.isArray(value.rollbackCandidateCacheNames) && + value.rollbackCandidateCacheNames.length <= + policy.retainedPreviousReleaseCount && + new Set(value.rollbackCandidateCacheNames).size === + value.rollbackCandidateCacheNames.length && + value.rollbackCandidateCacheNames.every( + (name) => + typeof name === "string" && + name !== value.candidateCacheName && + isOwnedReleaseCacheName(name, policy), + ) && + "activatedAtEpochMs" in value && + typeof value.activatedAtEpochMs === "number" && + Number.isSafeInteger(value.activatedAtEpochMs), + ); +} + +export function isOwnedReleaseCacheName( + name: string, + policy: PublicCacheRuntimePolicy, +): boolean { + if (!name.startsWith(`${policy.ownedCachePrefix}release:`)) { + return false; + } + const remainder = name.slice( + `${policy.ownedCachePrefix}release:`.length, + ); + const separator = remainder.lastIndexOf(":"); + if (separator < 1) return false; + const releaseRegistryId = remainder.slice(0, separator); + const digestHex = remainder.slice(separator + 1); + return ( + policy.isReleaseRegistryIdAllowed(releaseRegistryId) && + SHA256_HEX.test(digestHex) + ); +} + +export function canonicalManifest( + releaseRegistryId: string, + assets: readonly NormalizedAsset[], +): string { + return [ + "ca-public-cache-manifest-v1", + `release:${releaseRegistryId}`, + ...[...assets] + .sort((left, right) => assetKey(left).localeCompare(assetKey(right))) + .map( + (asset) => + `${assetKey(asset)}:${asset.expectedByteLength}:${JSON.stringify(asset.expectedContentType)}:${asset.digestHex}`, + ), + "", + ].join("\n"); +} + +export function assetKey( + asset: Pick, +): string { + return JSON.stringify([asset.absoluteUrl, asset.requestHeaders]); +} + +export function markerRequest(policy: PublicCacheRuntimePolicy): Request { + return new Request(markerRequestUrl(policy), { method: "GET" }); +} + +export function activePointerRequest(policy: PublicCacheRuntimePolicy): Request { + return new Request(activePointerRequestUrl(policy), { method: "GET" }); +} + +export function markerRequestUrl(policy: PublicCacheRuntimePolicy): string { + return `${policy.origin}/.well-known/ca-public-cache-v1/candidate`; +} + +export function activePointerRequestUrl(policy: PublicCacheRuntimePolicy): string { + return `${policy.origin}/.well-known/ca-public-cache-v1/active`; +} + +export function controlCacheName(policy: PublicCacheRuntimePolicy): string { + return `${policy.ownedCachePrefix}control`; +} + +export function releaseCacheName( + policy: PublicCacheRuntimePolicy, + releaseRegistryId: string, + manifestDigestHex: string, +): string { + return `${policy.ownedCachePrefix}release:${releaseRegistryId}:${manifestDigestHex}`; +} + +export function jsonResponse(value: unknown): Response { + return new Response(JSON.stringify(value), { + status: 200, + headers: { + "cache-control": "no-store", + "content-type": "application/json; charset=utf-8", + }, + }); +} + +export function validationFailure( + error: unknown, + operation: BrowserDataOperation, +): BrowserFailureResult { + return error instanceof CacheValidationFailure + ? failureForCode(error.code, operation) + : asFailure(browserDataFailure("INVALID_INPUT", operation)); +} + +export function exceptionFailure( + error: unknown, + operation: BrowserDataOperation, +): BrowserFailureResult { + if (error instanceof CacheValidationFailure) { + return failureForCode(error.code, operation); + } + const mapped = mapBrowserDataException(error, operation); + if (mapped.ok) { + return asFailure( + browserDataFailure("UNAVAILABLE", operation, { + retryable: true, + recovery: "RETRY", + }), + ); + } + return mapped; +} + +export function failureForCode( + code: BrowserDataFailureCode, + operation: BrowserDataOperation, +): BrowserFailureResult { + if (code === "ABORTED") { + return asFailure(browserDataFailure(code, operation)); + } + if (code === "INTEGRITY_FAILED" || code === "CORRUPT_DATA") { + return asFailure( + browserDataFailure(code, operation, { recovery: "REHYDRATE" }), + ); + } + if (code === "QUOTA_EXCEEDED") { + return asFailure( + browserDataFailure(code, operation, { + retryable: true, + recovery: "ONLINE_ONLY", + }), + ); + } + if (code === "BLOCKED" || code === "UNAVAILABLE") { + return asFailure( + browserDataFailure(code, operation, { + retryable: true, + recovery: "RETRY", + }), + ); + } + return asFailure(browserDataFailure(code, operation)); +} + +export function asFailure( + result: BrowserDataResult, +): BrowserFailureResult { + if (result.ok) { + throw new TypeError("Expected a browser data failure."); + } + return result; +} + +export async function sha256Hex( + crypto: PublicCacheCryptoFacade, + bytes: Uint8Array, +): Promise { + const digest = await crypto.digestSha256(bytes); + let hex = ""; + for (const byte of new Uint8Array(digest)) { + hex += byte.toString(16).padStart(2, "0"); + } + return hex; +} + +export function stableJson(value: unknown): string { + if ( + value === null || + typeof value === "string" || + typeof value === "boolean" || + typeof value === "number" + ) { + return JSON.stringify(value); + } + if (Array.isArray(value)) { + return `[${value.map(stableJson).join(",")}]`; + } + if (typeof value === "object") { + const record = value as Record; + return `{${Object.keys(record) + .sort() + .map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`) + .join(",")}}`; + } + throw new CacheValidationFailure("CORRUPT_DATA"); +} + +export const SHA256_HEX = /^[a-f0-9]{64}$/u; +export const ZERO_SHA256 = "0".repeat(64); +export const MAX_CONTROL_JSON_BYTES = 2 * 1024 * 1024; diff --git a/src/adapters/cache-storage/public-cache-response-validation.ts b/src/adapters/cache-storage/public-cache-response-validation.ts new file mode 100644 index 00000000..383081c0 --- /dev/null +++ b/src/adapters/cache-storage/public-cache-response-validation.ts @@ -0,0 +1,239 @@ +import type { PublicCacheHeader } from "../../application/ports/browser-file-storage/cache-storage-ports.ts"; +import type { BrowserDataResult } from "../../application/ports/browser-file-storage/shared.ts"; +import { browserDataSuccess } from "../browser-file-storage/result.ts"; +import { createAbortableOperation } from "../platform/abortable-operation.ts"; +import { + CacheValidationFailure, + cancelReaderSafely, + exceptionFailure, + normalizeContentType, + sha256Hex, + type NormalizedAsset, + type PublicCacheCryptoFacade, +} from "./public-cache-codec.ts"; +import type { PublicCacheRuntimePolicy } from "./public-cache-policy.ts"; + +/** + * Q-6.2-11. Admission of a network or cached response for one manifest asset: + * status, cache directives, content type, Vary, bounded body read and digest. + * Moved verbatim out of the adapter. + */ + +export type CacheReadResult = Readonly<{ + bytes: Uint8Array; + headers: readonly PublicCacheHeader[]; +}>; + +export async function readAndValidateResponse( + response: Response, + asset: NormalizedAsset, + policy: PublicCacheRuntimePolicy, + crypto: PublicCacheCryptoFacade, + signal: AbortSignal | undefined, +): Promise> { + try { + if ( + response.status !== 200 || + !response.ok || + response.redirected || + response.type === "opaque" || + response.type === "opaqueredirect" || + response.type === "error" || + (response.url.length > 0 && + new URL(response.url).href !== asset.absoluteUrl) + ) { + throw new CacheValidationFailure("POLICY_REJECTED"); + } + const cacheControl = response.headers.get("cache-control") ?? ""; + const directives = new Set( + cacheControl + .split(",") + .map((part) => part.trim().split("=", 1)[0]?.toLowerCase()) + .filter((part): part is string => Boolean(part)), + ); + if ( + directives.has("private") || + directives.has("no-store") || + directives.has("no-cache") || + (response.headers.get("pragma") ?? "") + .toLowerCase() + .includes("no-cache") || + response.headers.has("set-cookie") || + response.headers.has("set-cookie2") || + response.headers.has("www-authenticate") + ) { + throw new CacheValidationFailure("POLICY_REJECTED"); + } + const contentType = response.headers.get("content-type"); + if (!contentType || !policy.isContentTypeAllowed(contentType)) { + throw new CacheValidationFailure("POLICY_REJECTED"); + } + if ( + normalizeContentType(contentType, policy) !== + asset.expectedContentType + ) { + throw new CacheValidationFailure("INTEGRITY_FAILED"); + } + validateVary(response.headers.get("vary"), asset, policy); + const declaredLength = response.headers.get("content-length"); + if ( + declaredLength !== null && + (!/^\d+$/u.test(declaredLength) || + Number(declaredLength) > policy.maxEntryBytes) + ) { + throw new CacheValidationFailure("LIMIT_EXCEEDED"); + } + + const bytes = await readBodyBounded( + response, + asset.expectedByteLength, + policy.maxEntryBytes, + signal, + ); + const digestHex = await sha256Hex(crypto, bytes); + if (digestHex !== asset.digestHex) { + throw new CacheValidationFailure("INTEGRITY_FAILED"); + } + const headers = sanitizedResponseHeaders(response.headers, policy); + return browserDataSuccess({ bytes, headers }); + } catch (error) { + return exceptionFailure(error, "CACHE_STAGE"); + } +} + +export async function readBodyBounded( + response: Response, + expectedByteLength: number, + maxEntryBytes: number, + signal: AbortSignal | undefined, +): Promise { + if (expectedByteLength > maxEntryBytes) { + throw new CacheValidationFailure("LIMIT_EXCEEDED"); + } + if (!response.body) { + if (expectedByteLength === 0) return new Uint8Array(); + throw new CacheValidationFailure("INTEGRITY_FAILED"); + } + const output = new Uint8Array(expectedByteLength); + const reader = response.body.getReader(); + let offset = 0; + // The kernel owner ends a pending read on abort instead of a listener pair. + const owner = createAbortableOperation({ signal }); + const abortRead = (): CacheValidationFailure => { + cancelReaderSafely(reader, "Public cache body read was aborted."); + return new CacheValidationFailure("ABORTED"); + }; + try { + while (true) { + if (owner.signal.aborted) throw abortRead(); + const raced = await owner.race(reader.read()); + if (raced.kind === "REJECTED") throw raced.reason; + if (raced.kind === "TERMINAL" || owner.signal.aborted) { + throw abortRead(); + } + const part = raced.value; + if (part.done) break; + if ( + !(part.value instanceof Uint8Array) || + offset + part.value.byteLength > expectedByteLength || + offset + part.value.byteLength > maxEntryBytes + ) { + cancelReaderSafely( + reader, + "Public cache body exceeded its read budget.", + ); + throw new CacheValidationFailure( + offset + part.value.byteLength > maxEntryBytes + ? "LIMIT_EXCEEDED" + : "INTEGRITY_FAILED", + ); + } + output.set(part.value, offset); + offset += part.value.byteLength; + } + } finally { + owner.close(); + reader.releaseLock(); + } + if (offset !== expectedByteLength) { + throw new CacheValidationFailure("INTEGRITY_FAILED"); + } + return output; +} + +export function validateVary( + vary: string | null, + asset: NormalizedAsset, + policy: PublicCacheRuntimePolicy, +): void { + const expected = new Set( + asset.requestHeaders.map(([name]) => name.toLowerCase()), + ); + const actual = new Set(); + if (!vary) { + if (expected.size > 0) { + throw new CacheValidationFailure("POLICY_REJECTED"); + } + return; + } + const allowed = new Set(policy.allowedVaryHeaderNames); + for (const item of vary.split(",")) { + const name = item.trim().toLowerCase(); + // Browser-managed: Accept-Encoding is a forbidden request header, so no + // script-built Request carries it. Stored and lookup requests both lack it + // and Cache.match still matches exactly. nginx `gzip_vary` and most CDNs + // send it on every compressible asset. + if (name === "accept-encoding") continue; + if ( + name === "*" || + name === "authorization" || + name === "cookie" || + !allowed.has(name) + ) { + throw new CacheValidationFailure("POLICY_REJECTED"); + } + actual.add(name); + } + if ( + actual.size !== expected.size || + [...actual].some((name) => !expected.has(name)) + ) { + throw new CacheValidationFailure("POLICY_REJECTED"); + } +} + +export function sanitizedResponseHeaders( + headers: Headers, + policy: PublicCacheRuntimePolicy, +): readonly PublicCacheHeader[] { + const allowed = new Set(policy.allowedResponseHeaderNames); + const sanitized: PublicCacheHeader[] = []; + for (const [name, value] of headers.entries()) { + if (!allowed.has(name)) { + if (policy.unknownResponseHeaderAction === "REJECT") { + throw new CacheValidationFailure("POLICY_REJECTED"); + } + continue; + } + sanitized.push(Object.freeze([name, value])); + } + return Object.freeze(sanitized); +} + +export function createNativeRequest( + asset: NormalizedAsset, + signal?: AbortSignal, +): Request { + return new Request(asset.absoluteUrl, { + method: "GET", + headers: new Headers( + asset.requestHeaders.map(([name, value]) => [name, value]), + ), + credentials: "omit", + cache: "no-store", + redirect: "error", + referrerPolicy: "no-referrer", + mode: "same-origin", + signal, + }); +} diff --git a/src/adapters/cache-storage/public-response-cache-adapter.ts b/src/adapters/cache-storage/public-response-cache-adapter.ts index 91bf06e8..26fc4450 100644 --- a/src/adapters/cache-storage/public-response-cache-adapter.ts +++ b/src/adapters/cache-storage/public-response-cache-adapter.ts @@ -2,7 +2,6 @@ import type { CachedPublicResponse, PublicCacheAsset, PublicCacheCleanupReport, - PublicCacheHeader, PublicCacheInspection, PublicCacheReleaseManifest, PublicCacheReleaseSummary, @@ -10,7 +9,6 @@ import type { } from "../../application/ports/browser-file-storage/cache-storage-ports.ts"; import type { BrowserDataFailure, - BrowserDataFailureCode, BrowserDataOperation, BrowserDataResult, ByteSource, @@ -19,18 +17,48 @@ import { abortedResult, browserDataFailure, browserDataSuccess, - mapBrowserDataException, } from "../browser-file-storage/result.ts"; import { createAbortableOperation } from "../platform/abortable-operation.ts"; import { cacheByteBucket, cacheEntryBucket, - isAllowedPublicCacheOrigin, observePublicCacheSafely, resolvePublicCachePolicy, type PublicCacheRuntimePolicy, type PublicCacheSafeObserver, } from "./public-cache-policy.ts"; +import { + CacheValidationFailure, + MAX_CONTROL_JSON_BYTES, + SHA256_HEX, + activePointerRequest, + asFailure, + assetKey, + canonicalManifest, + controlCacheName, + exceptionFailure, + isActivePointer, + isReleaseMarker, + jsonResponse, + markerRequest, + normalizeAndVerifyManifest, + normalizeAssets, + normalizeLookupRequest, + readBoundedJson, + releaseCacheName, + sha256Hex, + validationFailure, + type ActiveReleasePointer, + type BrowserFailureResult, + type NormalizedAsset, + type NormalizedReleaseManifest, + type PublicCacheCryptoFacade, + type ReleaseMarker, +} from "./public-cache-codec.ts"; +import { + createNativeRequest, + readAndValidateResponse, +} from "./public-cache-response-validation.ts"; export interface PublicCacheMutationLock { run( @@ -60,10 +88,6 @@ type PublicCacheStorageFacade = Readonly<{ delete(name: string): Promise; }>; -type PublicCacheCryptoFacade = Readonly<{ - digestSha256(bytes: Uint8Array): Promise; -}>; - type PublicResponseCacheDependencySnapshot = Readonly<{ cacheStorage?: PublicCacheStorageFacade; fetcher?: (request: Request) => Promise; @@ -72,48 +96,14 @@ type PublicResponseCacheDependencySnapshot = Readonly<{ observer?: PublicCacheSafeObserver; }>; -type NormalizedAsset = Readonly<{ - absoluteUrl: string; - expectedByteLength: number; - expectedContentType: string; - digestHex: string; - requestHeaders: readonly PublicCacheHeader[]; -}>; - -type NormalizedReleaseManifest = Readonly<{ - releaseRegistryId: string; - manifestDigestHex: string; - assets: readonly NormalizedAsset[]; -}>; - -type ReleaseMarker = Readonly<{ - schemaVersion: 1; - verified: true; - releaseRegistryId: string; - manifestDigestHex: string; - entryCount: number; - totalBytes: number; - stagedAtEpochMs: number; - assets: readonly NormalizedAsset[]; -}>; - -type ActiveReleasePointer = Readonly<{ - schemaVersion: 1; - releaseRegistryId: string; - manifestDigestHex: string; - candidateCacheName: string; - rollbackCandidateCacheNames: readonly string[]; - activatedAtEpochMs: number; -}>; - -type BrowserFailureResult = Readonly<{ - ok: false; - error: BrowserDataFailure; -}>; - -type CacheReadResult = Readonly<{ - bytes: Uint8Array; - headers: readonly PublicCacheHeader[]; +/** + * Q-6.2-6. A lookup-ready view of a verified marker. The cache name already + * encodes the manifest digest and the digest binds every asset field, so a + * marker verified once for a key stays valid for that key. + */ +type VerifiedLookupMarker = Readonly<{ + key: string; + assetsByKey: ReadonlyMap; }>; type LockManagerLike = { @@ -124,16 +114,6 @@ type LockManagerLike = { ): Promise; }; -class CacheValidationFailure extends Error { - readonly code: BrowserDataFailureCode; - - constructor(code: BrowserDataFailureCode) { - super("Public cache validation failed."); - this.name = "CacheValidationFailure"; - this.code = code; - } -} - function snapshotPublicCacheDependencies( dependencies: PublicResponseCacheDependencies, ): PublicResponseCacheDependencySnapshot { @@ -231,6 +211,8 @@ export function createPublicResponseCacheAdapter( const dependencies = snapshotPublicCacheDependencies(inputDependencies); const policy = resolvePublicCachePolicy(inputDependencies.policy); const now = inputDependencies.now ?? Date.now; + // ponytail: one slot for the active release only; a rollback re-verifies. + let verifiedLookupMarker: VerifiedLookupMarker | undefined; const responses: PublicResponseCache["responses"] = Object.freeze({ async matchActiveExact( @@ -288,34 +270,48 @@ export function createPublicResponseCacheAdapter( const cache = await dependencies.cacheStorage.open( pointer.candidateCacheName, ); - const markerResult = await readMarker( - cache, - policy, - dependencies.crypto, - ); - if (!markerResult.ok) { - return observeFailure( - markerResult, - dependencies.observer, - pointer.releaseRegistryId, + const markerKey = `${pointer.candidateCacheName}\n${pointer.manifestDigestHex}`; + let verified = + verifiedLookupMarker?.key === markerKey + ? verifiedLookupMarker + : undefined; + if (!verified) { + const markerResult = await readMarker( + cache, + policy, + dependencies.crypto, ); + if (!markerResult.ok) { + return observeFailure( + markerResult, + dependencies.observer, + pointer.releaseRegistryId, + ); + } + const marker = markerResult.value; + if ( + !marker || + marker.releaseRegistryId !== pointer.releaseRegistryId || + marker.manifestDigestHex !== pointer.manifestDigestHex + ) { + return observeFailure( + browserDataFailure("INTEGRITY_FAILED", "CACHE_LOOKUP", { + recovery: "REHYDRATE", + }), + dependencies.observer, + pointer.releaseRegistryId, + ); + } + verified = Object.freeze({ + key: markerKey, + assetsByKey: new Map( + marker.assets.map((asset) => [assetKey(asset), asset]), + ), + }); + verifiedLookupMarker = verified; } - const marker = markerResult.value; - if ( - !marker || - marker.releaseRegistryId !== pointer.releaseRegistryId || - marker.manifestDigestHex !== pointer.manifestDigestHex - ) { - return observeFailure( - browserDataFailure("INTEGRITY_FAILED", "CACHE_LOOKUP", { - recovery: "REHYDRATE", - }), - dependencies.observer, - pointer.releaseRegistryId, - ); - } - const manifestAsset = marker.assets.find( - (asset) => assetKey(asset) === assetKey(assetRequest), + const manifestAsset = verified.assetsByKey.get( + assetKey(assetRequest), ); if (!manifestAsset) { observePublicCacheSafely(dependencies.observer, { @@ -948,431 +944,6 @@ export async function computePublicCacheManifestDigestHex( ); } -async function normalizeAndVerifyManifest( - manifest: PublicCacheReleaseManifest, - policy: PublicCacheRuntimePolicy, - crypto: PublicCacheCryptoFacade, -): Promise { - const snapshot = Object.freeze({ - releaseRegistryId: manifest.releaseRegistryId, - manifestDigestHex: manifest.manifestDigestHex, - assets: normalizeAssets(manifest.assets, policy), - }); - if ( - !policy.isReleaseRegistryIdAllowed(snapshot.releaseRegistryId) || - !SHA256_HEX.test(snapshot.manifestDigestHex) - ) { - throw new CacheValidationFailure("INVALID_INPUT"); - } - const actualDigest = await sha256Hex( - crypto, - new TextEncoder().encode( - canonicalManifest(snapshot.releaseRegistryId, snapshot.assets), - ), - ); - if (actualDigest !== snapshot.manifestDigestHex) { - throw new CacheValidationFailure("INTEGRITY_FAILED"); - } - return snapshot; -} - -function normalizeAssets( - assets: readonly PublicCacheAsset[], - policy: PublicCacheRuntimePolicy, -): readonly NormalizedAsset[] { - if ( - !Array.isArray(assets) || - assets.length < 1 || - assets.length > policy.maxEntriesPerRelease - ) { - throw new CacheValidationFailure("LIMIT_EXCEEDED"); - } - const normalized = assets.map((asset) => - normalizeAsset(asset, policy), - ); - const keys = normalized.map(assetKey); - if (new Set(keys).size !== keys.length) { - throw new CacheValidationFailure("CONFLICT"); - } - const declaredTotal = normalized.reduce( - (total, asset) => total + asset.expectedByteLength, - 0, - ); - if ( - !Number.isSafeInteger(declaredTotal) || - declaredTotal > policy.maxReleaseBytes - ) { - throw new CacheValidationFailure("LIMIT_EXCEEDED"); - } - return Object.freeze(normalized); -} - -function normalizeAsset( - asset: PublicCacheAsset, - policy: PublicCacheRuntimePolicy, -): NormalizedAsset { - if ( - !asset || - typeof asset !== "object" || - !Number.isSafeInteger(asset.expectedByteLength) || - asset.expectedByteLength < 0 || - asset.expectedByteLength > policy.maxEntryBytes || - asset.integrity?.algorithm !== "SHA-256" || - !SHA256_HEX.test(asset.integrity.digestHex) - ) { - throw new CacheValidationFailure("INVALID_INPUT"); - } - return Object.freeze({ - absoluteUrl: normalizePublicUrl(asset.absoluteUrl, policy), - expectedByteLength: asset.expectedByteLength, - expectedContentType: normalizeContentType( - asset.expectedContentType, - policy, - ), - digestHex: asset.integrity.digestHex, - requestHeaders: normalizeRequestHeaders( - asset.requestHeaders, - policy, - ), - }); -} - -function normalizeLookupRequest( - absoluteUrl: string, - requestHeaders: readonly PublicCacheHeader[] | undefined, - policy: PublicCacheRuntimePolicy, -): NormalizedAsset { - return { - absoluteUrl: normalizePublicUrl(absoluteUrl, policy), - expectedByteLength: 0, - expectedContentType: "", - digestHex: ZERO_SHA256, - requestHeaders: normalizeRequestHeaders(requestHeaders, policy), - }; -} - -function normalizeContentType( - input: string, - policy: PublicCacheRuntimePolicy, -): string { - if ( - typeof input !== "string" || - input.length < 1 || - input.length > 256 || - /[\r\n\0]/u.test(input) || - !policy.isContentTypeAllowed(input) - ) { - throw new CacheValidationFailure("POLICY_REJECTED"); - } - return input - .split(";") - .map((part) => part.trim()) - .filter((part) => part.length > 0) - .map((part, index) => - index === 0 ? part.toLowerCase() : part, - ) - .join("; "); -} - -function normalizePublicUrl( - input: string, - policy: PublicCacheRuntimePolicy, -): string { - if (typeof input !== "string" || input.length > 2_048) { - throw new CacheValidationFailure("INVALID_INPUT"); - } - let url: URL; - try { - url = new URL(input); - } catch { - throw new CacheValidationFailure("INVALID_INPUT"); - } - if ( - url.origin !== policy.origin || - !isAllowedPublicCacheOrigin(url) || - url.username.length > 0 || - url.password.length > 0 || - url.hash.length > 0 || - url.href === markerRequestUrl(policy) || - url.href === activePointerRequestUrl(policy) - ) { - throw new CacheValidationFailure("POLICY_REJECTED"); - } - const forbidden = new Set(policy.forbiddenQueryParameterNames); - const allowed = new Set(policy.allowedQueryParameterNames); - const seenNames = new Set(); - for (const [rawName, value] of url.searchParams.entries()) { - const name = rawName.toLowerCase(); - if ( - forbidden.has(name) || - !allowed.has(name) || - seenNames.has(name) || - !policy.isQueryParameterValueAllowed(name, value) - ) { - throw new CacheValidationFailure("POLICY_REJECTED"); - } - seenNames.add(name); - } - return url.href; -} - -function normalizeRequestHeaders( - input: readonly PublicCacheHeader[] | undefined, - policy: PublicCacheRuntimePolicy, -): readonly PublicCacheHeader[] { - const allowed = new Set(policy.allowedRequestHeaderNames); - const forbidden = new Set([ - "authorization", - "cookie", - "proxy-authorization", - "range", - ]); - const headers = new Headers(); - for (const pair of input ?? []) { - if ( - !Array.isArray(pair) || - pair.length !== 2 || - typeof pair[0] !== "string" || - typeof pair[1] !== "string" - ) { - throw new CacheValidationFailure("INVALID_INPUT"); - } - const name = pair[0].toLowerCase(); - if ( - forbidden.has(name) || - !allowed.has(name) || - pair[1].length > 1_024 || - /[\r\n\0]/u.test(pair[1]) - ) { - throw new CacheValidationFailure("POLICY_REJECTED"); - } - headers.append(name, pair[1].trim()); - } - return Object.freeze( - [...headers.entries()] - .sort(([left], [right]) => left.localeCompare(right)) - .map( - ([name, value]) => - Object.freeze([name, value]) as PublicCacheHeader, - ), - ); -} - -async function readAndValidateResponse( - response: Response, - asset: NormalizedAsset, - policy: PublicCacheRuntimePolicy, - crypto: PublicCacheCryptoFacade, - signal: AbortSignal | undefined, -): Promise> { - try { - if ( - response.status !== 200 || - !response.ok || - response.redirected || - response.type === "opaque" || - response.type === "opaqueredirect" || - response.type === "error" || - (response.url.length > 0 && - new URL(response.url).href !== asset.absoluteUrl) - ) { - throw new CacheValidationFailure("POLICY_REJECTED"); - } - const cacheControl = response.headers.get("cache-control") ?? ""; - const directives = new Set( - cacheControl - .split(",") - .map((part) => part.trim().split("=", 1)[0]?.toLowerCase()) - .filter((part): part is string => Boolean(part)), - ); - if ( - directives.has("private") || - directives.has("no-store") || - directives.has("no-cache") || - (response.headers.get("pragma") ?? "") - .toLowerCase() - .includes("no-cache") || - response.headers.has("set-cookie") || - response.headers.has("set-cookie2") || - response.headers.has("www-authenticate") - ) { - throw new CacheValidationFailure("POLICY_REJECTED"); - } - const contentType = response.headers.get("content-type"); - if (!contentType || !policy.isContentTypeAllowed(contentType)) { - throw new CacheValidationFailure("POLICY_REJECTED"); - } - if ( - normalizeContentType(contentType, policy) !== - asset.expectedContentType - ) { - throw new CacheValidationFailure("INTEGRITY_FAILED"); - } - validateVary(response.headers.get("vary"), asset, policy); - const declaredLength = response.headers.get("content-length"); - if ( - declaredLength !== null && - (!/^\d+$/u.test(declaredLength) || - Number(declaredLength) > policy.maxEntryBytes) - ) { - throw new CacheValidationFailure("LIMIT_EXCEEDED"); - } - - const bytes = await readBodyBounded( - response, - asset.expectedByteLength, - policy.maxEntryBytes, - signal, - ); - const digestHex = await sha256Hex(crypto, bytes); - if (digestHex !== asset.digestHex) { - throw new CacheValidationFailure("INTEGRITY_FAILED"); - } - const headers = sanitizedResponseHeaders(response.headers, policy); - return browserDataSuccess({ bytes, headers }); - } catch (error) { - return exceptionFailure(error, "CACHE_STAGE"); - } -} - -async function readBodyBounded( - response: Response, - expectedByteLength: number, - maxEntryBytes: number, - signal: AbortSignal | undefined, -): Promise { - if (expectedByteLength > maxEntryBytes) { - throw new CacheValidationFailure("LIMIT_EXCEEDED"); - } - if (!response.body) { - if (expectedByteLength === 0) return new Uint8Array(); - throw new CacheValidationFailure("INTEGRITY_FAILED"); - } - const output = new Uint8Array(expectedByteLength); - const reader = response.body.getReader(); - let offset = 0; - let aborted = signal?.aborted ?? false; - const onAbort = (): void => { - aborted = true; - cancelReaderSafely(reader, "Public cache body read was aborted."); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - try { - while (true) { - if (aborted) { - cancelReaderSafely(reader, "Public cache body read was aborted."); - throw new CacheValidationFailure("ABORTED"); - } - const part = await reader.read(); - if (aborted) { - throw new CacheValidationFailure("ABORTED"); - } - if (part.done) break; - if ( - !(part.value instanceof Uint8Array) || - offset + part.value.byteLength > expectedByteLength || - offset + part.value.byteLength > maxEntryBytes - ) { - cancelReaderSafely( - reader, - "Public cache body exceeded its read budget.", - ); - throw new CacheValidationFailure( - offset + part.value.byteLength > maxEntryBytes - ? "LIMIT_EXCEEDED" - : "INTEGRITY_FAILED", - ); - } - output.set(part.value, offset); - offset += part.value.byteLength; - } - } finally { - signal?.removeEventListener("abort", onAbort); - reader.releaseLock(); - } - if (offset !== expectedByteLength) { - throw new CacheValidationFailure("INTEGRITY_FAILED"); - } - return output; -} - -function validateVary( - vary: string | null, - asset: NormalizedAsset, - policy: PublicCacheRuntimePolicy, -): void { - const expected = new Set( - asset.requestHeaders.map(([name]) => name.toLowerCase()), - ); - const actual = new Set(); - if (!vary) { - if (expected.size > 0) { - throw new CacheValidationFailure("POLICY_REJECTED"); - } - return; - } - const allowed = new Set(policy.allowedVaryHeaderNames); - for (const item of vary.split(",")) { - const name = item.trim().toLowerCase(); - // Browser-managed: Accept-Encoding is a forbidden request header, so no - // script-built Request carries it. Stored and lookup requests both lack it - // and Cache.match still matches exactly. nginx `gzip_vary` and most CDNs - // send it on every compressible asset. - if (name === "accept-encoding") continue; - if ( - name === "*" || - name === "authorization" || - name === "cookie" || - !allowed.has(name) - ) { - throw new CacheValidationFailure("POLICY_REJECTED"); - } - actual.add(name); - } - if ( - actual.size !== expected.size || - [...actual].some((name) => !expected.has(name)) - ) { - throw new CacheValidationFailure("POLICY_REJECTED"); - } -} - -function sanitizedResponseHeaders( - headers: Headers, - policy: PublicCacheRuntimePolicy, -): readonly PublicCacheHeader[] { - const allowed = new Set(policy.allowedResponseHeaderNames); - const sanitized: PublicCacheHeader[] = []; - for (const [name, value] of headers.entries()) { - if (!allowed.has(name)) { - if (policy.unknownResponseHeaderAction === "REJECT") { - throw new CacheValidationFailure("POLICY_REJECTED"); - } - continue; - } - sanitized.push(Object.freeze([name, value])); - } - return Object.freeze(sanitized); -} - -function createNativeRequest( - asset: NormalizedAsset, - signal?: AbortSignal, -): Request { - return new Request(asset.absoluteUrl, { - method: "GET", - headers: new Headers( - asset.requestHeaders.map(([name, value]) => [name, value]), - ), - credentials: "omit", - cache: "no-store", - redirect: "error", - referrerPolicy: "no-referrer", - mode: "same-origin", - signal, - }); -} - async function readMarker( cache: PublicCacheFacade, policy: PublicCacheRuntimePolicy, @@ -1436,223 +1007,6 @@ async function readActivePointer( } } -async function readBoundedJson( - response: Response, - maximumBytes: number, -): Promise { - const contentLength = response.headers.get("content-length"); - if ( - !Number.isSafeInteger(maximumBytes) || - maximumBytes <= 0 || - (contentLength !== null && - (!/^\d+$/u.test(contentLength) || - Number(contentLength) > maximumBytes)) - ) { - throw new CacheValidationFailure("CORRUPT_DATA"); - } - if (!response.body) { - throw new CacheValidationFailure("CORRUPT_DATA"); - } - - const reader = response.body.getReader(); - const boundedBytes = new Uint8Array(maximumBytes); - let byteLength = 0; - let completelyRead = false; - try { - while (true) { - const chunk = await reader.read(); - if (chunk.done) { - completelyRead = true; - break; - } - if (chunk.value.byteLength > maximumBytes - byteLength) { - throw new CacheValidationFailure("CORRUPT_DATA"); - } - boundedBytes.set(chunk.value, byteLength); - byteLength += chunk.value.byteLength; - } - } catch (error) { - if (!completelyRead) { - cancelReaderSafely( - reader, - "Cache control JSON exceeded its read budget.", - ); - } - throw error; - } finally { - reader.releaseLock(); - } - - let text: string; - try { - text = new TextDecoder("utf-8", { fatal: true }).decode( - boundedBytes.subarray(0, byteLength), - ); - } catch { - throw new CacheValidationFailure("CORRUPT_DATA"); - } - try { - return JSON.parse(text); - } catch { - throw new CacheValidationFailure("CORRUPT_DATA"); - } -} - -function cancelReaderSafely( - reader: ReadableStreamDefaultReader, - reason: string, -): void { - try { - void reader.cancel(reason).catch(() => undefined); - } catch { - // Cancellation is best effort once the bounded consumer has stopped. - } -} - -function isReleaseMarker( - value: unknown, - policy: PublicCacheRuntimePolicy, -): value is ReleaseMarker { - if ( - !value || - typeof value !== "object" || - !("schemaVersion" in value) || - value.schemaVersion !== 1 || - !("verified" in value) || - value.verified !== true || - !("releaseRegistryId" in value) || - typeof value.releaseRegistryId !== "string" || - !policy.isReleaseRegistryIdAllowed(value.releaseRegistryId) || - !("manifestDigestHex" in value) || - typeof value.manifestDigestHex !== "string" || - !SHA256_HEX.test(value.manifestDigestHex) || - !("entryCount" in value) || - typeof value.entryCount !== "number" || - !Number.isSafeInteger(value.entryCount) || - !("totalBytes" in value) || - typeof value.totalBytes !== "number" || - !Number.isSafeInteger(value.totalBytes) || - !("stagedAtEpochMs" in value) || - typeof value.stagedAtEpochMs !== "number" || - !Number.isSafeInteger(value.stagedAtEpochMs) || - !("assets" in value) || - !Array.isArray(value.assets) || - value.assets.length > policy.maxEntriesPerRelease - ) { - return false; - } - try { - const normalized = normalizeAssets( - value.assets.map((asset) => markerAssetToPublicAsset(asset)), - policy, - ); - return stableJson(normalized) === stableJson(value.assets); - } catch { - return false; - } -} - -function markerAssetToPublicAsset(value: unknown): PublicCacheAsset { - if (!value || typeof value !== "object") { - throw new CacheValidationFailure("CORRUPT_DATA"); - } - const asset = value as Partial; - return { - absoluteUrl: asset.absoluteUrl ?? "", - expectedByteLength: asset.expectedByteLength ?? -1, - expectedContentType: asset.expectedContentType ?? "", - integrity: { - algorithm: "SHA-256", - digestHex: asset.digestHex ?? "", - }, - requestHeaders: asset.requestHeaders, - }; -} - -function isActivePointer( - value: unknown, - policy: PublicCacheRuntimePolicy, -): value is ActiveReleasePointer { - return Boolean( - value && - typeof value === "object" && - "schemaVersion" in value && - value.schemaVersion === 1 && - "releaseRegistryId" in value && - typeof value.releaseRegistryId === "string" && - policy.isReleaseRegistryIdAllowed(value.releaseRegistryId) && - "manifestDigestHex" in value && - typeof value.manifestDigestHex === "string" && - SHA256_HEX.test(value.manifestDigestHex) && - "candidateCacheName" in value && - typeof value.candidateCacheName === "string" && - value.candidateCacheName === - releaseCacheName( - policy, - value.releaseRegistryId, - value.manifestDigestHex, - ) && - "rollbackCandidateCacheNames" in value && - Array.isArray(value.rollbackCandidateCacheNames) && - value.rollbackCandidateCacheNames.length <= - policy.retainedPreviousReleaseCount && - new Set(value.rollbackCandidateCacheNames).size === - value.rollbackCandidateCacheNames.length && - value.rollbackCandidateCacheNames.every( - (name) => - typeof name === "string" && - name !== value.candidateCacheName && - isOwnedReleaseCacheName(name, policy), - ) && - "activatedAtEpochMs" in value && - typeof value.activatedAtEpochMs === "number" && - Number.isSafeInteger(value.activatedAtEpochMs), - ); -} - -function isOwnedReleaseCacheName( - name: string, - policy: PublicCacheRuntimePolicy, -): boolean { - if (!name.startsWith(`${policy.ownedCachePrefix}release:`)) { - return false; - } - const remainder = name.slice( - `${policy.ownedCachePrefix}release:`.length, - ); - const separator = remainder.lastIndexOf(":"); - if (separator < 1) return false; - const releaseRegistryId = remainder.slice(0, separator); - const digestHex = remainder.slice(separator + 1); - return ( - policy.isReleaseRegistryIdAllowed(releaseRegistryId) && - SHA256_HEX.test(digestHex) - ); -} - -function canonicalManifest( - releaseRegistryId: string, - assets: readonly NormalizedAsset[], -): string { - return [ - "ca-public-cache-manifest-v1", - `release:${releaseRegistryId}`, - ...[...assets] - .sort((left, right) => assetKey(left).localeCompare(assetKey(right))) - .map( - (asset) => - `${assetKey(asset)}:${asset.expectedByteLength}:${JSON.stringify(asset.expectedContentType)}:${asset.digestHex}`, - ), - "", - ].join("\n"); -} - -function assetKey( - asset: Pick, -): string { - return JSON.stringify([asset.absoluteUrl, asset.requestHeaders]); -} - function byteSourceFrom(bytes: Uint8Array): ByteSource { const stored = Uint8Array.from(bytes); return Object.freeze({ @@ -1667,44 +1021,6 @@ function byteSourceFrom(bytes: Uint8Array): ByteSource { }); } -function markerRequest(policy: PublicCacheRuntimePolicy): Request { - return new Request(markerRequestUrl(policy), { method: "GET" }); -} - -function activePointerRequest(policy: PublicCacheRuntimePolicy): Request { - return new Request(activePointerRequestUrl(policy), { method: "GET" }); -} - -function markerRequestUrl(policy: PublicCacheRuntimePolicy): string { - return `${policy.origin}/.well-known/ca-public-cache-v1/candidate`; -} - -function activePointerRequestUrl(policy: PublicCacheRuntimePolicy): string { - return `${policy.origin}/.well-known/ca-public-cache-v1/active`; -} - -function controlCacheName(policy: PublicCacheRuntimePolicy): string { - return `${policy.ownedCachePrefix}control`; -} - -function releaseCacheName( - policy: PublicCacheRuntimePolicy, - releaseRegistryId: string, - manifestDigestHex: string, -): string { - return `${policy.ownedCachePrefix}release:${releaseRegistryId}:${manifestDigestHex}`; -} - -function jsonResponse(value: unknown): Response { - return new Response(JSON.stringify(value), { - status: 200, - headers: { - "cache-control": "no-store", - "content-type": "application/json; charset=utf-8", - }, - }); -} - function summaryFromMarker( marker: ReleaseMarker, ): PublicCacheReleaseSummary { @@ -1817,74 +1133,6 @@ function unsupported( ); } -function validationFailure( - error: unknown, - operation: BrowserDataOperation, -): BrowserFailureResult { - return error instanceof CacheValidationFailure - ? failureForCode(error.code, operation) - : asFailure(browserDataFailure("INVALID_INPUT", operation)); -} - -function exceptionFailure( - error: unknown, - operation: BrowserDataOperation, -): BrowserFailureResult { - if (error instanceof CacheValidationFailure) { - return failureForCode(error.code, operation); - } - const mapped = mapBrowserDataException(error, operation); - if (mapped.ok) { - return asFailure( - browserDataFailure("UNAVAILABLE", operation, { - retryable: true, - recovery: "RETRY", - }), - ); - } - return mapped; -} - -function failureForCode( - code: BrowserDataFailureCode, - operation: BrowserDataOperation, -): BrowserFailureResult { - if (code === "ABORTED") { - return asFailure(browserDataFailure(code, operation)); - } - if (code === "INTEGRITY_FAILED" || code === "CORRUPT_DATA") { - return asFailure( - browserDataFailure(code, operation, { recovery: "REHYDRATE" }), - ); - } - if (code === "QUOTA_EXCEEDED") { - return asFailure( - browserDataFailure(code, operation, { - retryable: true, - recovery: "ONLINE_ONLY", - }), - ); - } - if (code === "BLOCKED" || code === "UNAVAILABLE") { - return asFailure( - browserDataFailure(code, operation, { - retryable: true, - recovery: "RETRY", - }), - ); - } - return asFailure(browserDataFailure(code, operation)); -} - -function asFailure( - result: BrowserDataResult, -): BrowserFailureResult { - if (result.ok) { - throw new TypeError("Expected a browser data failure."); - } - return result; -} - function rebaseFailure( failure: BrowserDataFailure, operation: BrowserDataOperation, @@ -1914,41 +1162,3 @@ function observeFailure( }); return result; } - -async function sha256Hex( - crypto: PublicCacheCryptoFacade, - bytes: Uint8Array, -): Promise { - const digest = await crypto.digestSha256(bytes); - let hex = ""; - for (const byte of new Uint8Array(digest)) { - hex += byte.toString(16).padStart(2, "0"); - } - return hex; -} - -function stableJson(value: unknown): string { - if ( - value === null || - typeof value === "string" || - typeof value === "boolean" || - typeof value === "number" - ) { - return JSON.stringify(value); - } - if (Array.isArray(value)) { - return `[${value.map(stableJson).join(",")}]`; - } - if (typeof value === "object") { - const record = value as Record; - return `{${Object.keys(record) - .sort() - .map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`) - .join(",")}}`; - } - throw new CacheValidationFailure("CORRUPT_DATA"); -} - -const SHA256_HEX = /^[a-f0-9]{64}$/u; -const ZERO_SHA256 = "0".repeat(64); -const MAX_CONTROL_JSON_BYTES = 2 * 1024 * 1024; diff --git a/src/adapters/cross-context-invalidation/browser-cross-context-host.ts b/src/adapters/cross-context-invalidation/browser-cross-context-host.ts index b3d55a28..62f6f2d8 100644 --- a/src/adapters/cross-context-invalidation/browser-cross-context-host.ts +++ b/src/adapters/cross-context-invalidation/browser-cross-context-host.ts @@ -36,6 +36,20 @@ const CHANNEL_NAME = "ca-client-cache-invalidation-v1"; const STORAGE_PULSE_KEY = STORAGE_REGISTRY.CACHE_INVALIDATION_PULSE.physicalKey; +/** + * Q-6.2-9. A release ID may hold any character (`1.2.3+sha.abc`, `feature/x`, + * `app@1.2.3`) and any length, but a cache epoch is an opaque identifier. The + * epoch is a stable 64-bit FNV-1a digest of the ID, so every tab of one release + * agrees on it and it always passes the wire rule. + */ +export function crossContextCacheEpochForRelease(releaseId: string): string { + let hash = 0xcbf29ce484222325n; + for (const byte of new TextEncoder().encode(releaseId)) { + hash = ((hash ^ BigInt(byte)) * 0x100000001b3n) & 0xffffffffffffffffn; + } + return `release.${hash.toString(16).padStart(16, "0")}`; +} + /** * Captures native capabilities without allowing a SecurityError getter or a * missing random source to fail application boot. @@ -49,17 +63,38 @@ export function createBrowserCrossContextInvalidationFromHost( const host = dependencies.host ?? (globalThis as unknown as Record); + // Q-6.2-9. Ending inactive is reported, so cross-tab invalidation is never + // switched off without a diagnostic. + const inactive = ( + reason: "INVALID_CACHE_EPOCH" | "SECURE_RANDOM_UNAVAILABLE", + ): undefined => { + try { + dependencies.observe?.( + Object.freeze({ + operation: "OPEN" as const, + outcome: "FAILED" as const, + transport: "NONE" as const, + reason, + }), + ); + } catch { + // Diagnostics cannot change the capability decision. + } + return undefined; + }; if ( !isCacheInvalidationOpaqueIdentifier(dependencies.cacheEpoch) ) { - return undefined; + return inactive("INVALID_CACHE_EPOCH"); } const createOpaqueId = randomIdFactory(host); - if (!createOpaqueId) return undefined; + if (!createOpaqueId) return inactive("SECURE_RANDOM_UNAVAILABLE"); const sourceId = createOpaqueId("tab"); const sourceEpoch = createOpaqueId("page"); - if (!sourceId || !sourceEpoch) return undefined; + if (!sourceId || !sourceEpoch) { + return inactive("SECURE_RANDOM_UNAVAILABLE"); + } const capturedLocalStorage = captureLocalStorage(host); diff --git a/src/adapters/cross-context-invalidation/browser-cross-context-invalidation.ts b/src/adapters/cross-context-invalidation/browser-cross-context-invalidation.ts index 6872046a..027cadfa 100644 --- a/src/adapters/cross-context-invalidation/browser-cross-context-invalidation.ts +++ b/src/adapters/cross-context-invalidation/browser-cross-context-invalidation.ts @@ -43,9 +43,11 @@ export type CrossContextInvalidationObservationReason = | "DELIVERED" | "DUPLICATE" | "HANDLER_FAILED" + | "INVALID_CACHE_EPOCH" | "OPENED" | "PUBLISHED" | "SELF_ECHO" + | "SECURE_RANDOM_UNAVAILABLE" | "SEQUENCE_EXHAUSTED" | "STALE" | "STORAGE_CLEANUP_FAILED" diff --git a/src/adapters/cross-context-invalidation/index.ts b/src/adapters/cross-context-invalidation/index.ts index acaa9173..7d44c008 100644 --- a/src/adapters/cross-context-invalidation/index.ts +++ b/src/adapters/cross-context-invalidation/index.ts @@ -19,5 +19,6 @@ export { } from "./browser-cross-context-invalidation.ts"; export { createBrowserCrossContextInvalidationFromHost, + crossContextCacheEpochForRelease, type BrowserCrossContextHostDependencies, } from "./browser-cross-context-host.ts"; diff --git a/src/adapters/http/client.ts b/src/adapters/http/client.ts index 5f5640e3..7cc38916 100644 --- a/src/adapters/http/client.ts +++ b/src/adapters/http/client.ts @@ -40,7 +40,7 @@ import type { ClockPort } from "../../application/ports/clock-port.ts"; import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.ts"; import type { TelemetryPort } from "../../application/ports/telemetry-port.ts"; import type { ApiOperation } from "../../contracts/api-operations.ts"; -import type { ApiFailure } from "../../contracts/errors.ts"; +import type { ApiFailure, FailureKind } from "../../contracts/errors.ts"; import type { OperationRequestInput } from "./request-builder.ts"; import { readBoundedJson } from "./bounded-json.ts"; import { admitCredentialHeaders } from "./http-contract-bridge.ts"; @@ -48,7 +48,7 @@ import type { MappingResult } from "../../contracts/boundary-mapper.ts"; import { createRestProviderProfile, resolveRestSecurityProfiles, - REST_AUTH_PROFILES, + INSTALLED_REST_AUTH_PROFILES, REST_CSRF_PROFILES, type RestAuthProfile, type RestCsrfProfile, @@ -336,12 +336,11 @@ export function createHttpClient( ); } + // Q-6.3-11. Recovery is its own single replay, bounded by + // `recoveryUsed` and the deadline, not by the retry budget: a disabled + // or spent budget must not turn a recoverable 401 into a logout. if (outcome.error.httpStatus === 401 && !recoveryUsed) { recoveryUsed = true; - if (physicalAttemptCount >= maxRetryAttempts + 1) { - authSession.onUnauthenticated(); - return finalize(outcome, "failed"); - } let recovered: SessionRecoveryOutcome; // LEG-01. The recovery collaborator receives the request lifetime, and // the transport races the same signal so a non-cooperative owner cannot @@ -562,7 +561,7 @@ export function createHttpClient( security = resolveRestSecurityProfiles( operation, provider, - dependencies.authProfiles ?? REST_AUTH_PROFILES, + dependencies.authProfiles ?? INSTALLED_REST_AUTH_PROFILES, dependencies.csrfProfiles ?? REST_CSRF_PROFILES, ); } @@ -842,6 +841,17 @@ export function createHttpClient( class LogicalDeadlineError extends Error {} +/** + * Q-6.3-3b. A gateway 5xx/408/425 with an HTML, empty or broken body is a + * server outage, not a contract breach: it keeps its status and the normal + * SERVER_FAILURE retry rule instead of a non-retryable body error. + */ +function gatewayFailureOr(status: number, kind: FailureKind): FailureKind { + return status >= 500 || status === 408 || status === 425 + ? "SERVER_FAILURE" + : kind; +} + async function parseResponse( response: Response, operation: ApiOperation, @@ -862,10 +872,12 @@ async function parseResponse( void response.body?.cancel().catch(() => {}); return { ok: false, - error: failure("CONTENT_TYPE_MISMATCH", operation.operationId, attempt, { - code: "CONTENT_TYPE_MISMATCH", - httpStatus: response.status, - }), + error: failure( + gatewayFailureOr(response.status, "CONTENT_TYPE_MISMATCH"), + operation.operationId, + attempt, + { code: "CONTENT_TYPE_MISMATCH", httpStatus: response.status }, + ), }; } @@ -876,10 +888,12 @@ async function parseResponse( if (!decoded.ok) { return { ok: false, - error: failure(decoded.code, operation.operationId, attempt, { - code: decoded.code, - httpStatus: response.status, - }), + error: failure( + gatewayFailureOr(response.status, decoded.code), + operation.operationId, + attempt, + { code: decoded.code, httpStatus: response.status }, + ), }; } const envelope = decoded.value; @@ -889,7 +903,9 @@ async function parseResponse( return { ok: false, error: failure( - response.ok ? "ENVELOPE_MISMATCH" : statusKind(response.status), + response.ok + ? "ENVELOPE_MISMATCH" + : gatewayFailureOr(response.status, statusKind(response.status)), operation.operationId, attempt, { diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index 992c8aa2..47138898 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -504,6 +504,17 @@ export function createContractHttpExecutor( kind: HttpTransportFailure["kind"], ): HttpExecutionOutcome => transportFailure(kind, false, abandonedCertainty()); + /** + * Q-6.3-7. What the attempts that were retried settled on. The logical + * accumulator above is raised at dispatch, before the attempt's own answer + * is known, so it cannot tell a rejected attempt from a lost one. + */ + let retriedCertainty: MutationEffectCertainty = "NOT_STARTED"; + const rememberRetried = (settled: MutationEffectCertainty) => { + if (isCommand) { + retriedCertainty = joinMutationEffectCertainty(retriedCertainty, settled); + } + }; let terminalCancellation: CancellationOwner | null = null; const lifetimeController = new AbortController(); const forwardCallerToLifetime = () => { @@ -582,6 +593,31 @@ export function createContractHttpExecutor( return outcome; }; + /** + * Q-6.3-6. The one classifier for a wait that a terminal owner ended. The + * caller cancels and the deadline times out. A scope fence during a `WAIT` + * (credentials, lease, dispatch, backoff) aborts the transport; during + * `ADMISSION` the response headers prove the request reached the server, + * so a stale generation stays the `SCOPE_FENCED` contract violation. + */ + const terminalOutcomeFor = ( + phase: "WAIT" | "ADMISSION", + ): HttpExecutionOutcome => { + switch (terminalCancellation) { + case "CALLER": + return finish(cancelled(abandonedCertainty()), "CANCELLED"); + case "SCOPE_FENCE": + return phase === "ADMISSION" + ? finish(scopeFenced(abandonedCertainty()), "SCOPE_FENCED") + : finish( + abandonedTransportFailure("ABORTED_BY_SCOPE"), + "SCOPE_FENCED", + ); + default: + return finish(abandonedTransportFailure("TIMEOUT"), "TIMEOUT"); + } + }; + try { // §7.7. The installed registry is the only source of a profile. Composition @@ -684,20 +720,7 @@ export function createContractHttpExecutor( "AUTH_INTEGRATION_FAILURE", ); } - if (patchResult === ABORTED) { - if (terminalCancellation === "SCOPE_FENCE") { - return finish( - abandonedTransportFailure("ABORTED_BY_SCOPE"), - "SCOPE_FENCED", - ); - } - return terminalCancellation === "CALLER" - ? finish(cancelled("NOT_STARTED"), "CANCELLED") - : finish( - abandonedTransportFailure("TIMEOUT"), - "TIMEOUT", - ); - } + if (patchResult === ABORTED) return terminalOutcomeFor("WAIT"); // NS-01. The whole answer is decoded once, inside the auth boundary, before // any field is used. Reading `kind` and `headers` off the raw object left // the decode outside that boundary: a throwing getter escaped into the @@ -818,16 +841,7 @@ export function createContractHttpExecutor( "TRAFFIC_BUDGET_EXCEEDED", ); } - if (terminalCancellation === "CALLER") { - return finish(cancelled(abandonedCertainty()), "CANCELLED"); - } - if (terminalCancellation === "SCOPE_FENCE") { - return finish( - abandonedTransportFailure("ABORTED_BY_SCOPE"), - "SCOPE_FENCED", - ); - } - return finish(abandonedTransportFailure("TIMEOUT"), "TIMEOUT"); + return terminalOutcomeFor("WAIT"); } try { const controller = new AbortController(); @@ -919,22 +933,10 @@ export function createContractHttpExecutor( } else { clearTimeout(deadlineTimer); lifetimeController.signal.removeEventListener("abort", forwardLifetime); - const owner = terminalCancellation; - if (owner === "CALLER") { - return finish( - cancelled(abandonedCertainty()), - "CANCELLED", - ); + if (terminalCancellation !== null) { + return terminalOutcomeFor("WAIT"); } - if (owner === "SCOPE_FENCE") { - return finish( - abandonedTransportFailure("ABORTED_BY_SCOPE"), - "SCOPE_FENCED", - ); - } - const kind = owner === "DEADLINE" ? "TIMEOUT" : "NETWORK_FAILURE"; if ( - owner === null && canRetryTransport(contract.retrySemantics, attemptState) && retryIndex < retryCeiling && remaining() > 0 @@ -946,23 +948,14 @@ export function createContractHttpExecutor( sleep(delay, lifetimeController.signal), lifetimeController.signal, ); - if (slept === ABORTED) { - return terminalCancellation === "CALLER" - ? finish( - cancelled(abandonedCertainty()), - "CANCELLED", - ) - : finish( - abandonedTransportFailure("TIMEOUT"), - "TIMEOUT", - ); - } + if (slept === ABORTED) return terminalOutcomeFor("WAIT"); + rememberRetried(certaintyForAbandonedAttempt(attemptState, isCommand)); continue; } } return finish( - abandonedTransportFailure(kind), - kind, + abandonedTransportFailure("NETWORK_FAILURE"), + "NETWORK_FAILURE", ); } @@ -983,44 +976,28 @@ export function createContractHttpExecutor( controller.signal, () => cancelResponseBody(response), ); - // LIVE-04. Once response headers are in hand the request demonstrably - // reached the server, so a terminal owner that lands during admission - // keeps the dispatched classification: a stale generation stays the - // `SCOPE_FENCED` contract violation it has always been, and only the - // deadline and the caller reclassify the outcome. - const abandonAdmission = (): - | HttpExecutionOutcome - | null => { - switch (terminalCancellation) { - case "DEADLINE": - return finish(abandonedTransportFailure("TIMEOUT"), "TIMEOUT"); - case "CALLER": - return finish(cancelled(abandonedCertainty()), "CANCELLED"); - case "SCOPE_FENCE": - return finish( - scopeFenced(abandonedCertainty()), - "SCOPE_FENCED", - ); - default: - return null; - } - }; + // LIVE-04. A terminal owner that lands during admission wins over the + // admitted answer. if (admission.kind !== "VALUE") { cancelResponseBody(response); - return ( - abandonAdmission() ?? - finish( - abandonedTransportFailure("NETWORK_FAILURE"), - "NETWORK_FAILURE", - ) - ); + return terminalCancellation === null + ? finish( + abandonedTransportFailure("NETWORK_FAILURE"), + "NETWORK_FAILURE", + ) + : terminalOutcomeFor("ADMISSION"); } const outcome = admission.value; attemptState = "SETTLED"; - const abandoned = abandonAdmission(); - if (abandoned) return abandoned; + if (terminalCancellation !== null) { + return terminalOutcomeFor("ADMISSION"); + } if ( outcome.retryHint && + // Q-6.3-7. An answer that says the command may already be applied + // is not replayed; reconciliation owns it from here. + outcome.certainty !== "MAYBE_APPLIED" && + outcome.certainty !== "APPLIED_CONFIRMED" && retryIndex < retryCeiling && isRetryableSemantics(contract.retrySemantics) ) { @@ -1036,21 +1013,28 @@ export function createContractHttpExecutor( sleep(delay, lifetimeController.signal), lifetimeController.signal, ); - if (slept === ABORTED) { - return terminalCancellation === "CALLER" - ? finish( - cancelled(abandonedCertainty()), - "CANCELLED", - ) - : finish( - abandonedTransportFailure("TIMEOUT"), - "TIMEOUT", - ); - } + if (slept === ABORTED) return terminalOutcomeFor("WAIT"); + rememberRetried(outcome.result.effect as MutationEffectCertainty); continue; } } - return finish(outcome.result, outcome.certainty); + // Q-6.3-7. A retry never reports less than an earlier attempt of the + // same command already established. + const effect = isCommand + ? joinMutationEffectCertainty( + retriedCertainty, + outcome.result.effect as MutationEffectCertainty, + ) + : outcome.result.effect; + return finish( + effect === outcome.result.effect + ? outcome.result + : (Object.freeze({ + ...outcome.result, + effect, + }) as HttpExecutionOutcome), + outcome.certainty, + ); } finally { clearTimeout(deadlineTimer); lifetimeController.signal.removeEventListener("abort", forwardLifetime); diff --git a/src/adapters/http/index.ts b/src/adapters/http/index.ts index a70f84e2..a5f6a645 100644 --- a/src/adapters/http/index.ts +++ b/src/adapters/http/index.ts @@ -42,7 +42,9 @@ export type { CredentialPatchOutcome } from "./http-contract-bridge.ts"; * * 이 템플릿은 V2의 오퍼레이션 레지스트리와 payload 매퍼를 비워서 출하한다. * 제품이 `RuntimeHttpContract`(`src/bootstrap/runtime-adapters.ts`)의 네 - * 슬롯을 주입해야 동작한다 — 주입 없이 V3에서 되돌리면 모든 요청이 실패한다. + * 슬롯을 주입해야 동작한다. V3의 롤백 경로는 아니다 — V2는 + * `{ success, data, meta }` 봉투를, V3는 DTO 자체를 검증하므로 V2로 되돌리려면 + * 슬롯 주입과 함께 서버 응답도 V2 봉투여야 한다. */ export { createHttpClient, diff --git a/src/adapters/http/retry-policy.ts b/src/adapters/http/retry-policy.ts index ef5c5299..baddfae3 100644 --- a/src/adapters/http/retry-policy.ts +++ b/src/adapters/http/retry-policy.ts @@ -1,3 +1,5 @@ +import { parseRetryAfterDelay } from "../platform/retry-after.ts"; + const retryKinds: ReadonlySet = new Set([ "NETWORK_UNREACHABLE", "REQUEST_TIMEOUT", @@ -18,16 +20,7 @@ export function parseRetryAfter( value: string | null | undefined, now = Date.now(), ): number | null { - if (!value) return null; - - const seconds = Number(value); - if (Number.isFinite(seconds)) { - return seconds < 0 ? null : seconds * 1_000; - } - - const timestamp = Date.parse(value); - if (!Number.isFinite(timestamp)) return null; - return Math.max(0, timestamp - now); + return parseRetryAfterDelay(value, now); } export type RetryOperation = Readonly<{ diff --git a/src/adapters/platform/abortable-operation.ts b/src/adapters/platform/abortable-operation.ts index c577f5d0..4084e0d8 100644 --- a/src/adapters/platform/abortable-operation.ts +++ b/src/adapters/platform/abortable-operation.ts @@ -267,3 +267,27 @@ export function compensateLateHandle( }) .catch(() => undefined); } + +/** + * Best-effort release of a response body whose result is already classified. + * Neither a synchronous throw nor a rejected cancellation can change that + * result. + */ +export function cancelBody(response: Response): void { + try { + void response.body?.cancel().catch(() => undefined); + } catch { + // The classified result wins over body cancellation. + } +} + +/** `cancelBody` for a reader that already holds the body's lock. */ +export function cancelReader( + reader: ReadableStreamDefaultReader, +): void { + try { + void reader.cancel().catch(() => undefined); + } catch { + // The classified result wins over reader cancellation. + } +} diff --git a/src/adapters/platform/indexeddb-connection.ts b/src/adapters/platform/indexeddb-connection.ts index c53b3dca..29015b51 100644 --- a/src/adapters/platform/indexeddb-connection.ts +++ b/src/adapters/platform/indexeddb-connection.ts @@ -332,7 +332,9 @@ export function openIndexedDbDatabase( // A null `newVersion` means a delete is in progress, and no `upgrade` // policy can be applied to a schema that is going away. It is reported // before the callback runs so a caller never sees a half-open upgrade. - if (!transaction || newVersion === null || !input.upgrade) { + // Q-6.5-10. An open that already settled (caller abort, BLOCKED, close) + // must not commit a migration behind its caller's back either. + if (settled || !transaction || newVersion === null || !input.upgrade) { upgradeRejection = { kind: "UPGRADE_REJECTED", oldVersion, newVersion }; abortUpgrade(); return; diff --git a/src/adapters/platform/indexeddb-transaction.ts b/src/adapters/platform/indexeddb-transaction.ts index 1570e9ad..e97a1617 100644 --- a/src/adapters/platform/indexeddb-transaction.ts +++ b/src/adapters/platform/indexeddb-transaction.ts @@ -26,7 +26,8 @@ export type IndexedDbDurability = "default" | "strict" | "relaxed"; */ export type IndexedDbRequestSink = Readonly<{ /** - * Records the failure and aborts the transaction. The first failure wins. + * Records the failure and aborts the transaction. The first failure wins, + * and it wins over an earlier `succeed`. * This is `indexeddb-runtime.ts:1047-1054`'s `fail`. */ fail(failure: Failure): void; @@ -266,7 +267,9 @@ export function runIndexedDbTransaction( candidate ??= succeeded(value); }, fail(failure) { - candidate ??= failed(failure); + // Q-6.5-10. A failure replaces an earlier `succeed`; only an earlier + // failure outranks it. + if (candidate?.ok !== false) candidate = failed(failure); try { transaction.abort(); } catch { diff --git a/src/adapters/realtime/json-member-scanner.ts b/src/adapters/platform/json-member-scanner.ts similarity index 100% rename from src/adapters/realtime/json-member-scanner.ts rename to src/adapters/platform/json-member-scanner.ts diff --git a/src/adapters/platform/retry-after.ts b/src/adapters/platform/retry-after.ts new file mode 100644 index 00000000..88946745 --- /dev/null +++ b/src/adapters/platform/retry-after.ts @@ -0,0 +1,38 @@ +/** + * Parses an HTTP Retry-After value: delta-seconds (digits only, surrounding + * whitespace allowed) or an IMF-fixdate. Anything else — decimals, exponents, + * blank text, other date spellings — is `null`, never a guessed delay. + * No runtime ceiling is applied; callers reject a value above their budget. + */ +export function parseRetryAfterDelay( + value: string | null | undefined, + nowEpochMs: number, +): number | null { + if ( + typeof value !== "string" || + value.length === 0 || + value.length > 128 || + !Number.isFinite(nowEpochMs) + ) { + return null; + } + const normalized = value.trim(); + if (/^\d+$/u.test(normalized)) { + const seconds = Number(normalized); + return Number.isSafeInteger(seconds) && + seconds <= Math.floor(Number.MAX_SAFE_INTEGER / 1_000) + ? seconds * 1_000 + : null; + } + if ( + !/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/u.test( + normalized, + ) + ) { + return null; + } + const timestamp = Date.parse(normalized); + return Number.isFinite(timestamp) + ? Math.max(0, timestamp - nowEpochMs) + : null; +} diff --git a/src/adapters/query-cache/conditional-validator-store.ts b/src/adapters/query-cache/conditional-validator-store.ts index 81e51004..2522b1f2 100644 --- a/src/adapters/query-cache/conditional-validator-store.ts +++ b/src/adapters/query-cache/conditional-validator-store.ts @@ -138,12 +138,11 @@ export function createConditionalValidatorStore( function isSafeEntityTag(value: string): boolean { if (value.length < 3 || value.length > 256) return false; - const opaque = value.startsWith('W/"') - ? value.slice(3, -1) - : value.startsWith('"') - ? value.slice(1, -1) - : null; - if (opaque === null || !value.endsWith('"')) return false; + const start = value.startsWith('W/"') ? 3 : value.startsWith('"') ? 1 : -1; + // Q-6.3-12. The closing quote must follow the opening one: a bare `W/"` + // ends with its opening quote and is unclosed. + if (start < 0 || value.length <= start || !value.endsWith('"')) return false; + const opaque = value.slice(start, -1); return [...opaque].every((character) => { const code = character.codePointAt(0) ?? 0; return code === 0x21 || (code >= 0x23 && code <= 0x7e) || diff --git a/src/adapters/query-cache/cursor-pagination-runtime.ts b/src/adapters/query-cache/cursor-pagination-runtime.ts index 4c74b1ca..f355a831 100644 --- a/src/adapters/query-cache/cursor-pagination-runtime.ts +++ b/src/adapters/query-cache/cursor-pagination-runtime.ts @@ -68,6 +68,7 @@ export function createCursorPaginationRuntime(dependencies: Readonly<{ return Object.freeze({ async loadAll(context) { const items: Value[] = []; + let pageBytes = 0; const cursors = new Set(); let cursor: string | null = null; let snapshot: string | null | undefined; @@ -108,16 +109,21 @@ export function createCursorPaginationRuntime(dependencies: Readonly<{ "PAGINATION_SNAPSHOT_CHANGED", ); } - items.push(...page.items); + // Q-6.3-12. Each page is measured once (the sum errs high by at most + // one byte per page) and appended item by item: re-serializing the + // accumulated items was O(pages × total), and `push(...items)` + // throws a RangeError for a large page. + pageBytes += estimatedBytes(page.items); if ( - items.length > profile.maxTotalItems || - estimatedBytes(items) > profile.maxEstimatedBytes + items.length + page.items.length > profile.maxTotalItems || + pageBytes > profile.maxEstimatedBytes ) { return failure( "RESULT_LIMIT_EXCEEDED", "PAGINATION_RESULT_LIMIT", ); } + for (const item of page.items) items.push(item); if (!page.hasMore) return { ok: true, value: Object.freeze(items) }; const nextCursor: string | null = page.nextCursor; if (!nextCursor || cursors.has(nextCursor)) { diff --git a/src/adapters/query-cache/tanstack-cache-coordinator.ts b/src/adapters/query-cache/tanstack-cache-coordinator.ts index 8855fa56..305db5d7 100644 --- a/src/adapters/query-cache/tanstack-cache-coordinator.ts +++ b/src/adapters/query-cache/tanstack-cache-coordinator.ts @@ -76,16 +76,19 @@ export function createTanStackCacheCoordinator( namespaces.set(queryNamespaceIdentityKey(namespace), namespace); } } - for (const namespace of namespaces.values()) { - try { - await dependencies.queryClient.invalidateQueries({ + // Q-6.3-8. invalidateQueries resolves only after the active refetches + // finish, so the namespaces run side by side instead of one after another. + const results = await Promise.allSettled( + [...namespaces.values()].map(async (namespace) => + dependencies.queryClient.invalidateQueries({ queryKey: createQueryInvalidationPrefix(namespace), exact: false, refetchType: "active", - }); - } catch { - report("invalidate"); - } + }), + ), + ); + for (const result of results) { + if (result.status === "rejected") report("invalidate"); } } diff --git a/src/adapters/realtime/event-codec.ts b/src/adapters/realtime/event-codec.ts index 90738014..15b1042f 100644 --- a/src/adapters/realtime/event-codec.ts +++ b/src/adapters/realtime/event-codec.ts @@ -24,14 +24,16 @@ import { } from "../../contracts/schema-registry.ts"; import { hasDuplicateJsonMembers, -} from "./json-member-scanner.ts"; +} from "../platform/json-member-scanner.ts"; export type ValidatedRealtimeEventDto = Readonly<{ envelope: RealtimeEventEnvelope; wireBytes: number; /** * Adapter-private semantic identity used only by the bounded conflict - * detector. It must never be logged or projected into diagnostics. + * detector: a fixed-size hash of the canonical envelope, so dedupe memory + * does not grow with payload size. It must never be logged or projected + * into diagnostics. */ semanticFingerprint: string; fingerprintBytes: number; @@ -99,13 +101,13 @@ function decodeUnsafe( if (typeof raw !== "string") { return realtimeFailure("MALFORMED_EVENT", "DECODE"); } - if ( - raw.length > REALTIME_HARD_LIMITS.maxEventBytes || - encoder.encode(raw).byteLength > REALTIME_HARD_LIMITS.maxEventBytes - ) { + if (raw.length > REALTIME_HARD_LIMITS.maxEventBytes) { return realtimeFailure("EVENT_TOO_LARGE", "DECODE"); } const wireBytes = encoder.encode(raw).byteLength; + if (wireBytes > REALTIME_HARD_LIMITS.maxEventBytes) { + return realtimeFailure("EVENT_TOO_LARGE", "DECODE"); + } let input: unknown; if ( @@ -186,11 +188,8 @@ function decodeUnsafe( eventType, payloadSnapshot, ); - const semanticFingerprint = canonicalJson(envelope); - const fingerprintBytes = encoder.encode(semanticFingerprint).byteLength; - if (fingerprintBytes > stream.limits.maxEventBytes) { - return realtimeFailure("EVENT_TOO_LARGE", "DECODE"); - } + const semanticFingerprint = hash64(canonicalJson(envelope)); + const fingerprintBytes = semanticFingerprint.length; const dto = Object.freeze({ envelope, @@ -367,6 +366,26 @@ function snapshotJson( return visit(value, 0); } +/** + * Two differently seeded 32-bit FNV-1a hashes as 16 hex characters. + * ponytail: not collision-proof against a hostile server; a collision only + * lets a conflicting redelivery pass as a duplicate. Use SHA-256 if the + * server is not trusted to keep event IDs unique. + */ +function hash64(text: string): string { + let first = 0x811c9dc5; + let second = 0x9e3779b9; + for (let index = 0; index < text.length; index += 1) { + const unit = text.charCodeAt(index); + first = Math.imul(first ^ unit, 0x01000193); + second = Math.imul(second ^ unit, 0x01000193); + } + return ( + (first >>> 0).toString(16).padStart(8, "0") + + (second >>> 0).toString(16).padStart(8, "0") + ); +} + function canonicalJson(value: unknown): string { if ( value === null || diff --git a/src/adapters/realtime/live-poll-handoff-coordinator.ts b/src/adapters/realtime/live-poll-handoff-coordinator.ts index 7ea3606f..ceb4e769 100644 --- a/src/adapters/realtime/live-poll-handoff-coordinator.ts +++ b/src/adapters/realtime/live-poll-handoff-coordinator.ts @@ -7,6 +7,7 @@ import { import { systemClock } from "../platform/system-clock.ts"; import { isRealtimeResult, + raceRealtimeTask, realtimeFailure, realtimeSuccess, } from "./result.ts"; @@ -132,8 +133,6 @@ type InternalProbe = { facade: LiveProbeLease; readonly buffer: BufferedValue[]; bufferedBytes: number; - acceptedEvents: number; - acceptedBytes: number; }; type QuiescenceOutcome = "QUIESCED" | "TIMER_FAILED" | "TIMED_OUT"; @@ -224,8 +223,6 @@ export function createLivePollHandoffCoordinator( lease, buffer: [], bufferedBytes: 0, - acceptedEvents: 0, - acceptedBytes: 0, facade: null as unknown as LiveProbeLease, }; selected.facade = Object.freeze({ @@ -263,11 +260,11 @@ export function createLivePollHandoffCoordinator( value: Value, wireBytes: number, ): RealtimeResult { + // Bounded by what is still buffered: activation drains the buffer while + // the probe keeps receiving. if ( - selected.acceptedEvents + 1 > - limits.maxProbeBufferedEvents || - selected.acceptedBytes + wireBytes > - limits.maxProbeBufferedBytes + selected.buffer.length + 1 > limits.maxProbeBufferedEvents || + selected.bufferedBytes + wireBytes > limits.maxProbeBufferedBytes ) { if (transitioning) { failClosed(); @@ -282,8 +279,6 @@ export function createLivePollHandoffCoordinator( } selected.buffer.push(Object.freeze({ value, wireBytes })); selected.bufferedBytes += wireBytes; - selected.acceptedEvents += 1; - selected.acceptedBytes += wireBytes; return realtimeSuccess( Object.freeze({ kind: "BUFFERED" as const, @@ -555,24 +550,6 @@ export function createLivePollHandoffCoordinator( from: LivePollWriterKind, candidate: InternalWriterLease, ): Promise> { - const timer = new AbortController(); - let releaseAbortGate = (): void => undefined; - const aborted = new Promise< - Readonly<{ kind: "ABORTED" }> - >((resolve) => { - const onAbort = () => resolve({ kind: "ABORTED" }); - candidate.controller.signal.addEventListener( - "abort", - onAbort, - { once: true }, - ); - releaseAbortGate = () => - candidate.controller.signal.removeEventListener( - "abort", - onAbort, - ); - if (candidate.controller.signal.aborted) onAbort(); - }); const operation = Promise.resolve() .then(() => dependencies.establishAuthoritativeCheckpoint( @@ -585,59 +562,30 @@ export function createLivePollHandoffCoordinator( isCheckpointCandidateCurrent(candidate), }), ), - ) - .then( - (value) => ({ kind: "VALUE" as const, value }), - () => ({ kind: "REJECTED" as const }), ); // RT-RR-04. Registered at the moment the authority is called, and removed // only when it settles, so `close()` cannot report quiescence over it. - checkpointTasks.add(operation); - void operation.finally(() => { - checkpointTasks.delete(operation); + const settled = operation.then( + () => undefined, + () => undefined, + ); + checkpointTasks.add(settled); + void settled.then(() => { + checkpointTasks.delete(settled); }); - const timeout = Promise.resolve() - .then(async () => { - await clock.sleep( - limits.quiescenceTimeoutMs, - timer.signal, - ); - return { kind: "TIMED_OUT" as const }; - }) - .catch(() => ({ - kind: timer.signal.aborted - ? ("CANCELED" as const) - : ("TIMER_FAILED" as const), - })); - const selected = await Promise.race([ - operation, - timeout, - aborted, - ]); - timer.abort(); - releaseAbortGate(); + const selected = await raceRealtimeTask( + () => operation, + candidate.controller.signal, + (signal) => clock.sleep(limits.quiescenceTimeoutMs, signal), + ); if (selected.kind === "ABORTED") { return handoffFailure("ABORTED", "RECOVER"); } - if (selected.kind === "TIMED_OUT") { + if (selected.kind === "TIMEOUT") { candidate.controller.abort(); return handoffFailure("IDLE_TIMEOUT", "RECOVER"); } - if ( - selected.kind === "TIMER_FAILED" || - selected.kind === "REJECTED" - ) { - candidate.controller.abort(); - return handoffFailure( - "PROVIDER_UNAVAILABLE", - "RECOVER", - true, - ); - } - if (selected.kind === "CANCELED") { - return handoffFailure("ABORTED", "RECOVER"); - } if (selected.kind !== "VALUE") { candidate.controller.abort(); return handoffFailure( @@ -673,50 +621,22 @@ export function createLivePollHandoffCoordinator( async function awaitTaskQuiescence( task: Promise, ): Promise { - const timer = new AbortController(); - const settled = task.then( - () => "QUIESCED" as const, - () => "QUIESCED" as const, + const outcome = await raceRealtimeTask( + () => task, + undefined, + (signal) => clock.sleep(limits.quiescenceTimeoutMs, signal), ); - const timeout = Promise.resolve() - .then(async () => { - await clock.sleep(limits.quiescenceTimeoutMs, timer.signal); - return "TIMED_OUT" as const; - }) - .catch(() => - timer.signal.aborted - ? ("QUIESCED" as const) - : ("TIMER_FAILED" as const), - ); - const outcome = await Promise.race([settled, timeout]); - timer.abort(); - return outcome; + return outcome.kind === "TIMEOUT" + ? "TIMED_OUT" + : outcome.kind === "CLOCK_FAILED" + ? "TIMER_FAILED" + : "QUIESCED"; } - async function awaitQuiescence( + function awaitQuiescence( lease: InternalWriterLease, ): Promise { - const timer = new AbortController(); - const settled = lease.tail.then( - () => "QUIESCED" as const, - () => "QUIESCED" as const, - ); - const timeout = Promise.resolve() - .then(async () => { - await clock.sleep( - limits.quiescenceTimeoutMs, - timer.signal, - ); - return "TIMED_OUT" as const; - }) - .catch(() => - timer.signal.aborted - ? ("QUIESCED" as const) - : ("TIMER_FAILED" as const), - ); - const outcome = await Promise.race([settled, timeout]); - timer.abort(); - return outcome; + return awaitTaskQuiescence(lease.tail); } function close(): Promise> { diff --git a/src/adapters/realtime/polling/bounded-poll-coordinator.ts b/src/adapters/realtime/polling/bounded-poll-coordinator.ts index 7eff8333..3ca803a1 100644 --- a/src/adapters/realtime/polling/bounded-poll-coordinator.ts +++ b/src/adapters/realtime/polling/bounded-poll-coordinator.ts @@ -13,8 +13,12 @@ import { } from "../../../application/ports/realtime/shared.ts"; import { systemClock } from "../../platform/system-clock.ts"; import { + captureRealtimeDataSnapshot, + hasExactSnapshotKeys, + raceRealtimeTask, realtimeFailure, realtimeSuccess, + type RealtimeRace, } from "../result.ts"; /** @@ -216,7 +220,7 @@ export function createBoundedPollCoordinator( ) { return pollFailure("POLL_BUDGET_EXHAUSTED"); } - const cadenceOutcome = await awaitTaskOrAbort( + const cadenceOutcome = await raceRealtimeTask( () => clock.sleep(nextDelayMs, controller.signal), controller.signal, ); @@ -231,7 +235,7 @@ export function createBoundedPollCoordinator( ); return pollFailure( afterSleepFailure ?? - (cadenceOutcome.kind === "THREW" + (cadenceOutcome.kind === "REJECTED" ? "PROVIDER_UNAVAILABLE" : "ABORTED"), afterSleepFailure === "OFFLINE", @@ -281,7 +285,7 @@ export function createBoundedPollCoordinator( ); if (attemptOutcome.kind === "VALUE") { result = attemptOutcome.value; - } else if (attemptOutcome.kind === "THREW") { + } else if (attemptOutcome.kind === "REJECTED") { result = realtimeFailure( controller.signal.aborted ? "ABORTED" : "OFFLINE", "POLL", @@ -347,7 +351,12 @@ export function createBoundedPollCoordinator( !result.error.retryable || !isPollRetryableFailureKind(result.error.kind) ) { - return pollFailure(result.error.kind); + // OFFLINE (a thrown executor included) ends this lease but stays + // retryable, like every other OFFLINE here. + return pollFailure( + result.error.kind, + result.error.kind === "OFFLINE" && result.error.retryable, + ); } consecutiveFailures += 1; const failureDelay = retryDelay( @@ -411,7 +420,7 @@ export function createBoundedPollCoordinator( controller.signal, () => stop("POLL_BUDGET_EXHAUSTED"), ); - if (applyOutcome.kind === "THREW") { + if (applyOutcome.kind === "REJECTED") { return applyFailure(); } if (applyOutcome.kind !== "VALUE") { @@ -550,156 +559,24 @@ function currentFailure( return null; } -type TaskOutcome = - | Readonly<{ kind: "VALUE"; value: Value }> - | Readonly<{ kind: "THREW" }> - | Readonly<{ kind: "ABORTED" }>; - -type LeaseTaskOutcome = - | TaskOutcome - | Readonly<{ kind: "LEASE_EXPIRED" }> - | Readonly<{ kind: "CLOCK_FAILED" }>; - -async function awaitTaskOrAbort( - task: () => Promise, - signal: AbortSignal, -): Promise> { - if (signal.aborted) return Object.freeze({ kind: "ABORTED" }); - - let removeAbortListener: () => void = () => undefined; - const aborted = new Promise>( - (resolve) => { - const onAbort = () => resolve(Object.freeze({ kind: "ABORTED" })); - signal.addEventListener("abort", onAbort, { once: true }); - removeAbortListener = () => - signal.removeEventListener("abort", onAbort); - if (signal.aborted) onAbort(); - }, - ); - if (signal.aborted) { - removeAbortListener(); - return Object.freeze({ kind: "ABORTED" }); - } - let taskPromise: Promise; - try { - taskPromise = task(); - } catch { - removeAbortListener(); - return Object.freeze({ kind: "THREW" }); - } - const completed = taskPromise.then< - TaskOutcome, - TaskOutcome - >( - (value) => Object.freeze({ kind: "VALUE", value }), - () => Object.freeze({ kind: "THREW" }), - ); - - try { - return await Promise.race([completed, aborted]); - } finally { - removeAbortListener(); - } -} +const LEASE_EXPIRED = Object.freeze({ kind: "TIMEOUT" as const }); +/** Bounds work by the lease's remaining time; expiry stops the whole run. */ async function awaitWithinLease( task: () => Promise, remainingMs: number, clock: ClockPort, signal: AbortSignal, onLeaseExpired: () => void, -): Promise> { - if (!Number.isFinite(remainingMs) || remainingMs <= 0) { - onLeaseExpired(); - return Object.freeze({ kind: "LEASE_EXPIRED" }); - } - if (signal.aborted) return Object.freeze({ kind: "ABORTED" }); - - const deadlineController = new AbortController(); - let resolveInterruption: - | ((outcome: LeaseTaskOutcome) => void) - | undefined; - let removeAbortListener: () => void = () => undefined; - let interruptionSettled = false; - const finishInterruption = ( - outcome: LeaseTaskOutcome, - ): boolean => { - if (interruptionSettled) return false; - interruptionSettled = true; - resolveInterruption?.(outcome); - return true; - }; - const interrupted = new Promise>((resolve) => { - resolveInterruption = resolve; - const onAbort = () => - finishInterruption(Object.freeze({ kind: "ABORTED" })); - signal.addEventListener("abort", onAbort, { once: true }); - removeAbortListener = () => - signal.removeEventListener("abort", onAbort); - if (signal.aborted) onAbort(); - }); - if (signal.aborted) { - removeAbortListener(); - return Object.freeze({ kind: "ABORTED" }); - } - let deadlineSleep: Promise; - try { - deadlineSleep = clock.sleep( - remainingMs, - deadlineController.signal, - ); - } catch { - removeAbortListener(); - deadlineController.abort(); - return Object.freeze({ kind: "CLOCK_FAILED" }); - } - const deadline = deadlineSleep.then( - () => { - if (deadlineController.signal.aborted) return; - if ( - finishInterruption( - Object.freeze({ kind: "LEASE_EXPIRED" }), +): Promise> { + const outcome = + Number.isFinite(remainingMs) && remainingMs > 0 + ? await raceRealtimeTask(task, signal, (lease) => + clock.sleep(remainingMs, lease), ) - ) { - onLeaseExpired(); - } - }, - () => { - if (!deadlineController.signal.aborted) { - finishInterruption( - Object.freeze({ kind: "CLOCK_FAILED" }), - ); - } - }, - ); - if (signal.aborted) { - removeAbortListener(); - deadlineController.abort(); - void deadline; - return Object.freeze({ kind: "ABORTED" }); - } - let taskPromise: Promise; - try { - taskPromise = task(); - } catch { - taskPromise = Promise.reject(new Error("Task failed.")); - } - const completed = taskPromise.then< - LeaseTaskOutcome, - LeaseTaskOutcome - >( - (value) => Object.freeze({ kind: "VALUE", value }), - () => Object.freeze({ kind: "THREW" }), - ); - - try { - const outcome = await Promise.race([completed, interrupted]); - void deadline; - return outcome; - } finally { - removeAbortListener(); - deadlineController.abort(); - } + : LEASE_EXPIRED; + if (outcome.kind === "TIMEOUT") onLeaseExpired(); + return outcome; } function parseAttemptResult( @@ -790,42 +667,10 @@ function snapshotDataRecord( value: unknown, allowedKeySets: readonly (readonly string[])[], ): Readonly> | null { - if (!value || typeof value !== "object" || Array.isArray(value)) { - return null; - } - try { - if (Object.getPrototypeOf(value) !== Object.prototype) { - return null; - } - const keys = Reflect.ownKeys(value); - if (keys.some((key) => typeof key !== "string")) return null; - const sortedKeys = (keys as string[]).sort(); - if ( - !allowedKeySets.some((allowed) => { - const sortedAllowed = [...allowed].sort(); - return ( - sortedKeys.length === sortedAllowed.length && - sortedKeys.every( - (key, index) => key === sortedAllowed[index], - ) - ); - }) - ) { - return null; - } - const descriptors = Object.getOwnPropertyDescriptors(value); - const snapshot: Record = {}; - for (const key of sortedKeys) { - const descriptor = descriptors[key]; - if (!descriptor || !Object.hasOwn(descriptor, "value")) { - return null; - } - snapshot[key] = descriptor.value; - } - return Object.freeze(snapshot); - } catch { - return null; - } + const snapshot = captureRealtimeDataSnapshot(value); + return snapshot && hasExactSnapshotKeys(snapshot, ...allowedKeySets) + ? snapshot.values + : null; } function retryDelay( diff --git a/src/adapters/realtime/reconnect-coordinator.ts b/src/adapters/realtime/reconnect-coordinator.ts index 1a2a269d..708014dc 100644 --- a/src/adapters/realtime/reconnect-coordinator.ts +++ b/src/adapters/realtime/reconnect-coordinator.ts @@ -16,9 +16,14 @@ import { type ReconnectPolicy, } from "./reconnect-policy.ts"; import { + captureRealtimeDataSnapshot, + hasExactSnapshotKeys, isRealtimeResult, isRealtimeTransportEventOutcome, + raceRealtimeTask, realtimeFailure, + timerDeadline, + type RealtimeDataSnapshot, } from "./result.ts"; type FailureResult = Extract, { ok: false }>; @@ -226,12 +231,6 @@ type ParsedCloseClassification = directive: ParsedRecoveryDirective; }>; -type DataSnapshot = Readonly<{ - source: object; - keys: readonly string[]; - values: Readonly>; -}>; - type ParsedRunInput = Readonly<{ signal: AbortSignal | undefined; initialRecovery: ParsedRecoveryDirective | null; @@ -590,6 +589,22 @@ export function createRealtimeReconnectCoordinator( activeRecoveryGate = null; } }; + /** + * Ends this attempt: settles its barrier gate when given a result, + * closes the opened session, and aborts and releases the phase. + */ + const endAttempt = ( + gateResult: RealtimeResult | null, + opened?: RealtimeReconnectSession, + ) => { + if (gateResult) settleAttemptGate(gateResult); + if (opened) { + safelyClose(opened); + if (session === opened) session = null; + } + phase.controller.abort(); + phase.dispose(); + }; const isAttemptCurrent = () => state === "RUNNING" && generation === runGeneration && @@ -653,24 +668,19 @@ export function createRealtimeReconnectCoordinator( continue; } const interrupted = currentFailure() ?? "ABORTED"; - settleAttemptGate(recoveryFailure(interrupted)); - phase.dispose(); + endAttempt(recoveryFailure(interrupted)); return failure(interrupted); } const afterAttempt = currentFailure(); if (afterAttempt) { closeLateSession(attempted); - settleAttemptGate(recoveryFailure(afterAttempt)); - phase.controller.abort(); - phase.dispose(); + endAttempt(recoveryFailure(afterAttempt)); return failure(afterAttempt); } if (attemptOffline) { closeLateSession(attempted); - settleAttemptGate(recoveryFailure("OFFLINE")); - phase.controller.abort(); - phase.dispose(); + endAttempt(recoveryFailure("OFFLINE")); retry = offlineRetry( safeNow(clock) ?? beforeAttempt, "CONNECT", @@ -684,9 +694,7 @@ export function createRealtimeReconnectCoordinator( "CONNECT", pendingRecovery?.terminalFailure.result, ); - settleAttemptGate(nextRetry.result); - phase.controller.abort(); - phase.dispose(); + endAttempt(nextRetry.result); retry = nextRetry; continue; } @@ -696,27 +704,19 @@ export function createRealtimeReconnectCoordinator( ); if (!opened) { const mismatch = failure("PROTOCOL_MISMATCH"); - settleAttemptGate(mismatch); - phase.controller.abort(); - phase.dispose(); + endAttempt(mismatch); return mismatch; } const afterAttemptValidation = currentFailure(); if (afterAttemptValidation) { if (opened.ok) safelyClose(opened.value.session); - settleAttemptGate( - recoveryFailure(afterAttemptValidation), - ); - phase.controller.abort(); - phase.dispose(); + endAttempt(recoveryFailure(afterAttemptValidation)); return failure(afterAttemptValidation); } if (!opened.ok) { - settleAttemptGate(opened.failure.result); - phase.controller.abort(); - phase.dispose(); + endAttempt(opened.failure.result); if (!reconnectable(opened.failure)) { return opened.failure.result; } @@ -743,21 +743,13 @@ export function createRealtimeReconnectCoordinator( const mismatch = recoveryFailure( "PROTOCOL_MISMATCH", ); - settleAttemptGate(mismatch); - safelyClose(active); - phase.controller.abort(); - phase.dispose(); + endAttempt(mismatch, active); return mismatch; } const beforeConfirmation = currentFailure(); if (beforeConfirmation) { - settleAttemptGate( - recoveryFailure(beforeConfirmation), - ); - safelyClose(active); - phase.controller.abort(); - phase.dispose(); + endAttempt(recoveryFailure(beforeConfirmation), active); return failure(beforeConfirmation); } @@ -773,28 +765,17 @@ export function createRealtimeReconnectCoordinator( const mismatch = recoveryFailure( "PROTOCOL_MISMATCH", ); - settleAttemptGate(mismatch); - safelyClose(active); - phase.controller.abort(); - phase.dispose(); + endAttempt(mismatch, active); return mismatch; } const afterConfirmation = currentFailure(); if (afterConfirmation) { - settleAttemptGate( - recoveryFailure(afterConfirmation), - ); - safelyClose(active); - phase.controller.abort(); - phase.dispose(); + endAttempt(recoveryFailure(afterConfirmation), active); return failure(afterConfirmation); } if (!confirmation.ok) { - settleAttemptGate(confirmation.failure.result); - safelyClose(active); - phase.controller.abort(); - phase.dispose(); + endAttempt(confirmation.failure.result, active); return confirmation.failure.result; } @@ -805,9 +786,7 @@ export function createRealtimeReconnectCoordinator( } else { settleAttemptGate(noPendingRecovery); if (opened.value.hasRecoveryBarrier) { - safelyClose(active); - phase.controller.abort(); - phase.dispose(); + endAttempt(null, active); return noPendingRecovery; } } @@ -821,9 +800,7 @@ export function createRealtimeReconnectCoordinator( openedAt, ) <= 0 ) { - safelyClose(active); - phase.controller.abort(); - phase.dispose(); + endAttempt(null, active); return ( retry?.terminalResult ?? failure("PROVIDER_UNAVAILABLE") @@ -841,10 +818,7 @@ export function createRealtimeReconnectCoordinator( const afterWaitClosed = currentFailure(); if (afterWaitClosed) { - safelyClose(active); - session = null; - phase.controller.abort(); - phase.dispose(); + endAttempt(null, active); return failure(afterWaitClosed); } if (closed.kind === "INTERRUPTED") { @@ -879,10 +853,7 @@ export function createRealtimeReconnectCoordinator( } if (closeOffline) { - safelyClose(active); - session = null; - phase.controller.abort(); - phase.dispose(); + endAttempt(null, active); retry = offlineRetry( safeNow(clock) ?? openedAt, "RECEIVE", @@ -890,10 +861,7 @@ export function createRealtimeReconnectCoordinator( continue; } if (closed.kind === "THREW") { - safelyClose(active); - session = null; - phase.controller.abort(); - phase.dispose(); + endAttempt(null, active); retry = providerRetry( safeNow(clock) ?? openedAt, "RECEIVE", @@ -908,10 +876,7 @@ export function createRealtimeReconnectCoordinator( rawClassification = null; } const afterClassification = currentFailure(); - safelyClose(active); - session = null; - phase.controller.abort(); - phase.dispose(); + endAttempt(null, active); if (afterClassification) { return failure(afterClassification); } @@ -1023,65 +988,31 @@ export function createRealtimeReconnectCoordinator( }); } +const INTERRUPTED = Object.freeze({ kind: "INTERRUPTED" as const }); + async function race( task: Promise>, signal: AbortSignal, ): Promise> { - if (signal.aborted) return Object.freeze({ kind: "INTERRUPTED" }); - let cleanup: () => void = () => undefined; - const interrupted = new Promise< - Readonly<{ kind: "INTERRUPTED" }> - >((resolve) => { - const abort = () => - resolve(Object.freeze({ kind: "INTERRUPTED" })); - signal.addEventListener("abort", abort, { once: true }); - cleanup = () => signal.removeEventListener("abort", abort); - if (signal.aborted) abort(); - }); - try { - return await Promise.race([task, interrupted]); - } finally { - cleanup(); - } + const raced = await raceRealtimeTask(() => task, signal); + return raced.kind === "VALUE" ? raced.value : INTERRUPTED; } async function drainWithinCeiling( task: Promise>, signal: AbortSignal, ): Promise> { - if (signal.aborted) return Object.freeze({ kind: "INTERRUPTED" }); - let timer: ReturnType | undefined; - let cleanup: () => void = () => undefined; - const boundary = new Promise< - | Readonly<{ kind: "INTERRUPTED" }> - | Readonly<{ kind: "TIMED_OUT" }> - >((resolve) => { - const abort = () => - resolve(Object.freeze({ kind: "INTERRUPTED" })); - cleanup = () => safelyRemoveAbortListener(signal, abort); - try { - signal.addEventListener("abort", abort, { once: true }); - timer = setTimeout( - () => resolve(Object.freeze({ kind: "TIMED_OUT" })), - REALTIME_RECONNECT_CEILINGS.drainTimeoutMs, - ); - } catch { - resolve(Object.freeze({ kind: "TIMED_OUT" })); - } - if (signal.aborted) abort(); - }); - try { - return await Promise.race([task, boundary]); - } finally { - cleanup(); - if (timer !== undefined) { - try { - clearTimeout(timer); - } catch { - // The generation remains fenced if host timer cleanup fails. - } - } - } + // A host timer, not the clock: a non-cooperative clock is one of the things + // this drain has to bound. + const raced = await raceRealtimeTask( + () => task, + signal, + timerDeadline(REALTIME_RECONNECT_CEILINGS.drainTimeoutMs), + ); + if (raced.kind === "VALUE") return raced.value; + return raced.kind === "ABORTED" + ? INTERRUPTED + : Object.freeze({ kind: "TIMED_OUT" }); } function createBarrierGate(): BarrierGate { @@ -1104,15 +1035,16 @@ function createBarrierGate(): BarrierGate { } function parseRunInput(value: unknown): ParsedRunInput | null { - const snapshot = captureDataSnapshot(value); + const snapshot = captureRealtimeDataSnapshot(value); if ( !snapshot || - !hasOneExactKeySet(snapshot, [ + !hasExactSnapshotKeys( + snapshot, [], ["signal"], ["initialRecovery"], ["initialRecovery", "signal"], - ]) + ) ) { return null; } @@ -1130,7 +1062,7 @@ function parseRunInput(value: unknown): ParsedRunInput | null { initialValue === undefined ? null : parseRecoveryDirectiveSnapshot( - captureDataSnapshot(initialValue), + captureRealtimeDataSnapshot(initialValue), ); if (initialValue !== undefined && !initialRecovery) return null; return Object.freeze({ @@ -1143,28 +1075,29 @@ function parseAttemptOutcome( value: unknown, ): ParsedOutcome> | null { return parseOutcomeSnapshot( - captureDataSnapshot(value), + captureRealtimeDataSnapshot(value), (candidate) => parseAttemptSuccess( - captureDataSnapshot(candidate), + captureRealtimeDataSnapshot(candidate), ), ); } function parseAttemptSuccess( - snapshot: DataSnapshot | null, + snapshot: RealtimeDataSnapshot | null, ): ParsedValue> | null { if ( !snapshot || - !hasOneExactKeySet(snapshot, [ + !hasExactSnapshotKeys( + snapshot, ["session"], ["establishedRecoveryBarrier", "session"], - ]) + ) ) { return null; } const session = parseSession( - captureDataSnapshot(snapshot.values.session), + captureRealtimeDataSnapshot(snapshot.values.session), ); if (!session) return null; const hasRecoveryBarrier = snapshot.keys.includes( @@ -1181,11 +1114,11 @@ function parseAttemptSuccess( } function parseSession( - snapshot: DataSnapshot | null, + snapshot: RealtimeDataSnapshot | null, ): RealtimeReconnectSession | null { if ( !snapshot || - !hasExactKeys(snapshot, [ + !hasExactSnapshotKeys(snapshot, [ "classifyClosed", "close", "waitClosed", @@ -1221,7 +1154,7 @@ function parseSession( function parseCloseClassification( value: unknown, ): ParsedCloseClassification | null { - const snapshot = captureDataSnapshot(value); + const snapshot = captureRealtimeDataSnapshot(value); if (!snapshot) return null; if (snapshot.values.kind === "RECOVERY_RECONNECT") { const directive = parseRecoveryDirectiveSnapshot(snapshot); @@ -1245,11 +1178,12 @@ function parseCloseClassification( } function parseRecoveryDirectiveSnapshot( - snapshot: DataSnapshot | null, + snapshot: RealtimeDataSnapshot | null, ): ParsedRecoveryDirective | null { if ( !snapshot || - !hasOneExactKeySet(snapshot, [ + !hasExactSnapshotKeys( + snapshot, ["kind", "recovery", "terminalResult"], [ "kind", @@ -1257,13 +1191,13 @@ function parseRecoveryDirectiveSnapshot( "serverNotBeforeMs", "terminalResult", ], - ]) || + ) || snapshot.values.kind !== "RECOVERY_RECONNECT" ) { return null; } const recovery = parseCommittedRecovery( - captureDataSnapshot(snapshot.values.recovery), + captureRealtimeDataSnapshot(snapshot.values.recovery), ); const terminalFailure = parseFailureResult( snapshot.values.terminalResult, @@ -1286,32 +1220,32 @@ function parseRecoveryDirectiveSnapshot( } function parseCommittedRecovery( - snapshot: DataSnapshot | null, + snapshot: RealtimeDataSnapshot | null, ): RealtimeCommittedRecovery | null { if ( !snapshot || - !hasExactKeys(snapshot, [ + !hasExactSnapshotKeys(snapshot, [ "checkpoint", "kind", "streamId", ]) || snapshot.values.kind !== "RECOVERY_COMMITTED" || - !safeFrozen(snapshot.source) + !snapshot.frozen ) { return null; } - const checkpoint = captureDataSnapshot( + const checkpoint = captureRealtimeDataSnapshot( snapshot.values.checkpoint, ); if ( !checkpoint || - !hasExactKeys(checkpoint, [ + !hasExactSnapshotKeys(checkpoint, [ "lastAppliedSequence", "recoveryMode", "resumeCursor", "streamEpoch", ]) || - !safeFrozen(checkpoint.source) + !checkpoint.frozen ) { return null; } @@ -1347,22 +1281,23 @@ function parseVoidResult( } function parseOutcomeSnapshot( - snapshot: DataSnapshot | null, + snapshot: RealtimeDataSnapshot | null, parseValue: (candidate: unknown) => ParsedValue | null, ): ParsedOutcome | null { if ( !snapshot || - !hasOneExactKeySet(snapshot, [ + !hasExactSnapshotKeys( + snapshot, ["result"], ["result", "serverNotBeforeMs"], - ]) + ) ) { return null; } const result = parseResult(snapshot.values.result, parseValue); if (!result) return null; if (result.ok) { - return hasExactKeys(snapshot, ["result"]) + return hasExactSnapshotKeys(snapshot, ["result"]) ? Object.freeze({ ok: true, result: result.result, @@ -1385,11 +1320,11 @@ function parseResult( value: unknown, parseValue: (candidate: unknown) => ParsedValue | null, ): ParsedResult | null { - const snapshot = captureDataSnapshot(value); - if (!snapshot || !safeFrozen(snapshot.source)) return null; + const snapshot = captureRealtimeDataSnapshot(value); + if (!snapshot || !snapshot.frozen) return null; if (snapshot.values.ok === true) { - if (!hasExactKeys(snapshot, ["ok", "value"])) return null; + if (!hasExactSnapshotKeys(snapshot, ["ok", "value"])) return null; const parsedValue = parseValue(snapshot.values.value); const canonical = Object.freeze({ ok: true, @@ -1420,29 +1355,29 @@ function parseResult( function parseFailureResult( value: unknown, ): FailureSnapshot | null { - return parseFailureResultSnapshot(captureDataSnapshot(value)); + return parseFailureResultSnapshot(captureRealtimeDataSnapshot(value)); } function parseFailureResultSnapshot( - snapshot: DataSnapshot | null, + snapshot: RealtimeDataSnapshot | null, ): FailureSnapshot | null { if ( !snapshot || - !hasExactKeys(snapshot, ["error", "ok"]) || + !hasExactSnapshotKeys(snapshot, ["error", "ok"]) || snapshot.values.ok !== false || - !safeFrozen(snapshot.source) + !snapshot.frozen ) { return null; } - const error = captureDataSnapshot(snapshot.values.error); + const error = captureRealtimeDataSnapshot(snapshot.values.error); if ( !error || - !hasExactKeys(error, [ + !hasExactSnapshotKeys(error, [ "kind", "operation", "retryable", ]) || - !safeFrozen(error.source) + !error.frozen ) { return null; } @@ -1472,69 +1407,6 @@ function parseFailureResultSnapshot( }); } -function captureDataSnapshot(value: unknown): DataSnapshot | null { - if (!value || typeof value !== "object" || Array.isArray(value)) { - return null; - } - try { - const prototype = Object.getPrototypeOf(value); - if ( - prototype !== Object.prototype && - prototype !== null - ) { - return null; - } - const descriptors = Object.getOwnPropertyDescriptors(value); - const ownKeys = Reflect.ownKeys(descriptors); - if (ownKeys.some((key) => typeof key !== "string")) { - return null; - } - const keys = (ownKeys as string[]).sort(); - const values = Object.create(null) as Record; - for (const key of keys) { - const descriptor = descriptors[key]; - if ( - !descriptor || - !("value" in descriptor) || - descriptor.enumerable !== true - ) { - return null; - } - Object.defineProperty(values, key, { - configurable: false, - enumerable: true, - value: descriptor.value, - writable: false, - }); - } - return Object.freeze({ - source: value, - keys: Object.freeze(keys), - values: Object.freeze(values), - }); - } catch { - return null; - } -} - -function hasOneExactKeySet( - snapshot: DataSnapshot, - expected: readonly (readonly string[])[], -): boolean { - return expected.some((keys) => hasExactKeys(snapshot, keys)); -} - -function hasExactKeys( - snapshot: DataSnapshot, - expected: readonly string[], -): boolean { - const sorted = [...expected].sort(); - return ( - snapshot.keys.length === sorted.length && - snapshot.keys.every((key, index) => key === sorted[index]) - ); -} - function parseNotBefore( value: unknown, ): number | null | undefined { @@ -1709,14 +1581,6 @@ function safeSignalAborted( } } -function safeFrozen(value: object): boolean { - try { - return Object.isFrozen(value); - } catch { - return false; - } -} - function safelyAddAbortListener( signal: AbortSignal | undefined, listener: () => void, diff --git a/src/adapters/realtime/reconnect-policy.ts b/src/adapters/realtime/reconnect-policy.ts index 7bc62312..d5f64582 100644 --- a/src/adapters/realtime/reconnect-policy.ts +++ b/src/adapters/realtime/reconnect-policy.ts @@ -1,3 +1,5 @@ +export { parseRetryAfterDelay } from "../platform/retry-after.ts"; + export const REALTIME_RECONNECT_CEILINGS = Object.freeze({ drainTimeoutMs: 2_000, maxAttempts: 10, @@ -126,57 +128,26 @@ export function reconnectBudgetRemaining( return Math.max(0, policy.maxElapsedMs - (nowMs - startedAtMs)); } +/** + * A connection earns a fresh retry budget only when it both proved itself + * with a valid heartbeat/event and stayed open for `stableOpenMs`. Either + * alone lets a server that sends one comment and drops keep the budget at + * zero forever. + */ export function isReconnectAttemptResetEligible(input: Readonly<{ policy: ReconnectPolicy; openedAtMs: number; nowMs: number; observedValidHeartbeatOrEvent: boolean; }>): boolean { - if (input.observedValidHeartbeatOrEvent) return true; return ( + input.observedValidHeartbeatOrEvent && Number.isFinite(input.openedAtMs) && Number.isFinite(input.nowMs) && input.nowMs - input.openedAtMs >= input.policy.stableOpenMs ); } -/** - * Parses the HTTP Retry-After delay without applying a runtime ceiling. - * Callers must reject a value that exceeds their remaining/max-delay budget. - */ -export function parseRetryAfterDelay( - value: string | null | undefined, - nowEpochMs: number, -): number | null { - if ( - typeof value !== "string" || - value.length === 0 || - value.length > 128 || - !Number.isFinite(nowEpochMs) - ) { - return null; - } - const normalized = value.trim(); - if (/^\d+$/u.test(normalized)) { - const seconds = Number(normalized); - return Number.isSafeInteger(seconds) && - seconds <= Math.floor(Number.MAX_SAFE_INTEGER / 1_000) - ? seconds * 1_000 - : null; - } - if ( - !/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/u.test( - normalized, - ) - ) { - return null; - } - const timestamp = Date.parse(normalized); - return Number.isFinite(timestamp) - ? Math.max(0, timestamp - nowEpochMs) - : null; -} - function positiveInteger(value: number): boolean { return Number.isSafeInteger(value) && value > 0; } diff --git a/src/adapters/realtime/result.ts b/src/adapters/realtime/result.ts index 8b5efa79..9325af0d 100644 --- a/src/adapters/realtime/result.ts +++ b/src/adapters/realtime/result.ts @@ -16,6 +16,7 @@ import { isRealtimeOpaqueIdentifier, isRealtimeResumeCursor, } from "../../contracts/realtime-events.ts"; +import { createAbortableOperation } from "../platform/abortable-operation.ts"; export type { RealtimeFailure, @@ -35,6 +36,8 @@ const FAILURE_KINDS = new Set(REALTIME_FAILURE_KINDS); const OPERATIONS = new Set(REALTIME_OPERATIONS); export type RealtimeDataSnapshot = Readonly<{ + /** The object that was read; never read its properties again. */ + source: object; keys: readonly string[]; values: Readonly>; frozen: boolean; @@ -67,6 +70,100 @@ export function isRealtimeFailure( return parseRealtimeFailure(value, true) !== null; } +export type RealtimeRace = + | Readonly<{ kind: "VALUE"; value: Value }> + | Readonly<{ kind: "REJECTED" }> + | Readonly<{ kind: "ABORTED" }> + | Readonly<{ kind: "TIMEOUT" }> + | Readonly<{ kind: "CLOCK_FAILED" }>; + +const REJECTED = Object.freeze({ kind: "REJECTED" as const }); +const ABORTED = Object.freeze({ kind: "ABORTED" as const }); +const TIMEOUT = Object.freeze({ kind: "TIMEOUT" as const }); +const CLOCK_FAILED = Object.freeze({ kind: "CLOCK_FAILED" as const }); + +/** + * Realtime's one abort/deadline race, on the kernel abortable operation. + * Settles with whichever comes first: the task's value or rejection (a + * synchronous throw counts as one), `signal` aborting, or `deadline` + * resolving. A deadline that throws or rejects on its own is CLOCK_FAILED. + * Nothing starts when `signal` is already aborted. + * + * The task gets the operation signal, which aborts with `signal`, at the + * deadline and once the race is over. The deadline is armed before the task + * starts, so it wins a tie, but the task always starts (a cancel must not be + * skipped because the clock broke). + */ +export function raceRealtimeTask( + task: (signal: AbortSignal) => Value | PromiseLike, + signal?: AbortSignal, + deadline?: (signal: AbortSignal) => PromiseLike, +): Promise> { + if (signal?.aborted) return Promise.resolve(ABORTED); + const timer = new AbortController(); + const operation = createAbortableOperation({ + signal, + ...(deadline && { + timeoutMs: 0, + setTimer: (fire: () => void) => + Promise.resolve(deadline(timer.signal)).then(fire, () => + operation.close(), + ), + clearTimer: () => timer.abort(), + }), + }); + let running: Promise; + try { + running = Promise.resolve(task(operation.signal)); + } catch (error) { + running = Promise.reject(error); + } + const raced = operation.race(running); + // Registered after the race, so the outcome is claimed first. + void running.then(operation.close, operation.close); + return raced.then((outcome) => + outcome.kind === "VALUE" + ? outcome + : outcome.kind === "REJECTED" + ? REJECTED + : outcome.terminal === "CALLER_ABORT" + ? ABORTED + : outcome.terminal === "DEADLINE" + ? TIMEOUT + : CLOCK_FAILED, + ); +} + +/** + * A `raceRealtimeTask` deadline on a host timer instead of the injected + * clock, for bounds that must hold even when the clock itself hangs. + */ +export function timerDeadline( + delayMs: number, + schedule: (callback: () => void, delayMs: number) => unknown = ( + callback, + delay, + ) => setTimeout(callback, delay), + cancel: (handle: unknown) => void = (handle) => + clearTimeout(handle as ReturnType), +): (signal: AbortSignal) => Promise { + return (signal) => + new Promise((resolve) => { + const handle = schedule(resolve, delayMs); + signal.addEventListener( + "abort", + () => { + try { + cancel(handle); + } catch { + // A broken scheduler cannot change the race outcome. + } + }, + { once: true }, + ); + }); +} + /** * Captures an external result through own data descriptors exactly once and * returns a new canonical value. Callers that need to use the validated fields @@ -186,6 +283,7 @@ export function captureRealtimeDataSnapshot( descriptor.writable === false; } return Object.freeze({ + source: value, keys: Object.freeze(keys), values: Object.freeze(values), frozen, @@ -266,13 +364,16 @@ function parseRealtimeFailure( }); } -function hasExactSnapshotKeys( +/** True when the snapshot's keys are exactly one of the given key sets. */ +export function hasExactSnapshotKeys( snapshot: RealtimeDataSnapshot, - expectedKeys: readonly string[], + ...keySets: readonly (readonly string[])[] ): boolean { - const expected = [...expectedKeys].sort(); - return ( - snapshot.keys.length === expected.length && - snapshot.keys.every((key, index) => key === expected[index]) - ); + return keySets.some((keySet) => { + const expected = [...keySet].sort(); + return ( + snapshot.keys.length === expected.length && + snapshot.keys.every((key, index) => key === expected[index]) + ); + }); } diff --git a/src/adapters/realtime/sse/fetch-sse-connection.ts b/src/adapters/realtime/sse/fetch-sse-connection.ts index 3115b9f5..049a186b 100644 --- a/src/adapters/realtime/sse/fetch-sse-connection.ts +++ b/src/adapters/realtime/sse/fetch-sse-connection.ts @@ -16,6 +16,7 @@ import { parseRetryAfterDelay } from "../reconnect-policy.ts"; import { isRealtimeResult, isRealtimeTransportEventOutcome, + raceRealtimeTask, realtimeFailure, realtimeSuccess, } from "../result.ts"; @@ -100,6 +101,7 @@ const MAX_CONNECT_TIMEOUT_MS = 30_000; const MAX_IDLE_TIMEOUT_MS = 120_000; const MAX_CURSOR_BYTES = 1_024; const READER_CANCEL_TIMEOUT_MS = 2_000; +const encoder = new TextEncoder(); export function createFetchSseConnection( dependencies: FetchSseConnectionDependencies, @@ -162,30 +164,36 @@ export function createFetchSseConnection( once: true, }); if (input.signal?.aborted) onCallerAbort(); + const timed = ( + task: () => Value | PromiseLike, + timeoutMs: number, + ) => + raceRealtimeTask(task, controller.signal, (signal) => + clock.sleep(timeoutMs, signal), + ); try { - const request = timed( - Promise.resolve().then(() => - fetcher(endpoint.href, { - method: "GET", - credentials: "same-origin", - redirect: "error", - cache: "no-store", - referrerPolicy: "no-referrer", - headers: { - Accept: "text/event-stream", - ...(input.resumeCursor === null - ? {} - : { "Last-Event-ID": input.resumeCursor }), - }, - signal: controller.signal, - }), - ), + const responseResult = await timed( + // The fetcher starts on the next microtask, like other collaborators. + () => + Promise.resolve().then(() => + fetcher(endpoint.href, { + method: "GET", + credentials: "same-origin", + redirect: "error", + cache: "no-store", + referrerPolicy: "no-referrer", + headers: { + Accept: "text/event-stream", + ...(input.resumeCursor === null + ? {} + : { "Last-Event-ID": input.resumeCursor }), + }, + signal: controller.signal, + }), + ), connectTimeoutMs, - clock, - controller.signal, ); - const responseResult = await request; if (responseResult.kind === "CLOCK_FAILED") { controller.abort(); return failed("PROVIDER_UNAVAILABLE", "CONNECT", true); @@ -241,23 +249,11 @@ export function createFetchSseConnection( const reader = response.body.getReader(); activeReader = reader; let retryHintMs: number | null = null; - if (input.onOpen) { - let opening: Promise>; - try { - opening = Promise.resolve(input.onOpen(controller.signal)); - } catch { - await cancelReader(reader, clock, controller); - return failed( - "PROVIDER_UNAVAILABLE", - "CONNECT", - false, - ); - } + const onOpen = input.onOpen; + if (onOpen) { const opened = await timed( - opening, + () => onOpen(controller.signal), connectTimeoutMs, - clock, - controller.signal, ); if (opened.kind !== "VALUE") { await cancelReader(reader, clock, controller); @@ -305,7 +301,7 @@ export function createFetchSseConnection( (!item.hasExplicitId || !item.id || !isRealtimeResumeCursor(item.id) || - new TextEncoder().encode(item.id).byteLength > + encoder.encode(item.id).byteLength > maxCursorBytes) ) { await cancelReader(reader, clock, controller); @@ -318,22 +314,9 @@ export function createFetchSseConnection( await cancelReader(reader, clock, controller); return failed("PROTOCOL_MISMATCH", "DECODE", false); } - let handler: Promise< - RealtimeResult - >; - try { - handler = Promise.resolve( - input.onEvent(item, controller.signal), - ); - } catch { - await cancelReader(reader, clock, controller); - return failed("APPLY_FAILED", "APPLY", false); - } const handled = await timed( - handler, + () => input.onEvent(item, controller.signal), idleTimeoutMs, - clock, - controller.signal, ); if (handled.kind === "ABORTED") { await cancelReader(reader, clock, controller); @@ -384,10 +367,8 @@ export function createFetchSseConnection( while (true) { const readResult = await timed( - reader.read(), + () => reader.read(), idleTimeoutMs, - clock, - controller.signal, ); if (readResult.kind === "ABORTED") { await cancelReader(reader, clock, controller); @@ -434,13 +415,20 @@ export function createFetchSseConnection( await cancelReader(reader, clock, controller); return failed("MALFORMED_EVENT", "DECODE", false); } - const parsed = parser.push(readResult.value.value); - if (!parsed.ok) { - await cancelReader(reader, clock, controller); - return parsed; + // Items past the parser's per-call cap arrive through drain(). + for ( + let parsed = parser.push(readResult.value.value); + ; + parsed = parser.drain() + ) { + if (!parsed.ok) { + await cancelReader(reader, clock, controller); + return parsed; + } + if (parsed.value.length === 0) break; + const dispatchFailure = await handleParserItems(parsed.value); + if (dispatchFailure) return dispatchFailure; } - const dispatchFailure = await handleParserItems(parsed.value); - if (dispatchFailure) return dispatchFailure; } } catch { return failed( @@ -532,7 +520,7 @@ function validResumeCursor( return ( typeof cursor === "string" && isRealtimeResumeCursor(cursor) && - new TextEncoder().encode(cursor).byteLength <= maxCursorBytes + encoder.encode(cursor).byteLength <= maxCursorBytes ); } @@ -591,66 +579,6 @@ function responseFailure( return failed("PROTOCOL_MISMATCH", "CONNECT", false); } -type TimedResult = - | Readonly<{ kind: "VALUE"; value: Value }> - | Readonly<{ kind: "REJECTED" }> - | Readonly<{ kind: "ABORTED" }> - | Readonly<{ kind: "CLOCK_FAILED" }> - | Readonly<{ kind: "TIMEOUT" }>; - -async function timed( - operation: Promise, - timeoutMs: number, - clock: ClockPort, - signal: AbortSignal, -): Promise> { - if (signal.aborted) { - return Object.freeze({ kind: "ABORTED" }); - } - const timer = new AbortController(); - let abortListener: (() => void) | undefined; - const operationResult = operation.then< - TimedResult, - TimedResult - >( - (value) => Object.freeze({ kind: "VALUE", value }), - () => Object.freeze({ kind: "REJECTED" }), - ); - let timeoutResult: Promise>; - try { - timeoutResult = clock.sleep(timeoutMs, timer.signal).then< - TimedResult, - TimedResult - >( - () => Object.freeze({ kind: "TIMEOUT" }), - () => - Object.freeze({ - kind: timer.signal.aborted - ? ("ABORTED" as const) - : ("CLOCK_FAILED" as const), - }), - ); - } catch { - return Object.freeze({ kind: "CLOCK_FAILED" }); - } - const abortedResult = new Promise>((resolve) => { - abortListener = () => - resolve(Object.freeze({ kind: "ABORTED" })); - signal.addEventListener("abort", abortListener, { once: true }); - if (signal.aborted) abortListener(); - }); - const result = await Promise.race([ - operationResult, - timeoutResult, - abortedResult, - ]); - timer.abort(); - if (abortListener) { - signal.removeEventListener("abort", abortListener); - } - return result; -} - function readClockNow(clock: ClockPort): number | null { try { const value = clock.now(); @@ -666,29 +594,11 @@ async function cancelReader( generation?: AbortController, ): Promise { generation?.abort(); - let cancellation: Promise; - try { - cancellation = Promise.resolve(reader.cancel()).then( - () => undefined, - () => undefined, - ); - } catch { - return; - } - const timeout = new AbortController(); - let timeoutPromise: Promise; - try { - timeoutPromise = clock - .sleep(READER_CANCEL_TIMEOUT_MS, timeout.signal) - .then( - () => undefined, - () => undefined, - ); - } catch { - timeoutPromise = Promise.resolve(); - } - await Promise.race([cancellation, timeoutPromise]); - timeout.abort(); + await raceRealtimeTask( + () => reader.cancel(), + undefined, + (signal) => clock.sleep(READER_CANCEL_TIMEOUT_MS, signal), + ); } function safelyNotify( diff --git a/src/adapters/realtime/sse/sse-parser.ts b/src/adapters/realtime/sse/sse-parser.ts index 94e0f790..103fef71 100644 --- a/src/adapters/realtime/sse/sse-parser.ts +++ b/src/adapters/realtime/sse/sse-parser.ts @@ -14,6 +14,10 @@ export const SSE_PARSER_CEILINGS = Object.freeze({ }); const LINE_BREAK = /[\r\n]/gu; +const NO_ITEMS: readonly SseParserItem[] = Object.freeze([]); +const COMMENT_ITEMS: readonly SseParserItem[] = Object.freeze([ + Object.freeze({ kind: "COMMENT" as const }), +]); export type SseParserLimits = Readonly<{ maxLineBytes: number; @@ -47,7 +51,13 @@ export type SseParserFinish = Readonly<{ }>; export type IncrementalSseParser = Readonly<{ + /** + * Returns at most `maxItemsPerChunk` items. Text past that cap is kept and + * must be taken with `drain()` until it returns no items; pushing or + * finishing before then fails with QUEUE_OVERFLOW. + */ push(chunk: Uint8Array): RealtimeResult; + drain(): RealtimeResult; finish(): RealtimeResult; }>; @@ -55,6 +65,8 @@ export function createIncrementalSseParser( limits: Partial = {}, ): IncrementalSseParser { const resolved = resolveLimits(limits); + // ignoreBOM: false makes the decoder strip the one leading BOM the + // stream grammar allows; a second one is ordinary text. const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false, @@ -62,10 +74,10 @@ export function createIncrementalSseParser( const encoder = new TextEncoder(); let state: "OPEN" | "FAILED" | "FINISHED" = "OPEN"; - let atStart = true; let pendingCarriageReturn = false; let line = ""; let lineBytes = 0; + let undrained = ""; let blockBytes = 0; let dataLines: string[] = []; let eventType = ""; @@ -84,6 +96,7 @@ export function createIncrementalSseParser( if (chunk.byteLength > resolved.maxChunkBytes) { return fail("EVENT_TOO_LARGE"); } + if (undrained.length > 0) return fail("QUEUE_OVERFLOW"); let text: string; try { text = decoder.decode(chunk, { stream: true }); @@ -93,10 +106,20 @@ export function createIncrementalSseParser( return consumeText(text); } + function drain(): RealtimeResult { + if (state !== "OPEN") { + return realtimeFailure("CLOSED", "DECODE"); + } + const text = undrained; + undrained = ""; + return consumeText(text); + } + function finish(): RealtimeResult { if (state !== "OPEN") { return realtimeFailure("CLOSED", "DECODE"); } + if (undrained.length > 0) return fail("QUEUE_OVERFLOW"); let tail: string; try { tail = decoder.decode(); @@ -110,9 +133,13 @@ export function createIncrementalSseParser( pendingCarriageReturn = false; const processed = processLine(1); if (!processed.ok) return processed; - if (!appendItems(items, processed.value)) { - return fail("QUEUE_OVERFLOW"); - } + items.push(...processed.value); + } + if ( + undrained.length > 0 || + items.length > resolved.maxItemsPerChunk + ) { + return fail("QUEUE_OVERFLOW"); } const incompleteEventDiscarded = lineBytes > 0 || @@ -136,31 +163,27 @@ export function createIncrementalSseParser( * Works a line at a time: find the next CR/LF, append the text before it * and count its UTF-8 bytes once. Byte counts only grow within a line, so * checking the limits per segment fails exactly where a per-character check - * would. + * would. Stops at `maxItemsPerChunk` items and keeps the rest for `drain()`. */ function consumeText( text: string, ): RealtimeResult { const items: SseParserItem[] = []; let index = 0; - if (atStart && text.length > 0) { - atStart = false; - if (text.charCodeAt(0) === 0xfeff) index = 1; - } while (index < text.length) { + if (items.length >= resolved.maxItemsPerChunk) { + undrained = text.slice(index); + break; + } if (pendingCarriageReturn) { pendingCarriageReturn = false; const lineFeed = text.charCodeAt(index) === 0x0a; const processed = processLine(lineFeed ? 2 : 1); if (!processed.ok) return processed; - if (!appendItems(items, processed.value)) { - return fail("QUEUE_OVERFLOW"); - } - if (lineFeed) { - index += 1; - continue; - } + items.push(...processed.value); + if (lineFeed) index += 1; + continue; } LINE_BREAK.lastIndex = index; @@ -185,9 +208,7 @@ export function createIncrementalSseParser( } const processed = processLine(1); if (!processed.ok) return processed; - if (!appendItems(items, processed.value)) { - return fail("QUEUE_OVERFLOW"); - } + items.push(...processed.value); } return success(Object.freeze(items)); } @@ -217,13 +238,7 @@ export function createIncrementalSseParser( return success(Object.freeze(items)); } - if (currentLine.startsWith(":")) { - return success( - Object.freeze([ - Object.freeze({ kind: "COMMENT" as const }), - ]), - ); - } + if (currentLine.startsWith(":")) return success(COMMENT_ITEMS); blockBytes += currentLineBytes + terminatorBytes; if (blockBytes > resolved.maxEventBytes) { @@ -244,18 +259,18 @@ export function createIncrementalSseParser( if (field === "data") { dataLines.push(value); - return success(Object.freeze([])); + return success(NO_ITEMS); } if (field === "event") { eventType = value; - return success(Object.freeze([])); + return success(NO_ITEMS); } if (field === "id") { if (!value.includes("\0")) { lastEventId = value; hasExplicitId = true; } - return success(Object.freeze([])); + return success(NO_ITEMS); } if (field === "retry" && /^\d+$/u.test(value)) { const retryMs = Number(value); @@ -270,7 +285,7 @@ export function createIncrementalSseParser( ); } } - return success(Object.freeze([])); + return success(NO_ITEMS); } function clearBlock(): void { @@ -289,25 +304,12 @@ export function createIncrementalSseParser( state = "FAILED"; line = ""; lineBytes = 0; + undrained = ""; clearBlock(); return realtimeFailure(kind, "DECODE"); } - function appendItems( - target: SseParserItem[], - additions: readonly SseParserItem[], - ): boolean { - if ( - target.length + additions.length > - resolved.maxItemsPerChunk - ) { - return false; - } - target.push(...additions); - return true; - } - - return Object.freeze({ push, finish }); + return Object.freeze({ push, drain, finish }); } function resolveLimits( diff --git a/src/adapters/realtime/stream-coordinator.ts b/src/adapters/realtime/stream-coordinator.ts index c90268e7..ba7abe23 100644 --- a/src/adapters/realtime/stream-coordinator.ts +++ b/src/adapters/realtime/stream-coordinator.ts @@ -35,6 +35,9 @@ import { } from "./event-codec.ts"; import { captureRealtimeDataSnapshot, + hasExactSnapshotKeys, + raceRealtimeTask, + timerDeadline, realtimeFailure, realtimeSuccess, snapshotRealtimeResult, @@ -184,15 +187,8 @@ export function createRealtimeStreamCoordinator( }); const states = new Map(); let closed = false; - - /** RT-02. Releasing a timer is best effort and never a public failure. */ - const clearTimerSafely = (handle: unknown): void => { - try { - clearScheduledTimeout(handle); - } catch { - // A broken scheduler cannot change an already classified outcome. - } - }; + const deadline = (delayMs: number) => + timerDeadline(delayMs, scheduleTimeout, clearScheduledTimeout); const TASK_TIMED_OUT = Symbol("REALTIME_TASK_TIMED_OUT"); @@ -227,26 +223,18 @@ export function createRealtimeStreamCoordinator( if (!state.closed) state.freshness = "STALE"; } }); - // RT-02. A scheduler that cannot install the deadline leaves the wait - // unbounded. Letting the exception escape turned a typed realtime result - // into a native rejection and — through the caller's own catch — started a - // recovery that overlapped the effect still running, so an install failure - // fails closed as an expired deadline instead. - let handle: unknown; - let installed = false; - const timeout = new Promise((resolve) => { - try { - handle = scheduleTimeout(() => resolve(TASK_TIMED_OUT), timeoutMs); - installed = true; - } catch { - resolve(TASK_TIMED_OUT); - } - }); - const outcome = await Promise.race([task, timeout]); - if (installed) clearTimerSafely(handle); - if (outcome !== TASK_TIMED_OUT) return outcome; - - // The commit capability is revoked immediately; the work itself is not. + const outcome = await raceRealtimeTask( + () => task, + undefined, + deadline(timeoutMs), + ); + if (outcome.kind === "VALUE") return outcome.value; + // The collaborator's own rejection reaches the caller unchanged. + if (outcome.kind === "REJECTED") return await task; + // Expired, or (RT-02) a scheduler that could not install the deadline and + // left the wait unbounded: both fail closed as an expired deadline, not a + // native rejection that would start an overlapping recovery. The commit + // capability is revoked immediately; the work itself is not. revokeAndAbort(); state.lifecycle = "DRAINING"; state.timedOutTasks.add(task); @@ -487,20 +475,6 @@ export function createRealtimeStreamCoordinator( signal, ); } - if ( - state.eventIds.size + 1 > - state.registration.limits.maxDedupeEntries || - state.dedupeBytes + event.fingerprintBytes > - state.registration.limits.maxDedupeBytes - ) { - return recoverForAccept( - state, - "DEDUPE_OVERFLOW", - true, - signal, - ); - } - const eventType = dependencies.registry.findStreamEventType( state.registration.id, event.envelope.eventType, @@ -626,6 +600,17 @@ export function createRealtimeStreamCoordinator( fingerprintBytes: event.fingerprintBytes, appliedAt: safeNow(state), }); + // The dedupe window is the newest entries: drop the oldest to make room. + for (const [eventId, oldest] of state.eventIds) { + if ( + state.eventIds.size < state.registration.limits.maxDedupeEntries && + state.dedupeBytes + entry.fingerprintBytes <= + state.registration.limits.maxDedupeBytes + ) { + break; + } + forgetDedupe(state, eventId, oldest); + } state.eventIds.set(entry.eventId, entry); state.sequences.set(entry.sequence, entry); state.dedupeBytes += entry.fingerprintBytes; @@ -923,32 +908,13 @@ export function createRealtimeStreamCoordinator( const active = state.recoveryPromise; const reason = state.activeRecoveryReason ?? "INITIALIZE"; if (!active) return dropped("RECOVERY_IN_PROGRESS"); - if (signal?.aborted) { - return realtimeFailure("ABORTED", "RECEIVE"); - } - let removeAbortListener: () => void = () => undefined; - const aborted = new Promise>( - (resolve) => { - if (!signal) return; - const onAbort = () => resolve({ kind: "ABORTED" }); - signal.addEventListener("abort", onAbort, { once: true }); - removeAbortListener = () => - signal.removeEventListener("abort", onAbort); - if (signal.aborted) onAbort(); - }, - ); - const settled = await Promise.race([ - active.then((result) => ({ - kind: "RESULT" as const, - result, - })), - aborted, - ]); - removeAbortListener(); + const settled = await raceRealtimeTask(() => active, signal); if (settled.kind === "ABORTED") { return realtimeFailure("ABORTED", "RECEIVE"); } - const result = settled.result; + // Only VALUE or REJECTED remain; a rejection propagates as before. + const result = + settled.kind === "VALUE" ? settled.value : await active; if (!result.ok) return result; return realtimeSuccess( Object.freeze({ @@ -1043,26 +1009,14 @@ export function createRealtimeStreamCoordinator( for (const state of states.values()) state.lifecycle = "CLOSED"; return realtimeSuccess(undefined); } - let handle: unknown; - let installed = false; - const drained = await Promise.race([ - Promise.allSettled(retained).then(() => true), - new Promise((resolve) => { - try { - handle = scheduleTimeout( - () => resolve(false), - limits.drainTimeoutMs, - ); - installed = true; - } catch { - // RT-02. Without a drain bound this call cannot prove quiescence, so - // it reports the honest failure rather than rejecting natively. - resolve(false); - } - }), - ]); - if (installed) clearTimerSafely(handle); - if (!drained) { + // RT-02. Without a drain bound (CLOCK_FAILED) this call cannot prove + // quiescence, so it reports the honest failure rather than rejecting. + const drained = await raceRealtimeTask( + () => Promise.allSettled(retained), + undefined, + deadline(limits.drainTimeoutMs), + ); + if (drained.kind !== "VALUE") { // Still DRAINING: the caller must not treat this as quiescence. return realtimeFailure("IDLE_TIMEOUT", "CLOSE", false); } @@ -1113,6 +1067,7 @@ export function createRealtimeStreamCoordinator( return candidate; } + /** Entries are kept in apply order and `appliedAt` never decreases. */ function pruneDedupe(state: StreamState): void { const selectedNow = safeNow(state); for (const [eventId, entry] of state.eventIds) { @@ -1120,19 +1075,27 @@ export function createRealtimeStreamCoordinator( selectedNow - entry.appliedAt < state.registration.limits.dedupeTtlMs ) { - continue; + break; } - state.eventIds.delete(eventId); - if (state.sequences.get(entry.sequence) === entry) { - state.sequences.delete(entry.sequence); - } - state.dedupeBytes = Math.max( - 0, - state.dedupeBytes - entry.fingerprintBytes, - ); + forgetDedupe(state, eventId, entry); } } + function forgetDedupe( + state: StreamState, + eventId: string, + entry: DedupeEntry, + ): void { + state.eventIds.delete(eventId); + if (state.sequences.get(entry.sequence) === entry) { + state.sequences.delete(entry.sequence); + } + state.dedupeBytes = Math.max( + 0, + state.dedupeBytes - entry.fingerprintBytes, + ); + } + function fenceState(state: StreamState): void { state.processingGeneration += 1; state.activeEffectAbort?.abort(); @@ -1408,14 +1371,3 @@ function captureSnapshotCheckpoint( ? checkpoint : null; } - -function hasExactSnapshotKeys( - snapshot: RealtimeDataSnapshot, - expected: readonly string[], -): boolean { - const selected = [...expected].sort(); - return ( - snapshot.keys.length === selected.length && - snapshot.keys.every((key, index) => key === selected[index]) - ); -} diff --git a/src/adapters/realtime/websocket/websocket-connection.ts b/src/adapters/realtime/websocket/websocket-connection.ts index 92358ce2..6b270ac0 100644 --- a/src/adapters/realtime/websocket/websocket-connection.ts +++ b/src/adapters/realtime/websocket/websocket-connection.ts @@ -11,6 +11,7 @@ import type { import { isRealtimeResult, isRealtimeTransportEventOutcome, + raceRealtimeTask, realtimeFailure, realtimeSuccess, } from "../result.ts"; @@ -306,7 +307,6 @@ export function createWebSocketConnection( "PROTOCOL_MISMATCH", "CONNECT", false, - "NONE", ), "PROTOCOL_MISMATCH", { @@ -348,12 +348,7 @@ export function createWebSocketConnection( failureKind: code, }); terminate( - failure( - code, - "RECEIVE", - false, - code === "EVENT_TOO_LARGE" ? "SNAPSHOT" : "NONE", - ), + failure(code, "RECEIVE", false), "PROTOCOL_MISMATCH", { subscriptionId: null, @@ -390,7 +385,6 @@ export function createWebSocketConnection( "QUEUE_OVERFLOW", "RECEIVE", false, - "SNAPSHOT", ), "CURSOR_RESET", { @@ -435,7 +429,6 @@ export function createWebSocketConnection( ? "CONNECT" : "RECEIVE", true, - "RECONNECT", ), "NETWORK_LOST", undefined, @@ -450,7 +443,6 @@ export function createWebSocketConnection( "CLOSED", "CONNECT", false, - "NONE", ); } if (connectPromise) return connectPromise; @@ -459,7 +451,6 @@ export function createWebSocketConnection( "CLOSED", "CONNECT", false, - "NONE", ); } if (signal?.aborted) { @@ -467,7 +458,6 @@ export function createWebSocketConnection( "ABORTED", "CONNECT", false, - "NONE", ); terminate( aborted.error, @@ -497,7 +487,6 @@ export function createWebSocketConnection( "PROVIDER_UNAVAILABLE", "CONNECT", true, - "RECONNECT", ), "NETWORK_LOST", undefined, @@ -512,7 +501,6 @@ export function createWebSocketConnection( "ABORTED", "CONNECT", false, - "NONE", ), "NORMAL", undefined, @@ -543,7 +531,6 @@ export function createWebSocketConnection( status === "OPEN" ? "PROTOCOL_MISMATCH" : "CLOSED", "SUBSCRIBE", false, - "NONE", ); } const eventWindowStartedAt = readClockNow(dependencies.clock); @@ -552,7 +539,6 @@ export function createWebSocketConnection( "PROVIDER_UNAVAILABLE", "SUBSCRIBE", true, - "RECONNECT", ); terminate( unavailable.error, @@ -595,7 +581,6 @@ export function createWebSocketConnection( status === "OPEN" ? "PROTOCOL_MISMATCH" : "CLOSED", "SUBSCRIBE", false, - "NONE", ); } const sent = sendCritical( @@ -637,7 +622,7 @@ export function createWebSocketConnection( if (sent.ok) drainOutboundQueue(); } terminate( - failure("CLOSED", "CLOSE", false, "NONE"), + failure("CLOSED", "CLOSE", false), category, undefined, ); @@ -664,7 +649,6 @@ export function createWebSocketConnection( "CONNECT_TIMEOUT", "CONNECT", true, - "RECONNECT", ), "NETWORK_LOST", undefined, @@ -680,7 +664,6 @@ export function createWebSocketConnection( "PROVIDER_UNAVAILABLE", "CONNECT", true, - "RECONNECT", ), "NETWORK_LOST", undefined, @@ -761,7 +744,6 @@ export function createWebSocketConnection( resetFailureCode(frame.reason), "RECEIVE", false, - "SNAPSHOT", ), "CURSOR_RESET", undefined, @@ -868,7 +850,6 @@ export function createWebSocketConnection( "SEQUENCE_GAP", "RECEIVE", false, - "SNAPSHOT", ), "CURSOR_RESET", undefined, @@ -882,91 +863,63 @@ export function createWebSocketConnection( terminateProtocol(); return; } - if (dependencies.onSubscribed) { - const barrierController = new AbortController(); - const abortBarrier = () => barrierController.abort(); - generation.signal.addEventListener("abort", abortBarrier, { - once: true, - }); - if (generation.signal.aborted) abortBarrier(); - try { - const outcome = await Promise.race([ - Promise.resolve() - .then(() => - dependencies.onSubscribed!( - Object.freeze({ - subscriptionId: frame.subscriptionId, - streamId: subscription.request.streamId, - streamEpoch: frame.streamEpoch, - acceptedCursor: frame.acceptedCursor, - nextExpectedSequence: frame.nextExpectedSequence, - }), - barrierController.signal, - ), - ) - .then((value) => + const onSubscribed = dependencies.onSubscribed; + if (onSubscribed) { + const outcome = await raceRealtimeTask( + (signal) => + Promise.resolve().then(() => + onSubscribed( Object.freeze({ - kind: "HANDLED" as const, - value, + subscriptionId: frame.subscriptionId, + streamId: subscription.request.streamId, + streamEpoch: frame.streamEpoch, + acceptedCursor: frame.acceptedCursor, + nextExpectedSequence: frame.nextExpectedSequence, }), + signal, ), - dependencies.clock - .sleep( - ceilings.maxApplyMs, - barrierController.signal, - ) - .then(() => - Object.freeze({ kind: "TIMED_OUT" as const }), - ), - ]); - if ( - outcome.kind === "TIMED_OUT" && - status !== "CLOSED" - ) { - requestRecovery({ - subscriptionId: frame.subscriptionId, - reason: "APPLY_FAILED", - }); - terminate( - failure( - "APPLY_FAILED", + ), + generation.signal, + (signal) => dependencies.clock.sleep(ceilings.maxApplyMs, signal), + ); + if (outcome.kind === "TIMEOUT" && status !== "CLOSED") { + requestRecovery({ + subscriptionId: frame.subscriptionId, + reason: "APPLY_FAILED", + }); + terminate( + failure( + "APPLY_FAILED", + "RECOVER", + false, + ), + "CURSOR_RESET", + undefined, + ); + return; + } + if (outcome.kind === "VALUE" && status !== "CLOSED") { + if (!isRealtimeResult(outcome.value, isUndefined)) { + terminateInboundFailure( + realtimeFailure( + "PROTOCOL_MISMATCH", "RECOVER", false, - "SNAPSHOT", - ), - "CURSOR_RESET", - undefined, + ).error, + frame.subscriptionId, ); return; } - if ( - outcome.kind === "HANDLED" && - status !== "CLOSED" - ) { - if (!isRealtimeResult(outcome.value, isUndefined)) { - terminateInboundFailure( - realtimeFailure( - "PROTOCOL_MISMATCH", - "RECOVER", - false, - ).error, - frame.subscriptionId, - ); - return; - } - if (!outcome.value.ok) { - terminateInboundFailure( - outcome.value.error, - frame.subscriptionId, - ); - return; - } + if (!outcome.value.ok) { + terminateInboundFailure( + outcome.value.error, + frame.subscriptionId, + ); + return; } - } catch { - if ( - status !== "CLOSED" && - !generation.signal.aborted - ) { + } + if (outcome.kind !== "TIMEOUT" && outcome.kind !== "VALUE") { + if (status !== "CLOSED" && !generation.signal.aborted) { terminateInboundFailure( realtimeFailure( "PROVIDER_UNAVAILABLE", @@ -977,12 +930,6 @@ export function createWebSocketConnection( ); } return; - } finally { - generation.signal.removeEventListener( - "abort", - abortBarrier, - ); - barrierController.abort(); } } if ( @@ -1023,7 +970,6 @@ export function createWebSocketConnection( "PROVIDER_UNAVAILABLE", "RECEIVE", true, - "RECONNECT", ), "NETWORK_LOST", undefined, @@ -1049,7 +995,6 @@ export function createWebSocketConnection( "QUEUE_OVERFLOW", "RECEIVE", false, - "SNAPSHOT", ), "CURSOR_RESET", undefined, @@ -1057,28 +1002,24 @@ export function createWebSocketConnection( return; } - const applyController = new AbortController(); - const abortApply = () => applyController.abort(); - generation.signal.addEventListener("abort", abortApply, { - once: true, - }); - try { - const outcome = await Promise.race([ - dependencies - .onEvent(frame, applyController.signal) - .then((value) => - Object.freeze({ - kind: "HANDLED" as const, - value, - }), - ), - dependencies.clock - .sleep(ceilings.maxApplyMs, applyController.signal) - .then(() => - Object.freeze({ kind: "TIMED_OUT" as const }), - ), - ]); - if (outcome.kind === "TIMED_OUT" && status !== "CLOSED") { + const outcome = await raceRealtimeTask( + (signal) => dependencies.onEvent(frame, signal), + generation.signal, + (signal) => dependencies.clock.sleep(ceilings.maxApplyMs, signal), + ); + const handled = + outcome.kind === "VALUE" && + isRealtimeResult(outcome.value, isRealtimeTransportEventOutcome) + ? outcome.value + : null; + if (!handled) { + // Timed out, returned no valid result, or failed while still current. + if ( + status !== "CLOSED" && + (outcome.kind === "TIMEOUT" || + outcome.kind === "VALUE" || + !generation.signal.aborted) + ) { requestRecovery({ subscriptionId: frame.subscriptionId, reason: "APPLY_FAILED", @@ -1088,74 +1029,27 @@ export function createWebSocketConnection( "APPLY_FAILED", "RECEIVE", false, - "SNAPSHOT", ), "CURSOR_RESET", undefined, ); - } else if (outcome.kind === "HANDLED" && status !== "CLOSED") { - if ( - !isRealtimeResult( - outcome.value, - isRealtimeTransportEventOutcome, - ) - ) { - requestRecovery({ - subscriptionId: frame.subscriptionId, - reason: "APPLY_FAILED", - }); - terminate( - failure( - "APPLY_FAILED", - "RECEIVE", - false, - "SNAPSHOT", - ), - "CURSOR_RESET", - undefined, - ); - } else if (!outcome.value.ok) { - terminateInboundFailure( - outcome.value.error, - frame.subscriptionId, - ); - } else if ( - outcome.value.value.kind === "RECOVERY_COMMITTED" - ) { - terminate( - failure( - "CURSOR_EXPIRED", - "RECEIVE", - false, - "SNAPSHOT", - ), - "CURSOR_RESET", - undefined, - true, - outcome.value.value, - ); - } } - } catch { - if (status !== "CLOSED" && !generation.signal.aborted) { - requestRecovery({ - subscriptionId: frame.subscriptionId, - reason: "APPLY_FAILED", - }); + } else if (status !== "CLOSED") { + if (!handled.ok) { + terminateInboundFailure(handled.error, frame.subscriptionId); + } else if (handled.value.kind === "RECOVERY_COMMITTED") { terminate( failure( - "APPLY_FAILED", + "CURSOR_EXPIRED", "RECEIVE", false, - "SNAPSHOT", ), "CURSOR_RESET", undefined, + true, + handled.value, ); } - } finally { - generation.signal.removeEventListener("abort", abortApply); - applyController.abort(); } } @@ -1256,7 +1150,6 @@ export function createWebSocketConnection( "PROVIDER_UNAVAILABLE", "RECEIVE", true, - "RECONNECT", ), "NETWORK_LOST", undefined, @@ -1269,7 +1162,6 @@ export function createWebSocketConnection( "IDLE_TIMEOUT", "RECEIVE", true, - "RECONNECT", ), "NETWORK_LOST", undefined, @@ -1286,7 +1178,6 @@ export function createWebSocketConnection( "PROTOCOL_MISMATCH", "RECEIVE", false, - "NONE", ), "PROTOCOL_MISMATCH", undefined, @@ -1303,7 +1194,7 @@ export function createWebSocketConnection( socket.readyState !== NATIVE_OPEN || !effectiveLimits ) { - return connectionFailure("CLOSED", operation, false, "NONE"); + return connectionFailure("CLOSED", operation, false); } const encoded = encodeWebSocketClientFrame( frame, @@ -1316,7 +1207,6 @@ export function createWebSocketConnection( : "PROTOCOL_MISMATCH", operation, false, - "NONE", ); } if ( @@ -1333,7 +1223,6 @@ export function createWebSocketConnection( "PROVIDER_UNAVAILABLE", operation, true, - "RECONNECT", ); terminate(result.error, "NETWORK_LOST", undefined); return result; @@ -1384,7 +1273,6 @@ export function createWebSocketConnection( "PROVIDER_UNAVAILABLE", queued.operation, true, - "RECONNECT", ), "NETWORK_LOST", undefined, @@ -1408,7 +1296,6 @@ export function createWebSocketConnection( "PROVIDER_UNAVAILABLE", queued.operation, true, - "RECONNECT", ), "NETWORK_LOST", undefined, @@ -1428,7 +1315,6 @@ export function createWebSocketConnection( "QUEUE_OVERFLOW", operation, false, - "NONE", ); terminate(result.error, "OVERLOADED", { subscriptionId: null, @@ -1543,7 +1429,6 @@ export function createWebSocketConnection( "IDLE_TIMEOUT", "SUBSCRIBE", true, - "RECONNECT", ), "NETWORK_LOST", undefined, @@ -1562,7 +1447,6 @@ export function createWebSocketConnection( "PROVIDER_UNAVAILABLE", "SUBSCRIBE", true, - "RECONNECT", ), "NETWORK_LOST", undefined, @@ -1919,49 +1803,43 @@ function closeFailure( ): RealtimeFailure { switch (category) { case "NORMAL": - return failure("CLOSED", "CLOSE", false, "NONE"); + return failure("CLOSED", "CLOSE", false); case "RESTART": case "NETWORK_LOST": return failure( "PROVIDER_UNAVAILABLE", "RECEIVE", true, - "RECONNECT", ); case "OVERLOADED": return failure( "PROVIDER_UNAVAILABLE", "RECEIVE", false, - "NONE", ); case "AUTH_REQUIRED": return failure( "AUTH_REQUIRED", "RECEIVE", false, - "SESSION_REVALIDATE", ); case "FORBIDDEN": return failure( "FORBIDDEN", "RECEIVE", false, - "NONE", ); case "PROTOCOL_MISMATCH": return failure( "PROTOCOL_MISMATCH", "RECEIVE", false, - "NONE", ); case "CURSOR_RESET": return failure( "CURSOR_EXPIRED", "RECEIVE", false, - "SNAPSHOT", ); } } @@ -1988,7 +1866,6 @@ function failure( kind: RealtimeFailureKind, operation: RealtimeOperation, retryable: boolean, - _recovery: "NONE" | "RECONNECT" | "SNAPSHOT" | "SESSION_REVALIDATE", ): RealtimeFailure { return realtimeFailure(kind, operation, retryable).error; } @@ -1997,7 +1874,6 @@ function connectionFailure( kind: RealtimeFailureKind, operation: RealtimeOperation, retryable: boolean, - _recovery: "NONE" | "RECONNECT" | "SNAPSHOT" | "SESSION_REVALIDATE", ): Extract, { ok: false }> { return realtimeFailure(kind, operation, retryable); } diff --git a/src/adapters/realtime/websocket/websocket-protocol.ts b/src/adapters/realtime/websocket/websocket-protocol.ts index cc8dc62e..c30b641d 100644 --- a/src/adapters/realtime/websocket/websocket-protocol.ts +++ b/src/adapters/realtime/websocket/websocket-protocol.ts @@ -1,6 +1,6 @@ import { hasDuplicateJsonMembers, -} from "../json-member-scanner.ts"; +} from "../../platform/json-member-scanner.ts"; export const REALTIME_WEBSOCKET_PROTOCOL = "realtime.v1" as const; @@ -469,6 +469,12 @@ function isUnsignedSequence(input: unknown): input is string { } } +const encoder = new TextEncoder(); + +function utf8ByteLength(input: string): number { + return encoder.encode(input).byteLength; +} + /** * R-05. Admission before allocation. * @@ -479,10 +485,6 @@ function isUnsignedSequence(input: unknown): input is string { * bytes and a lone surrogate as the three-byte replacement sequence, exactly * like `TextEncoder`. */ -function utf8ByteLength(input: string): number { - return new TextEncoder().encode(input).byteLength; -} - function exceedsUtf8ByteLimit(input: string, maxBytes: number): boolean { if (input.length > maxBytes) return true; let bytes = 0; diff --git a/src/adapters/service-worker/service-worker-entry.ts b/src/adapters/service-worker/service-worker-entry.ts index 57af0ebe..de2614d6 100644 --- a/src/adapters/service-worker/service-worker-entry.ts +++ b/src/adapters/service-worker/service-worker-entry.ts @@ -94,24 +94,18 @@ self.addEventListener("activate", (event) => { if (handlers.includes("PWA_STATIC_ASSETS")) { self.addEventListener("fetch", (event) => { const request = event.request; - // R-6.6. Decided synchronously: only a GET for a verified static asset of - // this release is answered. Navigations, API calls and cross-origin - // requests are left to the browser untouched. - if ( - request.method !== "GET" || - request.mode === "navigate" || - !runtime.manifestUrls.has(request.url) - ) { - return; - } + const described = { + method: request.method, + url: request.url, + mode: request.mode, + }; + // R-6.6 / Q-6.6-6b. Decided synchronously: only a same-origin GET for a + // verified asset of this release or a content-hashed old-build chunk is + // answered. Navigations, API calls, cross-origin and unhashed requests are + // left to the browser untouched. Every cache miss goes to the network. + if (!runtime.intercepts(described)) return; event.respondWith( - runtime - .onFetch({ - method: request.method, - url: request.url, - mode: request.mode, - }) - .then((cached) => cached ?? fetch(request)), + runtime.onFetch(described).then((cached) => cached ?? fetch(request)), ); }); } diff --git a/src/adapters/service-worker/service-worker-lifecycle.ts b/src/adapters/service-worker/service-worker-lifecycle.ts index 5617131b..7b633be9 100644 --- a/src/adapters/service-worker/service-worker-lifecycle.ts +++ b/src/adapters/service-worker/service-worker-lifecycle.ts @@ -157,6 +157,14 @@ export function createServiceWorkerRuntime( const highestOld = await highestMarkedCache(names, current); const currentMarker = await readActivationMarker(currentCache, current); const previous = highestOld?.cacheName ?? oldCaches.at(-1) ?? null; + // Q-6.6-9. Stale caches go first: when storage is full the marker write + // below is what fails, and deleting is the only way space comes back. + const stale = selectCachesToDelete(names, current, previous); + let deleted = 0; + for (const name of stale) { + if (await scope.caches.delete(name).catch(() => false)) deleted += 1; + } + void SERVICE_WORKER_BOUNDS.retainedPreviousCaches; if ( !currentMarker || currentMarker.activationSequence < (highestOld?.activationSequence ?? 0) @@ -165,27 +173,26 @@ export function createServiceWorkerRuntime( if (!Number.isSafeInteger(nextSequence)) { throw new Error("SERVICE_WORKER_ACTIVATION_SEQUENCE_EXHAUSTED"); } - await currentCache.put( - ACTIVATION_MARKER_URL, - new Response( - JSON.stringify({ - schemaVersion: 1, - cacheName: current, - activationSequence: nextSequence, - }), - { - status: 200, - headers: { "content-type": "application/json" }, - }, - ), - ); + try { + await currentCache.put( + ACTIVATION_MARKER_URL, + new Response( + JSON.stringify({ + schemaVersion: 1, + cacheName: current, + activationSequence: nextSequence, + }), + { + status: 200, + headers: { "content-type": "application/json" }, + }, + ), + ); + } catch { + // Q-6.6-9. Activation stands without a marker; the next release just + // cannot find this cache as its previous one for the hashed fallback. + } } - const stale = selectCachesToDelete(names, current, previous); - let deleted = 0; - for (const name of stale) { - if (await scope.caches.delete(name)) deleted += 1; - } - void SERVICE_WORKER_BOUNDS.retainedPreviousCaches; return deleted; } @@ -238,30 +245,54 @@ export function createServiceWorkerRuntime( } } - /** - * §18.5–§18.7. A verified cache hit is returned; anything else goes to the - * network and is never written back into the active cache at runtime. - */ - async function onFetch( - request: Readonly<{ method: string; url: string; mode?: string }>, - ): Promise { - const classification = classifyFetch({ + type FetchRequest = Readonly<{ method: string; url: string; mode?: string }>; + + function classify(request: FetchRequest) { + if (!staticEnabled) return "NETWORK_PASSTHROUGH"; + return classifyFetch({ method: request.method, requestUrl: request.url, isNavigation: request.mode === "navigate", runtimeConfigUrl: config.runtimeConfigUrl, releaseManifestUrl: config.releaseManifestUrl, manifestUrls, + scopeUrl: scope.registrationScope, }); - if (classification !== "VERIFIED_CACHE_FIRST") return null; + } - // SW-01. Only the current release cache may answer. A CacheStorage-wide - // match could return a previous release's response for the same URL, and - // the subsequent delete would then target a cache that was never read. + /** + * R-6.6 / Q-6.6-6b. Synchronous, so the fetch listener decides before it + * calls `respondWith`. Only a manifest asset of this release or a + * same-origin content-hashed URL (an old build's chunk) is answered; + * navigations, API calls, cross-origin and unhashed URLs are left alone. + */ + function intercepts(request: FetchRequest): boolean { + const classification = classify(request); + return ( + classification === "VERIFIED_CACHE_FIRST" || + classification === "PREVIOUS_RELEASE_FALLBACK" + ); + } + + /** + * §18.5–§18.7. A verified cache hit is returned; anything else goes to the + * network and is never written back into the active cache at runtime. + */ + async function onFetch(request: FetchRequest): Promise { + const classification = classify(request); + // SW-01. Only the current release cache may answer a manifest URL. A + // CacheStorage-wide match could return a previous release's response for + // the same URL, and the subsequent delete would then target a cache that + // was never read. const currentCacheName = config.manifest ? staticCacheName(config.manifest.setDigest) : null; if (!currentCacheName) return null; + if (classification === "PREVIOUS_RELEASE_FALLBACK") { + // Q-6.6-6b. Not listed by this release, so not in the current cache. + return matchPreviousRelease(request.url, currentCacheName); + } + if (classification !== "VERIFIED_CACHE_FIRST") return null; // SW-RR-04. Both `open` and `match` are storage calls that can throw // synchronously or reject. Either one escaping here rejects `respondWith` // itself, so the entry never reaches its network fallback and the page @@ -475,6 +506,7 @@ export function createServiceWorkerRuntime( onInstall, onActivate, onFetch, + intercepts, onActivateRequest, onClientMessage, onCacheResetRequest, diff --git a/src/adapters/service-worker/service-worker-page-controller.ts b/src/adapters/service-worker/service-worker-page-controller.ts index b511a0f7..5f33b034 100644 --- a/src/adapters/service-worker/service-worker-page-controller.ts +++ b/src/adapters/service-worker/service-worker-page-controller.ts @@ -38,6 +38,8 @@ export type PageControllerDependencies = Readonly<{ buildId: string; container?: ServiceWorkerContainer; caches?: CacheStorage; + /** Q-6.6-12. The host page; without it the global `document`, if any. */ + document?: Pick; /** §17.10. Any blocker returning true rejects automatic activation. */ blockers?: readonly ActivationBlocker[]; now?: () => number; @@ -349,10 +351,11 @@ export function createServiceWorkerPageController( function scheduleUpdateChecks(): void { // §17.14. At most one check per 6 hours, and none while the page is hidden. if (updateTimer) return; + const page = + dependencies.document ?? + (typeof document === "undefined" ? undefined : document); updateTimer = setInterval(() => { - if (typeof document !== "undefined" && document.visibilityState === "hidden") { - return; - } + if (page?.visibilityState === "hidden") return; void registration?.update().catch(() => { // A failed update check never fails a product flow. }); @@ -381,7 +384,12 @@ export function createServiceWorkerPageController( } const nonce = nonces.issue(); - const deadline = now() + SERVICE_WORKER_BOUNDS.clientDrainMs; + // Q-6.6-10b. With equal deadlines a tab draining at 29s left this page at + // TIMEOUT while the worker still committed skipWaiting(). + const deadline = + now() + + SERVICE_WORKER_BOUNDS.clientDrainMs + + SERVICE_WORKER_BOUNDS.activationReplySlackMs; const accepted = await new Promise( (resolve) => { const container = dependencies.container; diff --git a/src/adapters/service-worker/service-worker-static-assets.ts b/src/adapters/service-worker/service-worker-static-assets.ts index a2fe773c..2a594a5a 100644 --- a/src/adapters/service-worker/service-worker-static-assets.ts +++ b/src/adapters/service-worker/service-worker-static-assets.ts @@ -1,4 +1,5 @@ import { + HASHED_STATIC_ASSET_NAME, isOwnedStaticCacheName, SERVICE_WORKER_BOUNDS, staticCacheName, @@ -17,7 +18,13 @@ import { export type FetchClassification = | "NETWORK_PASSTHROUGH" | "NETWORK_ONLY" - | "VERIFIED_CACHE_FIRST"; + | "VERIFIED_CACHE_FIRST" + /** + * Q-6.6-6b. A same-origin content-hashed URL this release does not list, + * typically a lazy chunk of the build a tab still runs. Only the previous + * release cache may answer it; otherwise it goes to the network. + */ + | "PREVIOUS_RELEASE_FALLBACK"; export type ClassificationInput = Readonly<{ method: string; @@ -26,6 +33,8 @@ export type ClassificationInput = Readonly<{ runtimeConfigUrl: string; releaseManifestUrl: string; manifestUrls: ReadonlySet; + /** The registration scope; a hashed URL outside its origin is never cached. */ + scopeUrl: string; }>; /** @@ -42,9 +51,24 @@ export function classifyFetch(input: ClassificationInput): FetchClassification { return "NETWORK_ONLY"; } if (input.manifestUrls.has(input.requestUrl)) return "VERIFIED_CACHE_FIRST"; + if (isSameOriginHashedAsset(input.requestUrl, input.scopeUrl)) { + return "PREVIOUS_RELEASE_FALLBACK"; + } return "NETWORK_PASSTHROUGH"; } +function isSameOriginHashedAsset(requestUrl: string, scopeUrl: string): boolean { + try { + const request = new URL(requestUrl); + return ( + request.origin === new URL(scopeUrl).origin && + HASHED_STATIC_ASSET_NAME.test(request.pathname) + ); + } catch { + return false; + } +} + function sameResource(left: string, right: string): boolean { try { const a = new URL(left); @@ -77,6 +101,8 @@ export type InstallDependencies = Readonly<{ caches: Readonly<{ open(cacheName: string): Promise; delete(cacheName: string): Promise; + /** Q-6.6-8. Without it every failed candidate is treated as new. */ + keys?(): Promise; }>; fetcher: typeof fetch; digest(bytes: Uint8Array): Promise; @@ -114,7 +140,8 @@ export function validateStaticAssetManifest( /** * §17.9. A partial candidate is never used: any failure deletes the candidate - * cache and rejects install, leaving the previous verified revision in place. + * cache this install created and rejects install, leaving the previous + * verified revision in place. */ export async function installStaticAssets( manifest: StaticAssetManifestV1, @@ -124,6 +151,12 @@ export async function installStaticAssets( if (invalid) return invalid; const cacheName = staticCacheName(manifest.setDigest); + // Q-6.6-8. The name is the asset-set digest, so a worker whose assets did + // not change installs into the cache the active (or retained previous) + // worker serves from. Rewriting it only puts identical verified bytes, but + // deleting it on failure would take the serving cache and its marker away. + // Only a cache this install created is rolled back. + const rollBack = !(await cacheExists(dependencies.caches, cacheName)); const abortController = new AbortController(); let deadlineExceeded = false; let deadlineTimer: ReturnType | undefined; @@ -147,7 +180,7 @@ export async function installStaticAssets( ? rejected("INSTALL_DEADLINE_EXCEEDED") : raced; - if (outcome.kind === "REJECTED") { + if (outcome.kind === "REJECTED" && rollBack) { await dependencies.caches.delete(cacheName).catch(() => false); // SW-09. A non-cooperative fetch, digest or `cache.put` started before the // deadline cannot be cancelled, so it may recreate the candidate cache @@ -166,6 +199,17 @@ export async function installStaticAssets( return outcome; } +async function cacheExists( + caches: InstallDependencies["caches"], + cacheName: string, +): Promise { + try { + return (await caches.keys?.())?.includes(cacheName) ?? false; + } catch { + return false; + } +} + async function installCandidate( manifest: StaticAssetManifestV1, cacheName: string, diff --git a/src/adapters/storage/indexeddb/indexeddb-governance.ts b/src/adapters/storage/indexeddb/indexeddb-governance.ts index d1659e08..1fc0c6c5 100644 --- a/src/adapters/storage/indexeddb/indexeddb-governance.ts +++ b/src/adapters/storage/indexeddb/indexeddb-governance.ts @@ -3,9 +3,12 @@ import { assertValidStoragePolicy, type BrowserStoragePolicy, } from "../../../application/ports/browser-file-storage/shared.ts"; +import { + INDEXEDDB_DATASET_BUDGET_KEY, + isStoredDatasetBudget, +} from "./indexeddb-records.ts"; export const INDEXEDDB_DATASET_BINDING_KEY = "dataset-binding"; -export const INDEXEDDB_DATASET_BUDGET_KEY = "dataset-budget"; const OPAQUE_SCOPE_TOKEN = /^[A-Za-z0-9_-]{16,48}$/u; @@ -280,27 +283,8 @@ export function verifyIndexedDbDatasetBinding( } else if (!sameIndexedDbDatasetBinding(observed, expected)) { finish({ ok: false, reason: "MISMATCH" }); } else if ( - !observedBudget || - typeof observedBudget !== "object" || - (observedBudget as { bindingKey?: unknown }).bindingKey !== - INDEXEDDB_DATASET_BUDGET_KEY || - (observedBudget as { budgetVersion?: unknown }).budgetVersion !== - 1 || - !Number.isSafeInteger( - (observedBudget as { usedBytes?: unknown }).usedBytes, - ) || - typeof (observedBudget as { usedBytes?: unknown }).usedBytes !== - "number" || - (observedBudget as { usedBytes: number }).usedBytes < 0 || - (observedBudget as { usedBytes: number }).usedBytes > - expected.storagePolicy.hardBudgetBytes - || - !Number.isSafeInteger( - (observedBudget as { receiptCount?: unknown }).receiptCount, - ) || - typeof (observedBudget as { receiptCount?: unknown }) - .receiptCount !== "number" || - (observedBudget as { receiptCount: number }).receiptCount < 0 + !isStoredDatasetBudget(observedBudget) || + observedBudget.usedBytes > expected.storagePolicy.hardBudgetBytes ) { finish({ ok: false, reason: "CORRUPT" }); } else { diff --git a/src/adapters/storage/indexeddb/indexeddb-maintenance.ts b/src/adapters/storage/indexeddb/indexeddb-maintenance.ts index deada7a9..3bedea47 100644 --- a/src/adapters/storage/indexeddb/indexeddb-maintenance.ts +++ b/src/adapters/storage/indexeddb/indexeddb-maintenance.ts @@ -27,23 +27,29 @@ import { import { mapIndexedDbException } from "./indexeddb-failure.ts"; import { createIndexedDbDatasetBinding, - INDEXEDDB_DATASET_BUDGET_KEY, indexedDbPhysicalDatabaseName, verifyIndexedDbDatasetBinding, } from "./indexeddb-governance.ts"; +import { + countBucket, + failureOf, + INDEXEDDB_DATASET_BUDGET_KEY, + isPositiveInteger, + isStoredDatasetBudget, + isStoredReceipt, + isStoredRecord, + isStoredRetentionRecord, + isValidBoundaryIdentifier, + measureRecordBytes, + type StoredDatasetBudget, + type StoredRecord, + type StoredRetentionRecord, +} from "./indexeddb-records.ts"; import type { - IndexedDbCountBucket, IndexedDbMaintenanceDependencies, IndexedDbObservation, } from "./indexeddb-types.ts"; -type StoredRecord = Readonly<{ - key: string; - codecVersion: number; - revision: number; - payload: unknown; -}>; - type StoredCheckpoint = Readonly<{ checkpointKey: string; migrationId: string; @@ -52,32 +58,6 @@ type StoredCheckpoint = Readonly<{ state: "MORE" | "COMPLETE"; }>; -type StoredIdempotencyReceipt = Readonly<{ - idempotencyKey: string; - operation: "PUT" | "DELETE"; - recordKey: string; - expectedRevision: number | null; - fingerprint: string; - synchronization: "NONE" | "PENDING" | "CONFIRMED"; - revision: number; - expiresAtEpochMs: number; -}>; - -type StoredRetentionRecord = Readonly<{ - recordKey: string; - writtenAtEpochMs: number; - synchronization: "NONE" | "PENDING" | "CONFIRMED"; - measuredBytes: number; - eligibleAtEpochMs?: number; -}>; - -type StoredDatasetBudget = Readonly<{ - bindingKey: typeof INDEXEDDB_DATASET_BUDGET_KEY; - budgetVersion: 1; - usedBytes: number; - receiptCount: number; -}>; - type CheckpointState = Readonly<{ persisted: StoredCheckpoint | null; effective: Readonly<{ @@ -86,57 +66,22 @@ type CheckpointState = Readonly<{ }>; }>; -type ScannedRecord = Readonly<{ - key: string; - codecVersion: number; - revision: number; - payload: unknown; -}>; - type ScanBatch = Readonly<{ - rows: readonly ScannedRecord[]; + rows: readonly StoredRecord[]; reachedEnd: boolean; budgetExhausted: boolean; }>; type PreparedRecord = Readonly<{ - source: ScannedRecord; + source: StoredRecord; needsMigration: boolean; migratedPayload: WireValue | undefined; measuredBytes: number | undefined; }>; const SAFE_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; -const OPAQUE_SHA256_FINGERPRINT = /^[a-f0-9]{64}$/u; const MAX_BATCH_ROWS = 500; const MAX_BATCH_DURATION_MS = 30_000; -const RECORD_ENVELOPE_RESERVATION_BYTES = 512; -const MAX_MEASURED_RECORD_BYTES = 2_147_483_647; - -function isPositiveInteger(value: unknown): value is number { - return ( - typeof value === "number" && - Number.isSafeInteger(value) && - value >= 1 - ); -} - -function isStoredRecord( - value: unknown, - expectedKey?: string, -): value is StoredRecord { - if (!value || typeof value !== "object") return false; - const record = value as Partial; - return ( - typeof record.key === "string" && - record.key.length > 0 && - record.key.length <= 200 && - (expectedKey === undefined || record.key === expectedKey) && - isPositiveInteger(record.codecVersion) && - isPositiveInteger(record.revision) && - Object.hasOwn(record, "payload") - ); -} function isStoredCheckpoint( value: unknown, @@ -150,84 +95,12 @@ function isStoredCheckpoint( SAFE_IDENTIFIER.test(checkpoint.migrationId) && isPositiveInteger(checkpoint.targetCodecVersion) && (checkpoint.lastKey === null || - (typeof checkpoint.lastKey === "string" && - checkpoint.lastKey.length > 0 && - checkpoint.lastKey.length <= 200)) && + isValidBoundaryIdentifier(checkpoint.lastKey)) && (checkpoint.state === "MORE" || checkpoint.state === "COMPLETE") ); } -function isStoredReceipt( - value: unknown, -): value is StoredIdempotencyReceipt { - if (!value || typeof value !== "object") return false; - const receipt = value as Partial; - return ( - typeof receipt.idempotencyKey === "string" && - receipt.idempotencyKey.length > 0 && - receipt.idempotencyKey.length <= 200 && - (receipt.operation === "PUT" || - receipt.operation === "DELETE") && - typeof receipt.recordKey === "string" && - receipt.recordKey.length > 0 && - receipt.recordKey.length <= 200 && - (receipt.expectedRevision === null || - isPositiveInteger(receipt.expectedRevision)) && - typeof receipt.fingerprint === "string" && - OPAQUE_SHA256_FINGERPRINT.test(receipt.fingerprint) && - (receipt.synchronization === "NONE" || - receipt.synchronization === "PENDING" || - receipt.synchronization === "CONFIRMED") && - isPositiveInteger(receipt.revision) && - typeof receipt.expiresAtEpochMs === "number" && - Number.isSafeInteger(receipt.expiresAtEpochMs) && - receipt.expiresAtEpochMs >= 0 - ); -} - -function isStoredRetentionRecord( - value: unknown, - expectedKey: string, -): value is StoredRetentionRecord { - if (!value || typeof value !== "object") return false; - const record = value as Partial; - return ( - record.recordKey === expectedKey && - typeof record.writtenAtEpochMs === "number" && - Number.isSafeInteger(record.writtenAtEpochMs) && - record.writtenAtEpochMs >= 0 && - (record.synchronization === "NONE" || - record.synchronization === "PENDING" || - record.synchronization === "CONFIRMED") && - typeof record.measuredBytes === "number" && - Number.isSafeInteger(record.measuredBytes) && - record.measuredBytes >= 1 && - record.measuredBytes <= MAX_MEASURED_RECORD_BYTES && - (record.eligibleAtEpochMs === undefined || - (typeof record.eligibleAtEpochMs === "number" && - Number.isSafeInteger(record.eligibleAtEpochMs) && - record.eligibleAtEpochMs >= record.writtenAtEpochMs)) - ); -} - -function isStoredDatasetBudget( - value: unknown, -): value is StoredDatasetBudget { - if (!value || typeof value !== "object") return false; - const budget = value as Partial; - return ( - budget.bindingKey === INDEXEDDB_DATASET_BUDGET_KEY && - budget.budgetVersion === 1 && - typeof budget.usedBytes === "number" && - Number.isSafeInteger(budget.usedBytes) && - budget.usedBytes >= 0 && - typeof budget.receiptCount === "number" && - Number.isSafeInteger(budget.receiptCount) && - budget.receiptCount >= 0 - ); -} - function sameCheckpoint( left: StoredCheckpoint | null, right: StoredCheckpoint | null, @@ -242,14 +115,6 @@ function sameCheckpoint( ); } -function countBucket(count: number): IndexedDbCountBucket { - if (count <= 0) return "0"; - if (count === 1) return "1"; - if (count <= 10) return "2-10"; - if (count <= 100) return "11-100"; - return "101+"; -} - function invalidInput(): BrowserDataResult { return browserDataFailure("INVALID_INPUT", "INDEXEDDB_MIGRATE"); } @@ -273,19 +138,6 @@ function unsupported(): BrowserDataResult { }); } -/** - * `browserDataFailure` and `mapIndexedDbException` build a `Result`, while the - * kernel's `translate` and `context.fail` want the failure on its own. Both - * only ever build the failure arm, so the branch below is a narrowing rather - * than a claim. - */ -function failureOf(result: BrowserDataResult): BrowserDataFailure { - if (result.ok) { - throw new TypeError("A browser data failure was expected."); - } - return result.error; -} - function invalidInputFailure(): BrowserDataFailure { return failureOf(invalidInput()); } @@ -705,7 +557,7 @@ export function createIndexedDbMaintenance( return; } - const rows: ScannedRecord[] = []; + const rows: StoredRecord[] = []; // The scan bounds on rows it read, so the counter the kernel offers is // the right one here. The time check comes first so a batch that ran // out of both answers `budgetExhausted` the way it does today. @@ -830,28 +682,10 @@ export function createIndexedDbMaintenance( } catch { return migrationFailed(); } - let measuredPayloadBytes: number; - try { - measuredPayloadBytes = - dependencies.migrationPolicy.measureStoredBytes( - migratedPayload, - ); - } catch { - return migrationFailed(); - } - const measuredBytes = - measuredPayloadBytes + - RECORD_ENVELOPE_RESERVATION_BYTES + - source.key.length * 2; - if ( - !Number.isSafeInteger(measuredPayloadBytes) || - measuredPayloadBytes < 0 || - !Number.isSafeInteger(measuredBytes) || - measuredBytes < 1 || - measuredBytes > MAX_MEASURED_RECORD_BYTES - ) { - return migrationFailed(); - } + const measuredBytes = measureRecordBytes(source.key, () => + dependencies.migrationPolicy.measureStoredBytes(migratedPayload), + ); + if (measuredBytes === null) return migrationFailed(); const afterMigration = clock(); if (!afterMigration.ok) return afterMigration; if (afterMigration.value >= deadline) { diff --git a/src/adapters/storage/indexeddb/indexeddb-records.ts b/src/adapters/storage/indexeddb/indexeddb-records.ts new file mode 100644 index 00000000..188be397 --- /dev/null +++ b/src/adapters/storage/indexeddb/indexeddb-records.ts @@ -0,0 +1,188 @@ +import type { IndexedDbSynchronizationState } from "../../../application/ports/browser-file-storage/indexeddb-port.ts"; +import type { + BrowserDataFailure, + BrowserDataResult, +} from "../../../application/ports/browser-file-storage/shared.ts"; +import type { IndexedDbCountBucket } from "./indexeddb-types.ts"; + +/** + * Q-6.5-7. The one definition of the rows the runtime and maintenance store: + * their shapes, their validators and how a record is charged against the + * dataset budget. Each call site used to carry its own copy, so a field added + * to one copy made the other judge a healthy row corrupt. + */ + +export const INDEXEDDB_DATASET_BUDGET_KEY = "dataset-budget"; + +export const OPAQUE_SHA256_FINGERPRINT = /^[a-f0-9]{64}$/u; +const RECORD_ENVELOPE_RESERVATION_BYTES = 512; +const MAX_MEASURED_RECORD_BYTES = 2_147_483_647; + +type StoredSynchronization = IndexedDbSynchronizationState | "NONE"; + +export type StoredRecord = Readonly<{ + key: string; + codecVersion: number; + revision: number; + payload: unknown; +}>; + +export type StoredIdempotencyReceipt = Readonly<{ + idempotencyKey: string; + operation: "PUT" | "DELETE"; + recordKey: string; + expectedRevision: number | null; + fingerprint: string; + synchronization: StoredSynchronization; + revision: number; + expiresAtEpochMs: number; +}>; + +export type StoredRetentionRecord = Readonly<{ + recordKey: string; + writtenAtEpochMs: number; + synchronization: StoredSynchronization; + measuredBytes: number; + eligibleAtEpochMs?: number; +}>; + +export type StoredDatasetBudget = Readonly<{ + bindingKey: typeof INDEXEDDB_DATASET_BUDGET_KEY; + budgetVersion: 1; + usedBytes: number; + receiptCount: number; +}>; + +export function isPositiveInteger(value: unknown): value is number { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 1; +} + +export function isValidBoundaryIdentifier(value: unknown): value is string { + return typeof value === "string" && value.length > 0 && value.length <= 200; +} + +function isNonNegativeInteger(value: unknown): value is number { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} + +function isStoredSynchronization(value: unknown): boolean { + return value === "NONE" || value === "PENDING" || value === "CONFIRMED"; +} + +export function isStoredRecord( + value: unknown, + expectedKey?: string, +): value is StoredRecord { + if (!value || typeof value !== "object") return false; + const record = value as Partial; + return ( + isValidBoundaryIdentifier(record.key) && + (expectedKey === undefined || record.key === expectedKey) && + isPositiveInteger(record.codecVersion) && + isPositiveInteger(record.revision) && + Object.hasOwn(record, "payload") + ); +} + +export function isStoredReceipt( + value: unknown, +): value is StoredIdempotencyReceipt { + if (!value || typeof value !== "object") return false; + const receipt = value as Partial; + return ( + isValidBoundaryIdentifier(receipt.idempotencyKey) && + (receipt.operation === "PUT" || receipt.operation === "DELETE") && + isValidBoundaryIdentifier(receipt.recordKey) && + (receipt.expectedRevision === null || + isPositiveInteger(receipt.expectedRevision)) && + typeof receipt.fingerprint === "string" && + OPAQUE_SHA256_FINGERPRINT.test(receipt.fingerprint) && + isStoredSynchronization(receipt.synchronization) && + isPositiveInteger(receipt.revision) && + isNonNegativeInteger(receipt.expiresAtEpochMs) + ); +} + +export function isStoredRetentionRecord( + value: unknown, + expectedKey?: string, +): value is StoredRetentionRecord { + if (!value || typeof value !== "object") return false; + const record = value as Partial; + return ( + isValidBoundaryIdentifier(record.recordKey) && + (expectedKey === undefined || record.recordKey === expectedKey) && + isNonNegativeInteger(record.writtenAtEpochMs) && + isStoredSynchronization(record.synchronization) && + isPositiveInteger(record.measuredBytes) && + record.measuredBytes <= MAX_MEASURED_RECORD_BYTES && + (record.eligibleAtEpochMs === undefined || + (Number.isSafeInteger(record.eligibleAtEpochMs) && + record.eligibleAtEpochMs >= record.writtenAtEpochMs)) + ); +} + +/** + * A budget row's own shape. The dataset binding check additionally bounds + * `usedBytes` by the policy's `hardBudgetBytes`; transactions check the bytes + * they are about to add instead. + */ +export function isStoredDatasetBudget( + value: unknown, +): value is StoredDatasetBudget { + if (!value || typeof value !== "object") return false; + const budget = value as Partial; + return ( + budget.bindingKey === INDEXEDDB_DATASET_BUDGET_KEY && + budget.budgetVersion === 1 && + isNonNegativeInteger(budget.usedBytes) && + isNonNegativeInteger(budget.receiptCount) + ); +} + +/** + * The bytes a record is charged: the codec's payload size, a fixed envelope + * reservation and the key as UTF-16. `null` when the codec throws or the size + * is out of range; each caller maps that to its own failure code. + */ +export function measureRecordBytes( + key: string, + measurePayload: () => number, +): number | null { + let payloadBytes: number; + try { + payloadBytes = measurePayload(); + } catch { + return null; + } + const measuredBytes = + payloadBytes + RECORD_ENVELOPE_RESERVATION_BYTES + key.length * 2; + return isNonNegativeInteger(payloadBytes) && + isPositiveInteger(measuredBytes) && + measuredBytes <= MAX_MEASURED_RECORD_BYTES + ? measuredBytes + : null; +} + +export function countBucket(count: number): IndexedDbCountBucket { + if (count <= 0) return "0"; + if (count === 1) return "1"; + if (count <= 10) return "2-10"; + if (count <= 100) return "11-100"; + return "101+"; +} + +/** + * `browserDataFailure` and `mapIndexedDbException` build a `Result`, while the + * kernel's `translate` and `context.fail` want the failure on its own. Both + * only ever build the failure arm, so the branch below is a narrowing rather + * than a claim. + */ +export function failureOf( + result: BrowserDataResult, +): BrowserDataFailure { + if (result.ok) { + throw new TypeError("A browser data failure was expected."); + } + return result.error; +} diff --git a/src/adapters/storage/indexeddb/indexeddb-runtime.ts b/src/adapters/storage/indexeddb/indexeddb-runtime.ts index 60f6ca9c..ad4e4926 100644 --- a/src/adapters/storage/indexeddb/indexeddb-runtime.ts +++ b/src/adapters/storage/indexeddb/indexeddb-runtime.ts @@ -38,7 +38,6 @@ import { import { mapIndexedDbException } from "./indexeddb-failure.ts"; import { createIndexedDbDatasetBinding, - INDEXEDDB_DATASET_BUDGET_KEY, indexedDbPhysicalDatabaseName, queueIndexedDbUpgradeBinding, verifyIndexedDbDatasetBinding, @@ -48,47 +47,30 @@ import { assertIndexedDbRuntimeStores, validateIndexedDbMigrations, } from "./indexeddb-migrations.ts"; +import { + countBucket, + failureOf, + INDEXEDDB_DATASET_BUDGET_KEY, + isPositiveInteger, + isStoredDatasetBudget, + isStoredReceipt, + isStoredRecord, + isStoredRetentionRecord, + isValidBoundaryIdentifier, + measureRecordBytes, + OPAQUE_SHA256_FINGERPRINT, + type StoredDatasetBudget, + type StoredIdempotencyReceipt, + type StoredRecord, + type StoredRetentionRecord, +} from "./indexeddb-records.ts"; import type { - IndexedDbCountBucket, IndexedDbKeyRangePlan, IndexedDbObservation, IndexedDbQueryPlan, IndexedDbRuntimeDependencies, } from "./indexeddb-types.ts"; -type StoredRecord = Readonly<{ - key: string; - codecVersion: number; - revision: number; - payload: unknown; -}>; - -type StoredIdempotencyReceipt = Readonly<{ - idempotencyKey: string; - operation: "PUT" | "DELETE"; - recordKey: string; - expectedRevision: number | null; - fingerprint: string; - synchronization: IndexedDbSynchronizationState | "NONE"; - revision: number; - expiresAtEpochMs: number; -}>; - -type StoredRetentionRecord = Readonly<{ - recordKey: string; - writtenAtEpochMs: number; - synchronization: IndexedDbSynchronizationState | "NONE"; - measuredBytes: number; - eligibleAtEpochMs?: number; -}>; - -type StoredDatasetBudget = Readonly<{ - bindingKey: typeof INDEXEDDB_DATASET_BUDGET_KEY; - budgetVersion: 1; - usedBytes: number; - receiptCount: number; -}>; - type ReceiptLookup = | Readonly<{ kind: "MISSING" | "EXPIRED" }> | Readonly<{ @@ -102,7 +84,6 @@ type TransactionContext = IndexedDbTransactionContext< >; const SAFE_DATABASE_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u; -const OPAQUE_SHA256_FINGERPRINT = /^[a-f0-9]{64}$/u; const DELETE_OPERATION_FINGERPRINT = "65daeb378bdec35d90224389f6e10917bcc0b94c90c489014ba156dd6cbf9350"; const MAX_QUERY_LIMIT = 1_000; @@ -113,31 +94,9 @@ const MAX_RECEIPT_RETENTION_MS = 31 * 24 * 60 * 60 * 1_000; const MAX_LIFECYCLE_ROWS = 500; const MAX_LIFECYCLE_DURATION_MS = 30_000; const OPAQUE_AUTHORITY_PROOF = /^[A-Za-z0-9_-]{16,128}$/u; -const RECORD_ENVELOPE_RESERVATION_BYTES = 512; -const MAX_MEASURED_RECORD_BYTES = 2_147_483_647; const MAX_QUERY_SCANNED_ROWS = 5_000; const MAX_IDEMPOTENCY_RECEIPTS = 1_000_000; -function countBucket(count: number): IndexedDbCountBucket { - if (count <= 0) return "0"; - if (count === 1) return "1"; - if (count <= 10) return "2-10"; - if (count <= 100) return "11-100"; - return "101+"; -} - -function isValidBoundaryIdentifier(value: string): boolean { - return ( - typeof value === "string" && - value.length > 0 && - value.length <= 200 - ); -} - -function isRevision(value: unknown): value is number { - return Number.isSafeInteger(value) && typeof value === "number" && value >= 1; -} - function isBoundedCursorKey(value: unknown): value is IDBValidKey { const pending: Array> = [ { value, depth: 0 }, @@ -222,86 +181,6 @@ function isBoundedRangePlan( } } -function isStoredRecord(value: unknown, expectedKey?: string): value is StoredRecord { - if (!value || typeof value !== "object") return false; - const record = value as Partial; - return ( - typeof record.key === "string" && - isValidBoundaryIdentifier(record.key) && - (expectedKey === undefined || record.key === expectedKey) && - isRevision(record.codecVersion) && - isRevision(record.revision) && - Object.hasOwn(record, "payload") - ); -} - -function isStoredReceipt(value: unknown): value is StoredIdempotencyReceipt { - if (!value || typeof value !== "object") return false; - const receipt = value as Partial; - return ( - typeof receipt.idempotencyKey === "string" && - isValidBoundaryIdentifier(receipt.idempotencyKey) && - (receipt.operation === "PUT" || receipt.operation === "DELETE") && - typeof receipt.recordKey === "string" && - isValidBoundaryIdentifier(receipt.recordKey) && - (receipt.expectedRevision === null || - isRevision(receipt.expectedRevision)) && - typeof receipt.fingerprint === "string" && - OPAQUE_SHA256_FINGERPRINT.test(receipt.fingerprint) && - (receipt.synchronization === "NONE" || - receipt.synchronization === "PENDING" || - receipt.synchronization === "CONFIRMED") && - isRevision(receipt.revision) && - typeof receipt.expiresAtEpochMs === "number" && - Number.isSafeInteger(receipt.expiresAtEpochMs) && - receipt.expiresAtEpochMs >= 0 - ); -} - -function isStoredRetentionRecord( - value: unknown, - expectedKey?: string, -): value is StoredRetentionRecord { - if (!value || typeof value !== "object") return false; - const record = value as Partial; - return ( - typeof record.recordKey === "string" && - isValidBoundaryIdentifier(record.recordKey) && - (expectedKey === undefined || record.recordKey === expectedKey) && - typeof record.writtenAtEpochMs === "number" && - Number.isSafeInteger(record.writtenAtEpochMs) && - record.writtenAtEpochMs >= 0 && - (record.synchronization === "NONE" || - record.synchronization === "PENDING" || - record.synchronization === "CONFIRMED") && - typeof record.measuredBytes === "number" && - Number.isSafeInteger(record.measuredBytes) && - record.measuredBytes >= 1 && - record.measuredBytes <= MAX_MEASURED_RECORD_BYTES && - (record.eligibleAtEpochMs === undefined || - (typeof record.eligibleAtEpochMs === "number" && - Number.isSafeInteger(record.eligibleAtEpochMs) && - record.eligibleAtEpochMs >= record.writtenAtEpochMs)) - ); -} - -function isStoredDatasetBudget( - value: unknown, -): value is StoredDatasetBudget { - if (!value || typeof value !== "object") return false; - const budget = value as Partial; - return ( - budget.bindingKey === INDEXEDDB_DATASET_BUDGET_KEY && - budget.budgetVersion === 1 && - typeof budget.usedBytes === "number" && - Number.isSafeInteger(budget.usedBytes) && - budget.usedBytes >= 0 && - typeof budget.receiptCount === "number" && - Number.isSafeInteger(budget.receiptCount) && - budget.receiptCount >= 0 - ); -} - function normalizeCursorKey(value: IDBValidKey): IndexedDbCursorKey { if (Array.isArray(value)) { return Object.freeze(value.map((entry) => normalizeCursorKey(entry))); @@ -405,18 +284,6 @@ function unavailable( }); } -/** - * The kernel's `translate` and `context.fail` take the failure on its own while - * every helper above builds a whole `Result`. All of them only ever build the - * failure arm, so the branch below is a narrowing rather than a claim. - */ -function failureOf(result: BrowserDataResult): BrowserDataFailure { - if (result.ok) { - throw new TypeError("A browser data failure was expected."); - } - return result.error; -} - function mappedFailure( error: unknown, operation: BrowserDataOperation, @@ -1475,7 +1342,7 @@ export function createIndexedDbRuntime( !isValidBoundaryIdentifier(input.key) || !isValidBoundaryIdentifier(input.idempotencyKey) || (input.expectedRevision !== null && - !isRevision(input.expectedRevision)) || + !isPositiveInteger(input.expectedRevision)) || (storagePolicySnapshot.retention.kind === "UNTIL_SYNCED" ? input.synchronization !== "PENDING" && input.synchronization !== "CONFIRMED" @@ -1499,26 +1366,10 @@ export function createIndexedDbRuntime( } catch (error) { return mapIndexedDbException(error, operation); } - let measuredPayloadBytes: number; - try { - measuredPayloadBytes = - dependencies.codec.measureStoredBytes(wireValue); - } catch { - return invalidInput(operation); - } - const measuredBytes = - measuredPayloadBytes + - RECORD_ENVELOPE_RESERVATION_BYTES + - input.key.length * 2; - if ( - !Number.isSafeInteger(measuredPayloadBytes) || - measuredPayloadBytes < 0 || - !Number.isSafeInteger(measuredBytes) || - measuredBytes < 1 || - measuredBytes > MAX_MEASURED_RECORD_BYTES - ) { - return invalidInput(operation); - } + const measuredBytes = measureRecordBytes(input.key, () => + dependencies.codec.measureStoredBytes(wireValue), + ); + if (measuredBytes === null) return invalidInput(operation); const cancelled = abortedResult(input.signal, operation); if (cancelled) return cancelled; @@ -1887,7 +1738,7 @@ export function createIndexedDbRuntime( if ( !isValidBoundaryIdentifier(sourceInput.key) || !isValidBoundaryIdentifier(sourceInput.idempotencyKey) || - !isRevision(sourceInput.expectedRevision) + !isPositiveInteger(sourceInput.expectedRevision) ) { return observeResult(operation, invalidInput(operation)); } diff --git a/src/adapters/storage/opfs/opfs-byte-store-adapter.ts b/src/adapters/storage/opfs/opfs-byte-store-adapter.ts index cb755ffa..df10546e 100644 --- a/src/adapters/storage/opfs/opfs-byte-store-adapter.ts +++ b/src/adapters/storage/opfs/opfs-byte-store-adapter.ts @@ -246,19 +246,12 @@ export function createOpfsByteStoreAdapter( onProgress: request.onProgress, }); if (!prepared.ok) { - const compensated = await compensatePreparedPut( - begun.value, - physicalGenerationId, - ); - if (!compensated.ok) { - return observeFailure( - compensated, - dependencies.observer, - request.source.byteLength!, - ); - } return observeFailure( - prepared, + await compensatePreparedPut( + begun.value, + physicalGenerationId, + prepared.error, + ), dependencies.observer, request.source.byteLength!, ); @@ -270,19 +263,12 @@ export function createOpfsByteStoreAdapter( prepared.value, ); if (!filesReady.ok) { - const compensated = await compensatePreparedPut( - begun.value, - physicalGenerationId, - ); - if (!compensated.ok) { - return observeFailure( - compensated, - dependencies.observer, - request.source.byteLength!, - ); - } return observeFailure( - rebaseFailure(filesReady.error, "OBJECT_WRITE"), + await compensatePreparedPut( + begun.value, + physicalGenerationId, + filesReady.error, + ), dependencies.observer, request.source.byteLength!, ); @@ -928,29 +914,36 @@ export function createOpfsByteStoreAdapter( * `ALREADY_CLEAN`. A timeout, crash, malformed response or `EFFECT_UNKNOWN` * keeps `PREPARING`/`FILES_READY` in place and asks for reconciliation. */ + /** + * Compensates a put that failed before commit and returns that failure. + * Q-6.5-9. When the cleanup or the journal rollback does not complete, the + * journal row stays for reconciliation: the put keeps its own code and only + * its recovery becomes RECONCILE. + */ async function compensatePreparedPut( transaction: OpfsJournalTransaction, physicalGenerationId: OpfsPhysicalGenerationId, - ): Promise> { + failure: BrowserDataFailure, + ): Promise { const cleanup = await dependencies.worker.abortPreparedPut({ scope: transaction.scope, transactionId: transaction.transactionId, physicalGenerationId, ...(compensationSignal ? { signal: compensationSignal } : {}), }); - if (!cleanup.ok || cleanup.value.kind === "EFFECT_UNKNOWN") { - return browserDataFailure("CONFLICT", "OBJECT_RECONCILE", { - recovery: "RETRY", - }); - } - const rolledBack = await dependencies.journal.rollback( - transaction.transactionId, - transaction.fencingToken, + const compensated = + cleanup.ok && + cleanup.value.kind !== "EFFECT_UNKNOWN" && + ( + await dependencies.journal.rollback( + transaction.transactionId, + transaction.fencingToken, + ) + ).ok; + return rebaseFailure( + compensated ? failure : { ...failure, recovery: "RECONCILE" }, + "OBJECT_WRITE", ); - if (!rolledBack.ok) { - return rebaseFailure(rolledBack.error, "OBJECT_RECONCILE"); - } - return browserDataSuccess(undefined); } async function reconcileTransaction( diff --git a/src/adapters/storage/opfs/opfs-worker-client.ts b/src/adapters/storage/opfs/opfs-worker-client.ts index ba90fac0..9707ce79 100644 --- a/src/adapters/storage/opfs/opfs-worker-client.ts +++ b/src/adapters/storage/opfs/opfs-worker-client.ts @@ -342,7 +342,7 @@ export function createOpfsWorkerGateway( ) { const verified = await invoke( "OBJECT_READ", - { kind: "VERIFY_OBJECT", preparedObject }, + { kind: "VERIFY_OBJECT", preparedObject, manifestOnly: true }, signal, [], (value) => (typeof value === "boolean" ? value : null), diff --git a/src/adapters/storage/opfs/opfs-worker-protocol.ts b/src/adapters/storage/opfs/opfs-worker-protocol.ts index 67e68f38..69a7892a 100644 --- a/src/adapters/storage/opfs/opfs-worker-protocol.ts +++ b/src/adapters/storage/opfs/opfs-worker-protocol.ts @@ -77,6 +77,12 @@ export type OpfsWorkerRequest = protocolVersion: typeof OPFS_WORKER_PROTOCOL_VERSION; kind: "VERIFY_OBJECT"; preparedObject: OpfsPreparedObject; + /** + * Q-6.5-6. Compare the stored manifest only. `openObject` sends it: the + * stream then verifies each chunk as it reads it and the root digest + * before it releases the last chunk, so an object is not read twice. + */ + manifestOnly?: true; }> | Readonly<{ requestId: string; diff --git a/src/adapters/storage/opfs/opfs-worker-runtime.ts b/src/adapters/storage/opfs/opfs-worker-runtime.ts index 2ee07d46..68bf2691 100644 --- a/src/adapters/storage/opfs/opfs-worker-runtime.ts +++ b/src/adapters/storage/opfs/opfs-worker-runtime.ts @@ -248,7 +248,10 @@ export function createOpfsWorkerRuntime( return success( request.requestId, request.kind, - await verifyObject(request.preparedObject), + await verifyObject( + request.preparedObject, + request.manifestOnly === true, + ), ); case "READ_CHUNK": return success( @@ -693,6 +696,7 @@ export function createOpfsWorkerRuntime( async function verifyObject( expected: OpfsPreparedObject, + manifestOnly: boolean, ): Promise { if (!isPreparedObject(expected)) return false; let stored: unknown; @@ -708,15 +712,10 @@ export function createOpfsWorkerRuntime( ) { return false; } - const rootDigestHex = await treeDigestHex( - dependencies.crypto, - expected.descriptor.integrity.chunkSizeBytes, - expected.descriptor.byteLength, - expected.chunks, - ); - if (rootDigestHex !== expected.descriptor.integrity.rootDigestHex) { - return false; - } + // Q-6.5-6. READ_CHUNK checks the root digest at the last chunk; an empty + // object has no chunk to read, so its stream ends here. + if (manifestOnly && expected.chunks.length > 0) return true; + if (!(await rootDigestMatches(expected))) return false; for (const chunk of expected.chunks) { let bytes: Uint8Array; try { @@ -737,6 +736,19 @@ export function createOpfsWorkerRuntime( return true; } + async function rootDigestMatches( + expected: OpfsPreparedObject, + ): Promise { + return ( + (await treeDigestHex( + dependencies.crypto, + expected.descriptor.integrity.chunkSizeBytes, + expected.descriptor.byteLength, + expected.chunks, + )) === expected.descriptor.integrity.rootDigestHex + ); + } + async function readVerifiedChunk( expected: OpfsPreparedObject, sequence: number, @@ -757,7 +769,12 @@ export function createOpfsWorkerRuntime( ); if ( bytes.byteLength !== reference.byteLength || - (await sha256Hex(dependencies.crypto, bytes)) !== reference.digestHex + (await sha256Hex(dependencies.crypto, bytes)) !== reference.digestHex || + // Q-6.5-6. The last chunk is not released until the chunk list is + // proven against the root digest, so a stream never ends as a success + // on an unverified object. + (sequence === expected.chunks.length - 1 && + !(await rootDigestMatches(expected))) ) { throw new OpfsRuntimeFailure("INTEGRITY_FAILED"); } diff --git a/src/adapters/telemetry/best-effort-telemetry.ts b/src/adapters/telemetry/best-effort-telemetry.ts index 63027b44..0e6d66de 100644 --- a/src/adapters/telemetry/best-effort-telemetry.ts +++ b/src/adapters/telemetry/best-effort-telemetry.ts @@ -6,6 +6,10 @@ import type { } from "../../contracts/telemetry.ts"; import type { TelemetryPort } from "../../application/ports/telemetry-port.ts"; import { assertBoundedCapacity } from "../platform/bounded-capacity.ts"; +import { + createTelemetryCollector, + type TelemetryCollector, +} from "./telemetry-collector.ts"; export type TelemetryAdapter = TelemetryPort & Readonly<{ @@ -36,10 +40,14 @@ export type TelemetryAdapterOptions = Readonly<{ monotonicNow?: () => number; setTimer?: (callback: () => void, ms: number) => unknown; clearTimer?: (handle: unknown) => void; + /** + * Q-6.9-4. The collector transport shared with feature telemetry. When set, + * it owns `fetcher`, `lifecycle`, `maxSendsPerMinute` and `monotonicNow`. + */ + collector?: TelemetryCollector; }>; -export const DEFAULT_TELEMETRY_SENDS_PER_MINUTE = 20; -const SEND_WINDOW_MS = 60_000; +export { DEFAULT_TELEMETRY_SENDS_PER_MINUTE } from "./telemetry-collector.ts"; export const noOpTelemetry: TelemetryAdapter = Object.freeze({ emit: () => {}, @@ -67,27 +75,28 @@ export function createTelemetryAdapter( return noOpTelemetry; } - const endpoint = options.endpoint; - const fetcher = options.fetcher ?? fetch; const maxQueue = assertBoundedCapacity( options.maxQueue ?? 100, MAX_TELEMETRY_QUEUE, "telemetry maxQueue", ); const schedule = options.schedule ?? queueMicrotask; - const maxSendsPerMinute = assertBoundedCapacity( - options.maxSendsPerMinute ?? DEFAULT_TELEMETRY_SENDS_PER_MINUTE, - MAX_TELEMETRY_QUEUE, - "telemetry maxSendsPerMinute", - ); - const monotonicNow = options.monotonicNow ?? (() => performance.now()); + const collector = + options.collector ?? + createTelemetryCollector({ + endpoint: options.endpoint, + ...(options.fetcher === undefined ? {} : { fetcher: options.fetcher }), + ...(options.maxSendsPerMinute === undefined + ? {} + : { maxSendsPerMinute: options.maxSendsPerMinute }), + ...(options.monotonicNow === undefined ? {} : { now: options.monotonicNow }), + ...(options.lifecycle === undefined ? {} : { lifecycle: options.lifecycle }), + }); const setTimer = options.setTimer ?? ((callback: () => void, ms: number) => setTimeout(callback, ms)); const clearTimer = options.clearTimer ?? ((handle: unknown) => clearTimeout(handle as ReturnType)); - /** Send instants inside the current window; never longer than the limit. */ - const sendTimes: number[] = []; let rateTimer: unknown = null; const queue: TelemetryEvent[] = []; let lifecycleState: TelemetryLifecycle = "ACTIVE"; @@ -99,12 +108,6 @@ export function createTelemetryAdapter( let dropped = 0; const dropReasons = new Map(); let lastDeliveryEvidence: TelemetryEvent | null = null; - const lifecycle = - options.lifecycle ?? - (typeof globalThis.addEventListener === "function" && - typeof globalThis.removeEventListener === "function" - ? globalThis - : undefined); function recordDrop(reason: string, count = 1): void { const safeReason = @@ -173,16 +176,8 @@ export function createTelemetryAdapter( scheduleFlush(); } - function rateAllows(at: number): boolean { - while (sendTimes.length > 0 && at - (sendTimes[0] as number) >= SEND_WINDOW_MS) { - sendTimes.shift(); - } - return sendTimes.length < maxSendsPerMinute; - } - - function armRateTimer(at: number): void { + function armRateTimer(reopenIn: number): void { if (rateTimer !== null || lifecycleState === "DISPOSED") return; - const reopenIn = Math.max(1, (sendTimes[0] ?? at) + SEND_WINDOW_MS - at); rateTimer = setTimer(() => { rateTimer = null; void flush(); @@ -198,31 +193,18 @@ export function createTelemetryAdapter( if (lifecycleState === "DISPOSED" || queue.length === 0) { return Promise.resolve(); } - const at = monotonicNow(); - if (!rateAllows(at)) { - if (!bypassRate) { - armRateTimer(at); - return Promise.resolve(); - } + const reopenIn = collector.sendRate.take(bypassRate); + if (reopenIn > 0) { + armRateTimer(reopenIn); + return Promise.resolve(); } - sendTimes.push(at); - if (sendTimes.length > maxSendsPerMinute) sendTimes.shift(); const generation = scheduleGeneration; const run = async () => { const batch = queue.splice(0, queue.length); const controller = new AbortController(); activeSink = controller; try { - const response = await fetcher(endpoint, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ events: batch }), - keepalive: true, - signal: controller.signal, - }); - // A sink that ignored the abort must not update post-dispose state. - if (generation !== scheduleGeneration) return; - if (!response.ok) recordDrop("sink-failure", batch.length); + await collector.post(batch, controller.signal); } catch { if (generation !== scheduleGeneration) return; recordDrop("sink-failure", batch.length); @@ -239,10 +221,9 @@ export function createTelemetryAdapter( } // Page exit is the last chance to deliver: it may exceed the window once. - const flushBeforePageExit = () => { + const stopPageExitFlush = collector.onPageExit(() => { void flush(true); - }; - lifecycle?.addEventListener("pagehide", flushBeforePageExit); + }); /** * N-04. Terminal disposal: one state transition, no further admission, no @@ -253,7 +234,7 @@ export function createTelemetryAdapter( lifecycleState = "DISPOSED"; scheduleGeneration += 1; scheduled = false; - lifecycle?.removeEventListener("pagehide", flushBeforePageExit); + stopPageExitFlush(); if (rateTimer !== null) clearTimer(rateTimer); rateTimer = null; queue.length = 0; diff --git a/src/adapters/telemetry/feature-telemetry.ts b/src/adapters/telemetry/feature-telemetry.ts index 2b242e9f..f4a7a603 100644 --- a/src/adapters/telemetry/feature-telemetry.ts +++ b/src/adapters/telemetry/feature-telemetry.ts @@ -6,6 +6,10 @@ import { type TelemetryPipelineBudget, type TelemetryTransport, } from "../../platform/telemetry/telemetry-pipeline.ts"; +import { + createTelemetryCollector, + type TelemetryCollector, +} from "./telemetry-collector.ts"; /** * Spec §24–§27. Adapter side of the provider-neutral feature telemetry port. @@ -15,26 +19,31 @@ import { * transport here, never in feature code. */ export function createFetchTelemetryTransport( - options: Readonly<{ endpoint: string; fetcher?: typeof fetch }>, + options: Readonly<{ + endpoint: string; + fetcher?: typeof fetch; + /** Q-6.9-4. Posts through this shared collector instead of a private one. */ + collector?: TelemetryCollector; + /** Aborts in-flight batches (feature telemetry disposal). */ + signal?: AbortSignal; + }>, ): TelemetryTransport { - const fetcher = options.fetcher ?? fetch; + const collector = + options.collector ?? + createTelemetryCollector({ + endpoint: options.endpoint, + ...(options.fetcher === undefined ? {} : { fetcher: options.fetcher }), + }); return Object.freeze({ - async send(batch: readonly TelemetryBatchItem[]): Promise { - const response = await fetcher(options.endpoint, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - events: batch.map((item) => ({ - ...item.event, - fingerprint: item.fingerprint, - occurrences: item.occurrences, - })), - }), - keepalive: true, - credentials: "omit", - cache: "no-store", - }); - if (!response.ok) throw new Error("telemetry collector rejected batch"); + send(batch: readonly TelemetryBatchItem[]): Promise { + return collector.post( + batch.map((item) => ({ + ...item.event, + fingerprint: item.fingerprint, + occurrences: item.occurrences, + })), + options.signal, + ); }, }); } @@ -65,14 +74,42 @@ export function createFeatureTelemetry( endpoint?: string; fetcher?: typeof fetch; budget?: TelemetryPipelineBudget; + /** + * Q-6.9-4. The collector shared with the application telemetry port: one + * send-rate window and one page-exit flush for the endpoint. When set, it + * owns `fetcher` and the send rate. + */ + collector?: TelemetryCollector; }>, ): TelemetryPipeline { if (!options.enabled || !options.endpoint) return DISABLED_FEATURE_TELEMETRY; - return createTelemetryPipeline({ - transport: createFetchTelemetryTransport({ + const budget = options.budget ?? DEFAULT_TELEMETRY_PIPELINE_BUDGET; + const collector = + options.collector ?? + createTelemetryCollector({ endpoint: options.endpoint, ...(options.fetcher === undefined ? {} : { fetcher: options.fetcher }), + maxSendsPerMinute: budget.maxSendsPerMinute, + }); + const lifetime = new AbortController(); + const pipeline = createTelemetryPipeline({ + transport: createFetchTelemetryTransport({ + endpoint: options.endpoint, + collector, + signal: lifetime.signal, }), - budget: options.budget ?? DEFAULT_TELEMETRY_PIPELINE_BUDGET, + budget, + sendRate: collector.sendRate, + }); + const stopPageExitFlush = collector.onPageExit(() => { + void pipeline.flush(); + }); + return Object.freeze({ + ...pipeline, + dispose(): void { + stopPageExitFlush(); + lifetime.abort(); + pipeline.dispose(); + }, }); } diff --git a/src/adapters/telemetry/index.ts b/src/adapters/telemetry/index.ts index 5c1f6d57..1d762dd5 100644 --- a/src/adapters/telemetry/index.ts +++ b/src/adapters/telemetry/index.ts @@ -10,3 +10,9 @@ export { createFeatureTelemetry, createFetchTelemetryTransport, } from "./feature-telemetry.ts"; +/** Q-6.9-4. 두 텔레메트리 포트가 공유하는 수집기 전송(rate·타임아웃·pagehide). */ +export { + createTelemetryCollector, + type TelemetryCollector, + type TelemetryCollectorOptions, +} from "./telemetry-collector.ts"; diff --git a/src/adapters/telemetry/telemetry-collector.ts b/src/adapters/telemetry/telemetry-collector.ts new file mode 100644 index 00000000..db74f0c7 --- /dev/null +++ b/src/adapters/telemetry/telemetry-collector.ts @@ -0,0 +1,123 @@ +import { + createTelemetrySendRate, + type TelemetrySendRate, +} from "../../platform/telemetry/telemetry-pipeline.ts"; +import { createAbortableOperation } from "../platform/abortable-operation.ts"; +import { assertBoundedCapacity } from "../platform/bounded-capacity.ts"; + +/** + * Q-6.9-4. The one transport layer behind both telemetry ports. + * + * The application port (`best-effort-telemetry.ts`) and the feature port + * (`feature-telemetry.ts`) keep their own queue and body projection, but every + * POST to the collector goes through here: one send-rate window for the + * endpoint, no cookies, no HTTP cache, a deadline on every request, and one + * `pagehide` listener that flushes every queue. + */ +export type TelemetryCollector = Readonly<{ + /** Spec §27. Shared by every queue posting to this collector. */ + sendRate: TelemetrySendRate; + /** + * POSTs `{ events }`. Rejects when the collector refuses the batch, the + * deadline passes, or `signal` aborts — a hung collector never stalls the + * caller's next flush. + */ + post(events: readonly unknown[], signal?: AbortSignal): Promise; + /** Runs `flush` on `pagehide`. Returns the unsubscribe. */ + onPageExit(flush: () => void): () => void; +}>; + +export type TelemetryCollectorOptions = Readonly<{ + endpoint: string; + fetcher?: typeof fetch; + /** Sends per rolling minute across every queue (default 20). */ + maxSendsPerMinute?: number; + /** Per-request deadline (default 10s). */ + timeoutMs?: number; + /** Monotonic clock for the send-rate window (default `performance.now`). */ + now?: () => number; + lifecycle?: Pick; +}>; + +export const DEFAULT_TELEMETRY_SENDS_PER_MINUTE = 20; +export const DEFAULT_TELEMETRY_TIMEOUT_MS = 10_000; +/** Also bounds the send-time window the rate keeps in memory. */ +const MAX_SENDS_PER_MINUTE = 10_000; +const MAX_TIMEOUT_MS = 60_000; + +export function createTelemetryCollector( + options: TelemetryCollectorOptions, +): TelemetryCollector { + const { endpoint } = options; + const fetcher = options.fetcher ?? fetch; + const timeoutMs = assertBoundedCapacity( + options.timeoutMs ?? DEFAULT_TELEMETRY_TIMEOUT_MS, + MAX_TIMEOUT_MS, + "telemetry timeoutMs", + ); + const sendRate = createTelemetrySendRate( + assertBoundedCapacity( + options.maxSendsPerMinute ?? DEFAULT_TELEMETRY_SENDS_PER_MINUTE, + MAX_SENDS_PER_MINUTE, + "telemetry maxSendsPerMinute", + ), + options.now, + ); + const lifecycle = + options.lifecycle ?? + (typeof globalThis.addEventListener === "function" && + typeof globalThis.removeEventListener === "function" + ? globalThis + : undefined); + const exitFlushes = new Set<() => void>(); + const onPageHide = () => { + for (const flush of [...exitFlushes]) flush(); + }; + + async function post( + events: readonly unknown[], + signal?: AbortSignal, + ): Promise { + const operation = createAbortableOperation({ + ...(signal === undefined ? {} : { signal }), + timeoutMs, + }); + try { + const outcome = await operation.race( + Promise.resolve( + fetcher(endpoint, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ events }), + keepalive: true, + credentials: "omit", + cache: "no-store", + signal: operation.signal, + }), + ), + ); + if (outcome.kind !== "VALUE" || !outcome.value.ok) { + throw new Error("telemetry collector did not accept the batch"); + } + } finally { + operation.close(); + } + } + + return Object.freeze({ + sendRate, + post, + onPageExit(flush: () => void): () => void { + // The listener exists only while some queue wants a page-exit flush. + if (exitFlushes.size === 0) { + lifecycle?.addEventListener("pagehide", onPageHide); + } + exitFlushes.add(flush); + return () => { + if (exitFlushes.delete(flush) && exitFlushes.size === 0) { + lifecycle?.removeEventListener("pagehide", onPageHide); + } + }; + }, + }); +} diff --git a/src/adapters/web-push/codec-primitives.ts b/src/adapters/web-push/codec-primitives.ts new file mode 100644 index 00000000..67e4d55d --- /dev/null +++ b/src/adapters/web-push/codec-primitives.ts @@ -0,0 +1,101 @@ +import type { PushAuthoritySnapshot } from "../../contracts/web-push.ts"; + +/** + * Q-6.6-12. The validation primitives every web-push codec shares. Each file + * used to carry its own copy, and the copies had drifted: one authority check + * threw on `null`, one base64url decoder accepted a lone trailing character. + * Where they differed, the stricter behavior is the one kept here. + */ + +/** Opaque ids: bounded, ASCII, starting with an alphanumeric. */ +export const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; + +export function validOpaqueId(value: unknown): value is string { + return typeof value === "string" && OPAQUE_ID.test(value); +} + +export function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +/** `expected` must be sorted; the record's own keys must equal it exactly. */ +export function hasExactKeys( + value: Record, + expected: readonly string[], +): boolean { + const actual = Object.keys(value).sort(); + return ( + actual.length === expected.length && + actual.every((key, index) => key === expected[index]) + ); +} + +export function exactRecord( + value: unknown, + expected: readonly string[], +): value is Record { + return isRecord(value) && hasExactKeys(value, expected); +} + +/** A missing or non-object authority is invalid input, never a TypeError. */ +export function validAuthority(value: unknown): value is PushAuthoritySnapshot { + return ( + isRecord(value) && + validOpaqueId(value.fenceGeneration) && + validOpaqueId(value.sessionBindingEpoch) && + validOpaqueId(value.releaseEpoch) + ); +} + +const BASE64URL_ALPHABET = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + +/** + * Unpadded base64url. Rejects non-strings, characters outside the alphabet, + * a lone trailing character (6 bits cannot finish a byte) and non-zero spare + * bits, so every accepted string has exactly one decoding. + */ +export function base64UrlDecode(value: unknown): Uint8Array | null { + if (typeof value !== "string") return null; + const output = new Uint8Array( + new ArrayBuffer(Math.floor((value.length * 6) / 8)), + ); + let accumulator = 0; + let bitCount = 0; + let outputIndex = 0; + for (const character of value) { + const digit = BASE64URL_ALPHABET.indexOf(character); + if (digit < 0) return null; + accumulator = (accumulator << 6) | digit; + bitCount += 6; + if (bitCount >= 8) { + bitCount -= 8; + output[outputIndex] = (accumulator >>> bitCount) & 0xff; + outputIndex += 1; + } + } + return bitCount < 6 && + outputIndex === output.length && + (accumulator & ((1 << bitCount) - 1)) === 0 + ? output + : null; +} + +/** Unpadded base64url with zero spare bits: the inverse of the decoder. */ +export function base64UrlEncode(bytes: Uint8Array): string { + let output = ""; + let accumulator = 0; + let bitCount = 0; + for (const byte of bytes) { + accumulator = (accumulator << 8) | byte; + bitCount += 8; + while (bitCount >= 6) { + bitCount -= 6; + output += BASE64URL_ALPHABET[(accumulator >>> bitCount) & 63]; + } + } + if (bitCount > 0) { + output += BASE64URL_ALPHABET[(accumulator << (6 - bitCount)) & 63]; + } + return output; +} diff --git a/src/adapters/web-push/inbound/notification-click-adapter.ts b/src/adapters/web-push/inbound/notification-click-adapter.ts index ec6d391a..b49fe4d1 100644 --- a/src/adapters/web-push/inbound/notification-click-adapter.ts +++ b/src/adapters/web-push/inbound/notification-click-adapter.ts @@ -125,7 +125,12 @@ export function createNotificationClickAdapter(dependencies: Readonly<{ tails: [], }; const processing = withAbortableDeadline( - (signal) => process(event.notification.data, signal, effect), + async (signal) => + openAppRootIfRejected( + await process(event.notification.data, signal, effect), + signal, + effect, + ), { deadlineMs: handlerDeadlineMs, operation: "NOTIFICATION_CLICK", @@ -206,49 +211,6 @@ export function createNotificationClickAdapter(dependencies: Readonly<{ expiresAt: decoded.value.expiresAt, path, }); - // WP-RR-01. `focus` and `openWindow` are user-visible native effects, so - // they carry the same certainty phase `showNotification` already does: - // NOT_APPLIED before the call, MAYBE_APPLIED while the promise is pending, - // CONFIRMED on fulfilment. An effect that lands after this handler's - // deadline is still observed exactly once — as evidence only, never as - // authorization to retry. - const observeLateEffect = ( - pending: Promise, - appliedWhen: (value: unknown) => boolean, - ): void => { - let observed = false; - // WP-01. The tail is tracked so `waitUntil` owns it. Certainty is - // monotone: once the native call has been made the effect can only be - // confirmed or stay uncertain. A rejection says the call did not report - // success, not that it never happened, so downgrading it to NOT_APPLIED - // told operators the click had definitely not been applied. - effect.tails.push( - pending.then( - (value) => { - if (observed) return; - observed = true; - const applied = appliedWhen(value); - effect.certainty = applied ? "CONFIRMED" : "NOT_APPLIED"; - observeWebPush(dependencies.observer, { - event: "web_push_click_dispatched", - outcome: applied ? "DEGRADED" : "FAILED", - reason: "ABORTED", - nativeEffect: effect.certainty, - }); - }, - () => { - if (observed) return; - observed = true; - observeWebPush(dependencies.observer, { - event: "web_push_click_dispatched", - outcome: "DEGRADED", - reason: "ABORTED", - nativeEffect: "MAYBE_APPLIED", - }); - }, - ), - ); - }; try { if (signal.aborted) { return webPushFailure("ABORTED", "NOTIFICATION_CLICK"); @@ -259,26 +221,16 @@ export function createNotificationClickAdapter(dependencies: Readonly<{ effect.certainty = "MAYBE_APPLIED"; const raced = await raceAbort(focused, signal); if (raced === ABORT_OWNED) { - observeLateEffect(focused, () => true); + observeLateEffect(effect, focused, () => true); return webPushFailure("ABORTED", "NOTIFICATION_CLICK"); } effect.certainty = "CONFIRMED"; } else { - const opening = Promise.resolve( - dependencies.clients.openWindow(target), - ); - effect.certainty = "MAYBE_APPLIED"; - const raced = await raceAbort(opening, signal); - if (raced === ABORT_OWNED) { - observeLateEffect(opening, (value) => value !== null); + const opened = await openWindowBounded(target, signal, effect); + if (opened === ABORT_OWNED) { return webPushFailure("ABORTED", "NOTIFICATION_CLICK"); } - if (!raced) { - // An explicit null is the one answer that confirms no window opened. - effect.certainty = "NOT_APPLIED"; - return nativeFailure("NOTIFICATION_CLICK", true); - } - effect.certainty = "CONFIRMED"; + if (!opened) return nativeFailure("NOTIFICATION_CLICK", true); } if (signal.aborted) { return webPushFailure("ABORTED", "NOTIFICATION_CLICK"); @@ -291,6 +243,103 @@ export function createNotificationClickAdapter(dependencies: Readonly<{ return webPushSuccess(undefined); } + /** + * Q-6.6-11 / D-14. A click whose data or authority was refused (expired, + * fence or release mismatch, unreadable fence, unknown route) still opens + * the app, at the same-origin root and with no handoff data, so the user's + * tap is never silently dropped. The refusal stays the result. Native + * failures (the browser refused a window) and aborts are not retried. + */ + async function openAppRootIfRejected( + result: WebPushResult, + signal: AbortSignal, + effect: ClickEffectState, + ): Promise> { + // Every failure after a native window call is ABORTED or NATIVE_FAILURE, + // so the rest are refusals made before any window was touched. + if ( + result.ok || + result.error.code === "NATIVE_FAILURE" || + result.error.code === "ABORTED" || + signal.aborted + ) { + return result; + } + // `origin` is already a parsed origin, so this is its root URL. + await openWindowBounded(`${origin}/`, signal, effect).catch(() => { + // The native call threw: whether a window opened is unknown. + }); + return result; + } + + /** + * WP-RR-01. `openWindow` bounded by the handler signal: MAYBE_APPLIED while + * pending, then CONFIRMED, or NOT_APPLIED for an explicit null (the one + * answer that confirms no window opened). A late result is still observed. + */ + async function openWindowBounded( + url: string, + signal: AbortSignal, + effect: ClickEffectState, + ): Promise { + const opening = Promise.resolve(dependencies.clients.openWindow(url)); + effect.certainty = "MAYBE_APPLIED"; + const raced = await raceAbort(opening, signal); + if (raced === ABORT_OWNED) { + observeLateEffect(effect, opening, (value) => value !== null); + return ABORT_OWNED; + } + effect.certainty = raced ? "CONFIRMED" : "NOT_APPLIED"; + return raced !== null; + } + + /** + * WP-RR-01. `focus` and `openWindow` are user-visible native effects, so + * they carry the same certainty phase `showNotification` already does: + * NOT_APPLIED before the call, MAYBE_APPLIED while the promise is pending, + * CONFIRMED on fulfilment. An effect that lands after this handler's + * deadline is still observed exactly once — as evidence only, never as + * authorization to retry. + */ + function observeLateEffect( + effect: ClickEffectState, + pending: Promise, + appliedWhen: (value: unknown) => boolean, + ): void { + let observed = false; + // WP-01. The tail is tracked so `waitUntil` owns it. Certainty is + // monotone: once the native call has been made the effect can only be + // confirmed or stay uncertain. A rejection says the call did not report + // success, not that it never happened, so downgrading it to NOT_APPLIED + // told operators the click had definitely not been applied. + effect.tails.push( + pending.then( + (value) => { + if (observed) return; + observed = true; + const applied = appliedWhen(value); + effect.certainty = applied ? "CONFIRMED" : "NOT_APPLIED"; + observeWebPush(dependencies.observer, { + event: "web_push_click_dispatched", + outcome: applied ? "DEGRADED" : "FAILED", + reason: "ABORTED", + nativeEffect: effect.certainty, + }); + }, + () => { + if (observed) return; + observed = true; + observeWebPush(dependencies.observer, { + event: "web_push_click_dispatched", + outcome: "DEGRADED", + reason: "ABORTED", + nativeEffect: "MAYBE_APPLIED", + }); + }, + ), + ); + } + async function validateActiveFence( associationEpoch: string, releaseEpoch: string, diff --git a/src/adapters/web-push/push-association-fence-store.ts b/src/adapters/web-push/push-association-fence-store.ts index e5b7d5c5..6bf49044 100644 --- a/src/adapters/web-push/push-association-fence-store.ts +++ b/src/adapters/web-push/push-association-fence-store.ts @@ -10,13 +10,27 @@ import { type WebPushOperation, type WebPushResult, } from "../../contracts/web-push.ts"; +import { + exactRecord, + hasExactKeys, + isRecord, + validAuthority, + validOpaqueId, +} from "./codec-primitives.ts"; import { withAbortableDeadline, type TimeoutScheduler, } from "./runtime-support.ts"; const CONTROL_KEY = "push-control-v1"; -const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; +const CONTROL_KEYS = Object.freeze([ + "association", + "fenceGeneration", + "protocol", + "releaseEpoch", + "sessionBindingEpoch", + "updatedAt", +]); const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/u; @@ -621,13 +635,9 @@ function controlSnapshot(value: PushControlV1): PushControlV1 { } function decodeControl(value: unknown): PushControlV1 | null { - if (!value || typeof value !== "object" || Array.isArray(value)) return null; - const record = value as Record; - const keys = Object.keys(record).sort(); + if (!exactRecord(value, CONTROL_KEYS)) return null; + const record = value; if ( - keys.length !== 6 || - keys.join("|") !== - "association|fenceGeneration|protocol|releaseEpoch|sessionBindingEpoch|updatedAt" || record.protocol !== WEB_PUSH_PROTOCOLS.control || !validOpaqueId(record.fenceGeneration) || !validOpaqueId(record.sessionBindingEpoch) || @@ -650,29 +660,12 @@ function decodeControl(value: unknown): PushControlV1 | null { function validAssociation( value: unknown, ): value is PushControlAssociationV1 { - if (!value || typeof value !== "object" || Array.isArray(value)) return false; - const record = value as Record; - const keys = Object.keys(record).sort(); - if (record.state === "UNASSOCIATED") { - return keys.length === 1 && keys[0] === "state"; - } + if (!isRecord(value)) return false; + if (value.state === "UNASSOCIATED") return hasExactKeys(value, ["state"]); return ( - (record.state === "ACTIVE" || record.state === "REVOKED") && - keys.length === 2 && - keys[0] === "associationEpoch" && - keys[1] === "state" && - validOpaqueId(record.associationEpoch) - ); -} - -function validAuthority( - value: PushAuthoritySnapshot, -): value is PushAuthoritySnapshot { - return ( - Boolean(value) && - validOpaqueId(value.fenceGeneration) && - validOpaqueId(value.sessionBindingEpoch) && - validOpaqueId(value.releaseEpoch) + (value.state === "ACTIVE" || value.state === "REVOKED") && + hasExactKeys(value, ["associationEpoch", "state"]) && + validOpaqueId(value.associationEpoch) ); } @@ -720,10 +713,6 @@ function validIdempotencyKey(value: unknown): value is string { ); } -function validOpaqueId(value: unknown): value is string { - return typeof value === "string" && OPAQUE_ID.test(value); -} - function validRevision(value: unknown): value is number { return ( typeof value === "number" && diff --git a/src/adapters/web-push/push-codec.ts b/src/adapters/web-push/push-codec.ts index 8301cd67..2150b66a 100644 --- a/src/adapters/web-push/push-codec.ts +++ b/src/adapters/web-push/push-codec.ts @@ -7,8 +7,9 @@ import { type WebPushHintV1, type WebPushResult, } from "../../contracts/web-push.ts"; +import { hasExactKeys, isRecord, validOpaqueId } from "./codec-primitives.ts"; +import { hasDuplicateJsonMembers } from "../platform/json-member-scanner.ts"; -const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; const REGISTRY_ID = /^[A-Z][A-Z0-9_]{0,63}$/u; const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/u; @@ -31,25 +32,6 @@ const CLICK_KEYS = Object.freeze([ "routeIntent", ] as const); -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === "object" && !Array.isArray(value); -} - -function hasExactKeys( - value: Record, - expected: readonly string[], -): boolean { - const actual = Object.keys(value).sort(); - return ( - actual.length === expected.length && - actual.every((key, index) => key === expected[index]) - ); -} - -function validOpaqueId(value: unknown): value is string { - return typeof value === "string" && OPAQUE_ID.test(value); -} - function instant(value: unknown): number | null { if (typeof value !== "string" || !ISO_INSTANT.test(value)) return null; const parsed = Date.parse(value); @@ -90,7 +72,13 @@ export function decodeWebPushHint( } catch { return webPushFailure("CONTRACT_REJECTED", "PUSH_DECODE"); } - if (hasDuplicateTopLevelJsonKeys(decoded)) { + // The byte cap already bounds the scan, so the budget never trips first. + if ( + hasDuplicateJsonMembers(decoded, { + maxDepth: WEB_PUSH_LIMITS.decodedHintBytes, + maxMembers: WEB_PUSH_LIMITS.decodedHintBytes, + }) + ) { return webPushFailure("CONTRACT_REJECTED", "PUSH_DECODE"); } if (isRecord(value) && Object.hasOwn(value, "web_push")) { @@ -208,101 +196,3 @@ export function clickDataFromHint( expiresAt: hint.expiresAt, }); } - -function hasDuplicateTopLevelJsonKeys(source: string): boolean { - let cursor = skipWhitespace(source, 0); - if (source[cursor] !== "{") return false; - cursor = skipWhitespace(source, cursor + 1); - const keys = new Set(); - while (cursor < source.length && source[cursor] !== "}") { - if (source[cursor] !== "\"") return false; - const keyEnd = jsonStringEnd(source, cursor); - if (keyEnd === null) return false; - let key: unknown; - try { - key = JSON.parse(source.slice(cursor, keyEnd)); - } catch { - return false; - } - if (typeof key !== "string") return false; - if (keys.has(key)) return true; - keys.add(key); - cursor = skipWhitespace(source, keyEnd); - if (source[cursor] !== ":") return false; - const valueEnd = jsonValueEnd(source, cursor + 1); - if (valueEnd === null) return false; - cursor = skipWhitespace(source, valueEnd); - if (source[cursor] === ",") { - cursor = skipWhitespace(source, cursor + 1); - continue; - } - if (source[cursor] !== "}") return false; - } - return false; -} - -function jsonStringEnd( - source: string, - start: number, -): number | null { - let escaped = false; - for (let cursor = start + 1; cursor < source.length; cursor += 1) { - const character = source[cursor]; - if (escaped) { - escaped = false; - } else if (character === "\\") { - escaped = true; - } else if (character === "\"") { - return cursor + 1; - } - } - return null; -} - -function jsonValueEnd( - source: string, - start: number, -): number | null { - let cursor = skipWhitespace(source, start); - let depth = 0; - let inString = false; - let escaped = false; - for (; cursor < source.length; cursor += 1) { - const character = source[cursor]; - if (inString) { - if (escaped) { - escaped = false; - } else if (character === "\\") { - escaped = true; - } else if (character === "\"") { - inString = false; - } - continue; - } - if (character === "\"") { - inString = true; - } else if (character === "{" || character === "[") { - depth += 1; - } else if (character === "}" || character === "]") { - if (depth === 0) return cursor; - depth -= 1; - } else if (character === "," && depth === 0) { - return cursor; - } - } - return inString || depth !== 0 ? null : cursor; -} - -function skipWhitespace(source: string, start: number): number { - let cursor = start; - while ( - cursor < source.length && - (source[cursor] === " " || - source[cursor] === "\n" || - source[cursor] === "\r" || - source[cursor] === "\t") - ) { - cursor += 1; - } - return cursor; -} diff --git a/src/adapters/web-push/push-registration-gateway.ts b/src/adapters/web-push/push-registration-gateway.ts index f9a1241a..19472536 100644 --- a/src/adapters/web-push/push-registration-gateway.ts +++ b/src/adapters/web-push/push-registration-gateway.ts @@ -5,8 +5,12 @@ import { type PushAuthoritySnapshot, type WebPushResult, } from "../../contracts/web-push.ts"; - -const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; +import { + base64UrlDecode, + exactRecord, + validAuthority, + validOpaqueId, +} from "./codec-primitives.ts"; export const WEB_PUSH_REGISTRATION_OPERATIONS = Object.freeze({ register: "REGISTER_WEB_PUSH_SUBSCRIPTION", @@ -228,30 +232,6 @@ function decodeRevoke( : null; } -function exactRecord( - value: unknown, - keys: readonly string[], -): value is Record { - if (!value || typeof value !== "object" || Array.isArray(value)) return false; - const actual = Object.keys(value).sort(); - return ( - actual.length === keys.length && - actual.every((key, index) => key === keys[index]) - ); -} - -function validOpaqueId(value: unknown): value is string { - return typeof value === "string" && OPAQUE_ID.test(value); -} - -function validAuthority(value: PushAuthoritySnapshot): boolean { - return ( - validOpaqueId(value.fenceGeneration) && - validOpaqueId(value.sessionBindingEpoch) && - validOpaqueId(value.releaseEpoch) - ); -} - function validMaterial(value: NativePushSubscriptionMaterial): boolean { const p256dh = base64UrlDecode(value?.p256dh); const auth = base64UrlDecode(value?.auth); @@ -294,32 +274,3 @@ function snapshotMaterial( expirationTime: value.expirationTime, }); } - -function base64UrlDecode(value: unknown): Uint8Array | null { - if (typeof value !== "string") return null; - const alphabet = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - const output = new Uint8Array( - new ArrayBuffer(Math.floor((value.length * 6) / 8)), - ); - let accumulator = 0; - let bitCount = 0; - let outputIndex = 0; - for (const character of value) { - const digit = alphabet.indexOf(character); - if (digit < 0) return null; - accumulator = (accumulator << 6) | digit; - bitCount += 6; - if (bitCount >= 8) { - bitCount -= 8; - output[outputIndex] = (accumulator >> bitCount) & 0xff; - outputIndex += 1; - } - } - return bitCount < 6 && - outputIndex === output.length && - (bitCount === 0 || - (accumulator & ((1 << bitCount) - 1)) === 0) - ? output - : null; -} diff --git a/src/adapters/web-push/push-subscription-adapter.ts b/src/adapters/web-push/push-subscription-adapter.ts index 59ffebd4..418c2297 100644 --- a/src/adapters/web-push/push-subscription-adapter.ts +++ b/src/adapters/web-push/push-subscription-adapter.ts @@ -12,6 +12,7 @@ import { type WebPushResult, type WebPushUnavailableReason, } from "../../contracts/web-push.ts"; +import { base64UrlDecode, base64UrlEncode } from "./codec-primitives.ts"; import type { PushAssociationFenceStore, PushControlReceipt, @@ -1112,51 +1113,3 @@ function decodeVapidPublicKey( const decoded = base64UrlDecode(value); return decoded?.byteLength === 65 && decoded[0] === 4 ? decoded : null; } - -function base64UrlDecode(value: string): Uint8Array | null { - const alphabet = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - const outputLength = Math.floor((value.length * 6) / 8); - const output = new Uint8Array(new ArrayBuffer(outputLength)); - let accumulator = 0; - let bitCount = 0; - let outputIndex = 0; - for (const character of value) { - const digit = alphabet.indexOf(character); - if (digit < 0) return null; - accumulator = (accumulator << 6) | digit; - bitCount += 6; - if (bitCount >= 8) { - bitCount -= 8; - output[outputIndex] = (accumulator >>> bitCount) & 0xff; - outputIndex += 1; - } - } - if ( - outputIndex !== outputLength || - (bitCount > 0 && (accumulator & ((1 << bitCount) - 1)) !== 0) - ) { - return null; - } - return output; -} - -function base64UrlEncode(bytes: Uint8Array): string { - const alphabet = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - let output = ""; - let accumulator = 0; - let bitCount = 0; - for (const byte of bytes) { - accumulator = (accumulator << 8) | byte; - bitCount += 8; - while (bitCount >= 6) { - bitCount -= 6; - output += alphabet[(accumulator >>> bitCount) & 63]; - } - } - if (bitCount > 0) { - output += alphabet[(accumulator << (6 - bitCount)) & 63]; - } - return output; -} diff --git a/src/adapters/web-push/service-worker-runtime.ts b/src/adapters/web-push/service-worker-runtime.ts index 88b0a73e..4182c241 100644 --- a/src/adapters/web-push/service-worker-runtime.ts +++ b/src/adapters/web-push/service-worker-runtime.ts @@ -6,6 +6,7 @@ import { webPushSuccess, type WebPushObserver, } from "../../contracts/web-push.ts"; +import { isRecord } from "./codec-primitives.ts"; import type { PushAssociationFenceStore } from "./push-association-fence-store.ts"; import { createPushEventAdapter, @@ -290,7 +291,3 @@ function windowClientFacade(value: unknown): WindowClientFacade | null { } return value as WindowClientFacade; } - -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === "object" && !Array.isArray(value); -} diff --git a/src/application/ports/browser-file-storage/indexeddb-port.ts b/src/application/ports/browser-file-storage/indexeddb-port.ts index 98ad6eb8..cf71d6f3 100644 --- a/src/application/ports/browser-file-storage/indexeddb-port.ts +++ b/src/application/ports/browser-file-storage/indexeddb-port.ts @@ -68,6 +68,14 @@ export type IndexedDbPage = Readonly<{ export type IndexedDbWriteReceipt = Readonly<{ key: string; + /** + * D-13. A revision orders writes to one live record only. `remove` deletes + * the row without a tombstone, so the next create starts again at 1 and a + * `(key, revision)` pair is not unique across the key's lifetime: a writer + * holding revision N from before a delete can compare-and-swap over the + * recreated record once it reaches N. Pair the revision with a value the + * caller owns (a server version, an id in the payload) when that matters. + */ revision: number; replayed: boolean; }>; diff --git a/src/application/ports/browser-file-storage/opfs-ports.ts b/src/application/ports/browser-file-storage/opfs-ports.ts index 25d1fb72..dbd2f2ac 100644 --- a/src/application/ports/browser-file-storage/opfs-ports.ts +++ b/src/application/ports/browser-file-storage/opfs-ports.ts @@ -26,6 +26,13 @@ export type OpfsStorageScope = Readonly<{ export type DurableObjectDescriptor = Readonly<{ objectId: string; scope: OpfsStorageScope; + /** + * D-13. A generation orders puts to one live object only. Once `remove` + * commits, the next put starts again at 1, so a generation (or + * `expectedGeneration`) remembered from before the delete can match a + * different object. Do not treat `(objectId, generation)` as unique across + * the object's lifetime; compare the integrity root digest when it matters. + */ generation: number; byteLength: number; mediaType: string; diff --git a/src/application/ports/browser-file-storage/shared.ts b/src/application/ports/browser-file-storage/shared.ts index 38448744..0a83b2b7 100644 --- a/src/application/ports/browser-file-storage/shared.ts +++ b/src/application/ports/browser-file-storage/shared.ts @@ -183,6 +183,43 @@ export function isValidByteLength(value: number): boolean { return Number.isSafeInteger(value) && value >= 0; } +export function isNonNegativeSafeInteger(value: unknown): value is number { + return Number.isSafeInteger(value) && (value as number) >= 0; +} + +/** True when `value` carries a C0 control character or DEL. */ +export function hasControlCharacter(value: string): boolean { + return [...value].some((character) => { + const codePoint = character.codePointAt(0) ?? 0; + return codePoint < 0x20 || codePoint === 0x7f; + }); +} + +export function isPositiveSafeInteger(value: unknown): value is number { + return Number.isSafeInteger(value) && (value as number) > 0; +} + +/** + * The observation bucket for a byte length. An absent, fractional, negative or + * unsafe length has no bucket, so an observation never reports a guessed size. + */ +export function browserDataByteBucket( + byteLength: number | null | undefined, +): BrowserDataObservation["byteBucket"] { + if ( + byteLength === null || + byteLength === undefined || + !isValidByteLength(byteLength) + ) { + return undefined; + } + if (byteLength === 0) return "ZERO"; + if (byteLength < 1_048_576) return "LT1MIB"; + if (byteLength < 10_485_760) return "1_TO_9MIB"; + if (byteLength < 104_857_600) return "10_TO_99MIB"; + return "GTE100MIB"; +} + export function assertValidStoragePolicy( policy: BrowserStoragePolicy, ): void { diff --git a/src/application/ports/browser-transfer/resumable-upload.ts b/src/application/ports/browser-transfer/resumable-upload.ts index 8195ce33..34762ad5 100644 --- a/src/application/ports/browser-transfer/resumable-upload.ts +++ b/src/application/ports/browser-transfer/resumable-upload.ts @@ -273,6 +273,18 @@ export interface ResumableUploadCheckpointStore { expectedRevision: number; signal?: AbortSignal; }>): Promise>; + /** + * Q-6.1-6. Deletes the row only when it cannot be read as a checkpoint + * (corrupt, or written by a schema this build does not know); a readable row + * is left alone and reported as `CONFLICT`. An absent row is a success. + * Explicit abort uses it so such a row does not block the upload key until + * the whole partition is deleted. Optional: a store without it keeps the + * old behavior. + */ + removeUnreadable?(input: Readonly<{ + uploadKey: string; + signal?: AbortSignal; + }>): Promise>; close(): void; } diff --git a/src/application/use-cases/decide-chunk-recovery.ts b/src/application/use-cases/decide-chunk-recovery.ts index dd51469c..9e68ae35 100644 --- a/src/application/use-cases/decide-chunk-recovery.ts +++ b/src/application/use-cases/decide-chunk-recovery.ts @@ -1,3 +1,4 @@ +import { createReloadOnceGuard } from "../../platform/release/release-mismatch-recovery.ts"; import type { StoragePort } from "../ports/storage-port.ts"; const RECOVERABLE_KINDS = new Set(["CHUNK_LOAD_FAILURE", "DEPLOY_MISMATCH"]); @@ -35,17 +36,23 @@ export function decideChunkRecovery( const releasePair = `${input.currentBuildId}/${input.currentReleaseId}` + `->${input.activeBuildId}/${input.activeReleaseId}`; - const guard = input.storage.read("CHUNK_RELOAD_GUARD"); - if (!guard.ok) { - return { action: "support", reason: "guard-read-failed" }; - } - if (guard.value === releasePair) { - return { action: "support", reason: "reload-already-attempted" }; - } - - const recorded = input.storage.write("CHUNK_RELOAD_GUARD", releasePair); - if (!recorded.ok) { - return { action: "support", reason: "guard-write-failed" }; - } - return { action: "reload-once", releasePair }; + // Q-6.9-9. The boot reload guard's rule: at most one automatic reload per + // marker TTL, whatever the pair. A pair-keyed marker let replicas that + // alternate A/B reload on every chunk failure. The marker is never cleared; + // it only expires. + const decision = createReloadOnceGuard({ + read() { + const guard = input.storage.read("CHUNK_RELOAD_GUARD"); + if (!guard.ok) throw new Error("chunk reload guard is unreadable"); + return typeof guard.value === "string" ? guard.value : null; + }, + write(value) { + if (!input.storage.write("CHUNK_RELOAD_GUARD", value).ok) { + throw new Error("chunk reload guard was not persisted"); + } + }, + }).decide(releasePair); + return decision === "reload-once" + ? { action: "reload-once", releasePair } + : { action: "support", reason: decision }; } diff --git a/src/bootstrap/load-runtime-config.ts b/src/bootstrap/load-runtime-config.ts index 5cd5f40f..9cfc3a36 100644 --- a/src/bootstrap/load-runtime-config.ts +++ b/src/bootstrap/load-runtime-config.ts @@ -116,16 +116,18 @@ export async function loadRuntimeConfig( const validated = validateRuntimeConfig(rawConfig); if (!validated.success) { + // Q-6.9-10. Only a value that passed a check reaches the safe error. The + // declared schema version did when it selected a parser; nothing else in + // a rejected document did (RELEASE_ID could be 64 KB of anything). + const versionAccepted = !validated.issues.some( + (issue) => issue.path === "CONFIG_SCHEMA_VERSION", + ); throw new BootConfigError("CONFIG_SCHEMA_INVALID", { buildId: buildConfig.buildId, configSchemaVersion: - typeof rawConfig.CONFIG_SCHEMA_VERSION === "string" + versionAccepted && typeof rawConfig.CONFIG_SCHEMA_VERSION === "string" ? rawConfig.CONFIG_SCHEMA_VERSION : undefined, - releaseId: - typeof rawConfig.RELEASE_ID === "string" - ? rawConfig.RELEASE_ID - : undefined, }); } diff --git a/src/bootstrap/register-service-worker.ts b/src/bootstrap/register-service-worker.ts index 24e567bb..5f553c11 100644 --- a/src/bootstrap/register-service-worker.ts +++ b/src/bootstrap/register-service-worker.ts @@ -51,6 +51,7 @@ export function createServiceWorkerRuntimeHost( buildId: input.buildId, ...(container ? { container } : {}), ...(host?.caches ? { caches: host.caches } : {}), + ...(host?.document ? { document: host.document } : {}), ...(input.blockers ? { blockers: input.blockers } : {}), ...(input.observe ? { observe: input.observe } : {}), }); diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index dfa1e1da..2025e0ed 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -18,7 +18,10 @@ import { type DiagnosticRecordInput, } from "../contracts/diagnostics.ts"; import type { TelemetryEventName } from "../contracts/telemetry.ts"; -import { createBrowserCrossContextInvalidationFromHost } from "../adapters/cross-context-invalidation/index.ts"; +import { + createBrowserCrossContextInvalidationFromHost, + crossContextCacheEpochForRelease, +} from "../adapters/cross-context-invalidation/index.ts"; import { createConditionalValidatorStore, createQueryClient, @@ -30,6 +33,7 @@ import { createBrowserMutationIntentFactory } from "../adapters/platform/index.t import { createFeatureTelemetry, createTelemetryAdapter, + createTelemetryCollector, } from "../adapters/telemetry/index.ts"; import type { AuthSessionPort } from "../application/ports/auth-session-port.ts"; import type { ReleaseInfo } from "../application/ports/release-info-port.ts"; @@ -77,8 +81,12 @@ type HttpClientDependencies = Parameters[0]; * V2로 어떤 오퍼레이션도 실행되지 않는다** — 그건 결함이 아니라 제품이 * 채우는 자리다. * - * V2를 rollback/compatibility 경로로 쓰려는 제품은 이 네 슬롯을 주입해야 - * 한다. 주입하지 않은 채 V3에서 되돌리면 모든 요청이 실패한다. + * V2는 V3를 그대로 되돌리는 롤백 경로가 아니다. 두 경로는 wire 형식이 + * 다르다. V2는 `{ success, data, meta }` 봉투를 검증하고 + * (`adapters/http/schema-registry.ts`), V3는 봉투 없는 DTO 자체를 검증한다. + * 그래서 네 슬롯을 모두 주입해도 같은 백엔드로 V2로 되돌리면 모든 응답이 + * `ENVELOPE_MISMATCH`다. V2로 되돌리려면 슬롯 주입과 함께 서버도 V2 봉투로 + * 응답해야 한다. * V3(`createContractHttpExecutor`)는 설치된 feature 계약에서 오퍼레이션을 * 받으므로 이 슬롯과 무관하게 동작한다. */ @@ -300,10 +308,20 @@ export async function createRuntimeAdapters( ? createExternalAuthSessionAdapter(externalOwner) : createUnavailableSessionAdapter(); const diagnostics = createDiagnosticsAdapter(); + // Q-6.9-4. Both telemetry ports post through one collector transport: one + // send-rate window, one page-exit flush and one fetch policy per endpoint. + const telemetryCollector = + config.TELEMETRY_ENABLED && config.TELEMETRY_ENDPOINT + ? createTelemetryCollector({ + endpoint: config.TELEMETRY_ENDPOINT, + ...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }), + }) + : undefined; const telemetry = createTelemetryAdapter({ enabled: config.TELEMETRY_ENABLED, endpoint: config.TELEMETRY_ENDPOINT, fetcher: context.fetcher, + ...(telemetryCollector === undefined ? {} : { collector: telemetryCollector }), onDrop(event) { const attributes = event.attributes && typeof event.attributes === "object" @@ -327,7 +345,9 @@ export async function createRuntimeAdapters( const crossContextInvalidation = createBrowserCrossContextInvalidationFromHost({ ...(context.host === undefined ? {} : { host: context.host }), - cacheEpoch: `release.${context.release.releaseId}`, + cacheEpoch: crossContextCacheEpochForRelease( + context.release.releaseId, + ), topics: [...invalidationTopicVersions].map(([topic, topicVersion]) => Object.freeze({ topic, @@ -534,13 +554,16 @@ export async function createRuntimeAdapters( ? {} : { endpoint: config.TELEMETRY_ENDPOINT }), ...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }), + ...(telemetryCollector === undefined ? {} : { collector: telemetryCollector }), }); // Each installed contribution receives only the capabilities it declares. const featureCapabilities = Object.freeze({ http: contractOperations, telemetry: featureTelemetry, }); - const featureInputs = createInstalledFeatureInputs(featureCapabilities); + const featureInputs = createInstalledFeatureInputs(featureCapabilities, [ + ...activeFeatureIds, + ]); return Object.freeze({ outputPorts: Object.freeze({ diff --git a/src/contracts/api-operations.ts b/src/contracts/api-operations.ts index 6ceebc18..692021e6 100644 --- a/src/contracts/api-operations.ts +++ b/src/contracts/api-operations.ts @@ -207,7 +207,9 @@ export function getApiOperation( operationId: string, operations: Readonly> = API_OPERATIONS, ): ApiOperation { - const selected = operations[operationId]; + const selected = Object.hasOwn(operations, operationId) + ? operations[operationId] + : undefined; if (!selected) { throw new Error(`Unregistered API operation: ${operationId}`); } diff --git a/src/contracts/boundary-mapper.ts b/src/contracts/boundary-mapper.ts index a6b97576..5b21f7b3 100644 --- a/src/contracts/boundary-mapper.ts +++ b/src/contracts/boundary-mapper.ts @@ -1,12 +1,36 @@ +import type { MappingResult as ContractMappingResult } from "./external-contract-runtime.ts"; + export type MappingFailureCode = | "MAPPING_INVARIANT_REJECTED" | "UNSUPPORTED_WIRE_VALUE" | "OUTPUT_LIMIT_EXCEEDED"; -export type MappingResult = +/** + * D-15. The boundary mapper's own result: a flat failure `code`. The canonical + * mapping result is `MappingResult` in `external-contract-runtime.ts` + * (`error: { kind, code }`); convert with `toContractMappingResult`. + */ +export type BoundaryMappingResult = | Readonly<{ ok: true; value: Value }> | Readonly<{ ok: false; code: MappingFailureCode }>; +/** Compatible alias kept for existing importers; see `BoundaryMappingResult`. */ +export type MappingResult = BoundaryMappingResult; + +/** Adapts a boundary mapper result to the canonical contract mapping result. */ +export function toContractMappingResult( + result: BoundaryMappingResult, +): ContractMappingResult { + if (result.ok) return result; + return Object.freeze({ + ok: false as const, + error: Object.freeze({ + kind: "MAPPING_CONTRACT_VIOLATION" as const, + code: result.code, + }), + }); +} + export type BoundaryMapper = Readonly<{ mapperId: string; mapperVersion: number; @@ -51,7 +75,9 @@ export function mapWithBoundaryRegistry( input: unknown, registry: Readonly>, ): MappingResult { - const mapper = registry[mapperId]; + const mapper = Object.hasOwn(registry, mapperId) + ? registry[mapperId] + : undefined; if (!mapper) return mappingFailure("MAPPING_INVARIANT_REJECTED"); try { return mapper.map(input); diff --git a/src/contracts/browser-rpc.ts b/src/contracts/browser-rpc.ts index 9188132a..03774152 100644 --- a/src/contracts/browser-rpc.ts +++ b/src/contracts/browser-rpc.ts @@ -2,6 +2,12 @@ import { createReadOnlyRegistry, type ReadOnlyRegistry, } from "./read-only-registry.ts"; +import { + decodeExactObject, + decodeOwnDataRecord, + snapshotExactArray, +} from "./exact-snapshot.ts"; +import { isLoopbackHostname } from "./deployment-admission.ts"; import type { InstalledBoundaryMapper } from "./boundary-mapper.ts"; import type { RuntimeSchemaCodec } from "./schema-registry.ts"; @@ -361,36 +367,19 @@ function installRegistrySnapshot( label: string, allowedKeys: readonly string[], ): ReadOnlyRegistry { - let ownKeys: string[]; - let symbols: readonly symbol[]; - let prototype: object | null; - try { - // RPC-03. Own *names*, not just enumerable keys: a non-enumerable own entry - // is as much a smuggled row as an inherited one, and `Object.keys` never - // saw either. - ownKeys = Object.getOwnPropertyNames(source); - symbols = Object.getOwnPropertySymbols(source); - prototype = Reflect.getPrototypeOf(source); - } catch { - throw new TypeError(`Browser RPC ${label} registry is unreadable.`); - } - if (symbols.length > 0) { - throw new TypeError(`Browser RPC ${label} registry has symbol keys.`); - } - if (prototype !== Object.prototype && prototype !== null) { - throw new TypeError(`Browser RPC ${label} registry has a custom prototype.`); + // RPC-03 / Q-6.7-6. Own *names*, not just enumerable keys: a non-enumerable + // or inherited entry is a smuggled row, and so is a symbol-keyed one. + const registry = decodeOwnDataRecord(source, Number.POSITIVE_INFINITY); + if (!registry.ok) { + throw new TypeError( + `Browser RPC ${label} registry is not exact: ${registry.detail}`, + ); } const installed = new Map(); - for (const key of ownKeys) { - const descriptor = Object.getOwnPropertyDescriptor(source, key); - if (!descriptor || !("value" in descriptor)) { - throw new TypeError( - `Browser RPC ${label} registry entry is not a data property: ${key}`, - ); - } + for (const [key, row] of Object.entries(registry.value)) { installed.set( key, - installRowSnapshot(descriptor.value as Value, `${label}.${key}`, allowedKeys), + installRowSnapshot(row as Value, `${label}.${key}`, allowedKeys), ); } return createReadOnlyRegistry(installed); @@ -401,46 +390,25 @@ function installRowSnapshot( label: string, allowedKeys: readonly string[], ): Value { - if (!row || typeof row !== "object") { - throw new TypeError(`Browser RPC ${label} row is not an object.`); - } - let ownKeys: string[]; - let symbols: readonly symbol[]; - let prototype: object | null; - try { - ownKeys = Object.getOwnPropertyNames(row); - symbols = Object.getOwnPropertySymbols(row); - prototype = Reflect.getPrototypeOf(row); - } catch { - throw new TypeError(`Browser RPC ${label} row is unreadable.`); - } - if (symbols.length > 0) { - throw new TypeError(`Browser RPC ${label} row has symbol keys.`); - } // RPC-03. A custom prototype carries fields the name sweep never sees and // stays live after installation, so the installed row would not be the row - // that was checked. - if (prototype !== Object.prototype && prototype !== null) { - throw new TypeError(`Browser RPC ${label} row has a custom prototype.`); + // that was checked. Accessors are refused without being called. + const decoded = decodeExactObject(row, { allowed: allowedKeys }); + if (!decoded.ok) { + throw new TypeError(`Browser RPC ${label} row is not exact: ${decoded.detail}`); } const snapshot = Object.create(null) as Record; - for (const key of ownKeys) { - if (!allowedKeys.includes(key)) { - throw new TypeError( - `Browser RPC ${label} row has an unexpected key: ${key}`, - ); + for (const [key, value] of Object.entries(decoded.value)) { + if (!Array.isArray(value)) { + snapshot[key] = value; + continue; } - const descriptor = Object.getOwnPropertyDescriptor(row, key); - // Reading an accessor would invoke a getter; refuse without calling it. - if (!descriptor || !("value" in descriptor)) { - throw new TypeError( - `Browser RPC ${label} row key is not a data property: ${key}`, - ); + // Copied by index, never through an own `Symbol.iterator`. + const items = snapshotExactArray(value); + if (!items) { + throw new TypeError(`Browser RPC ${label} row array is not exact: ${key}`); } - const value = descriptor.value as unknown; - snapshot[key] = Array.isArray(value) - ? Object.freeze([...value]) - : value; + snapshot[key] = items; } return Object.freeze(snapshot) as Value; } @@ -777,7 +745,7 @@ function validateProviderProfile(profile: BrowserRpcProviderProfile): void { } const localHttp = endpoint.protocol === "http:" && - ["localhost", "127.0.0.1", "[::1]"].includes(endpoint.hostname); + isLoopbackHostname(endpoint.hostname); if ( !REGISTRY_ID.test(profile.runtimeProfileId) || !REGISTRY_ID.test(profile.providerId) || diff --git a/src/contracts/cache-invalidation.ts b/src/contracts/cache-invalidation.ts index 4725e3c8..63722e23 100644 --- a/src/contracts/cache-invalidation.ts +++ b/src/contracts/cache-invalidation.ts @@ -1,3 +1,5 @@ +import { snapshotExactObject } from "./exact-snapshot.ts"; + /** * Cross-context cache invalidation is a best-effort hint protocol. The wire * event intentionally carries neither cached data nor a concrete query key. @@ -130,10 +132,16 @@ export function parseCacheInvalidationWireEvent( } function parseCacheInvalidationWireEventUnsafe( - input: unknown, + source: unknown, policy: CacheInvalidationParsePolicy, ): CacheInvalidationParseResult { - if (!isExactWireRecord(input)) { + // Q-6.7-6. Every check below reads one owned snapshot, so an accessor cannot + // answer the checks and the returned event differently. + const input = snapshotExactObject(source, { + allowed: WIRE_KEYS, + required: WIRE_KEYS, + }) as Readonly> | null; + if (!input) { return failure("INVALID_ENVELOPE"); } @@ -205,19 +213,6 @@ function parseCacheInvalidationWireEventUnsafe( }; } -function isExactWireRecord( - value: unknown, -): value is Readonly> { - if (!value || typeof value !== "object" || Array.isArray(value)) { - return false; - } - const keys = Object.keys(value).sort(); - return ( - keys.length === WIRE_KEYS.length && - keys.every((key, index) => key === WIRE_KEYS[index]) - ); -} - function isPositiveSafeInteger(value: unknown): value is number { return ( typeof value === "number" && diff --git a/src/contracts/contract-set.ts b/src/contracts/contract-set.ts index caf39568..5f36455c 100644 --- a/src/contracts/contract-set.ts +++ b/src/contracts/contract-set.ts @@ -82,6 +82,11 @@ export async function verifyContractSet( const expectedById = new Map( input.expected.map((entry) => [entry.packageId, entry] as const), ); + // Q-6.7-12. A duplicated expectation is a failure code, not a rejection + // from the digest computation further down. + if (expectedById.size !== input.expected.length) { + return failure("CONTRACT_SET_DUPLICATE_PACKAGE"); + } for (const entry of input.manifest.packages) { if (!expectedById.has(entry.packageId)) { return failure("CONTRACT_SET_PACKAGE_UNEXPECTED"); @@ -115,8 +120,14 @@ export async function verifyContractSet( return failure("CONTRACT_SET_DIGEST_MISMATCH"); } - const expectedDigest = - input.expectedSetDigest ?? (await computeContractSetDigest(input.expected)); + let expectedDigest: `sha256:${string}`; + try { + expectedDigest = + input.expectedSetDigest ?? + (await computeContractSetDigest(input.expected)); + } catch { + return failure("CONTRACT_SET_DIGEST_INVALID"); + } if (expectedDigest !== input.manifest.setDigest) { return failure("CONTRACT_SET_DIGEST_MISMATCH"); } diff --git a/src/contracts/deployment-admission.ts b/src/contracts/deployment-admission.ts index 08139100..09fd3ae3 100644 --- a/src/contracts/deployment-admission.ts +++ b/src/contracts/deployment-admission.ts @@ -131,30 +131,61 @@ function publicEndpointViolations( return violations; } +/** + * Q-6.7-10. The one list of loopback hosts (in `URL.hostname` form) on which + * a REST or browser RPC provider may use plain `http:`. + */ +export const LOOPBACK_HOSTNAMES = Object.freeze([ + "localhost", + "127.0.0.1", + "[::1]", +] as const); + +export function isLoopbackHostname(hostname: string): boolean { + return (LOOPBACK_HOSTNAMES as readonly string[]).includes(hostname); +} + /** * Hosts that only resolve inside the machine or network that built the * artifact. A deployment pointing at one of these is a developer configuration - * that escaped, not a production endpoint. + * that escaped, not a production endpoint. `hostname` comes from `URL`, so + * IPv4 and IPv6 literals are already in canonical form. */ function isNonPublicHost(hostname: string): boolean { - const host = hostname.toLowerCase().replace(/^\[|\]$/gu, ""); + if (isLoopbackHostname(hostname)) return true; + const host = hostname + .toLowerCase() + .replace(/^\[|\]$/gu, "") + .replace(/\.$/u, ""); if ( host === "localhost" || host.endsWith(".localhost") || - host === "::1" || - host === "0.0.0.0" || - host === "::" + host.endsWith(".local") || + host.endsWith(".internal") ) { return true; } + if (host.includes(":")) return isNonPublicIpv6(host); const octets = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u.exec(host); if (!octets) return false; const [first, second] = [Number(octets[1]), Number(octets[2])]; return ( - first === 127 || + first === 0 || first === 10 || - (first === 192 && second === 168) || + first === 127 || + (first === 100 && second >= 64 && second <= 127) || + (first === 169 && second === 254) || (first === 172 && second >= 16 && second <= 31) || - (first === 169 && second === 254) + (first === 192 && second === 168) ); } + +/** Unspecified, loopback, IPv4-mapped, unique-local (fc00::/7), link-local (fe80::/10). */ +function isNonPublicIpv6(host: string): boolean { + if (host === "::" || host === "::1") return true; + if (/^::ffff:[0-9a-f]{1,4}:[0-9a-f]{1,4}$/u.test(host)) return true; + const first = host.startsWith(":") + ? 0 + : Number.parseInt(host.slice(0, host.indexOf(":")), 16); + return (first & 0xfe00) === 0xfc00 || (first & 0xffc0) === 0xfe80; +} diff --git a/src/contracts/exact-snapshot.ts b/src/contracts/exact-snapshot.ts index 1707b1f0..8989ab48 100644 --- a/src/contracts/exact-snapshot.ts +++ b/src/contracts/exact-snapshot.ts @@ -57,36 +57,52 @@ export function hasOwnDataKey(source: unknown, key: string): boolean { } } -/** - * Copies `source` into a frozen plain object, reading every property exactly - * once. Returns `null` when the value is not an object, carries a symbol or an - * unexpected own key, exposes an accessor, has an unapproved prototype, misses a - * required key, or makes any reflection operation throw. - */ -export function snapshotExactObject( - source: unknown, - policy: ExactObjectPolicy, -): Readonly> | null { - if (source === null || typeof source !== "object") return null; - try { - const prototypes = policy.prototypes ?? DEFAULT_PROTOTYPES; - if (!prototypes.includes(Reflect.getPrototypeOf(source))) return null; - if (Object.getOwnPropertySymbols(source).length > 0) return null; +export type ExactDecodeResult = + | Readonly<{ ok: true; value: T }> + | Readonly<{ ok: false; detail: string }>; - const allowed = new Set(policy.allowed); +function violation(detail: string): ExactDecodeResult { + return Object.freeze({ ok: false as const, detail }); +} + +/** + * The one exact-record reader every contract shares. `allowed: null` leaves + * the key set open (a header bag, a registry keyed by id). Each property is + * read once through its own descriptor, and the frozen copy is what callers + * validate and install. + */ +function decodeOwnData( + source: unknown, + allowed: ReadonlySet | null, + required: readonly string[], + prototypes: readonly (object | null)[], + maximumKeys: number, +): ExactDecodeResult>> { + if (source === null || typeof source !== "object") { + return violation("object required"); + } + try { + if (!prototypes.includes(Reflect.getPrototypeOf(source))) { + return violation("custom prototype"); + } + if (Object.getOwnPropertySymbols(source).length > 0) { + return violation("symbol keys"); + } const names = Object.getOwnPropertyNames(source); + if (names.length > maximumKeys) return violation("too many keys"); const snapshot: Record = {}; for (const name of names) { - if (!allowed.has(name)) return null; + if (allowed && !allowed.has(name)) { + return violation(`unexpected key: ${name}`); + } const descriptor = Object.getOwnPropertyDescriptor(source, name); - // A non-enumerable own property is as much a smuggled field as an - // inherited one, and an accessor is a second read waiting to happen. - if ( - !descriptor || - !("value" in descriptor) || - descriptor.enumerable !== true - ) { - return null; + // An accessor is a second read waiting to happen; a non-enumerable own + // property is as much a smuggled field as an inherited one. + if (!descriptor || !("value" in descriptor)) { + return violation(`not a data property: ${name}`); + } + if (descriptor.enumerable !== true) { + return violation(`non-enumerable key: ${name}`); } Object.defineProperty(snapshot, name, { value: descriptor.value, @@ -95,56 +111,84 @@ export function snapshotExactObject( configurable: false, }); } - for (const name of policy.required ?? []) { - if (!Object.hasOwn(snapshot, name)) return null; + for (const name of required) { + if (!Object.hasOwn(snapshot, name)) { + return violation(`missing key: ${name}`); + } } - return Object.freeze(snapshot); + return Object.freeze({ ok: true as const, value: Object.freeze(snapshot) }); } catch { - return null; + return violation("unreadable"); } } +/** + * Copies `source` into a frozen plain object, reading every property exactly + * once, or says why it cannot: not an object, a symbol or unexpected own key, + * an accessor or non-enumerable property, an unapproved prototype, a missing + * required key, or a reflection trap that throws. + */ +export function decodeExactObject( + source: unknown, + policy: ExactObjectPolicy, +): ExactDecodeResult>> { + return decodeOwnData( + source, + new Set(policy.allowed), + policy.required ?? [], + policy.prototypes ?? DEFAULT_PROTOTYPES, + Number.POSITIVE_INFINITY, + ); +} + +/** `decodeExactObject` for an open-keyed record of at most `maximumKeys`. */ +export function decodeOwnDataRecord( + source: unknown, + maximumKeys = 64, +): ExactDecodeResult>> { + return decodeOwnData(source, null, [], DEFAULT_PROTOTYPES, maximumKeys); +} + +/** `decodeExactObject`, answering `null` instead of a reason. */ +export function snapshotExactObject( + source: unknown, + policy: ExactObjectPolicy, +): Readonly> | null { + const decoded = decodeExactObject(source, policy); + return decoded.ok ? decoded.value : null; +} + /** * Copies an open-keyed record — a header bag, a query map — into a frozen owned * object, reading every property exactly once. The key set is not constrained * here; admission against an allow-list stays with the policy that owns it, so - * the more specific rejection can still be reported. Returns `null` for a - * non-object, a symbol key, an accessor, a non-enumerable own key, an - * unapproved prototype, more than `maximumKeys` entries, or a throwing trap. + * the more specific rejection can still be reported. Returns `null` wherever + * `decodeOwnDataRecord` names a reason. */ export function snapshotOwnDataRecord( source: unknown, maximumKeys = 64, ): Readonly> | null { - if (source === null || typeof source !== "object") return null; - try { - if (!DEFAULT_PROTOTYPES.includes(Reflect.getPrototypeOf(source))) { - return null; - } - if (Object.getOwnPropertySymbols(source).length > 0) return null; - const names = Object.getOwnPropertyNames(source); - if (names.length > maximumKeys) return null; - const snapshot: Record = {}; - for (const name of names) { - const descriptor = Object.getOwnPropertyDescriptor(source, name); - if ( - !descriptor || - !("value" in descriptor) || - descriptor.enumerable !== true - ) { - return null; - } - Object.defineProperty(snapshot, name, { - value: descriptor.value, - enumerable: true, - writable: false, - configurable: false, - }); - } - return Object.freeze(snapshot); - } catch { - return null; - } + const decoded = decodeOwnDataRecord(source, maximumKeys); + return decoded.ok ? decoded.value : null; +} + +/** + * The throwing form for composition-time registries: the row must be an exact + * own-data record over `allowedKeys`, and `onViolation` receives the reason. + */ +export function exactOwnDataSnapshot( + source: unknown, + allowedKeys: readonly (keyof Shape & string)[], + requiredKeys: readonly (keyof Shape & string)[], + onViolation: (detail: string) => never, +): Readonly { + const decoded = decodeExactObject(source, { + allowed: allowedKeys, + required: requiredKeys, + }); + if (!decoded.ok) onViolation(decoded.detail); + return decoded.value as Readonly; } /** diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 5cfc844f..671eaa7b 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -8,7 +8,10 @@ */ import { isOperationId } from "./operation-id.ts"; -import { INSTALLED_REST_AUTH_PROFILES } from "./rest-profiles.ts"; +import { + INSTALLED_REST_AUTH_PROFILES, + type InstalledRestAuthProfiles, +} from "./rest-profiles.ts"; import { defineTrafficBudget, TRAFFIC_BUDGET_KEYS, @@ -16,9 +19,9 @@ import { } from "../platform/traffic/traffic-budget.ts"; import { createReadOnlyRegistry, - exactOwnDataSnapshot, type ReadOnlyRegistry, } from "./read-only-registry.ts"; +import { exactOwnDataSnapshot, snapshotExactArray } from "./exact-snapshot.ts"; /** §7.3 hard ceilings. A contribution may lower these, never raise them. */ export const HTTP_EXECUTION_CEILINGS = Object.freeze({ @@ -36,6 +39,11 @@ export const HTTP_EXECUTION_CEILINGS = Object.freeze({ finalUrlBytes: 16_384, }); +/* + * D-15. The validator protocol and `MappingResult` below are the canonical + * shapes. `RuntimeSchemaCodec` (`schema-registry.ts`) and the boundary + * mapper's result (`boundary-mapper.ts`) are adapters over them. + */ export type RuntimeValidationIssue = Readonly<{ path: readonly (string | number)[]; code: string; @@ -319,6 +327,7 @@ function assertStatuses( function assertExecutionPolicy( policy: HttpExecutionPolicy, label: string, + authProfiles: InstalledRestAuthProfiles, ): void { const ceilings = HTTP_EXECUTION_CEILINGS; if ( @@ -334,7 +343,7 @@ function assertExecutionPolicy( } // §7.7 / VD-23. A declared profile that the installed registry does not own // is a composition failure; the executor must never resolve it at runtime. - if (!INSTALLED_REST_AUTH_PROFILES.has(policy.authProfileId)) { + if (!authProfiles.has(policy.authProfileId)) { fail(`${label}: unknown authProfileId ${policy.authProfileId}`); } if ( @@ -379,6 +388,7 @@ function assertExecutionPolicy( function assertHttpContract( installed: InstalledHttpContract, featureId: string, + authProfiles: InstalledRestAuthProfiles, ): void { const contract = installed?.contract; if (!contract || typeof contract !== "object") { @@ -475,7 +485,7 @@ function assertHttpContract( fail(`${label}: command recovery descriptor`); } } - assertExecutionPolicy(installed.frontend, label); + assertExecutionPolicy(installed.frontend, label, authProfiles); if ( installed.frontend.retryBudget > 0 && contract.retrySemantics === "NEVER" @@ -592,7 +602,7 @@ function snapshotHttpContract( policy.traffic, TRAFFIC_BUDGET_KEYS, TRAFFIC_BUDGET_KEYS, - reject, + (detail) => reject(`traffic policy ${detail}`), ), }); const source = exactOwnDataSnapshot< @@ -600,8 +610,8 @@ function snapshotHttpContract( >(row.contract, HTTP_CONTRACT_KEYS, HTTP_CONTRACT_KEYS, reject); const contract = Object.freeze({ ...source, - acceptedStatuses: Object.freeze([...source.acceptedStatuses]), - emptyBodyStatuses: Object.freeze([...source.emptyBodyStatuses]), + acceptedStatuses: statusArray(source.acceptedStatuses, reject), + emptyBodyStatuses: statusArray(source.emptyBodyStatuses, reject), commandRecovery: source.commandRecovery === null ? null @@ -615,6 +625,19 @@ function snapshotHttpContract( return Object.freeze({ contract, frontend }); } +/** + * Q-6.7-6. Arrays are copied by index, never through their iterator, so an own + * `Symbol.iterator` cannot hand composition a different list than `length` + * and the indices describe. + */ +function statusArray( + value: readonly number[], + reject: (detail: string) => never, +): readonly number[] { + return (snapshotExactArray(value, 32) as readonly number[] | null) ?? + reject("status array"); +} + function snapshotEventContract( event: InstalledEventContract, label: string, @@ -634,8 +657,14 @@ function snapshotEventContract( */ export function composeContractContributions( contributions: readonly InstalledContractContribution[], + /** + * Q-6.7-9. The registry the executor will resolve against. Pass the same + * one the executor receives; the default is the shared installed registry. + */ + authProfiles: InstalledRestAuthProfiles = INSTALLED_REST_AUTH_PROFILES, ): ComposedContractContributions { - if (!Array.isArray(contributions)) fail("contributions: array required"); + const rows = + snapshotExactArray(contributions) ?? fail("contributions: array required"); const httpByOperationId = new Map< string, InstalledHttpContract @@ -648,7 +677,7 @@ export function composeContractContributions( const contributionIds = new Set(); const installedContributions: InstalledContractContribution[] = []; - for (const raw of contributions) { + for (const raw of rows) { if (!raw || typeof raw !== "object") { fail("contribution: object required"); } @@ -681,9 +710,9 @@ export function composeContractContributions( if (!rawSource || typeof rawSource !== "object" || !("kind" in rawSource)) { fail(`${featureId}: source`); } - if (!Array.isArray(contribution.http) || !Array.isArray(contribution.events)) { - fail(`${featureId}: contribution arrays`); - } + const httpRows = snapshotExactArray(contribution.http); + const eventRows = snapshotExactArray(contribution.events); + if (!httpRows || !eventRows) fail(`${featureId}: contribution arrays`); const rejectSource = (detail: string): never => fail(`${featureId}: source ${detail}`); let source: ContractContributionSource; @@ -740,12 +769,13 @@ export function composeContractContributions( rejectSource, ); if ( + fixture.kind !== "TEMPLATE_FIXTURE" || fixture.fixtureId !== "REFERENCE_FEATURE_V1" || fixture.revision !== 1 ) { fail(`${featureId}: template fixture identity`); } - if (contribution.events.length !== 0) { + if (eventRows.length !== 0) { fail(`${featureId}: template fixture must not contribute events`); } source = fixture; @@ -753,9 +783,12 @@ export function composeContractContributions( fail(`${featureId}: unknown contribution source kind`); } const installedHttp: InstalledHttpContract[] = []; - for (const installed of contribution.http) { - const snapshot = snapshotHttpContract(installed, featureId); - assertHttpContract(snapshot, featureId); + for (const installed of httpRows) { + const snapshot = snapshotHttpContract( + installed as InstalledHttpContract, + featureId, + ); + assertHttpContract(snapshot, featureId, authProfiles); const operationId = snapshot.contract.operationId; const previous = httpByOperationId.get(operationId); if (previous) fail(`duplicate operation: ${operationId}`); @@ -764,8 +797,11 @@ export function composeContractContributions( } const installedEvents: InstalledEventContract[] = []; - for (const event of contribution.events) { - const snapshot = snapshotEventContract(event, featureId); + for (const event of eventRows) { + const snapshot = snapshotEventContract( + event as InstalledEventContract, + featureId, + ); assertEventContract(snapshot, featureId); if (eventByType.has(snapshot.eventType)) { fail(`duplicate event type: ${snapshot.eventType}`); diff --git a/src/contracts/offline-command.ts b/src/contracts/offline-command.ts index 1c57aa91..a6e382ed 100644 --- a/src/contracts/offline-command.ts +++ b/src/contracts/offline-command.ts @@ -7,6 +7,8 @@ * defines server idempotency or an inspect protocol of its own. */ +import { exactOwnDataSnapshot, snapshotExactArray } from "./exact-snapshot.ts"; + export const OFFLINE_COMMAND_BOUNDS = Object.freeze({ operations: 64, defaultRequestBytes: 262_144, @@ -99,6 +101,8 @@ export function isAllowedOfflineTransition( from: OfflineCommandState, to: OfflineCommandState, ): boolean { + // Q-6.7-11. A state that is not listed has no allowed transition. + if (!Object.hasOwn(ALLOWED_TRANSITIONS, from)) return false; const allowed: readonly OfflineCommandState[] = ALLOWED_TRANSITIONS[from]; return allowed.includes(to); } @@ -118,20 +122,52 @@ export interface OfflineCommandSummary { | "DISMISS"; } +const CONTRIBUTION_KEYS = Object.freeze(["datasetId", "operations"] as const); +const OPERATION_KEYS = Object.freeze([ + "operationId", + "contractPackageId", + "maximumRequestBytes", + "retentionClass", +] as const); + +function invalid(detail: string): never { + throw new TypeError(`Offline command contribution is not exact: ${detail}`); +} + +/** + * Q-6.7-7. Validates and returns owned frozen snapshots, so a later write to + * the caller's operation row cannot raise a bound that was already checked. + */ export function validateOfflineCommandContribution( - contribution: InstalledOfflineCommandContribution, + source: InstalledOfflineCommandContribution, ): InstalledOfflineCommandContribution { + const contribution = exactOwnDataSnapshot( + source, + CONTRIBUTION_KEYS, + CONTRIBUTION_KEYS, + invalid, + ); if (contribution.datasetId !== "OFFLINE_COMMANDS_V1") { throw new TypeError("Offline command dataset identity is invalid."); } + const rows = snapshotExactArray(contribution.operations); if ( - contribution.operations.length === 0 || - contribution.operations.length > OFFLINE_COMMAND_BOUNDS.operations + !rows || + rows.length === 0 || + rows.length > OFFLINE_COMMAND_BOUNDS.operations ) { throw new TypeError("Offline command operation count is out of range."); } + const operations = rows.map((row) => + exactOwnDataSnapshot( + row, + OPERATION_KEYS, + OPERATION_KEYS, + invalid, + ), + ); const seen = new Set(); - for (const operation of contribution.operations) { + for (const operation of operations) { if (!operation.operationId || seen.has(operation.operationId)) { throw new TypeError("Duplicate offline command operation."); } @@ -149,6 +185,6 @@ export function validateOfflineCommandContribution( } return Object.freeze({ datasetId: contribution.datasetId, - operations: Object.freeze([...contribution.operations]), + operations: Object.freeze(operations), }); } diff --git a/src/contracts/query-invalidation.ts b/src/contracts/query-invalidation.ts index aa58c336..1a73949d 100644 --- a/src/contracts/query-invalidation.ts +++ b/src/contracts/query-invalidation.ts @@ -4,6 +4,7 @@ import { queryNamespaceIdentityKey, type QueryNamespaceIdentity, } from "./query-keys.ts"; +import { createReadOnlyMap } from "./read-only-registry.ts"; declare const queryInvalidationTopicBrand: unique symbol; @@ -181,14 +182,16 @@ export function indexInvalidationRegistry( } } + // Q-6.7-7. Read facades, not `Map`s: freezing the wrapper object would + // leave `clear()` able to empty the validated fan-out. return Object.freeze({ - namespacesForTopic: new Map( + namespacesForTopic: createReadOnlyMap( [...namespacesForTopic].map(([key, value]) => [ key, Object.freeze([...value]) as readonly QueryNamespaceIdentity[], ]), ), - topicsForNamespace: new Map( + topicsForNamespace: createReadOnlyMap( [...topicsForNamespace].map(([key, value]) => [ key, Object.freeze([...value]) as readonly string[], @@ -229,7 +232,7 @@ export function indexInvalidationTopicVersions( } versions.set(definition.topicId, definition.topicVersion); } - return versions; + return createReadOnlyMap(versions); } export type QueryMutationLease = Readonly<{ diff --git a/src/contracts/query-keys.ts b/src/contracts/query-keys.ts index 2a0f23fc..8de078e3 100644 --- a/src/contracts/query-keys.ts +++ b/src/contracts/query-keys.ts @@ -215,16 +215,16 @@ export function createRuntimeIdentityRegistry( let closed = false; function evictAvailable(requiredBytes: number): void { + const fits = () => + byCanonical.size < maxEntries && + totalCanonicalBytes + requiredBytes <= maxCanonicalBytes; + // Q-6.7-12. Copy and sort the rows only when something must be evicted. + if (fits()) return; const candidates = [...byCanonical.values()] .filter((row) => row.refCount === 0) .sort((left, right) => left.touched - right.touched); for (const row of candidates) { - if ( - byCanonical.size < maxEntries && - totalCanonicalBytes + requiredBytes <= maxCanonicalBytes - ) { - return; - } + if (fits()) return; byCanonical.delete(row.canonical); byToken.delete(row.token); totalCanonicalBytes -= row.canonicalBytes; diff --git a/src/contracts/read-only-registry.ts b/src/contracts/read-only-registry.ts index bc5598bc..a9ecfe3b 100644 --- a/src/contracts/read-only-registry.ts +++ b/src/contracts/read-only-registry.ts @@ -22,9 +22,9 @@ export type ReadOnlyRegistry = Readonly<{ [Symbol.iterator](): IterableIterator; }>; -export function createReadOnlyRegistry( +function readOnlyFacade( entries: Iterable, -): ReadOnlyRegistry { +) { const store = new Map(entries as Iterable<[Key, Value]>); const facade = { get: (key: Key) => store.get(key), @@ -32,58 +32,34 @@ export function createReadOnlyRegistry( keys: () => store.keys(), values: () => store.values(), entries: () => store.entries(), - forEach: (visit: (value: Value, key: Key) => void) => { - for (const [key, value] of store) visit(value, key); + forEach: ( + visit: (value: Value, key: Key, map: ReadonlyMap) => void, + ): void => { + for (const [key, value] of store) visit(value, key, facade); }, get size() { return store.size; }, [Symbol.iterator]: () => store.entries(), }; - return Object.freeze(facade) as ReadOnlyRegistry; + return Object.freeze(facade); +} + +export function createReadOnlyRegistry( + entries: Iterable, +): ReadOnlyRegistry { + return readOnlyFacade(entries); } /** - * Rejects anything that is not an exact own-data record over `allowedKeys`. - * - * A validated row must survive the validation: an accessor re-runs on every - * later read, an inherited field can be replaced through the prototype, and a - * symbol-keyed field escapes a name-based sweep entirely. Only own data - * descriptors are copied, and the result is frozen. + * Q-6.7-7. The same facade for an index already published as a `ReadonlyMap`, + * so the public type stays put while `set`/`delete`/`clear` stop existing. */ -export function exactOwnDataSnapshot( - source: unknown, - allowedKeys: readonly (keyof Shape & string)[], - requiredKeys: readonly (keyof Shape & string)[], - onViolation: (detail: string) => never, -): Readonly { - if (source === null || typeof source !== "object") { - onViolation("object required"); - } - if (Object.getOwnPropertySymbols(source).length > 0) { - onViolation("symbol-keyed field"); - } - // NS-02. A custom prototype carries fields a name sweep never sees, and it - // stays live: replacing one after composition changes what the row answers. - const prototype = Reflect.getPrototypeOf(source); - if (prototype !== Object.prototype && prototype !== null) { - onViolation("unexpected prototype"); - } - const allowed = new Set(allowedKeys); - const snapshot: Record = {}; - for (const key of Object.getOwnPropertyNames(source)) { - if (!allowed.has(key)) onViolation(`unexpected field ${key}`); - const descriptor = Object.getOwnPropertyDescriptor(source, key); - if (!descriptor || !("value" in descriptor)) { - onViolation(`accessor field ${key}`); - } - if (descriptor.enumerable !== true) { - onViolation(`non-enumerable field ${key}`); - } - snapshot[key] = descriptor.value; - } - for (const key of requiredKeys) { - if (!Object.hasOwn(snapshot, key)) onViolation(`missing field ${key}`); - } - return Object.freeze(snapshot) as Readonly; +export function createReadOnlyMap( + entries: Iterable, +): ReadonlyMap { + return readOnlyFacade(entries); } + +/** Kept here for existing importers; the implementation lives in `exact-snapshot.ts`. */ +export { exactOwnDataSnapshot } from "./exact-snapshot.ts"; diff --git a/src/contracts/realtime-streams.ts b/src/contracts/realtime-streams.ts index 4e64512f..42675281 100644 --- a/src/contracts/realtime-streams.ts +++ b/src/contracts/realtime-streams.ts @@ -1,6 +1,11 @@ import type { ApiOperation } from "./api-operations.ts"; import type { InstalledBoundaryMapper } from "./boundary-mapper.ts"; import type { RuntimeSchemaCodec } from "./schema-registry.ts"; +import { + ownDataValue, + snapshotExactArray, + snapshotExactObject, +} from "./exact-snapshot.ts"; declare const streamRegistrationIdBrand: unique symbol; declare const eventTypeIdBrand: unique symbol; @@ -41,8 +46,8 @@ export type RealtimeLimits = Readonly<{ maxDedupeEntries: number; /** * Additional implementation memory ceiling for semantic conflict - * fingerprints. Reaching it has the same recovery meaning as exhausting the - * count/time dedupe window. + * fingerprints. Reaching it evicts the oldest entries, the same as + * exhausting the count/time dedupe window. */ maxDedupeBytes: number; dedupeTtlMs: number; @@ -192,41 +197,45 @@ export function defineRealtimeKillSwitchId(value: string): KillSwitchId { export function createRealtimePolicyRegistry( input: RealtimePolicyRegistryInput, ): RealtimePolicyRegistry { + // Q-6.7-6. Arrays are copied by index, so an own `Symbol.iterator` cannot + // hand the loops below more rows than the bounds checked. + const streamInputs = snapshotExactArray(ownDataValue(input, "streams"), 128); + const eventTypeInputs = snapshotExactArray( + ownDataValue(input, "eventTypes"), + 512, + ); if ( - !input || - typeof input !== "object" || - !Array.isArray(input.streams) || - input.streams.length < 1 || - input.streams.length > 128 || - !Array.isArray(input.eventTypes) || - input.eventTypes.length < 1 || - input.eventTypes.length > 512 + !streamInputs || + streamInputs.length < 1 || + !eventTypeInputs || + eventTypeInputs.length < 1 ) { throw new TypeError("Realtime policy registry is invalid."); } + const bindings = input.bindings; const endpointIds = identifierSet( - input.bindings.endpointIds, + bindings.endpointIds, "endpoint", ); const effectProfileIds = identifierSet( - input.bindings.effectProfileIds, + bindings.effectProfileIds, "effect profile", ); const killSwitchIds = identifierSet( - input.bindings.killSwitchIds, + bindings.killSwitchIds, "kill switch", ); const rebuildInputIds = ownedIdentifierSet( - input.bindings.rebuildInputIds ?? [], + bindings.rebuildInputIds ?? [], "rebuild input", ); const eventTypes = new Map(); - for (const candidate of input.eventTypes) { + for (const candidate of eventTypeInputs) { const registration = snapshotEventType( - candidate, - input.bindings, + candidate as RealtimeEventTypeRegistration, + bindings, effectProfileIds, ); if (eventTypes.has(registration.id)) { @@ -237,10 +246,10 @@ export function createRealtimePolicyRegistry( const streams = new Map(); const referencedEventTypes = new Set(); - for (const candidate of input.streams) { + for (const candidate of streamInputs) { const registration = snapshotStream( - candidate, - input.bindings, + candidate as RealtimeStreamRegistration, + bindings, eventTypes, endpointIds, killSwitchIds, @@ -286,12 +295,13 @@ export function createRealtimePolicyRegistry( } function snapshotEventType( - input: RealtimeEventTypeRegistration, + source: RealtimeEventTypeRegistration, bindings: RealtimePolicyRegistryBindings, effectProfileIds: ReadonlySet, ): RealtimeEventTypeRegistration { + const input = exactRow(source, EVENT_TYPE_KEYS); if ( - !hasExactKeys(input, EVENT_TYPE_KEYS) || + !input || !REGISTRY_ID.test(input.id) || !OWNER.test(input.owner) || !OWNED_ID.test(input.payloadSchemaId) || @@ -307,19 +317,23 @@ function snapshotEventType( ) { throw new TypeError("Realtime event type registration is invalid."); } - return Object.freeze({ ...input }); + return input; } function snapshotStream( - input: RealtimeStreamRegistration, + source: RealtimeStreamRegistration, bindings: RealtimePolicyRegistryBindings, eventTypes: ReadonlyMap, endpointIds: ReadonlySet, killSwitchIds: ReadonlySet, rebuildInputIds: ReadonlySet, ): RealtimeStreamRegistration { + const input = exactRow(source, STREAM_KEYS); + const eventTypeIds = snapshotExactArray(input?.eventTypeIds, 128) as + | readonly EventTypeId[] + | null; if ( - !hasExactKeys(input, STREAM_KEYS) || + !input || !REGISTRY_ID.test(input.id) || input.protocol !== REALTIME_EVENT_PROTOCOL || !OWNER.test(input.owner) || @@ -329,11 +343,10 @@ function snapshotStream( !["SSE", "WEBSOCKET", "NONE"].includes(input.primaryTransport) || !REGISTRY_ID.test(input.endpointId) || !endpointIds.has(input.endpointId) || - !Array.isArray(input.eventTypeIds) || - input.eventTypeIds.length < 1 || - input.eventTypeIds.length > 128 || - new Set(input.eventTypeIds).size !== input.eventTypeIds.length || - input.eventTypeIds.some( + !eventTypeIds || + eventTypeIds.length < 1 || + new Set(eventTypeIds).size !== eventTypeIds.length || + eventTypeIds.some( (eventTypeId) => !REGISTRY_ID.test(eventTypeId) || !eventTypes.has(eventTypeId), ) || @@ -354,7 +367,7 @@ function snapshotStream( bindings, rebuildInputIds, ); - const selectedEventTypes = input.eventTypeIds.map((eventTypeId) => { + const selectedEventTypes = eventTypeIds.map((eventTypeId) => { const selected = eventTypes.get(eventTypeId); if (!selected) { throw new TypeError("Realtime stream event type is unresolved."); @@ -384,61 +397,55 @@ function snapshotStream( throw new TypeError("Realtime stream recovery contract is contradictory."); } - return Object.freeze({ - ...input, - eventTypeIds: Object.freeze([...input.eventTypeIds]), - recovery, - limits, - }); + return Object.freeze({ ...input, eventTypeIds, recovery, limits }); } +const SNAPSHOT_RECOVERY_KEYS = Object.freeze([ + "barrier", + "checkpointCodecId", + "mode", + "snapshotOperationId", +] as const); +const SESSION_REBUILD_KEYS = Object.freeze(["mode", "rebuildInputId"] as const); + function snapshotRecovery( - input: RealtimeRecoveryProfile, + source: RealtimeRecoveryProfile, bindings: RealtimePolicyRegistryBindings, rebuildInputIds: ReadonlySet, ): RealtimeRecoveryProfile { - if (!input || typeof input !== "object") { + // The mode only picks the key set; every check below reads the snapshot. + const input = exactRow( + source, + ownDataValue(source, "mode") === "SESSION_REBUILD" + ? SESSION_REBUILD_KEYS + : SNAPSHOT_RECOVERY_KEYS, + ); + if (!input) { throw new TypeError("Realtime recovery profile is invalid."); } if (input.mode === "CURSOR") { - if ( - !hasExactKeys(input, [ - "barrier", - "checkpointCodecId", - "mode", - "snapshotOperationId", - ]) || - input.barrier !== "REPLAY" || - !validSnapshotBindings(input, bindings) - ) { + if (input.barrier !== "REPLAY" || !validSnapshotBindings(input, bindings)) { throw new TypeError("Realtime cursor recovery profile is invalid."); } - return Object.freeze({ ...input }); + return input; } if (input.mode === "SNAPSHOT_ONLY") { if ( - !hasExactKeys(input, [ - "barrier", - "checkpointCodecId", - "mode", - "snapshotOperationId", - ]) || !["CONNECT_BUFFER", "SERVER_HOLD", "NONE"].includes(input.barrier) || !validSnapshotBindings(input, bindings) ) { throw new TypeError("Realtime snapshot recovery profile is invalid."); } - return Object.freeze({ ...input }); + return input; } if ( input.mode !== "SESSION_REBUILD" || - !hasExactKeys(input, ["mode", "rebuildInputId"]) || !OWNED_ID.test(input.rebuildInputId) || !rebuildInputIds.has(input.rebuildInputId) ) { throw new TypeError("Realtime session rebuild profile is invalid."); } - return Object.freeze({ ...input }); + return input; } function validSnapshotBindings( @@ -462,8 +469,9 @@ function validSnapshotBindings( ); } -function snapshotLimits(input: RealtimeLimits): RealtimeLimits { - if (!hasExactKeys(input, LIMIT_KEYS)) { +function snapshotLimits(source: RealtimeLimits): RealtimeLimits { + const input = exactRow(source, LIMIT_KEYS); + if (!input) { throw new TypeError("Realtime limits are invalid."); } for (const key of LIMIT_KEYS) { @@ -482,14 +490,15 @@ function snapshotLimits(input: RealtimeLimits): RealtimeLimits { ) { throw new TypeError("Realtime memory limits cannot hold one event."); } - return Object.freeze({ ...input }); + return input; } function identifierSet( - values: readonly string[], + source: readonly string[], label: string, ): ReadonlySet { - if (!Array.isArray(values)) { + const values = snapshotExactArray(source) as readonly string[] | null; + if (!values) { throw new TypeError(`Realtime ${label} bindings are invalid.`); } const result = new Set(); @@ -503,10 +512,11 @@ function identifierSet( } function ownedIdentifierSet( - values: readonly string[], + source: readonly string[], label: string, ): ReadonlySet { - if (!Array.isArray(values)) { + const values = snapshotExactArray(source) as readonly string[] | null; + if (!values) { throw new TypeError(`Realtime ${label} bindings are invalid.`); } const result = new Set(); @@ -526,23 +536,9 @@ function defineRegistryId(value: string, label: string): string { return value; } -function hasExactKeys( - value: unknown, - expected: readonly string[], -): value is Readonly> { - if ( - !value || - typeof value !== "object" || - Array.isArray(value) || - (Object.getPrototypeOf(value) !== Object.prototype && - Object.getPrototypeOf(value) !== null) - ) { - return false; - } - const keys = Object.keys(value).sort(); - const selected = [...expected].sort(); - return ( - keys.length === selected.length && - keys.every((key, index) => key === selected[index]) - ); +/** Q-6.7-6. One owned read of an exact row; checks run on the copy. */ +function exactRow(source: unknown, keys: readonly string[]): Row | null { + return snapshotExactObject(source, { allowed: keys, required: keys }) as + | Row + | null; } diff --git a/src/contracts/release-tokens.ts b/src/contracts/release-tokens.ts index 1c4135ef..e9d5a6d0 100644 --- a/src/contracts/release-tokens.ts +++ b/src/contracts/release-tokens.ts @@ -32,11 +32,19 @@ function token(name: string, source: string, compatibilityRole: string) { return Object.freeze({ token: name, source, compatibilityRole }); } +/** + * Q-6.7-12. Runtime configuration carries no asset manifest hash, so that + * field is never compared. It used to be filled from the release itself and + * therefore read as a pass; it is reported as unverified instead. + */ +const UNVERIFIED_BY_RUNTIME_CONFIG = Object.freeze([ + "assetManifestHash", +] as const); + /** * Compare a release manifest and runtime configuration structurally. Version * fields are delegated to the numeric compatibility policy, never compared * lexically. - * */ export function compareReleaseToRuntime( release: Readonly<{ @@ -53,14 +61,16 @@ export function compareReleaseToRuntime( RELEASE_ID: string; }>, ) { - return verifyCompatibilityTuple({ + const result = verifyCompatibilityTuple({ frontend: release, runtime: { buildId: runtimeConfig.BUILD_ID, configSchemaVersion: runtimeConfig.CONFIG_SCHEMA_VERSION, apiContractVersion: runtimeConfig.API_CONTRACT_VERSION, + // Placeholder only; see UNVERIFIED_BY_RUNTIME_CONFIG. assetManifestHash: release.assetManifestHash, releaseId: runtimeConfig.RELEASE_ID, }, }); + return Object.freeze({ ...result, unverified: UNVERIFIED_BY_RUNTIME_CONFIG }); } diff --git a/src/contracts/rest-profiles.ts b/src/contracts/rest-profiles.ts index 317f3b05..9010708a 100644 --- a/src/contracts/rest-profiles.ts +++ b/src/contracts/rest-profiles.ts @@ -2,6 +2,8 @@ import { createReadOnlyRegistry, type ReadOnlyRegistry, } from "./read-only-registry.ts"; +import { snapshotExactArray, snapshotExactObject } from "./exact-snapshot.ts"; +import { isLoopbackHostname } from "./deployment-admission.ts"; export type FetchCredentialsMode = "omit" | "same-origin" | "include"; @@ -80,10 +82,12 @@ function isCredentialHeaderName(value: unknown): value is CredentialHeaderName { } function exactHeaderSet( - names: unknown, + source: unknown, label: string, ): readonly CredentialHeaderName[] { - if (!Array.isArray(names)) { + // Q-6.7-6. Copied by index, so the set that is checked is the set installed. + const names = snapshotExactArray(source); + if (!names) { throw new TypeError(`REST auth profile ${label} must be an array.`); } const seen = new Set(); @@ -93,9 +97,17 @@ function exactHeaderSet( } seen.add(name); } - return Object.freeze([...(names as readonly CredentialHeaderName[])]); + return names as readonly CredentialHeaderName[]; } +const AUTH_PROFILE_KEYS = Object.freeze([ + "authProfileId", + "transport", + "credentials", + "allowedCredentialHeaders", + "requiredCredentialHeaders", +] as const); + /** * §7.7 / VD-23. Installs the composition-owned auth profile registry once. * @@ -107,9 +119,16 @@ export function installRestAuthProfileRegistry( profiles: Readonly> = REST_AUTH_PROFILES, ): InstalledRestAuthProfiles { const installed = new Map(); - for (const [key, candidate] of Object.entries(profiles)) { - if (!candidate || typeof candidate !== "object") { - throw new TypeError(`REST auth profile ${key} is not an object.`); + for (const [key, source] of Object.entries(profiles)) { + // Q-6.7-6. Every check reads one owned snapshot, never the caller's row. + const candidate = snapshotExactObject(source, { + allowed: AUTH_PROFILE_KEYS, + required: AUTH_PROFILE_KEYS, + }) as RestAuthProfile | null; + if (!candidate) { + throw new TypeError( + `REST auth profile ${key} is not an exact own-data object.`, + ); } const authProfileId = candidate.authProfileId; if ( @@ -179,7 +198,35 @@ export function installRestAuthProfileRegistry( if (installed.size === 0) { throw new TypeError("REST auth profile registry cannot be empty."); } - return createReadOnlyRegistry(installed); + const registry = createReadOnlyRegistry(installed); + INSTALLED_REGISTRIES.add(registry); + return registry; +} + +/** Registries this module installed, as opposed to look-alike objects. */ +const INSTALLED_REGISTRIES = new WeakSet(); + +/** + * REST auth profiles as accepted by resolve: the installed registry, or a raw + * record that is installed (validated) before any lookup. + */ +export type RestAuthProfileSource = + | InstalledRestAuthProfiles + | Readonly>; + +/** + * Q-6.7-9. Composition, the V3 executor and V2 resolve answer from one + * validated registry. A raw record never reaches a lookup unvalidated, so a + * profile installation would refuse cannot be resolved either. + */ +function installedAuthProfiles( + profiles: RestAuthProfileSource, +): InstalledRestAuthProfiles { + return INSTALLED_REGISTRIES.has(profiles) + ? (profiles as InstalledRestAuthProfiles) + : installRestAuthProfileRegistry( + profiles as Readonly>, + ); } /** The single installed registry every composition root shares. */ @@ -202,7 +249,7 @@ export function createRestProviderProfile( const parsed = new URL(baseUrl); const localHttp = parsed.protocol === "http:" && - ["localhost", "127.0.0.1", "[::1]"].includes(parsed.hostname); + isLoopbackHostname(parsed.hostname); if ( !providerId || (parsed.protocol !== "https:" && !localHttp) || @@ -232,11 +279,16 @@ export function resolveRestSecurityProfiles( csrfProfileId?: string; }>, provider: RestProviderProfile, - authProfiles: Readonly> = REST_AUTH_PROFILES, + authProfiles: RestAuthProfileSource = INSTALLED_REST_AUTH_PROFILES, csrfProfiles: Readonly> = REST_CSRF_PROFILES, ): Readonly<{ auth: RestAuthProfile; csrf: RestCsrfProfile }> { - const auth = authProfiles[operation.authProfileId ?? ""]; - const csrf = csrfProfiles[operation.csrfProfileId ?? ""]; + const auth = installedAuthProfiles(authProfiles).get( + operation.authProfileId ?? "", + ); + const csrfProfileId = operation.csrfProfileId ?? ""; + const csrf = Object.hasOwn(csrfProfiles, csrfProfileId) + ? csrfProfiles[csrfProfileId] + : undefined; const unsafe = !["GET", "HEAD", "OPTIONS"].includes(operation.method); if ( !auth || @@ -273,9 +325,10 @@ export function validateRestProfileBindings( providerCredentialModes: Readonly< Record >, - authProfiles: Readonly> = REST_AUTH_PROFILES, + authProfiles: RestAuthProfileSource = INSTALLED_REST_AUTH_PROFILES, csrfProfiles: Readonly> = REST_CSRF_PROFILES, ): true { + const installed = installedAuthProfiles(authProfiles); for (const operation of Object.values(operations)) { if (operation.contractVersion !== 2) continue; const allowed = providerCredentialModes[operation.providerId ?? ""]; @@ -293,7 +346,7 @@ export function validateRestProfileBindings( redirect: "error", referrerPolicy: "no-referrer", }), - authProfiles, + installed, csrfProfiles, ); } diff --git a/src/contracts/runtime-capabilities.ts b/src/contracts/runtime-capabilities.ts index e6d448fc..97232c8b 100644 --- a/src/contracts/runtime-capabilities.ts +++ b/src/contracts/runtime-capabilities.ts @@ -1,6 +1,11 @@ import type { InstalledOfflineCommandContribution } from "./offline-command.ts"; import type { InstalledServiceWorkerSelection } from "./service-worker.ts"; import type { InstalledWebWorkerContribution } from "./web-worker.ts"; +import { + exactOwnDataSnapshot, + ownDataValue, + snapshotExactArray, +} from "./exact-snapshot.ts"; /** * §3.4–§3.6. Optional runtime capability selection and hosting. @@ -129,18 +134,95 @@ export function resolveRuntimeCapabilities( }); } +const REALTIME_CONTRIBUTION_KEYS = Object.freeze([ + "contributionId", + "featureId", + "contractSourcePackageId", + "streamId", + "recoveryMode", + "eventEffects", + "transport", +] as const); +const EVENT_EFFECT_KEYS = Object.freeze([ + "eventType", + "mapperId", + "effect", + "invalidationTopics", +] as const); +const ENDPOINT_TRANSPORT_KEYS = Object.freeze(["kind", "endpointId"] as const); +const POLLING_TRANSPORT_KEYS = Object.freeze([ + "kind", + "operationId", + "intervalMs", +] as const); + +function invalidRealtime(detail: string): never { + throw new TypeError(`Realtime contribution is not exact: ${detail}`); +} + +function snapshotTransport(source: unknown): InstalledRealtimeTransport { + const polling = ownDataValue(source, "kind") === "POLLING"; + const keys = polling ? POLLING_TRANSPORT_KEYS : ENDPOINT_TRANSPORT_KEYS; + const transport = exactOwnDataSnapshot>( + source, + keys, + keys, + invalidRealtime, + ) as InstalledRealtimeTransport; + // The key set was chosen by one read; the snapshot must agree with it. + if ((transport.kind === "POLLING") !== polling) invalidRealtime("transport"); + return transport; +} + +function snapshotEventEffect(source: unknown): InstalledRealtimeEventEffect { + const effect = exactOwnDataSnapshot( + source, + EVENT_EFFECT_KEYS, + EVENT_EFFECT_KEYS, + invalidRealtime, + ); + const topics = + snapshotExactArray(effect.invalidationTopics) ?? + invalidRealtime("invalidationTopics"); + return Object.freeze({ + ...effect, + invalidationTopics: topics as readonly string[], + }); +} + +/** + * Q-6.7-7. Validates and returns owned frozen snapshots, so a later write to + * the caller's row cannot change a polling interval or topic list that was + * already checked. + */ export function validateRealtimeContributions( - contributions: readonly InstalledRealtimeContribution[], + source: readonly InstalledRealtimeContribution[], ): readonly InstalledRealtimeContribution[] { const bounds = REALTIME_CONTRIBUTION_BOUNDS; - if (contributions.length > bounds.contributions) { + const rows = snapshotExactArray(source) ?? invalidRealtime("array required"); + if (rows.length > bounds.contributions) { throw new TypeError("Realtime contributions exceed their bound."); } const contributionIds = new Set(); const streamIds = new Set(); let eventTypeCount = 0; + const installed: InstalledRealtimeContribution[] = []; - for (const contribution of contributions) { + for (const row of rows) { + const outer = exactOwnDataSnapshot( + row, + REALTIME_CONTRIBUTION_KEYS, + REALTIME_CONTRIBUTION_KEYS, + invalidRealtime, + ); + const effectRows = + snapshotExactArray(outer.eventEffects) ?? + invalidRealtime("eventEffects"); + const contribution: InstalledRealtimeContribution = Object.freeze({ + ...outer, + eventEffects: Object.freeze(effectRows.map(snapshotEventEffect)), + transport: snapshotTransport(outer.transport), + }); if ( !contribution.contributionId || contributionIds.has(contribution.contributionId) @@ -195,8 +277,9 @@ export function validateRealtimeContributions( ); } } + installed.push(contribution); } - return Object.freeze([...contributions]); + return Object.freeze(installed); } export type RuntimeCapabilityId = diff --git a/src/contracts/schema-registry.ts b/src/contracts/schema-registry.ts index 2ce68194..ace442c1 100644 --- a/src/contracts/schema-registry.ts +++ b/src/contracts/schema-registry.ts @@ -1,3 +1,4 @@ +import type { RuntimeValidator } from "./external-contract-runtime.ts"; import { projectValidationIssues } from "./validation-issues.ts"; export type SchemaDefinition = Readonly<{ @@ -22,11 +23,37 @@ export type RuntimeSchemaResult = issues: readonly Readonly<{ path: string; code: string }>[]; }>; +/** + * D-15. The registry-facing form of the canonical `RuntimeValidator` + * (`external-contract-runtime.ts`): same `schemaId`, `parse` instead of + * `safeParse`, and dotted string paths. Build one from a validator with + * `runtimeSchemaCodecFromValidator` rather than wrapping a schema twice. + */ export type RuntimeSchemaCodec = Readonly<{ schemaId: string; parse(value: unknown): RuntimeSchemaResult; }>; +export function runtimeSchemaCodecFromValidator( + validator: RuntimeValidator, +): RuntimeSchemaCodec { + return Object.freeze({ + schemaId: validator.schemaId, + parse(value: unknown): RuntimeSchemaResult { + const result = validator.safeParse(value); + if (result.success) return result; + return Object.freeze({ + success: false as const, + issues: Object.freeze( + result.issues.map((issue) => + Object.freeze({ path: issue.path.join("."), code: issue.code }), + ), + ), + }); + }, + }); +} + export function composeRuntimeSchemaCodecs( contributions: readonly Readonly>[], ): Readonly> { @@ -52,7 +79,9 @@ export function validateWithRuntimeSchemaRegistry( value: unknown, registry: Readonly>, ): RuntimeSchemaResult { - const codec = registry[schemaId]; + const codec = Object.hasOwn(registry, schemaId) + ? registry[schemaId] + : undefined; if (!codec) { return Object.freeze({ success: false, diff --git a/src/contracts/service-worker-static-manifest.ts b/src/contracts/service-worker-static-manifest.ts index 86c2f051..6d556fdd 100644 --- a/src/contracts/service-worker-static-manifest.ts +++ b/src/contracts/service-worker-static-manifest.ts @@ -1,4 +1,5 @@ import { SERVICE_WORKER_BOUNDS } from "./service-worker.ts"; +import { snapshotExactArray, snapshotExactObject } from "./exact-snapshot.ts"; /** * SW-05. Runtime-neutral static manifest codec. @@ -95,18 +96,12 @@ export type StaticManifestDecodeResult = | Readonly<{ ok: true; manifest: StaticAssetManifest }> | Readonly<{ ok: false; error: StaticManifestDecodeFailure }>; +/** Q-6.7-6. One owned read per field; the checks never touch the source. */ function exactKeys( value: unknown, - allowed: readonly string[], -): Record | null { - if (!value || typeof value !== "object" || Array.isArray(value)) return null; - const record = value as Record; - if (Object.getOwnPropertySymbols(record).length > 0) return null; - const keys = Object.keys(record).sort(); - return keys.length === allowed.length && - keys.every((key, index) => key === allowed[index]) - ? record - : null; + keys: readonly string[], +): Readonly> | null { + return snapshotExactObject(value, { allowed: keys, required: keys }); } function extensionOf(url: string): string { @@ -142,12 +137,15 @@ export function decodeStaticAssetManifest( if (record.assets.length > SERVICE_WORKER_BOUNDS.assets) { return failure("asset count exceeds its bound"); } + // Copied by index, so an own `Symbol.iterator` cannot yield unbounded rows. + const assets = snapshotExactArray(record.assets, SERVICE_WORKER_BOUNDS.assets); + if (!assets) return failure("assets must be an array"); const rows: StaticAssetRow[] = []; const seen = new Set(); let totalBytes = 0; let previousUrl: string | null = null; - for (const candidate of record.assets) { + for (const candidate of assets) { const row = exactKeys(candidate, ASSET_ROW_KEYS); if (!row) return failure("asset row keys are not exact"); const { url, sha256, bytes, contentType } = row; diff --git a/src/contracts/service-worker.ts b/src/contracts/service-worker.ts index 0dc5ef66..51004f16 100644 --- a/src/contracts/service-worker.ts +++ b/src/contracts/service-worker.ts @@ -17,6 +17,11 @@ export const SERVICE_WORKER_BOUNDS = Object.freeze({ fetchConcurrency: 4, installDeadlineMs: 60_000, clientDrainMs: 30_000, + /** + * Q-6.6-10b. The page waits the worker's whole drain window plus this, so + * a drain that ends just in time is followed by skipWaiting() and the reply. + */ + activationReplySlackMs: 5_000, updateCheckIntervalMs: 6 * 60 * 60 * 1_000, retainedPreviousCaches: 1, reloadGuardBytes: 512, diff --git a/src/contracts/storage-keys.ts b/src/contracts/storage-keys.ts index fb71082e..0537041c 100644 --- a/src/contracts/storage-keys.ts +++ b/src/contracts/storage-keys.ts @@ -172,7 +172,9 @@ export function buildPhysicalKey( export function getStorageDefinition(logicalName: string): StorageDefinition { const registry: Readonly> = STORAGE_REGISTRY; - const definition = registry[logicalName]; + const definition = Object.hasOwn(registry, logicalName) + ? registry[logicalName] + : undefined; if (!definition) throw new Error(`Unregistered storage key: ${logicalName}`); if (definition.classification === "sensitive-forbidden") { throw new Error(`Forbidden storage key: ${logicalName}`); diff --git a/src/contracts/web-worker.ts b/src/contracts/web-worker.ts index 894e9c9c..07160861 100644 --- a/src/contracts/web-worker.ts +++ b/src/contracts/web-worker.ts @@ -7,6 +7,8 @@ * runtime is separate from the OPFS dedicated worker and the Service Worker. */ +import { exactOwnDataSnapshot, snapshotExactArray } from "./exact-snapshot.ts"; + export const WEB_WORKER_PROTOCOL = "CA_WEB_WORKER_V1" as const; export const WEB_WORKER_BOUNDS = Object.freeze({ @@ -93,27 +95,66 @@ export type WorkerResponseMessage = code: WorkerFailureCode; }>; +const CONTRIBUTION_KEYS = Object.freeze([ + "taskGroupId", + "tasks", + "fallback", +] as const); +const TASK_KEYS = Object.freeze([ + "taskId", + "taskVersion", + "maximumInputBytes", + "maximumOutputBytes", + "deadlineMs", +] as const); + +function invalid(detail: string): never { + throw new TypeError(`Web Worker contribution is not exact: ${detail}`); +} + +/** + * Q-6.7-7. Validates and returns owned frozen snapshots, so a later write to + * the caller's task row cannot raise a bound that was already checked. + */ export function validateWebWorkerContributions( - contributions: readonly InstalledWebWorkerContribution[], + source: readonly InstalledWebWorkerContribution[], ): readonly InstalledWebWorkerContribution[] { const bounds = WEB_WORKER_BOUNDS; - if (contributions.length > bounds.taskGroups) { + const rows = snapshotExactArray(source) ?? invalid("array required"); + if (rows.length > bounds.taskGroups) { throw new TypeError("Web Worker task groups exceed their bound."); } const groupIds = new Set(); const taskIds = new Set(); - for (const contribution of contributions) { + const installed: InstalledWebWorkerContribution[] = []; + for (const row of rows) { + const contribution = exactOwnDataSnapshot( + row, + CONTRIBUTION_KEYS, + CONTRIBUTION_KEYS, + invalid, + ); if (!contribution.taskGroupId || groupIds.has(contribution.taskGroupId)) { throw new TypeError("Web Worker task group identity is invalid."); } groupIds.add(contribution.taskGroupId); + const taskRows = snapshotExactArray(contribution.tasks); if ( - contribution.tasks.length === 0 || - contribution.tasks.length > bounds.tasksPerGroup + !taskRows || + taskRows.length === 0 || + taskRows.length > bounds.tasksPerGroup ) { throw new TypeError("Web Worker task count is out of range."); } - for (const task of contribution.tasks) { + const tasks = taskRows.map((taskRow) => + exactOwnDataSnapshot( + taskRow, + TASK_KEYS, + TASK_KEYS, + invalid, + ), + ); + for (const task of tasks) { const qualified = `${contribution.taskGroupId}/${task.taskId}`; if (!task.taskId || taskIds.has(qualified)) { throw new TypeError("Duplicate Web Worker task."); @@ -134,6 +175,9 @@ export function validateWebWorkerContributions( throw new TypeError(`Web Worker task bounds invalid: ${qualified}`); } } + installed.push( + Object.freeze({ ...contribution, tasks: Object.freeze(tasks) }), + ); } - return Object.freeze([...contributions]); + return Object.freeze(installed); } diff --git a/src/features/feature-adapter-contribution.ts b/src/features/feature-adapter-contribution.ts index 6e657e9d..d58eee8e 100644 --- a/src/features/feature-adapter-contribution.ts +++ b/src/features/feature-adapter-contribution.ts @@ -155,6 +155,7 @@ export function composeFeatureAdapterInputs< context: ContributionsCapabilityContext, ): InstalledFeatureInputs { const enabled = new Set(enabledFeatureIds); + const seen = new Set(); const result: Partial = {}; for (const contribution of contributions) { @@ -163,6 +164,15 @@ export function composeFeatureAdapterInputs< "Feature adapter contribution must be defined through defineFeatureAdapterContribution()", ); } + // Q-6.9-6. Route codecs and message catalogs throw on a duplicate; this + // registry silently let the later contribution win, so a feature copied + // without renaming its id replaced the original's API. + if (seen.has(contribution.featureId)) { + throw new TypeError( + `duplicate feature adapter contribution: ${contribution.featureId}`, + ); + } + seen.add(contribution.featureId); if (!enabled.has(contribution.featureId)) continue; const installed = invokeContribution( @@ -172,6 +182,11 @@ export function composeFeatureAdapterInputs< >, context as FeaturePlatformCapabilities, ); + if (installed.featureId !== contribution.featureId) { + throw new TypeError( + `feature adapter contribution ${contribution.featureId} installed an input for ${String(installed.featureId)}`, + ); + } setFeatureInput(result, installed.featureId, installed.input); } diff --git a/src/features/installed-feature-adapters.ts b/src/features/installed-feature-adapters.ts index 165f38ec..fbea274b 100644 --- a/src/features/installed-feature-adapters.ts +++ b/src/features/installed-feature-adapters.ts @@ -16,13 +16,22 @@ type InstalledFeatureCapabilityContext = ContributionsCapabilityContext< /** * Adapter installation is a projection of feature-owned descriptors. Adding a * feature changes its descriptor and the generated index, not this composer. + * + * Q-6.9-5. The runtime composer passes `activeFeatureIds` (installed minus + * `FEATURE_OVERRIDES`). A feature switched off there gets no input, so + * `application.features.get()` cannot hand out its API; the router was the + * only place that honoured the switch before. The default (every installed + * feature) is for callers that have no runtime configuration. */ export function createInstalledFeatureInputs( context: InstalledFeatureCapabilityContext, + activeFeatureIds: readonly string[] = INSTALLED_PRODUCT_FEATURE_MODULES.map( + (module) => module.id, + ), ): InstalledFeatureInputs { return composeFeatureAdapterInputs( INSTALLED_FEATURE_ADAPTER_CONTRIBUTIONS, - INSTALLED_PRODUCT_FEATURE_MODULES.map((module) => module.id), + activeFeatureIds, context, ); } diff --git a/src/features/installed-feature-messages.ts b/src/features/installed-feature-messages.ts index b6aa5763..ecd72782 100644 --- a/src/features/installed-feature-messages.ts +++ b/src/features/installed-feature-messages.ts @@ -1,3 +1,4 @@ +import type { FeatureMessageCatalogs } from "./feature-module.ts"; import { INSTALLED_PRODUCT_FEATURE_MODULES } from "./installed-product-manifest.ts"; type InstalledModule = (typeof INSTALLED_PRODUCT_FEATURE_MODULES)[number]; @@ -13,26 +14,44 @@ type LocaleCatalog = UnionToIntersection< : Readonly> : never >; +type InstalledLocale = InstalledModule extends unknown + ? Extract + : never; -function composeLocale(locale: Locale): LocaleCatalog { - const result: Record = {}; - for (const module of INSTALLED_PRODUCT_FEATURE_MODULES) { - const catalogs = module.messages as Readonly< - Record>> - >; - const catalog = catalogs[locale]; - if (!catalog) continue; - for (const [key, value] of Object.entries(catalog)) { - if (Object.hasOwn(result, key)) { - throw new TypeError(`Duplicate ${locale} message key: ${key}`); +/** + * Q-6.9-12. One catalog per locale that any installed feature declares. The + * locale list used to be fixed at ko-KR/en-US, so a feature's other catalogs + * were dropped without a word. A key two features define for one locale + * still throws. + */ +export function composeInstalledMessageCatalogs( + modules: readonly Readonly<{ messages: FeatureMessageCatalogs }>[], +): Readonly>>> { + const locales = new Map>(); + for (const module of modules) { + for (const [locale, catalog] of Object.entries(module.messages)) { + let result = locales.get(locale); + if (!result) { + result = {}; + locales.set(locale, result); + } + for (const [key, value] of Object.entries(catalog)) { + if (Object.hasOwn(result, key)) { + throw new TypeError(`Duplicate ${locale} message key: ${key}`); + } + result[key] = value; } - result[key] = value; } } - return Object.freeze(result) as LocaleCatalog; + return Object.freeze( + Object.fromEntries( + [...locales].map(([locale, catalog]) => [locale, Object.freeze(catalog)]), + ), + ); } -export const INSTALLED_MESSAGE_CATALOGS = Object.freeze({ - "ko-KR": composeLocale("ko-KR"), - "en-US": composeLocale("en-US"), -} as const); +export const INSTALLED_MESSAGE_CATALOGS = composeInstalledMessageCatalogs( + INSTALLED_PRODUCT_FEATURE_MODULES, +) as { + readonly [Locale in InstalledLocale]: LocaleCatalog; +}; diff --git a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts index 48003b2a..48985218 100644 --- a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts +++ b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts @@ -4,7 +4,6 @@ import type { CommandEffectDescriptor, InstalledContractContribution, InstalledHttpContract, - RuntimeValidator, } from "../../../contracts/external-contract-runtime.ts"; import { REFERENCE_FEATURE_ID } from "./reference-feature-contract.ts"; import { @@ -14,6 +13,7 @@ import { referenceResourceListQuerySchema, referenceResourceParamsSchema, type ReferenceProblem, + zodValidator, } from "./reference-schemas.ts"; export type { ReferenceProblem } from "./reference-schemas.ts"; @@ -25,39 +25,6 @@ export type { ReferenceProblem } from "./reference-schemas.ts"; * import it from its own `contracts/-contract-contribution.ts`. */ -function zodValidator( - schemaId: string, - schema: z.ZodType, -): RuntimeValidator { - return Object.freeze({ - schemaId, - safeParse(value: unknown) { - const result = schema.safeParse(value); - if (result.success) { - return Object.freeze({ - success: true as const, - data: structuredClone(result.data), - }); - } - return Object.freeze({ - success: false as const, - issues: Object.freeze( - result.error.issues.map((issue) => - Object.freeze({ - path: Object.freeze( - issue.path.map((segment): string | number => - typeof segment === "number" ? segment : String(segment), - ), - ), - code: String(issue.code), - }), - ), - ), - }); - }, - }); -} - const PROBLEM_VALIDATOR = zodValidator( "ReferenceProblem", referenceProblemSchema, diff --git a/src/features/reference-feature/contracts/reference-schemas.ts b/src/features/reference-feature/contracts/reference-schemas.ts index dff64aad..62372639 100644 --- a/src/features/reference-feature/contracts/reference-schemas.ts +++ b/src/features/reference-feature/contracts/reference-schemas.ts @@ -1,5 +1,6 @@ import { z } from "zod"; -import type { RuntimeSchemaCodec } from "../../../contracts/schema-registry.ts"; +import type { RuntimeValidator } from "../../../contracts/external-contract-runtime.ts"; +import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts"; export const referenceResourceListQuerySchema = z .object({ @@ -67,28 +68,47 @@ const requestSchemas = { CreateReferenceResourceCommand: createReferenceResourceCommandSchema, } satisfies Record; -function project(result: z.ZodSafeParseResult) { - return result.success - ? ({ success: true as const, data: structuredClone(result.data) }) - : ({ - success: false as const, - issues: result.error.issues.map((issue) => ({ - path: issue.path.join("."), - code: issue.code, - })), - }); -} - -function codec( +/** + * D-15. The one zod wrapper: every reference schema is exposed through the + * canonical `RuntimeValidator`, and the registry codecs below are adapters + * over it. + */ +export function zodValidator( schemaId: string, - schema: z.ZodType, -): RuntimeSchemaCodec { + schema: z.ZodType, +): RuntimeValidator { return Object.freeze({ schemaId, - parse: (value: unknown) => project(schema.safeParse(value)), + safeParse(value: unknown) { + const result = schema.safeParse(value); + if (result.success) { + return Object.freeze({ + success: true as const, + data: structuredClone(result.data), + }); + } + return Object.freeze({ + success: false as const, + issues: Object.freeze( + result.error.issues.map((issue) => + Object.freeze({ + path: Object.freeze( + issue.path.map((segment): string | number => + typeof segment === "number" ? segment : String(segment), + ), + ), + code: String(issue.code), + }), + ), + ), + }); + }, }); } +const codec = (schemaId: string, schema: z.ZodType) => + runtimeSchemaCodecFromValidator(zodValidator(schemaId, schema)); + export const REFERENCE_RUNTIME_SCHEMA_CODECS = Object.freeze({ ReferenceResourceParams: codec( "ReferenceResourceParams", @@ -113,16 +133,29 @@ export const REFERENCE_RUNTIME_SCHEMA_CODECS = Object.freeze({ ), }); +const NOT_REGISTERED = Object.freeze({ + success: false as const, + issues: Object.freeze([ + Object.freeze({ path: "", code: "SCHEMA_NOT_REGISTERED" }), + ]), +}); + +function validateOwned( + owned: Readonly>, + schemaId: string, + value: unknown, +) { + return Object.hasOwn(owned, schemaId) + ? REFERENCE_RUNTIME_SCHEMA_CODECS[ + schemaId as keyof typeof REFERENCE_RUNTIME_SCHEMA_CODECS + ].parse(value) + : NOT_REGISTERED; +} + export function validateReferencePayload(schemaId: string, value: unknown) { - const schema = payloadSchemas[schemaId as keyof typeof payloadSchemas]; - return schema - ? project(schema.safeParse(value)) - : { success: false as const, issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }] }; + return validateOwned(payloadSchemas, schemaId, value); } export function validateReferenceRequest(schemaId: string, value: unknown) { - const schema = requestSchemas[schemaId as keyof typeof requestSchemas]; - return schema - ? project(schema.safeParse(value)) - : { success: false as const, issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }] }; + return validateOwned(requestSchemas, schemaId, value); } diff --git a/src/features/reference-feature/presentation/reference-feature-runtime.tsx b/src/features/reference-feature/presentation/reference-feature-runtime.tsx deleted file mode 100644 index 4f9fe72b..00000000 --- a/src/features/reference-feature/presentation/reference-feature-runtime.tsx +++ /dev/null @@ -1,5 +0,0 @@ -export { - REFERENCE_FEATURE_ROUTE_CODECS, - REFERENCE_FEATURE_ROUTE_RUNTIME, - REFERENCE_FEATURE_RUNTIME_CONTRIBUTION, -} from "./reference-feature-runtime.ts"; diff --git a/src/platform/execution/execution-context.ts b/src/platform/execution/execution-context.ts index 84efd8f0..e60de32e 100644 --- a/src/platform/execution/execution-context.ts +++ b/src/platform/execution/execution-context.ts @@ -49,6 +49,13 @@ export interface ExecutionContext { readonly clock: () => number; /** Time left before the absolute interaction deadline; never negative. */ remainingMs(): number; + /** + * Q-6.9-7. Ends the interaction normally: it detaches from the owner + * `signal` without aborting its own. Idempotent. Without it, every + * interaction under a long-lived owner signal left one abort listener (and + * its controller) on that owner until the owner itself aborted. + */ + complete(): void; } export type ExecutionContextOptions = Readonly<{ @@ -95,17 +102,20 @@ export function createExecutionContext( const controller = new AbortController(); const parent = options.signal; + let detachFromParent = () => {}; if (parent) { if (parent.aborted) controller.abort(); else { const forward = () => controller.abort(); parent.addEventListener("abort", forward, { once: true }); + detachFromParent = () => { + detachFromParent = () => {}; + parent.removeEventListener("abort", forward); + }; // The interaction must not keep the parent's listener alive after it ends. - controller.signal.addEventListener( - "abort", - () => parent.removeEventListener("abort", forward), - { once: true }, - ); + controller.signal.addEventListener("abort", () => detachFromParent(), { + once: true, + }); } } @@ -127,5 +137,8 @@ export function createExecutionContext( return 0; } }, + complete() { + detachFromParent(); + }, }); } diff --git a/src/platform/release/release-mismatch-recovery.ts b/src/platform/release/release-mismatch-recovery.ts index 7a6e5853..1b5efcf5 100644 --- a/src/platform/release/release-mismatch-recovery.ts +++ b/src/platform/release/release-mismatch-recovery.ts @@ -19,7 +19,8 @@ export type RecoveryMarkerStore = Readonly<{ read(): string | null; write(value: string): void; - clear(): void; + /** Absent for a marker that only expires (chunk recovery never clears). */ + clear?(): void; }>; export type ReleaseMismatchDecision = "reload-once" | "show-failure"; @@ -29,15 +30,36 @@ export interface ReleaseMismatchRecovery { markCoherentBoot(): void; } +/** + * Q-6.9-9. Why a reload-once guard allowed or refused a reload. Every refusal + * fails closed: without a working marker there is no automatic reload. + */ +export type ReloadOnceDecision = + | "reload-once" + | "reload-already-attempted" + | "guard-read-failed" + | "guard-write-failed"; + +/** + * Q-6.9-9. The one "reload at most once" guard. Boot mismatch recovery and + * chunk recovery each keep their own marker (store) and key, but share this + * rule, so a fix to one cannot leave the other looping. + */ +export interface ReloadOnceGuard { + decide(key: string): ReloadOnceDecision; + /** Drops the marker, e.g. after a coherent boot. Never throws. */ + clear(): void; +} + const MAX_KEY_LENGTH = 256; -export function createReleaseMismatchRecovery( +export function createReloadOnceGuard( store: RecoveryMarkerStore | null, options: Readonly<{ now?: () => number; ttlMs?: number; }> = {}, -): ReleaseMismatchRecovery { +): ReloadOnceGuard { const now = options.now ?? (() => Date.now()); const ttlMs = options.ttlMs ?? 10 * 60_000; @@ -51,31 +73,55 @@ export function createReleaseMismatchRecovery( } return Object.freeze({ - decide(mismatchKey: string): ReleaseMismatchDecision { - const key = mismatchKey.slice(0, MAX_KEY_LENGTH); + decide(rawKey: string): ReloadOnceDecision { + const key = rawKey.slice(0, MAX_KEY_LENGTH); + if (!store) return "guard-read-failed"; + let current: number; try { - if (!store) return "show-failure"; const previous = read(); - const current = now(); - // Key-independent: alternating replicas change the key on every boot. + current = now(); + // Key-independent: alternating replicas change the key every time. if (previous && current - previous.at < ttlMs) { - return "show-failure"; + return "reload-already-attempted"; } + } catch { + return "guard-read-failed"; + } + try { store.write(`${key}@${current}`); // Only a marker that is really persisted may authorize a reload; - // otherwise the next boot could not know it already reloaded. - return read()?.key === key ? "reload-once" : "show-failure"; + // otherwise the next attempt could not know it already reloaded. + return read()?.key === key ? "reload-once" : "guard-write-failed"; } catch { - // Fail closed: without a working marker, never reload automatically. - return "show-failure"; + return "guard-write-failed"; } }, - markCoherentBoot(): void { + clear(): void { try { - store?.clear(); + store?.clear?.(); } catch { // A stale marker only means the next mismatch shows the failure. } }, }); } + +export function createReleaseMismatchRecovery( + store: RecoveryMarkerStore | null, + options: Readonly<{ + now?: () => number; + ttlMs?: number; + }> = {}, +): ReleaseMismatchRecovery { + const guard = createReloadOnceGuard(store, options); + return Object.freeze({ + decide(mismatchKey: string): ReleaseMismatchDecision { + return guard.decide(mismatchKey) === "reload-once" + ? "reload-once" + : "show-failure"; + }, + markCoherentBoot(): void { + guard.clear(); + }, + }); +} diff --git a/src/platform/telemetry/telemetry-buffer.ts b/src/platform/telemetry/telemetry-buffer.ts index f42dc97e..44ba9015 100644 --- a/src/platform/telemetry/telemetry-buffer.ts +++ b/src/platform/telemetry/telemetry-buffer.ts @@ -6,10 +6,11 @@ import { /** * Spec §25 / §27. Bounded, severity-aware telemetry buffer. * - * The buffer never exceeds `maxEvents` or `maxBytes`. When full, the lowest - * severity (oldest first) event is evicted; an incoming event that is not more - * important than everything buffered is dropped instead. Buffer growth is - * never used as backpressure. + * The buffer never exceeds `maxEvents` or `maxBytes`. When full, buffered + * events no more severe than the incoming one are evicted, lowest severity + * first and oldest first within a severity, but only if that frees enough + * room; otherwise the incoming event is dropped and nothing is evicted. + * Buffer growth is never used as backpressure. */ export type BufferedTelemetryEvent = Readonly<{ event: TelemetryEvent; @@ -46,7 +47,7 @@ export function createTelemetryBuffer( options: Readonly<{ maxEvents: number; maxBytes: number; - /** Called for each buffered event evicted to make room for a more important one. */ + /** Called for each buffered event evicted to make room for an incoming one. */ onEvict?: (entry: BufferedTelemetryEvent) => void; }>, ): TelemetryBuffer { @@ -61,19 +62,6 @@ export function createTelemetryBuffer( let bytes = 0; let dropped = 0; - function lowestIndex(): number { - let index = -1; - let rank = Number.POSITIVE_INFINITY; - for (let i = 0; i < entries.length; i += 1) { - const candidate = TELEMETRY_SEVERITY_RANK[(entries[i] as BufferedTelemetryEvent).event.severity]; - if (candidate < rank) { - rank = candidate; - index = i; - } - } - return index; - } - return { get size() { return entries.length; @@ -93,20 +81,37 @@ export function createTelemetryBuffer( return false; } const incomingRank = TELEMETRY_SEVERITY_RANK[event.severity]; - while (entries.length >= maxEvents || bytes + size > maxBytes) { - const victim = lowestIndex(); - const victimEntry = entries[victim]; - if ( - !victimEntry || - TELEMETRY_SEVERITY_RANK[victimEntry.event.severity] > incomingRank - ) { + // Q-6.9-11. Plan the evictions before making any: an event is evicted + // only when the plan frees enough room for the incoming one. + const victims: BufferedTelemetryEvent[] = []; + let count = entries.length; + let used = bytes; + const full = () => count >= maxEvents || used + size > maxBytes; + if (full()) { + // Lowest severity first; the sort is stable, so oldest first within one. + const candidates = entries + .filter((entry) => TELEMETRY_SEVERITY_RANK[entry.event.severity] <= incomingRank) + .sort( + (a, b) => + TELEMETRY_SEVERITY_RANK[a.event.severity] - + TELEMETRY_SEVERITY_RANK[b.event.severity], + ); + for (const candidate of candidates) { + if (!full()) break; + victims.push(candidate); + count -= 1; + used -= candidate.bytes; + } + if (full()) { dropped += 1; return false; } - entries.splice(victim, 1); - bytes -= victimEntry.bytes; + } + for (const victim of victims) { + entries.splice(entries.indexOf(victim), 1); + bytes -= victim.bytes; dropped += 1; - onEvict?.(victimEntry); + onEvict?.(victim); } entries.push( Object.freeze( diff --git a/src/platform/telemetry/telemetry-pipeline.ts b/src/platform/telemetry/telemetry-pipeline.ts index fe3c96cf..94ba7799 100644 --- a/src/platform/telemetry/telemetry-pipeline.ts +++ b/src/platform/telemetry/telemetry-pipeline.ts @@ -93,12 +93,53 @@ function assertPositive(name: string, value: number): void { } } +/** + * Spec §27. A rolling one-minute send budget. Several queues that post to the + * same collector share one instance, so the limit belongs to the collector + * rather than to each queue (Q-6.9-4). + */ +export interface TelemetrySendRate { + /** + * Takes a send slot and returns 0, or returns the milliseconds until a slot + * reopens. `force` always takes one: page exit may exceed the window once. + */ + take(force?: boolean): number; +} + +export function createTelemetrySendRate( + maxSendsPerMinute: number, + now: () => number = () => performance.now(), +): TelemetrySendRate { + assertPositive("maxSendsPerMinute", maxSendsPerMinute); + /** Send instants inside the current window; never longer than the limit. */ + const sendTimes: number[] = []; + return Object.freeze({ + take(force = false): number { + const at = now(); + while (sendTimes.length > 0 && at - (sendTimes[0] as number) >= RATE_WINDOW_MS) { + sendTimes.shift(); + } + if (!force && sendTimes.length >= maxSendsPerMinute) { + return Math.max(1, (sendTimes[0] as number) + RATE_WINDOW_MS - at); + } + sendTimes.push(at); + if (sendTimes.length > maxSendsPerMinute) sendTimes.shift(); + return 0; + }, + }); +} + export function createTelemetryPipeline( options: Readonly<{ transport: TelemetryTransport; budget?: TelemetryPipelineBudget; /** Monotonic clock. */ now?: () => number; + /** + * A send-rate window shared with other queues posting to the same + * collector. Default: a private one from `budget.maxSendsPerMinute`. + */ + sendRate?: TelemetrySendRate; /** Schedules a flush soon (default: microtask). */ schedule?: (callback: () => void) => void; /** Schedules a flush after a rate window reopens (default: setTimeout). */ @@ -136,8 +177,8 @@ export function createTelemetryPipeline( }); /** Duplicates counted but not yet reported, per fingerprint. */ const held = new Map; count: number }>(); - /** Send timestamps inside the current rate window; never above the limit. */ - const sendTimes: number[] = []; + const sendRate = + options.sendRate ?? createTelemetrySendRate(budget.maxSendsPerMinute, now); let disposed = false; let flushScheduled = false; @@ -156,16 +197,8 @@ export function createTelemetryPipeline( peakBuffered: 0, }; - function rateAllows(at: number): boolean { - while (sendTimes.length > 0 && at - (sendTimes[0] as number) >= RATE_WINDOW_MS) { - sendTimes.shift(); - } - return sendTimes.length < budget.maxSendsPerMinute; - } - - function armRateTimer(at: number): void { + function armRateTimer(reopenIn: number): void { if (rateTimer !== null || disposed) return; - const reopenIn = Math.max(1, (sendTimes[0] ?? at) + RATE_WINDOW_MS - at); rateTimer = setTimer(() => { rateTimer = null; void flush(); @@ -227,13 +260,12 @@ export function createTelemetryPipeline( async function drain(): Promise { while (!disposed && pending()) { - const at = now(); - if (!rateAllows(at)) { - armRateTimer(at); + const reopenIn = sendRate.take(); + if (reopenIn > 0) { + armRateTimer(reopenIn); return; } const batch = takeBatch(); - sendTimes.push(at); counters.sends += 1; try { await options.transport.send(batch); diff --git a/src/presentation/boundaries/chunk-recovery-boundary.tsx b/src/presentation/boundaries/chunk-recovery-boundary.tsx index 5f9cb8e2..8cc8e375 100644 --- a/src/presentation/boundaries/chunk-recovery-boundary.tsx +++ b/src/presentation/boundaries/chunk-recovery-boundary.tsx @@ -3,7 +3,7 @@ import { type ErrorInfo, type ReactNode, } from "react"; -import { Button } from "../design-system/index.ts"; +import { Button, LoadingSurface } from "../design-system/index.ts"; import { useLocale } from "../i18n/index.ts"; type RecoveryResult = @@ -99,9 +99,9 @@ function ChunkRecoverySurface({ const { message } = useLocale(); if (recovery === "checking") { return ( -
- {message("chunk.checking")} -
+
+ +
); } if (recovery === "reload-requested") { diff --git a/src/presentation/boundaries/render-error-boundary.tsx b/src/presentation/boundaries/render-error-boundary.tsx index 782638ac..36e69ad8 100644 --- a/src/presentation/boundaries/render-error-boundary.tsx +++ b/src/presentation/boundaries/render-error-boundary.tsx @@ -1,7 +1,7 @@ import { Component, type ReactNode } from "react"; import type { RenderFailureReport } from "../../application/ports/in/application-api.ts"; -import { formatMessage } from "../i18n/index.ts"; +import { useLocale } from "../i18n/index.ts"; export type RenderBoundaryProps = Readonly<{ children: ReactNode; @@ -50,20 +50,26 @@ export class RenderErrorBoundary extends Component< render(): ReactNode { if (this.state.hasError) { return ( - this.props.fallback ?? ( -
-

{formatMessage("ko-KR", "error.render_failure")}

- -
- ) + this.props.fallback ?? ); } return this.props.children; } } +/** The default fallback, in the current locale. */ +function DefaultRenderFailure({ onRetry }: Readonly<{ onRetry(): void }>) { + const { message } = useLocale(); + return ( +
+

{message("error.render_failure")}

+ +
+ ); +} + export function RouteBoundary( props: Omit, ) { diff --git a/src/presentation/components/async-surface.tsx b/src/presentation/components/async-surface.tsx index f172014c..ee494478 100644 --- a/src/presentation/components/async-surface.tsx +++ b/src/presentation/components/async-surface.tsx @@ -6,9 +6,13 @@ import { useLocale } from "../i18n/index.ts"; import { errorMessage } from "./error-copy.ts"; import { Button } from "./ui/button.ts"; -export function LoadingSurface({ label }: Readonly<{ label?: string }>) { +export function LoadingSurface({ + label, + description, +}: Readonly<{ label?: string; description?: string }>) { const { message } = useLocale(); - const accessibleLabel = label ?? message("async.loading"); + // Visible copy doubles as the name unless a separate label is given. + const accessibleLabel = label ?? description ?? message("async.loading"); return (
) { aria-atomic="true" >
); } diff --git a/src/presentation/design-system/index.ts b/src/presentation/design-system/index.ts index 11f42a6c..3467658e 100644 --- a/src/presentation/design-system/index.ts +++ b/src/presentation/design-system/index.ts @@ -23,6 +23,7 @@ export type { DialogProps, IconButtonProps, LinkButtonProps, + LinkTarget, SpinnerProps, TextFieldProps, } from "./primitives/core.tsx"; diff --git a/src/presentation/design-system/primitives/core.tsx b/src/presentation/design-system/primitives/core.tsx index 7b7be11c..681af63a 100644 --- a/src/presentation/design-system/primitives/core.tsx +++ b/src/presentation/design-system/primitives/core.tsx @@ -6,6 +6,7 @@ import { useRef, } from "react"; import { createPortal } from "react-dom"; +import { Link, type To } from "react-router-dom"; import { CloseIcon } from "../icons/semantic-icons.tsx"; import { useLocale } from "../../i18n/index.ts"; @@ -68,9 +69,21 @@ export const Button = forwardRef( }, ); -export type LinkButtonProps = React.AnchorHTMLAttributes & +/** + * Where a link goes. `to` is an in-app destination rendered as a router link, + * so it keeps the router basename and navigates without a document reload. + * `href` stays a plain anchor for external or document-level targets. + */ +export type LinkTarget = + | Readonly<{ href: string; to?: undefined }> + | Readonly<{ to: To; href?: undefined }>; + +export type LinkButtonProps = Omit< + React.AnchorHTMLAttributes, + "href" +> & + LinkTarget & Readonly<{ - href: string; variant?: ButtonVariant; size?: ButtonSize; }>; @@ -79,6 +92,7 @@ export const LinkButton = forwardRef( function LinkButton( { href, + to, variant = "primary", size = "default", className = "", @@ -86,20 +100,18 @@ export const LinkButton = forwardRef( }, ref, ) { - return ( - + const classes = [ + "ui-button", + `ui-button--${variant}`, + size === "compact" ? "ui-button--compact" : "", + className, + ] + .filter(Boolean) + .join(" "); + return to === undefined ? ( + + ) : ( + ); }, ); diff --git a/src/presentation/design-system/primitives/forms.tsx b/src/presentation/design-system/primitives/forms.tsx index 56fe63e7..3f167359 100644 --- a/src/presentation/design-system/primitives/forms.tsx +++ b/src/presentation/design-system/primitives/forms.tsx @@ -2,6 +2,7 @@ import { forwardRef, useEffect, useId, + useImperativeHandle, useRef, useState, } from "react"; @@ -373,6 +374,8 @@ export const SearchField = forwardRef( }, ref, ) { + const inputRef = useRef(null); + useImperativeHandle(ref, () => inputRef.current as HTMLInputElement); return (
@@ -390,7 +393,7 @@ export const SearchField = forwardRef( aria-invalid={invalid || undefined} className="ui-field__input" id={controlId} - ref={ref} + ref={inputRef} type="search" value={value} /> @@ -399,7 +402,12 @@ export const SearchField = forwardRef( {String(value ?? "").length > 0 ? ( { + onClear(); + // The button unmounts once the value is empty; keep focus in + // the field instead of dropping it to the body. + inputRef.current?.focus(); + }} variant="ghost" > diff --git a/src/presentation/design-system/primitives/navigation.tsx b/src/presentation/design-system/primitives/navigation.tsx index bc69c711..d19b6074 100644 --- a/src/presentation/design-system/primitives/navigation.tsx +++ b/src/presentation/design-system/primitives/navigation.tsx @@ -1,12 +1,20 @@ -import { useId, useRef, useState } from "react"; +import { createContext, useContext, useId, useRef, useState } from "react"; +import { + Link, + useInRouterContext, + useLocation, + type To, +} from "react-router-dom"; import { useLocale } from "../../i18n/index.ts"; import { NextIcon, PreviousIcon } from "../icons/semantic-icons.tsx"; -import { IconButton, LinkButton } from "./core.tsx"; +import { IconButton, LinkButton, type LinkTarget } from "./core.tsx"; export type BreadcrumbItem = Readonly<{ label: string; href?: string; + /** In-app destination, rendered as a router link. Wins over `href`. */ + to?: To; }>; export function Breadcrumbs({ @@ -20,7 +28,9 @@ export function Breadcrumbs({ const current = index === items.length - 1; return (
  • - {item.href && !current ? ( + {item.to !== undefined && !current ? ( + {item.label} + ) : item.href && !current ? ( {item.label} ) : ( @@ -140,15 +150,7 @@ export function Tabs({ ); } -export function Pagination({ - label, - page, - pageCount, - previousLabel, - nextLabel, - pageLabel, - onChange, -}: Readonly<{ +type PaginationProps = Readonly<{ label: string; page: number; pageCount: number; @@ -156,14 +158,30 @@ export function Pagination({ nextLabel: string; pageLabel(page: number): string; onChange(page: number): void; -}>) { - const pages = Array.from({ length: pageCount }, (_, index) => index + 1); +}>; + +/** + * Set by a container that already is the pagination navigation landmark + * (CollectionPage), so Pagination renders a labelled group instead of a + * nested `nav`. + */ +export const PaginationLandmarkContext = createContext(false); + +export function Pagination(props: PaginationProps) { + const { label, page, pageCount, previousLabel, nextLabel, onChange } = props; + const inRouter = useInRouterContext(); + const nested = useContext(PaginationLandmarkContext); + const Container = nested ? "div" : "nav"; const { direction } = useLocale(); const PreviousDirectionalIcon = direction === "rtl" ? NextIcon : PreviousIcon; const NextDirectionalIcon = direction === "rtl" ? PreviousIcon : NextIcon; return ( - + + ); +} + +/** + * The first and last page, the current page and its neighbours. A gap of one + * page shows that page instead of an ellipsis. + */ +function visiblePages(page: number, pageCount: number): Array { + const wanted = [...new Set([1, page - 1, page, page + 1, pageCount])] + .filter((candidate) => candidate >= 1 && candidate <= pageCount) + .sort((left, right) => left - right); + const visible: Array = []; + let previous = 0; + for (const candidate of wanted) { + if (candidate - previous === 2) visible.push(candidate - 1); + else if (candidate - previous > 2) visible.push("gap"); + visible.push(candidate); + previous = candidate; + } + return visible; +} + +/** Keeps every other search parameter and only replaces `page`. */ +function withPage(search: string, page: number): string { + const params = new URLSearchParams(search); + params.set("page", String(page)); + return `?${params}`; +} + +function RouterPageLinks(props: PaginationProps) { + const { search } = useLocation(); + return ( + ({ to: { search: withPage(search, candidate) } })} + /> + ); +} + +function PageLinks({ + page, + pageCount, + pageLabel, + onChange, + target, +}: PaginationProps & Readonly<{ target(page: number): LinkTarget }>) { + return visiblePages(page, pageCount).map((candidate, index) => + candidate === "gap" ? ( + + ) : ( + { + // The owner decides how a page change is applied; the href is for + // open-in-new-tab and copy-link. + event.preventDefault(); + onChange(candidate); + }} + variant={candidate === page ? "primary" : "ghost"} + > + {pageLabel(candidate)} + + ), ); } diff --git a/src/presentation/design-system/primitives/overlays.tsx b/src/presentation/design-system/primitives/overlays.tsx index 2a75cc2c..2b7aba07 100644 --- a/src/presentation/design-system/primitives/overlays.tsx +++ b/src/presentation/design-system/primitives/overlays.tsx @@ -1,4 +1,5 @@ import { + cloneElement, createContext, useCallback, useContext, @@ -104,17 +105,42 @@ export function Popover({ triggerLabel, children }: PopoverProps) { export type TooltipProps = Readonly<{ content: string; - children: React.ReactElement; + children: React.ReactElement<{ "aria-describedby"?: string | undefined }>; }>; +/** + * Describes its focusable child (WCAG 1.4.13): the child carries + * `aria-describedby`, and Escape hides the tooltip until the next hover or + * focus. + */ export function Tooltip({ content, children }: TooltipProps) { const tooltipId = useId(); + const [dismissed, setDismissed] = useState(false); + useEffect(() => { + if (dismissed) return; + // Document level: a hovered trigger does not have keyboard focus. + function dismissOnEscape(event: KeyboardEvent) { + if (event.key === "Escape") setDismissed(true); + } + document.addEventListener("keydown", dismissOnEscape); + return () => document.removeEventListener("keydown", dismissOnEscape); + }, [dismissed]); + const describedBy = [children.props["aria-describedby"], tooltipId] + .filter(Boolean) + .join(" "); return ( - - - {children} - - + setDismissed(false)} + onMouseEnter={() => setDismissed(false)} + > + {cloneElement(children, { "aria-describedby": describedBy })} + diff --git a/src/presentation/examples/auth-example-page.tsx b/src/presentation/examples/auth-example-page.tsx index aa7a1b37..41e2b1ca 100644 --- a/src/presentation/examples/auth-example-page.tsx +++ b/src/presentation/examples/auth-example-page.tsx @@ -1,26 +1,12 @@ -import { useState } from "react"; -import { useLocation } from "react-router-dom"; - import { PageHeader } from "../design-system/index.ts"; -import { useSession } from "../providers/session-provider.tsx"; +import { + useSession, + useSessionAction, +} from "../providers/session-provider.tsx"; export default function AuthExamplePage() { - const location = useLocation(); - const { sessionState, beginSignIn, signOut, recover } = useSession(); - const [pending, setPending] = useState(false); - const [failed, setFailed] = useState(false); - - async function execute(action: () => Promise): Promise { - setPending(true); - setFailed(false); - try { - await action(); - } catch { - setFailed(true); - } finally { - setPending(false); - } - } + const { sessionState } = useSession(); + const { pending, failed, run } = useSessionAction(); return (
    @@ -41,11 +27,7 @@ export default function AuthExamplePage() { className="ui-button" type="button" disabled={pending || sessionState === "integration-failed"} - onClick={() => - void execute(() => - beginSignIn(`${location.pathname}${location.search}`), - ) - } + onClick={() => run("sign-in")} > 로그인 시작 @@ -53,7 +35,7 @@ export default function AuthExamplePage() { className="ui-button ui-button--secondary" type="button" disabled={pending || sessionState !== "authenticated"} - onClick={() => void execute(signOut)} + onClick={() => run("sign-out")} > 로그아웃 @@ -61,7 +43,7 @@ export default function AuthExamplePage() { className="ui-button ui-button--secondary" type="button" disabled={pending || sessionState !== "recovery-pending"} - onClick={() => void execute(recover)} + onClick={() => run("recover")} > 세션 복구 diff --git a/src/presentation/examples/platform-overview-page.tsx b/src/presentation/examples/platform-overview-page.tsx index bc950363..0c4e73f3 100644 --- a/src/presentation/examples/platform-overview-page.tsx +++ b/src/presentation/examples/platform-overview-page.tsx @@ -281,14 +281,19 @@ function buildOperationRows(): readonly OperationRow[] { export default function PlatformOverviewPage() { const runtime = useApplicationRuntime(); const [release, setRelease] = useState< - Awaited> | null + Awaited> | "failed" | null >(null); useEffect(() => { let active = true; - void runtime.getReleaseSummary().then((summary) => { - if (active) setRelease(summary); - }); + runtime.getReleaseSummary().then( + (summary) => { + if (active) setRelease(summary); + }, + () => { + if (active) setRelease("failed"); + }, + ); return () => { active = false; }; @@ -325,7 +330,9 @@ export default function PlatformOverviewPage() {

    - {release ? ( + {release === "failed" ? ( + + ) : release ? ( <> diff --git a/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts index 663b0cb1..bf389ab3 100644 --- a/src/presentation/forms/use-app-form.ts +++ b/src/presentation/forms/use-app-form.ts @@ -7,6 +7,7 @@ import { type ChangeEvent, type FormEvent, } from "react"; +import { flushSync } from "react-dom"; import type { ZodType, ZodIssue } from "zod"; import { useLocale, @@ -63,7 +64,7 @@ export function useAppForm< const [formErrors, setFormErrors] = useState([]); const [pending, setPending] = useState(false); const [result, setResult] = useState("idle"); - const pendingRef = useRef> | null>(null); + const pendingRef = useRef | null> | null>(null); const unknownSubmissionRef = useRef(null); const dirty = useMemo( @@ -142,16 +143,20 @@ export function useAppForm< const settleSuccessfulValues = useCallback( (settledValues: Values) => { unknownSubmissionRef.current = null; - setFieldErrors({} as FieldErrors); - setFormErrors([]); - setResult("success"); - if (resetOnSuccess) { - setValues(defaultValues); - setInitialValues(defaultValues); - setTouched(new Set()); - } else { - setInitialValues(settledValues); - } + // Committed before the caller continues: a `navigate()` right after a + // save must meet a clean form, not the dirty guard of the last render. + flushSync(() => { + setFieldErrors({} as FieldErrors); + setFormErrors([]); + setResult("success"); + if (resetOnSuccess) { + setValues(defaultValues); + setInitialValues(defaultValues); + setTouched(new Set()); + } else { + setInitialValues(settledValues); + } + }); }, [defaultValues, resetOnSuccess], ); @@ -170,11 +175,8 @@ export function useAppForm< setResult("idle"); }, []); - const submitForm = useCallback( - async (event?: FormEvent): Promise | null> => { - event?.preventDefault(); - if (pendingRef.current) return pendingRef.current; - if (unknownSubmissionRef.current) return null; + const validateAndSubmit = useCallback( + async (): Promise | null> => { setFieldErrors({} as FieldErrors); setFormErrors([]); @@ -201,10 +203,8 @@ export function useAppForm< const command = mapToCommand(parsed.data); setPending(true); - const execution = submit(command); - pendingRef.current = execution; try { - const outcome = await execution; + const outcome = await submit(command); if (outcome.ok) { settleSuccessfulValues(parsed.data); return outcome; @@ -239,7 +239,6 @@ export function useAppForm< } return outcome; } finally { - pendingRef.current = null; setPending(false); } }, @@ -255,6 +254,22 @@ export function useAppForm< ], ); + const submitForm = useCallback( + (event?: FormEvent): Promise | null> => { + event?.preventDefault(); + // One submission from validation to outcome: an async refine must not + // let a second submit through before the command starts. + if (pendingRef.current) return pendingRef.current; + if (unknownSubmissionRef.current) return Promise.resolve(null); + const submission = validateAndSubmit().finally(() => { + pendingRef.current = null; + }); + pendingRef.current = submission; + return submission; + }, + [validateAndSubmit], + ); + return Object.freeze({ formId, values, diff --git a/src/presentation/i18n/message-contract.ts b/src/presentation/i18n/message-contract.ts index a5dc2940..ac193b51 100644 --- a/src/presentation/i18n/message-contract.ts +++ b/src/presentation/i18n/message-contract.ts @@ -72,7 +72,8 @@ export function resolveMessage( const catalog = MESSAGE_CATALOGS[sourceLocale] ?? MESSAGE_CATALOGS[FALLBACK_LOCALE]; - const fallback = KO_MESSAGES["common.unavailable"]; + const fallback = + catalog["common.unavailable"] ?? KO_MESSAGES["common.unavailable"]; const canonicalKey = MESSAGE_KEY_ALIASES[key as keyof typeof MESSAGE_KEY_ALIASES] ?? key; const template = catalog[canonicalKey as MessageKey] ?? fallback; diff --git a/src/presentation/layouts/app-shell.tsx b/src/presentation/layouts/app-shell.tsx index 6ba47f63..cf6336da 100644 --- a/src/presentation/layouts/app-shell.tsx +++ b/src/presentation/layouts/app-shell.tsx @@ -21,7 +21,10 @@ import { type MessageKey, } from "../i18n/index.ts"; import { useApplicationRuntime } from "../providers/application-provider.tsx"; -import { useSession } from "../providers/session-provider.tsx"; +import { + useSession, + useSessionAction, +} from "../providers/session-provider.tsx"; import { useTheme } from "../providers/theme-provider.tsx"; const SESSION_MESSAGE_KEYS = Object.freeze({ @@ -33,38 +36,17 @@ const SESSION_MESSAGE_KEYS = Object.freeze({ export function AppShell() { const location = useLocation(); - const { sessionState, beginSignIn, signOut, recover } = useSession(); + const { sessionState } = useSession(); + const sessionAction = useSessionAction(); const { preference, setPreference } = useTheme(); const { locale, setLocale, message } = useLocale(); const [navigationOpen, setNavigationOpen] = useState(false); const navigationTriggerRef = useRef(null); - const [sessionActionPending, setSessionActionPending] = useState(false); - const [sessionActionFailed, setSessionActionFailed] = useState(false); useEffect(() => { setNavigationOpen(false); }, [location.pathname]); - async function runSessionAction() { - setSessionActionPending(true); - setSessionActionFailed(false); - try { - if (sessionState === "authenticated") { - await signOut(); - } else if (sessionState === "recovery-pending") { - await recover(); - } else { - await beginSignIn( - `${location.pathname}${location.search}${location.hash}`, - ); - } - } catch { - setSessionActionFailed(true); - } finally { - setSessionActionPending(false); - } - } - const sessionActionLabel = sessionState === "authenticated" ? message("action.signOut") @@ -128,17 +110,25 @@ export function AppShell() { {integrationAvailable ? ( ) : null}
  • - {sessionActionFailed ? ( + {sessionAction.failed ? (

    {message("shell.session.actionFailed")}

    diff --git a/src/presentation/pages/home-page.tsx b/src/presentation/pages/home-page.tsx index 6dfeab71..3412ffa2 100644 --- a/src/presentation/pages/home-page.tsx +++ b/src/presentation/pages/home-page.tsx @@ -23,14 +23,19 @@ const READINESS_ITEMS = Object.freeze([ export default function HomePage() { const runtime = useApplicationRuntime(); const [release, setRelease] = useState< - Awaited> | null + Awaited> | "failed" | null >(null); useEffect(() => { let active = true; - void runtime.getReleaseSummary().then((summary) => { - if (active) setRelease(summary); - }); + runtime.getReleaseSummary().then( + (summary) => { + if (active) setRelease(summary); + }, + () => { + if (active) setRelease("failed"); + }, + ); return () => { active = false; }; @@ -52,9 +57,11 @@ export default function HomePage() { ))}

    - {release - ? `빌드 ${release.buildId} · 릴리스 ${release.releaseId}` - : "검증된 런타임 정보를 확인하고 있습니다."} + {release === "failed" + ? "런타임 정보를 확인하지 못했습니다." + : release + ? `빌드 ${release.buildId} · 릴리스 ${release.releaseId}` + : "검증된 런타임 정보를 확인하고 있습니다."}

    diff --git a/src/presentation/pages/not-found-page.tsx b/src/presentation/pages/not-found-page.tsx index b59836ca..c75a8a3c 100644 --- a/src/presentation/pages/not-found-page.tsx +++ b/src/presentation/pages/not-found-page.tsx @@ -1,22 +1,21 @@ -import { Link } from "react-router-dom"; - import { routePath } from "../../features/installed-feature-contracts.ts"; -import { PageHeader } from "../design-system/index.ts"; +import { StatusPage } from "../design-system/index.ts"; import { useLocale } from "../i18n/index.ts"; export default function NotFoundPage() { const { message } = useLocale(); return ( -
    - -
    - - {message("action.goHome")} - -
    -
    + ); } diff --git a/src/presentation/providers/session-provider.tsx b/src/presentation/providers/session-provider.tsx index b87129e6..8fafa3d8 100644 --- a/src/presentation/providers/session-provider.tsx +++ b/src/presentation/providers/session-provider.tsx @@ -2,9 +2,11 @@ import { createContext, useContext, useMemo, + useState, useSyncExternalStore, type ReactNode, } from "react"; +import { useLocation } from "react-router-dom"; import type { ApplicationApi, @@ -53,3 +55,36 @@ export function useSession(): SessionContextValue { } return session; } + +export type SessionAction = "sign-in" | "sign-out" | "recover"; + +/** + * One session action at a time, with the pending and failed state every + * session button shows. Sign-in returns to the current URL, hash included. + */ +export function useSessionAction(): Readonly<{ + pending: boolean; + failed: boolean; + run(action: SessionAction): void; +}> { + const { pathname, search, hash } = useLocation(); + const { beginSignIn, signOut, recover } = useSession(); + const [pending, setPending] = useState(false); + const [failed, setFailed] = useState(false); + + async function execute(action: SessionAction): Promise { + setPending(true); + setFailed(false); + try { + if (action === "sign-out") await signOut(); + else if (action === "recover") await recover(); + else await beginSignIn(`${pathname}${search}${hash}`); + } catch { + setFailed(true); + } finally { + setPending(false); + } + } + + return { pending, failed, run: (action) => void execute(action) }; +} diff --git a/src/presentation/routes/app-router.tsx b/src/presentation/routes/app-router.tsx index c21fa07d..f29122e6 100644 --- a/src/presentation/routes/app-router.tsx +++ b/src/presentation/routes/app-router.tsx @@ -21,6 +21,7 @@ import { getRoute, ROUTE_FEATURE_OWNER, ROUTE_REGISTRY, + ROUTE_RUNTIME_CONTRACT, } from "../../features/installed-feature-contracts.ts"; import { PLATFORM_ROUTE_REGISTRY, @@ -41,7 +42,7 @@ import { } from "../boundaries/chunk-recovery-boundary.tsx"; import { ContextErrorBoundary } from "../../platform/errors/context-error-boundary.tsx"; import { FeatureErrorBoundary } from "../../platform/errors/feature-error-boundary.tsx"; -import { Button, PageHeader } from "../design-system/index.ts"; +import { LoadingSurface, StatusPage } from "../design-system/index.ts"; import { useLocale } from "../i18n/index.ts"; import { AppShell } from "../layouts/app-shell.tsx"; import { @@ -49,7 +50,11 @@ import { useApplicationRecovery, useApplicationRuntime, } from "../providers/application-provider.tsx"; -import { SessionProvider, useSession } from "../providers/session-provider.tsx"; +import { + SessionProvider, + useSession, + useSessionAction, +} from "../providers/session-provider.tsx"; import { createRedirectLoopGuard, decideRouteAccess, @@ -63,22 +68,24 @@ import { ROUTE_RUNTIME } from "../../features/installed-feature-runtimes.tsx"; import type { ParsedRouteInput } from "./route-contract.ts"; import { RouteInputProvider } from "./route-input.tsx"; -function RouteLoadingSurface({ definition }: { definition: RouteDefinition }) { +/** Route-level loading: the shared LoadingSurface inside the page frame. */ +function RouteLoadingSurface({ + definition, +}: Readonly<{ definition?: RouteDefinition }>) { const { message, resolve } = useLocale(); - const title = resolve(`route.${definition.routeId}.title`); return ( -
    -
    +
    + +
    ); } @@ -89,28 +96,30 @@ function RouteFailureSurface({ }) { const { message } = useLocale(); return ( -
    - -
    + ); } function InvalidRouteSurface({ code }: { code: string }) { const { message } = useLocale(); return ( -
    - +

    {message("route.invalid.action")}

    -
    +
    ); } @@ -122,15 +131,18 @@ function InvalidRouteSurface({ code }: { code: string }) { function DisabledFeatureSurface({ featureId }: { featureId: string }) { const { message } = useLocale(); return ( -
    - +

    {message("route.disabledFeature.action")}

    -
    +
    ); } @@ -180,10 +192,15 @@ function CanonicalRouteRedirect({ useEffect(() => { if (input.routeId === "NOT_FOUND") return; const source = `${location.pathname}${location.search}`; - const target = buildRouteUrl(input.routeId, { + const canonical = buildRouteUrl(input.routeId, { params: input.params, search: input.search, }); + // D-16: a route that ignores its query leaves the query in the URL. + const target = + ROUTE_RUNTIME_CONTRACT[input.routeId].searchCodec === "none" + ? `${canonical}${location.search}` + : canonical; if (source === target) { guard.current.reset(); } else if (guard.current.allow(source, target)) { @@ -200,73 +217,57 @@ function ProtectedRoute({ routeId: RouteId; children: ReactNode; }) { - const location = useLocation(); - const { sessionState, beginSignIn, recover } = useSession(); + const { sessionState } = useSession(); const { message } = useLocale(); - const [pending, setPending] = useState(false); - const [failed, setFailed] = useState(false); + const { pending, failed, run } = useSessionAction(); const decision = decideRouteAccess(routeId, sessionState); - async function continueSession() { - setPending(true); - setFailed(false); - try { - if (decision.action === "wait-for-session") { - await recover(); - } else { - await beginSignIn( - `${location.pathname}${location.search}${location.hash}`, - ); - } - } catch { - setFailed(true); - } finally { - setPending(false); - } - } - if (decision.allowed) return children; if (sessionState === "integration-failed") { return ( -
    - -
    + ); } const recovering = decision.action === "wait-for-session"; return ( -
    - -
    +
    ); } @@ -402,7 +403,6 @@ function ContextRouteGateway({ buildId, }: Readonly<{ routeModule: ContextRouteModule; buildId: string }>) { const location = useLocation(); - const { message } = useLocale(); const recovery = useApplicationRecovery(); const [routes, setRoutes] = useState(null); const [failure, setFailure] = useState | null>( @@ -451,14 +451,7 @@ function ContextRouteGateway({ ); } - if (routes === null) { - return ( -
    -
    - ); - } + if (routes === null) return ; const selectedMatch = matchRoutes([...routes], location.pathname)?.at(-1); if (!isContextRouteHandle(selectedMatch?.route.handle)) { diff --git a/src/presentation/routes/platform-route-codecs.ts b/src/presentation/routes/platform-route-codecs.ts index 830f2e6f..103b3302 100644 --- a/src/presentation/routes/platform-route-codecs.ts +++ b/src/presentation/routes/platform-route-codecs.ts @@ -1,6 +1,8 @@ import { z } from "zod"; export const PLATFORM_ROUTE_CODECS = { - none: z.object({}).strict(), + // D-16: a route without input ignores unknown keys (`?utm_source=`, OAuth + // callback parameters) instead of calling the address invalid. + none: z.object({}), NotFoundSplat: z.object({ "*": z.string().optional() }).strict(), } as const; diff --git a/src/presentation/styles/theme.css b/src/presentation/styles/theme.css index e12c1dd1..c0df5bc5 100644 --- a/src/presentation/styles/theme.css +++ b/src/presentation/styles/theme.css @@ -2,1434 +2,9 @@ @import "../design-system/tokens/primitive.css"; @import "../design-system/tokens/semantic.css"; @import "../design-system/tokens/component.css"; - -@layer base { - :root { - color: var(--color-content); - background: var(--color-surface); - font-family: var(--font-sans); - } - - body { - margin: 0; - min-width: 20rem; - min-height: 100vh; - } - - button, - input, - textarea, - select { - font: inherit; - } - - a { - color: inherit; - } - - h1, - h2, - p { - margin-block-start: 0; - } - - h1 { - font-size: clamp(2rem, 5vw, 3.5rem); - line-height: 1.05; - letter-spacing: -0.04em; - } - - h2 { - line-height: 1.25; - } - - :focus-visible { - outline: 0.1875rem solid var(--color-focus); - outline-offset: 0.1875rem; - } -} - -@layer components { - .visually-hidden { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); - white-space: nowrap; - border: 0; - } - - .skip-link { - position: fixed; - z-index: 100; - top: 0.75rem; - left: 0.75rem; - padding: 0.75rem 1rem; - border-radius: var(--radius-control); - color: var(--color-panel); - background: var(--color-content); - transform: translateY(-200%); - } - - .skip-link:focus { - transform: translateY(0); - } - - .app-shell { - display: grid; - min-height: 100vh; - grid-template-rows: 4.5rem 1fr; - grid-template-columns: 15rem minmax(0, 1fr); - grid-template-areas: - "header header" - "sidebar content"; - } - - .app-shell__header { - position: sticky; - z-index: 30; - top: 0; - grid-area: header; - display: flex; - align-items: center; - gap: 1rem; - min-width: 0; - padding: 0.75rem 1.25rem; - border-bottom: 1px solid var(--color-surface-muted); - background: color-mix(in oklch, var(--color-panel) 92%, var(--color-surface)); - box-shadow: 0 1px 8px color-mix(in oklch, var(--color-content) 8%, transparent); - } - - .app-shell__brand { - overflow: hidden; - font-size: 1.05rem; - font-weight: 800; - text-decoration: none; - text-overflow: ellipsis; - white-space: nowrap; - } - - .app-shell__menu-button { - display: none; - align-items: center; - gap: 0.4rem; - border: 1px solid var(--color-surface-muted); - border-radius: var(--radius-control); - padding: 0.55rem 0.75rem; - color: var(--color-content); - background: var(--color-panel); - cursor: pointer; - } - - .app-shell__session { - display: flex; - align-items: center; - gap: 0.75rem; - margin-inline-start: auto; - } - - .theme-selector, - .locale-selector { - display: block; - } - - .theme-selector .ui-field__label, - .locale-selector .ui-field__label { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip: rect(0, 0, 0, 0); - white-space: nowrap; - border: 0; - } - - .theme-selector .ui-field__input, - .locale-selector .ui-field__input { - min-height: var(--size-control-sm); - max-width: 8.5rem; - padding: 0.35rem 2rem 0.35rem 0.65rem; - cursor: pointer; - } - - .locale-selector .ui-field__input { - max-width: 7rem; - } - - .app-shell__session-error { - position: absolute; - top: calc(100% + 0.25rem); - right: 1rem; - padding: 0.5rem; - color: var(--color-danger); - background: var(--color-panel); - } - - .session-status { - display: inline-flex; - width: fit-content; - align-items: center; - border-radius: 999px; - padding: 0.3rem 0.65rem; - color: var(--color-content-muted); - background: var(--color-surface-muted); - font-size: 0.8rem; - font-weight: 700; - } - - .session-status[data-state="authenticated"] { - color: var(--color-success-content); - background: var(--color-success-surface); - } - - .session-status[data-state="integration-failed"] { - color: var(--color-danger); - } - - .app-shell__sidebar { - position: sticky; - top: 4.5rem; - grid-area: sidebar; - height: calc(100vh - 4.5rem); - padding: 1.25rem 0.75rem; - border-right: 1px solid var(--color-border); - background: var(--color-panel); - } - - .app-navigation { - display: flex; - flex-direction: column; - gap: 0.25rem; - margin: 0; - padding: 0; - list-style: none; - } - - .app-navigation__link { - display: block; - border-radius: var(--radius-control); - padding: 0.75rem 0.9rem; - color: var(--color-content-muted); - font-weight: 650; - text-decoration: none; - } - - .app-navigation__link:hover { - color: var(--color-content); - background: var(--color-surface); - } - - .app-navigation__link.is-active { - color: var(--color-action-hover); - background: color-mix( - in oklch, - var(--color-action) 14%, - var(--color-panel) - ); - font-weight: 800; - } - - .app-shell__content { - grid-area: content; - min-width: 0; - } - - .ui-page { - @apply mx-auto flex max-w-6xl flex-col gap-6 p-page; - width: 100%; - box-sizing: border-box; - } - - .ui-panel { - @apply rounded-surface p-6 shadow-sm; - border: 1px solid var(--color-border); - background: var(--color-panel); - } - - .ui-button { - @apply rounded-control bg-action px-4 py-2 font-semibold; - display: inline-flex; - min-height: 2.75rem; - align-items: center; - justify-content: center; - border: 0; - color: var(--color-on-action); - text-decoration: none; - cursor: pointer; - } - - .ui-button:hover { - @apply bg-action-hover; - } - - .ui-button:disabled { - cursor: not-allowed; - opacity: var(--opacity-disabled); - } - - .ui-button--pending { - gap: var(--space-2); - cursor: progress; - } - - .ui-button--secondary { - border: 1px solid var(--color-surface-muted); - color: var(--color-content); - background: var(--color-panel); - } - - .ui-button--secondary:hover { - color: var(--color-action); - background: var(--color-surface); - } - - .ui-button--danger { - color: var(--color-on-action); - background: var(--color-danger); - } - - .ui-button--danger:hover { - background: var(--color-danger-hover); - } - - .ui-button--ghost { - color: var(--color-content); - background: transparent; - } - - .ui-button--ghost:hover { - color: var(--color-action); - background: var(--color-surface-muted); - } - - .ui-button--compact { - min-height: var(--size-control-sm); - padding: 0.4rem 0.75rem; - font-size: 0.85rem; - } - - .ui-icon-button { - width: var(--size-touch-target); - min-width: var(--size-touch-target); - padding: 0; - } - - .app-shell__menu-button.ui-icon-button { - display: none; - } - - .ui-icon { - display: inline-block; - flex: 0 0 auto; - stroke-width: var(--icon-stroke-default); - } - - .ui-icon--small { - width: var(--size-icon-sm); - height: var(--size-icon-sm); - } - - .ui-icon--medium { - width: var(--size-icon-md); - height: var(--size-icon-md); - } - - .ui-icon--large { - width: var(--size-icon-lg); - height: var(--size-icon-lg); - } - - .ui-spinner { - display: inline-block; - width: var(--size-icon-sm); - height: var(--size-icon-sm); - box-sizing: border-box; - border: 2px solid currentColor; - border-inline-end-color: transparent; - border-radius: var(--radius-full); - animation: ui-spin var(--duration-slow) linear infinite; - } - - @keyframes ui-spin { - to { - transform: rotate(360deg); - } - } - - .ui-skeleton { - @apply h-24 animate-pulse rounded-surface bg-surface-muted; - } - - .ui-empty, - .ui-terminal-error { - @apply rounded-surface border border-surface-muted p-6; - } - - .ui-field { - display: grid; - gap: 0.45rem; - } - - .ui-field__label { - font-weight: 750; - } - - .ui-field__description, - .ui-field__error { - margin: 0; - font-size: 0.875rem; - line-height: 1.5; - } - - .ui-field__description { - color: var(--color-content-muted); - } - - .ui-field__error { - color: var(--color-danger); - font-weight: 650; - } - - .ui-field__input { - width: 100%; - min-height: 2.75rem; - box-sizing: border-box; - border: 1px solid - color-mix(in oklch, var(--color-content-muted) 55%, var(--color-panel)); - border-radius: var(--radius-control); - padding: 0.65rem 0.8rem; - color: var(--color-content); - background: var(--color-panel); - } - - .ui-field__input[aria-invalid="true"] { - border-color: var(--field-border-invalid); - } - - .ui-field__textarea { - min-height: 7rem; - resize: vertical; - } - - .ui-field__counter { - justify-self: end; - color: var(--color-content-muted); - font-size: var(--font-size-sm); - } - - .ui-choice-field, - .ui-radio-group, - .ui-switch-field { - display: grid; - gap: var(--space-2); - } - - .ui-choice-field__control { - display: flex; - min-height: var(--size-touch-target); - align-items: center; - gap: var(--space-2); - cursor: pointer; - } - - .ui-choice-field__control input { - width: 1.15rem; - height: 1.15rem; - accent-color: var(--color-action); - } - - .ui-choice-field__control small { - display: block; - color: var(--color-content-muted); - } - - .ui-radio-group { - min-width: 0; - border: 1px solid var(--color-border); - border-radius: var(--radius-control); - padding: var(--space-3); - } - - .ui-radio-group legend { - padding-inline: var(--space-1); - font-weight: var(--font-weight-bold); - } - - .ui-switch { - display: inline-flex; - width: fit-content; - min-height: var(--size-touch-target); - align-items: center; - gap: var(--space-2); - border: 0; - color: var(--color-content); - background: transparent; - cursor: pointer; - } - - .ui-switch__thumb { - display: inline-block; - width: 2.5rem; - height: 1.5rem; - border: 1px solid var(--color-border-strong); - border-radius: var(--radius-full); - background: var(--color-disabled-surface); - } - - .ui-switch__thumb::after { - display: block; - width: 1rem; - height: 1rem; - margin: 0.2rem; - border-radius: var(--radius-full); - background: var(--color-content-muted); - content: ""; - transition: transform var(--duration-normal) var(--easing-standard); - } - - .ui-switch[aria-checked="true"] .ui-switch__thumb { - border-color: var(--color-action); - background: var(--color-action); - } - - .ui-switch[aria-checked="true"] .ui-switch__thumb::after { - background: var(--color-on-action); - transform: translateX(1rem); - } - - [dir="rtl"] .ui-switch[aria-checked="true"] .ui-switch__thumb::after { - transform: translateX(-1rem); - } - - .ui-search-field { - position: relative; - display: grid; - grid-template-columns: auto minmax(0, 1fr) auto; - align-items: end; - gap: var(--space-2); - } - - .ui-card { - display: flex; - min-width: 0; - flex-direction: column; - gap: 1.25rem; - border: 1px solid var(--color-border); - border-radius: var(--radius-surface); - padding: 1.25rem; - background: var(--color-panel); - box-shadow: 0 8px 28px color-mix(in oklch, var(--color-content) 6%, transparent); - } - - .ui-card__header :is(h2, h3, h4), - .ui-card__header p { - margin-block-end: 0; - } - - .ui-card__header p { - margin-block-start: 0.4rem; - color: var(--color-content-muted); - line-height: 1.55; - } - - .ui-card__content { - flex: 1; - } - - .ui-card__footer { - padding-block-start: 1rem; - border-top: 1px solid var(--color-surface-muted); - } - - .ui-alert { - display: flex; - align-items: flex-start; - justify-content: space-between; - gap: 1rem; - border: 1px solid var(--color-surface-muted); - border-radius: var(--radius-control); - padding: 1rem; - background: var(--color-surface); - } - - .ui-alert--info { - border-color: var(--color-info-border); - background: var(--color-info-surface); - } - - .ui-alert--success { - border-color: var(--color-success-border); - background: var(--color-success-surface); - } - - .ui-alert--warning { - border-color: var(--color-warning-border); - background: var(--color-warning-surface); - } - - .ui-alert--danger { - border-color: var(--color-danger-border); - background: var(--color-danger-surface); - } - - .ui-alert__content, - .ui-alert__content p { - margin-block: 0.35rem 0; - color: var(--color-content-muted); - } - - .ui-alert__dismiss, - .ui-dialog__close { - display: inline-grid; - width: 2rem; - height: 2rem; - flex: 0 0 auto; - place-items: center; - border: 0; - border-radius: var(--radius-control); - color: var(--color-content); - background: transparent; - font-size: 1.35rem; - cursor: pointer; - } - - .ui-alert__dismiss.ui-icon-button, - .ui-dialog__close.ui-icon-button { - min-width: 2rem; - min-height: 2rem; - padding: 0; - } - - .ui-alert__dismiss:hover, - .ui-dialog__close:hover { - background: color-mix(in oklch, var(--color-content) 8%, transparent); - } - - .ui-badge { - display: inline-flex; - border-radius: 999px; - padding: 0.3rem 0.65rem; - color: var(--color-content); - background: var(--color-surface-muted); - font-size: 0.8rem; - font-weight: 750; - } - - .ui-badge--info { - color: var(--color-info-content); - background: var(--color-info-surface); - } - - .ui-badge--success { - color: var(--color-success-content); - background: var(--color-success-surface); - } - - .ui-badge--warning { - color: var(--color-warning-content); - background: var(--color-warning-surface); - } - - .ui-badge--danger { - color: var(--color-danger-content); - background: var(--color-danger-surface); - } - - .ui-dialog { - width: min(34rem, calc(100vw - 2rem)); - max-height: calc(100vh - 2rem); - box-sizing: border-box; - overflow: auto; - border: 0; - border-radius: var(--radius-surface); - padding: 0; - color: var(--color-content); - background: var(--color-panel); - box-shadow: var(--dialog-elevation); - } - - .ui-dialog::backdrop { - background: color-mix(in oklch, var(--color-content) 55%, transparent); - backdrop-filter: blur(2px); - } - - .ui-drawer { - width: var(--drawer-width); - max-width: none; - height: 100dvh; - max-height: none; - margin-block: 0; - border-radius: 0; - } - - .ui-drawer--start { - margin-inline: 0 auto; - } - - .ui-drawer--end { - margin-inline: auto 0; - } - - .ui-drawer .ui-dialog__surface { - min-height: 100%; - box-sizing: border-box; - } - - .ui-popover, - .ui-menu, - .ui-tooltip { - position: relative; - display: inline-block; - } - - .ui-popover__content, - .ui-menu__content { - position: absolute; - z-index: var(--layer-popover); - top: calc(100% + var(--space-2)); - inset-inline-start: 0; - min-width: 12rem; - border: 1px solid var(--color-border); - border-radius: var(--radius-control); - padding: var(--space-2); - background: var(--color-surface-elevated); - box-shadow: var(--elevation-popover); - } - - .ui-menu__content { - display: grid; - gap: var(--space-1); - } - - .ui-menu__item { - min-height: var(--size-control-sm); - border: 0; - border-radius: var(--radius-control); - padding: var(--space-2) var(--space-3); - color: var(--color-content); - background: transparent; - text-align: start; - cursor: pointer; - } - - .ui-menu__item:hover, - .ui-menu__item:focus-visible { - background: var(--color-surface-muted); - } - - .ui-tooltip__content { - position: absolute; - z-index: var(--layer-popover); - inset-block-end: calc(100% + var(--space-2)); - inset-inline-start: 50%; - width: max-content; - max-width: 16rem; - padding: var(--space-2); - border-radius: var(--radius-control); - color: var(--color-content-inverse); - background: var(--color-content); - opacity: 0; - pointer-events: none; - transform: translateX(-50%); - transition: opacity var(--duration-fast) var(--easing-standard); - } - - .ui-tooltip:focus-within .ui-tooltip__content, - .ui-tooltip:hover .ui-tooltip__content { - opacity: 1; - } - - .ui-progress, - .ui-progress__label { - display: grid; - gap: var(--space-2); - } - - .ui-progress__label { - grid-template-columns: 1fr auto; - } - - .ui-progress__bar { - width: 100%; - accent-color: var(--color-action); - } - - .ui-skeleton--text { - height: 1em; - } - - .ui-skeleton--control { - height: var(--size-control-md); - } - - .ui-skeleton--surface { - height: 6rem; - } - - .ui-separator { - width: 100%; - border: 0; - border-block-start: 1px solid var(--color-border); - } - - .ui-breadcrumbs ol, - .ui-pagination, - .ui-tabs__list { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: var(--space-2); - margin: 0; - padding: 0; - list-style: none; - } - - .ui-breadcrumbs li:not(:last-child)::after { - margin-inline-start: var(--space-2); - color: var(--color-content-muted); - content: "/"; - } - - .ui-tabs { - display: grid; - gap: var(--space-3); - } - - .ui-tabs__list { - border-block-end: 1px solid var(--color-border); - } - - .ui-tabs__tab { - min-height: var(--size-touch-target); - border: 0; - border-block-end: 0.2rem solid transparent; - padding: var(--space-2) var(--space-3); - color: var(--color-content-muted); - background: transparent; - cursor: pointer; - } - - .ui-tabs__tab[aria-selected="true"] { - border-block-end-color: var(--color-action); - color: var(--color-content); - font-weight: var(--font-weight-bold); - } - - .ui-tabs__panel { - padding: var(--space-3); - } - - .ui-toast-region { - position: fixed; - z-index: var(--layer-toast); - inset-block-end: var(--space-4); - inset-inline-end: var(--space-4); - display: grid; - width: var(--toast-width); - gap: var(--space-2); - } - - .ui-toast { - display: flex; - align-items: flex-start; - justify-content: space-between; - gap: var(--space-3); - border: 1px solid var(--color-border); - border-inline-start: 0.25rem solid var(--color-info-border); - border-radius: var(--radius-control); - padding: var(--space-3); - background: var(--color-surface-elevated); - box-shadow: var(--elevation-popover); - } - - .ui-toast--success { - border-inline-start-color: var(--color-success-border); - } - - .ui-toast--warning { - border-inline-start-color: var(--color-warning-border); - } - - .ui-toast--danger { - border-inline-start-color: var(--color-danger-border); - } - - .ui-toast p { - margin: var(--space-1) 0 0; - color: var(--color-content-muted); - } - - .ui-data-table__scroll { - max-width: 100%; - overflow-x: auto; - } - - .ui-data-table { - width: 100%; - border-collapse: collapse; - } - - .ui-data-table caption { - margin-block-end: var(--space-2); - font-weight: var(--font-weight-bold); - text-align: start; - } - - .ui-data-table th, - .ui-data-table td { - border-block-end: 1px solid var(--color-border); - padding: var(--space-3); - text-align: start; - } - - .ui-search-filter-toolbar, - .ui-pagination-bar { - display: flex; - flex-wrap: wrap; - align-items: end; - justify-content: space-between; - gap: var(--space-3); - } - - .ui-disclosure-group { - display: grid; - gap: var(--space-2); - } - - .ui-disclosure-group details { - border: 1px solid var(--color-border); - border-radius: var(--radius-control); - padding: var(--space-3); - } - - .ui-disclosure-group summary { - min-height: var(--size-control-sm); - cursor: pointer; - font-weight: var(--font-weight-bold); - } - - .ui-focus-ring { - display: inline-flex; - border-radius: var(--radius-control); - } - - .ui-focus-ring:focus-within { - outline: 0.1875rem solid var(--color-focus); - outline-offset: 0.1875rem; - } - - .ui-dialog__surface { - padding: 1.5rem; - } - - .ui-dialog__header { - display: flex; - align-items: flex-start; - justify-content: space-between; - gap: 1rem; - } - - .ui-dialog__header h2 { - margin-block-end: 0.35rem; - } - - .ui-dialog__header p, - .ui-dialog__content p { - color: var(--color-content-muted); - line-height: 1.6; - } - - .ui-dialog__content { - padding-block: 1rem; - } - - .ui-dialog__actions { - display: flex; - flex-wrap: wrap; - justify-content: flex-end; - gap: 0.75rem; - padding-block-start: 1rem; - border-top: 1px solid var(--color-surface-muted); - } - - .page-header { - max-width: 50rem; - padding-block: clamp(1rem, 5vw, 3.5rem) 0.5rem; - } - - [data-route-heading]:focus { - outline: none; - } - - .page-header__eyebrow { - margin-block-end: 0.75rem; - color: var(--color-action); - font-size: 0.8rem; - font-weight: 800; - letter-spacing: 0.08em; - text-transform: uppercase; - } - - .page-header__description { - max-width: 45rem; - color: var(--color-content-muted); - font-size: 1.05rem; - line-height: 1.7; - } - - .page-template { - display: grid; - gap: 1.25rem; - min-width: 0; - } - - .page-template__breadcrumb { - padding-block-start: 1rem; - color: var(--color-content-muted); - font-size: 0.9rem; - } - - .page-template__heading { - display: grid; - min-width: 0; - grid-template-columns: minmax(0, 1fr) auto; - align-items: end; - gap: 1rem; - } - - .page-template__heading .page-header { - grid-row: span 2; - min-width: 0; - } - - .page-template__status, - .page-template__actions, - .status-page__actions, - .form-actions { - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: flex-end; - gap: 0.75rem; - } - - .page-template__layout { - display: grid; - min-width: 0; - gap: 1.5rem; - } - - .page-template__layout[data-has-aside="true"] { - grid-template-columns: minmax(0, 1fr) minmax(14rem, 20rem); - } - - .page-template__content, - .page-template__aside, - .collection-page__results, - .detail-page__sections, - .form-page__fields { - min-width: 0; - } - - .page-template__aside, - .detail-page__metadata, - .collection-page__toolbar, - .form-error-summary { - border: 1px solid var(--color-border); - border-radius: var(--radius-surface); - padding: 1rem; - background: var(--color-panel); - } - - .collection-page__toolbar, - .collection-page__active-filters, - .collection-page__bulk-actions { - display: flex; - flex-wrap: wrap; - align-items: end; - gap: 0.75rem; - } - - .collection-page__result-count { - color: var(--color-content-muted); - } - - .collection-page__results, - .detail-page__sections, - .form-page__fields, - .form-page__error-summary { - display: grid; - gap: 1rem; - } - - .collection-page__pagination { - margin-block-start: 1.25rem; - } - - .detail-page__danger { - margin-block-start: 2rem; - border-top: 1px solid var(--color-danger-border); - padding-block-start: 1rem; - } - - .form-error-summary { - border-color: var(--color-danger-border); - background: var(--color-danger-surface); - } - - .form-error-summary h2 { - font-size: 1.1rem; - } - - .form-error-summary p, - .form-error-summary ul { - margin-block-end: 0; - } - - .form-actions { - padding-block-start: 1rem; - border-top: 1px solid var(--color-border); - } - - .form-actions--sticky { - position: sticky; - z-index: 10; - bottom: 0; - padding: 0.75rem; - background: color-mix(in oklch, var(--color-panel) 94%, transparent); - } - - .status-page { - max-width: 48rem; - padding-block: 2rem; - } - - .status-page__actions { - justify-content: flex-start; - } - - .status-page__support { - color: var(--color-content-muted); - } - - .readiness-grid { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 1rem; - } - - .readiness-grid p, - .starter-actions p { - margin-block-end: 0; - color: var(--color-content-muted); - line-height: 1.65; - } - - .starter-actions, - .auth-example { - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: space-between; - gap: 1.5rem; - } - - .button-row { - display: flex; - flex-wrap: wrap; - gap: 0.75rem; - } - - .route-loading { - padding-block-start: 4rem; - } - - .gallery-section { - display: grid; - gap: 1rem; - padding-block: 0.5rem; - } - - .gallery-section__header { - max-width: 45rem; - } - - .gallery-section__header h2, - .gallery-section__header p { - margin-block-end: 0; - } - - .gallery-section__header p { - margin-block-start: 0.4rem; - color: var(--color-content-muted); - line-height: 1.6; - } - - .component-grid { - display: grid; - gap: 1rem; - } - - .component-grid--two { - grid-template-columns: repeat(2, minmax(0, 1fr)); - } - - .component-grid--three { - grid-template-columns: repeat(3, minmax(0, 1fr)); - } - - .component-stack, - .example-form { - display: grid; - gap: 1rem; - } - - .platform-metric-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(13rem, 1fr)); - gap: 1rem; - margin-block: 0; - } - - .platform-metric { - display: grid; - gap: 0.25rem; - padding: 0.85rem 1rem; - border: 1px solid var(--color-border); - border-radius: var(--radius-surface); - background: var(--color-panel); - } - - .platform-metric dt { - font-size: 0.8125rem; - color: var(--color-content-muted); - } - - .platform-metric dd { - display: grid; - gap: 0.15rem; - margin-inline-start: 0; - } - - .platform-metric__value { - font-weight: 600; - overflow-wrap: anywhere; - } - - .platform-metric__hint, - .platform-operation__path { - display: block; - font-size: 0.8125rem; - color: var(--color-content-muted); - overflow-wrap: anywhere; - } - - .badge-row { - display: flex; - flex-wrap: wrap; - gap: 0.5rem; - } - - .token-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr)); - gap: 0.75rem; - } - - .token-swatch { - display: grid; - gap: 0.45rem; - min-width: 0; - border: 1px solid var(--color-border); - border-radius: var(--radius-control); - padding: 0.75rem; - background: var(--color-panel); - } - - .token-swatch__color { - height: 4rem; - border: 1px solid color-mix(in oklch, var(--color-content) 15%, transparent); - border-radius: calc(var(--radius-control) / 1.5); - } - - .token-swatch code { - overflow: hidden; - color: var(--color-content-muted); - font-size: 0.75rem; - text-overflow: ellipsis; - white-space: nowrap; - } - - .gallery-notice { - display: block; - width: fit-content; - max-width: 100%; - box-sizing: border-box; - border: 1px solid var(--color-surface-muted); - border-radius: 999px; - padding: 0.65rem 1rem; - color: var(--color-content); - background: var(--color-panel); - box-shadow: 0 8px 28px color-mix(in oklch, var(--color-content) 10%, transparent); - font-size: 0.875rem; - font-weight: 650; - } - - .state-surface { - display: flex; - min-height: 12rem; - box-sizing: border-box; - flex-direction: column; - align-items: flex-start; - justify-content: center; - border: 1px solid var(--color-surface-muted); - border-radius: var(--radius-surface); - padding: 1.25rem; - background: var(--color-surface); - } - - .state-surface h2, - .state-surface p { - margin-block-end: 0.75rem; - } - - .state-surface > p:not(.state-surface__eyebrow) { - color: var(--color-content-muted); - line-height: 1.55; - } - - .state-surface__eyebrow { - color: var(--color-action-hover); - font-size: 0.75rem; - font-weight: 800; - letter-spacing: 0.04em; - } - - .state-surface--warning { - border-color: var(--color-warning-border); - background: var(--color-warning-surface); - } - - .state-surface--danger, - .ui-terminal-error { - border-color: var(--color-danger-border); - background: var(--color-danger-surface); - } - - .state-surface--loading { - gap: 0.75rem; - } - - .state-surface--loading .ui-skeleton { - width: 100%; - } - - .state-preview-content { - border-radius: var(--radius-control); - padding: 1rem; - background: var(--color-surface); - } - - .app-shell__scrim { - display: none; - } -} - -@media (max-width: 47.999rem) { - .app-shell { - grid-template-columns: minmax(0, 1fr); - grid-template-areas: - "header" - "content"; - } - - .app-shell__header { - padding-inline: 0.75rem; - } - - .app-shell__menu-button.ui-icon-button { - display: inline-flex; - } - - .app-shell__sidebar { - position: fixed; - z-index: 50; - top: 4.5rem; - bottom: 0; - left: 0; - display: none; - width: min(18rem, 85vw); - height: auto; - box-sizing: border-box; - box-shadow: 10px 0 30px color-mix(in oklch, var(--color-content) 15%, transparent); - } - - .app-shell__sidebar[data-open="true"] { - display: block; - } - - .app-shell__scrim { - position: fixed; - z-index: 40; - inset: 4.5rem 0 0; - display: block; - border: 0; - background: color-mix(in oklch, var(--color-content) 35%, transparent); - cursor: pointer; - } - - .app-shell__session .session-status { - display: none; - } - - .app-shell__session .theme-selector { - display: none; - } - - .app-shell__brand { - display: none; - } - - .readiness-grid { - grid-template-columns: minmax(0, 1fr); - } - - .component-grid--two, - .component-grid--three { - grid-template-columns: minmax(0, 1fr); - } - - .page-template__heading, - .page-template__layout[data-has-aside="true"] { - grid-template-columns: minmax(0, 1fr); - } - - .page-template__heading .page-header { - grid-row: auto; - } - - .page-template__actions, - .page-template__status { - justify-content: flex-start; - } - - .form-actions--sticky { - margin-inline: calc(var(--spacing-page) * -1); - } -} - -@media (prefers-reduced-motion: reduce) { - *, - *::before, - *::after { - scroll-behavior: auto !important; - animation-duration: 0.01ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.01ms !important; - } -} +@import "./theme/base.css"; +@import "./theme/shell.css"; +@import "./theme/primitives.css"; +@import "./theme/templates.css"; +@import "./theme/pages.css"; +@import "./theme/responsive.css"; diff --git a/src/presentation/styles/theme/base.css b/src/presentation/styles/theme/base.css new file mode 100644 index 00000000..aeb4f630 --- /dev/null +++ b/src/presentation/styles/theme/base.css @@ -0,0 +1,45 @@ +@layer base { + :root { + color: var(--color-content); + background: var(--color-surface); + font-family: var(--font-sans); + } + + body { + margin: 0; + min-width: 20rem; + min-height: 100vh; + } + + button, + input, + textarea, + select { + font: inherit; + } + + a { + color: inherit; + } + + h1, + h2, + p { + margin-block-start: 0; + } + + h1 { + font-size: clamp(2rem, 5vw, 3.5rem); + line-height: 1.05; + letter-spacing: -0.04em; + } + + h2 { + line-height: 1.25; + } + + :focus-visible { + outline: 0.1875rem solid var(--color-focus); + outline-offset: 0.1875rem; + } +} diff --git a/src/presentation/styles/theme/pages.css b/src/presentation/styles/theme/pages.css new file mode 100644 index 00000000..7d118b71 --- /dev/null +++ b/src/presentation/styles/theme/pages.css @@ -0,0 +1,223 @@ +@layer components { + .readiness-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 1rem; + } + + .readiness-grid p, + .starter-actions p { + margin-block-end: 0; + color: var(--color-content-muted); + line-height: 1.65; + } + + .starter-actions, + .auth-example { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 1.5rem; + } + + .button-row { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + } + + .route-loading { + padding-block-start: 4rem; + } + + .gallery-section { + display: grid; + gap: 1rem; + padding-block: 0.5rem; + } + + .gallery-section__header { + max-width: 45rem; + } + + .gallery-section__header h2, + .gallery-section__header p { + margin-block-end: 0; + } + + .gallery-section__header p { + margin-block-start: 0.4rem; + color: var(--color-content-muted); + line-height: 1.6; + } + + .component-grid { + display: grid; + gap: 1rem; + } + + .component-grid--two { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .component-grid--three { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + + .component-stack, + .example-form { + display: grid; + gap: 1rem; + } + + .platform-metric-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(13rem, 1fr)); + gap: 1rem; + margin-block: 0; + } + + .platform-metric { + display: grid; + gap: 0.25rem; + padding: 0.85rem 1rem; + border: 1px solid var(--color-border); + border-radius: var(--radius-surface); + background: var(--color-panel); + } + + .platform-metric dt { + font-size: 0.8125rem; + color: var(--color-content-muted); + } + + .platform-metric dd { + display: grid; + gap: 0.15rem; + margin-inline-start: 0; + } + + .platform-metric__value { + font-weight: 600; + overflow-wrap: anywhere; + } + + .platform-metric__hint, + .platform-operation__path { + display: block; + font-size: 0.8125rem; + color: var(--color-content-muted); + overflow-wrap: anywhere; + } + + .badge-row { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + } + + .token-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr)); + gap: 0.75rem; + } + + .token-swatch { + display: grid; + gap: 0.45rem; + min-width: 0; + border: 1px solid var(--color-border); + border-radius: var(--radius-control); + padding: 0.75rem; + background: var(--color-panel); + } + + .token-swatch__color { + height: 4rem; + border: 1px solid color-mix(in oklch, var(--color-content) 15%, transparent); + border-radius: calc(var(--radius-control) / 1.5); + } + + .token-swatch code { + overflow: hidden; + color: var(--color-content-muted); + font-size: 0.75rem; + text-overflow: ellipsis; + white-space: nowrap; + } + + .gallery-notice { + display: block; + width: fit-content; + max-width: 100%; + box-sizing: border-box; + border: 1px solid var(--color-surface-muted); + border-radius: 999px; + padding: 0.65rem 1rem; + color: var(--color-content); + background: var(--color-panel); + box-shadow: 0 8px 28px color-mix(in oklch, var(--color-content) 10%, transparent); + font-size: 0.875rem; + font-weight: 650; + } + + .state-surface { + display: flex; + min-height: 12rem; + box-sizing: border-box; + flex-direction: column; + align-items: flex-start; + justify-content: center; + border: 1px solid var(--color-surface-muted); + border-radius: var(--radius-surface); + padding: 1.25rem; + background: var(--color-surface); + } + + .state-surface h2, + .state-surface p { + margin-block-end: 0.75rem; + } + + .state-surface > p:not(.state-surface__eyebrow) { + color: var(--color-content-muted); + line-height: 1.55; + } + + .state-surface__eyebrow { + color: var(--color-action-hover); + font-size: 0.75rem; + font-weight: 800; + letter-spacing: 0.04em; + } + + .state-surface--warning { + border-color: var(--color-warning-border); + background: var(--color-warning-surface); + } + + .state-surface--danger, + .ui-terminal-error { + border-color: var(--color-danger-border); + background: var(--color-danger-surface); + } + + .state-surface--loading { + gap: 0.75rem; + } + + .state-surface--loading .ui-skeleton { + width: 100%; + } + + .state-preview-content { + border-radius: var(--radius-control); + padding: 1rem; + background: var(--color-surface); + } + + .app-shell__scrim { + display: none; + } +} diff --git a/src/presentation/styles/theme/primitives.css b/src/presentation/styles/theme/primitives.css new file mode 100644 index 00000000..92f73d56 --- /dev/null +++ b/src/presentation/styles/theme/primitives.css @@ -0,0 +1,719 @@ +@layer components { + .ui-page { + @apply mx-auto flex max-w-6xl flex-col gap-6 p-page; + width: 100%; + box-sizing: border-box; + } + + .ui-panel { + @apply rounded-surface p-6 shadow-sm; + border: 1px solid var(--color-border); + background: var(--color-panel); + } + + .ui-button { + @apply rounded-control bg-action px-4 py-2 font-semibold; + display: inline-flex; + min-height: 2.75rem; + align-items: center; + justify-content: center; + border: 0; + color: var(--color-on-action); + text-decoration: none; + cursor: pointer; + } + + .ui-button:hover { + @apply bg-action-hover; + } + + .ui-button:disabled { + cursor: not-allowed; + opacity: var(--opacity-disabled); + } + + .ui-button--pending { + gap: var(--space-2); + cursor: progress; + } + + .ui-button--secondary { + border: 1px solid var(--color-surface-muted); + color: var(--color-content); + background: var(--color-panel); + } + + .ui-button--secondary:hover { + color: var(--color-action); + background: var(--color-surface); + } + + .ui-button--danger { + color: var(--color-on-action); + background: var(--color-danger); + } + + .ui-button--danger:hover { + background: var(--color-danger-hover); + } + + .ui-button--ghost { + color: var(--color-content); + background: transparent; + } + + .ui-button--ghost:hover { + color: var(--color-action); + background: var(--color-surface-muted); + } + + .ui-button--compact { + min-height: var(--size-control-sm); + padding: 0.4rem 0.75rem; + font-size: 0.85rem; + } + + .ui-icon-button { + width: var(--size-touch-target); + min-width: var(--size-touch-target); + padding: 0; + } + + .app-shell__menu-button.ui-icon-button { + display: none; + } + + .ui-icon { + display: inline-block; + flex: 0 0 auto; + stroke-width: var(--icon-stroke-default); + } + + .ui-icon--small { + width: var(--size-icon-sm); + height: var(--size-icon-sm); + } + + .ui-icon--medium { + width: var(--size-icon-md); + height: var(--size-icon-md); + } + + .ui-icon--large { + width: var(--size-icon-lg); + height: var(--size-icon-lg); + } + + .ui-spinner { + display: inline-block; + width: var(--size-icon-sm); + height: var(--size-icon-sm); + box-sizing: border-box; + border: 2px solid currentColor; + border-inline-end-color: transparent; + border-radius: var(--radius-full); + animation: ui-spin var(--duration-slow) linear infinite; + } + + @keyframes ui-spin { + to { + transform: rotate(360deg); + } + } + + .ui-skeleton { + @apply h-24 animate-pulse rounded-surface bg-surface-muted; + } + + .ui-empty, + .ui-terminal-error { + @apply rounded-surface border border-surface-muted p-6; + } + + .ui-field { + display: grid; + gap: 0.45rem; + } + + .ui-field__label { + font-weight: 750; + } + + .ui-field__description, + .ui-field__error { + margin: 0; + font-size: 0.875rem; + line-height: 1.5; + } + + .ui-field__description { + color: var(--color-content-muted); + } + + .ui-field__error { + color: var(--color-danger); + font-weight: 650; + } + + .ui-field__input { + width: 100%; + min-height: 2.75rem; + box-sizing: border-box; + border: 1px solid + color-mix(in oklch, var(--color-content-muted) 55%, var(--color-panel)); + border-radius: var(--radius-control); + padding: 0.65rem 0.8rem; + color: var(--color-content); + background: var(--color-panel); + } + + .ui-field__input[aria-invalid="true"] { + border-color: var(--field-border-invalid); + } + + .ui-field__textarea { + min-height: 7rem; + resize: vertical; + } + + .ui-field__counter { + justify-self: end; + color: var(--color-content-muted); + font-size: var(--font-size-sm); + } + + .ui-choice-field, + .ui-radio-group, + .ui-switch-field { + display: grid; + gap: var(--space-2); + } + + .ui-choice-field__control { + display: flex; + min-height: var(--size-touch-target); + align-items: center; + gap: var(--space-2); + cursor: pointer; + } + + .ui-choice-field__control input { + width: 1.15rem; + height: 1.15rem; + accent-color: var(--color-action); + } + + .ui-choice-field__control small { + display: block; + color: var(--color-content-muted); + } + + .ui-radio-group { + min-width: 0; + border: 1px solid var(--color-border); + border-radius: var(--radius-control); + padding: var(--space-3); + } + + .ui-radio-group legend { + padding-inline: var(--space-1); + font-weight: var(--font-weight-bold); + } + + .ui-switch { + display: inline-flex; + width: fit-content; + min-height: var(--size-touch-target); + align-items: center; + gap: var(--space-2); + border: 0; + color: var(--color-content); + background: transparent; + cursor: pointer; + } + + .ui-switch__thumb { + display: inline-block; + width: 2.5rem; + height: 1.5rem; + border: 1px solid var(--color-border-strong); + border-radius: var(--radius-full); + background: var(--color-disabled-surface); + } + + .ui-switch__thumb::after { + display: block; + width: 1rem; + height: 1rem; + margin: 0.2rem; + border-radius: var(--radius-full); + background: var(--color-content-muted); + content: ""; + transition: transform var(--duration-normal) var(--easing-standard); + } + + .ui-switch[aria-checked="true"] .ui-switch__thumb { + border-color: var(--color-action); + background: var(--color-action); + } + + .ui-switch[aria-checked="true"] .ui-switch__thumb::after { + background: var(--color-on-action); + transform: translateX(1rem); + } + + [dir="rtl"] .ui-switch[aria-checked="true"] .ui-switch__thumb::after { + transform: translateX(-1rem); + } + + .ui-search-field { + position: relative; + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + align-items: end; + gap: var(--space-2); + } + + .ui-card { + display: flex; + min-width: 0; + flex-direction: column; + gap: 1.25rem; + border: 1px solid var(--color-border); + border-radius: var(--radius-surface); + padding: 1.25rem; + background: var(--color-panel); + box-shadow: 0 8px 28px color-mix(in oklch, var(--color-content) 6%, transparent); + } + + .ui-card__header :is(h2, h3, h4), + .ui-card__header p { + margin-block-end: 0; + } + + .ui-card__header p { + margin-block-start: 0.4rem; + color: var(--color-content-muted); + line-height: 1.55; + } + + .ui-card__content { + flex: 1; + } + + .ui-card__footer { + padding-block-start: 1rem; + border-top: 1px solid var(--color-surface-muted); + } + + .ui-alert { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + border: 1px solid var(--color-surface-muted); + border-radius: var(--radius-control); + padding: 1rem; + background: var(--color-surface); + } + + .ui-alert--info { + border-color: var(--color-info-border); + background: var(--color-info-surface); + } + + .ui-alert--success { + border-color: var(--color-success-border); + background: var(--color-success-surface); + } + + .ui-alert--warning { + border-color: var(--color-warning-border); + background: var(--color-warning-surface); + } + + .ui-alert--danger { + border-color: var(--color-danger-border); + background: var(--color-danger-surface); + } + + .ui-alert__content, + .ui-alert__content p { + margin-block: 0.35rem 0; + color: var(--color-content-muted); + } + + .ui-alert__dismiss, + .ui-dialog__close { + display: inline-grid; + width: 2rem; + height: 2rem; + flex: 0 0 auto; + place-items: center; + border: 0; + border-radius: var(--radius-control); + color: var(--color-content); + background: transparent; + font-size: 1.35rem; + cursor: pointer; + } + + .ui-alert__dismiss.ui-icon-button, + .ui-dialog__close.ui-icon-button { + min-width: 2rem; + min-height: 2rem; + padding: 0; + } + + .ui-alert__dismiss:hover, + .ui-dialog__close:hover { + background: color-mix(in oklch, var(--color-content) 8%, transparent); + } + + .ui-badge { + display: inline-flex; + border-radius: 999px; + padding: 0.3rem 0.65rem; + color: var(--color-content); + background: var(--color-surface-muted); + font-size: 0.8rem; + font-weight: 750; + } + + .ui-badge--info { + color: var(--color-info-content); + background: var(--color-info-surface); + } + + .ui-badge--success { + color: var(--color-success-content); + background: var(--color-success-surface); + } + + .ui-badge--warning { + color: var(--color-warning-content); + background: var(--color-warning-surface); + } + + .ui-badge--danger { + color: var(--color-danger-content); + background: var(--color-danger-surface); + } + + .ui-dialog { + width: min(34rem, calc(100vw - 2rem)); + max-height: calc(100vh - 2rem); + box-sizing: border-box; + overflow: auto; + border: 0; + border-radius: var(--radius-surface); + padding: 0; + color: var(--color-content); + background: var(--color-panel); + box-shadow: var(--dialog-elevation); + } + + .ui-dialog::backdrop { + background: color-mix(in oklch, var(--color-content) 55%, transparent); + backdrop-filter: blur(2px); + } + + .ui-drawer { + width: var(--drawer-width); + max-width: none; + height: 100dvh; + max-height: none; + margin-block: 0; + border-radius: 0; + } + + .ui-drawer--start { + margin-inline: 0 auto; + } + + .ui-drawer--end { + margin-inline: auto 0; + } + + .ui-drawer .ui-dialog__surface { + min-height: 100%; + box-sizing: border-box; + } + + .ui-popover, + .ui-menu, + .ui-tooltip { + position: relative; + display: inline-block; + } + + .ui-popover__content, + .ui-menu__content { + position: absolute; + z-index: var(--layer-popover); + top: calc(100% + var(--space-2)); + inset-inline-start: 0; + min-width: 12rem; + border: 1px solid var(--color-border); + border-radius: var(--radius-control); + padding: var(--space-2); + background: var(--color-surface-elevated); + box-shadow: var(--elevation-popover); + } + + .ui-menu__content { + display: grid; + gap: var(--space-1); + } + + .ui-menu__item { + min-height: var(--size-control-sm); + border: 0; + border-radius: var(--radius-control); + padding: var(--space-2) var(--space-3); + color: var(--color-content); + background: transparent; + text-align: start; + cursor: pointer; + } + + .ui-menu__item:hover, + .ui-menu__item:focus-visible { + background: var(--color-surface-muted); + } + + .ui-tooltip__content { + position: absolute; + z-index: var(--layer-popover); + inset-block-end: calc(100% + var(--space-2)); + inset-inline-start: 50%; + width: max-content; + max-width: 16rem; + padding: var(--space-2); + border-radius: var(--radius-control); + color: var(--color-content-inverse); + background: var(--color-content); + opacity: 0; + pointer-events: none; + transform: translateX(-50%); + transition: opacity var(--duration-fast) var(--easing-standard); + } + + .ui-tooltip:focus-within .ui-tooltip__content, + .ui-tooltip:hover .ui-tooltip__content { + opacity: 1; + } + + .ui-progress, + .ui-progress__label { + display: grid; + gap: var(--space-2); + } + + .ui-progress__label { + grid-template-columns: 1fr auto; + } + + .ui-progress__bar { + width: 100%; + accent-color: var(--color-action); + } + + .ui-skeleton--text { + height: 1em; + } + + .ui-skeleton--control { + height: var(--size-control-md); + } + + .ui-skeleton--surface { + height: 6rem; + } + + .ui-separator { + width: 100%; + border: 0; + border-block-start: 1px solid var(--color-border); + } + + .ui-breadcrumbs ol, + .ui-pagination, + .ui-tabs__list { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-2); + margin: 0; + padding: 0; + list-style: none; + } + + .ui-breadcrumbs li:not(:last-child)::after { + margin-inline-start: var(--space-2); + color: var(--color-content-muted); + content: "/"; + } + + .ui-tabs { + display: grid; + gap: var(--space-3); + } + + .ui-tabs__list { + border-block-end: 1px solid var(--color-border); + } + + .ui-tabs__tab { + min-height: var(--size-touch-target); + border: 0; + border-block-end: 0.2rem solid transparent; + padding: var(--space-2) var(--space-3); + color: var(--color-content-muted); + background: transparent; + cursor: pointer; + } + + .ui-tabs__tab[aria-selected="true"] { + border-block-end-color: var(--color-action); + color: var(--color-content); + font-weight: var(--font-weight-bold); + } + + .ui-tabs__panel { + padding: var(--space-3); + } + + .ui-toast-region { + position: fixed; + z-index: var(--layer-toast); + inset-block-end: var(--space-4); + inset-inline-end: var(--space-4); + display: grid; + width: var(--toast-width); + gap: var(--space-2); + } + + .ui-toast { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: var(--space-3); + border: 1px solid var(--color-border); + border-inline-start: 0.25rem solid var(--color-info-border); + border-radius: var(--radius-control); + padding: var(--space-3); + background: var(--color-surface-elevated); + box-shadow: var(--elevation-popover); + } + + .ui-toast--success { + border-inline-start-color: var(--color-success-border); + } + + .ui-toast--warning { + border-inline-start-color: var(--color-warning-border); + } + + .ui-toast--danger { + border-inline-start-color: var(--color-danger-border); + } + + .ui-toast p { + margin: var(--space-1) 0 0; + color: var(--color-content-muted); + } + + .ui-data-table__scroll { + max-width: 100%; + overflow-x: auto; + } + + .ui-data-table { + width: 100%; + border-collapse: collapse; + } + + .ui-data-table caption { + margin-block-end: var(--space-2); + font-weight: var(--font-weight-bold); + text-align: start; + } + + .ui-data-table th, + .ui-data-table td { + border-block-end: 1px solid var(--color-border); + padding: var(--space-3); + text-align: start; + } + + .ui-search-filter-toolbar, + .ui-pagination-bar { + display: flex; + flex-wrap: wrap; + align-items: end; + justify-content: space-between; + gap: var(--space-3); + } + + .ui-disclosure-group { + display: grid; + gap: var(--space-2); + } + + .ui-disclosure-group details { + border: 1px solid var(--color-border); + border-radius: var(--radius-control); + padding: var(--space-3); + } + + .ui-disclosure-group summary { + min-height: var(--size-control-sm); + cursor: pointer; + font-weight: var(--font-weight-bold); + } + + .ui-focus-ring { + display: inline-flex; + border-radius: var(--radius-control); + } + + .ui-focus-ring:focus-within { + outline: 0.1875rem solid var(--color-focus); + outline-offset: 0.1875rem; + } + + .ui-dialog__surface { + padding: 1.5rem; + } + + .ui-dialog__header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + } + + .ui-dialog__header h2 { + margin-block-end: 0.35rem; + } + + .ui-dialog__header p, + .ui-dialog__content p { + color: var(--color-content-muted); + line-height: 1.6; + } + + .ui-dialog__content { + padding-block: 1rem; + } + + .ui-dialog__actions { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 0.75rem; + padding-block-start: 1rem; + border-top: 1px solid var(--color-surface-muted); + } +} diff --git a/src/presentation/styles/theme/responsive.css b/src/presentation/styles/theme/responsive.css new file mode 100644 index 00000000..0f07bb6a --- /dev/null +++ b/src/presentation/styles/theme/responsive.css @@ -0,0 +1,93 @@ +@media (max-width: 47.999rem) { + .app-shell { + grid-template-columns: minmax(0, 1fr); + grid-template-areas: + "header" + "content"; + } + + .app-shell__header { + padding-inline: 0.75rem; + } + + .app-shell__menu-button.ui-icon-button { + display: inline-flex; + } + + .app-shell__sidebar { + position: fixed; + z-index: 50; + top: 4.5rem; + bottom: 0; + left: 0; + display: none; + width: min(18rem, 85vw); + height: auto; + box-sizing: border-box; + box-shadow: 10px 0 30px color-mix(in oklch, var(--color-content) 15%, transparent); + } + + .app-shell__sidebar[data-open="true"] { + display: block; + } + + .app-shell__scrim { + position: fixed; + z-index: 40; + inset: 4.5rem 0 0; + display: block; + border: 0; + background: color-mix(in oklch, var(--color-content) 35%, transparent); + cursor: pointer; + } + + .app-shell__session .session-status { + display: none; + } + + .app-shell__session .theme-selector { + display: none; + } + + .app-shell__brand { + display: none; + } + + .readiness-grid { + grid-template-columns: minmax(0, 1fr); + } + + .component-grid--two, + .component-grid--three { + grid-template-columns: minmax(0, 1fr); + } + + .page-template__heading, + .page-template__layout[data-has-aside="true"] { + grid-template-columns: minmax(0, 1fr); + } + + .page-template__heading .page-header { + grid-row: auto; + } + + .page-template__actions, + .page-template__status { + justify-content: flex-start; + } + + .form-actions--sticky { + margin-inline: calc(var(--spacing-page) * -1); + } +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + scroll-behavior: auto !important; + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +} diff --git a/src/presentation/styles/theme/shell.css b/src/presentation/styles/theme/shell.css new file mode 100644 index 00000000..2d2afee3 --- /dev/null +++ b/src/presentation/styles/theme/shell.css @@ -0,0 +1,190 @@ +@layer components { + .visually-hidden { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; + } + + .skip-link { + position: fixed; + z-index: 100; + top: 0.75rem; + left: 0.75rem; + padding: 0.75rem 1rem; + border-radius: var(--radius-control); + color: var(--color-panel); + background: var(--color-content); + transform: translateY(-200%); + } + + .skip-link:focus { + transform: translateY(0); + } + + .app-shell { + display: grid; + min-height: 100vh; + grid-template-rows: 4.5rem 1fr; + grid-template-columns: 15rem minmax(0, 1fr); + grid-template-areas: + "header header" + "sidebar content"; + } + + .app-shell__header { + position: sticky; + z-index: 30; + top: 0; + grid-area: header; + display: flex; + align-items: center; + gap: 1rem; + min-width: 0; + padding: 0.75rem 1.25rem; + border-bottom: 1px solid var(--color-surface-muted); + background: color-mix(in oklch, var(--color-panel) 92%, var(--color-surface)); + box-shadow: 0 1px 8px color-mix(in oklch, var(--color-content) 8%, transparent); + } + + .app-shell__brand { + overflow: hidden; + font-size: 1.05rem; + font-weight: 800; + text-decoration: none; + text-overflow: ellipsis; + white-space: nowrap; + } + + .app-shell__menu-button { + display: none; + align-items: center; + gap: 0.4rem; + border: 1px solid var(--color-surface-muted); + border-radius: var(--radius-control); + padding: 0.55rem 0.75rem; + color: var(--color-content); + background: var(--color-panel); + cursor: pointer; + } + + .app-shell__session { + display: flex; + align-items: center; + gap: 0.75rem; + margin-inline-start: auto; + } + + .theme-selector, + .locale-selector { + display: block; + } + + .theme-selector .ui-field__label, + .locale-selector .ui-field__label { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; + } + + .theme-selector .ui-field__input, + .locale-selector .ui-field__input { + min-height: var(--size-control-sm); + max-width: 8.5rem; + padding: 0.35rem 2rem 0.35rem 0.65rem; + cursor: pointer; + } + + .locale-selector .ui-field__input { + max-width: 7rem; + } + + .app-shell__session-error { + position: absolute; + top: calc(100% + 0.25rem); + right: 1rem; + padding: 0.5rem; + color: var(--color-danger); + background: var(--color-panel); + } + + .session-status { + display: inline-flex; + width: fit-content; + align-items: center; + border-radius: 999px; + padding: 0.3rem 0.65rem; + color: var(--color-content-muted); + background: var(--color-surface-muted); + font-size: 0.8rem; + font-weight: 700; + } + + .session-status[data-state="authenticated"] { + color: var(--color-success-content); + background: var(--color-success-surface); + } + + .session-status[data-state="integration-failed"] { + color: var(--color-danger); + } + + .app-shell__sidebar { + position: sticky; + top: 4.5rem; + grid-area: sidebar; + height: calc(100vh - 4.5rem); + padding: 1.25rem 0.75rem; + border-right: 1px solid var(--color-border); + background: var(--color-panel); + } + + .app-navigation { + display: flex; + flex-direction: column; + gap: 0.25rem; + margin: 0; + padding: 0; + list-style: none; + } + + .app-navigation__link { + display: block; + border-radius: var(--radius-control); + padding: 0.75rem 0.9rem; + color: var(--color-content-muted); + font-weight: 650; + text-decoration: none; + } + + .app-navigation__link:hover { + color: var(--color-content); + background: var(--color-surface); + } + + .app-navigation__link.is-active { + color: var(--color-action-hover); + background: color-mix( + in oklch, + var(--color-action) 14%, + var(--color-panel) + ); + font-weight: 800; + } + + .app-shell__content { + grid-area: content; + min-width: 0; + } +} diff --git a/src/presentation/styles/theme/templates.css b/src/presentation/styles/theme/templates.css new file mode 100644 index 00000000..66c5646b --- /dev/null +++ b/src/presentation/styles/theme/templates.css @@ -0,0 +1,161 @@ +@layer components { + .page-header { + max-width: 50rem; + padding-block: clamp(1rem, 5vw, 3.5rem) 0.5rem; + } + + [data-route-heading]:focus { + outline: none; + } + + .page-header__eyebrow { + margin-block-end: 0.75rem; + color: var(--color-action); + font-size: 0.8rem; + font-weight: 800; + letter-spacing: 0.08em; + text-transform: uppercase; + } + + .page-header__description { + max-width: 45rem; + color: var(--color-content-muted); + font-size: 1.05rem; + line-height: 1.7; + } + + .page-template { + display: grid; + gap: 1.25rem; + min-width: 0; + } + + .page-template__breadcrumb { + padding-block-start: 1rem; + color: var(--color-content-muted); + font-size: 0.9rem; + } + + .page-template__heading { + display: grid; + min-width: 0; + grid-template-columns: minmax(0, 1fr) auto; + align-items: end; + gap: 1rem; + } + + .page-template__heading .page-header { + grid-row: span 2; + min-width: 0; + } + + .page-template__status, + .page-template__actions, + .status-page__actions, + .form-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + gap: 0.75rem; + } + + .page-template__layout { + display: grid; + min-width: 0; + gap: 1.5rem; + } + + .page-template__layout[data-has-aside="true"] { + grid-template-columns: minmax(0, 1fr) minmax(14rem, 20rem); + } + + .page-template__content, + .page-template__aside, + .collection-page__results, + .detail-page__sections, + .form-page__fields { + min-width: 0; + } + + .page-template__aside, + .detail-page__metadata, + .collection-page__toolbar, + .form-error-summary { + border: 1px solid var(--color-border); + border-radius: var(--radius-surface); + padding: 1rem; + background: var(--color-panel); + } + + .collection-page__toolbar, + .collection-page__active-filters, + .collection-page__bulk-actions { + display: flex; + flex-wrap: wrap; + align-items: end; + gap: 0.75rem; + } + + .collection-page__result-count { + color: var(--color-content-muted); + } + + .collection-page__results, + .detail-page__sections, + .form-page__fields, + .form-page__error-summary { + display: grid; + gap: 1rem; + } + + .collection-page__pagination { + margin-block-start: 1.25rem; + } + + .detail-page__danger { + margin-block-start: 2rem; + border-top: 1px solid var(--color-danger-border); + padding-block-start: 1rem; + } + + .form-error-summary { + border-color: var(--color-danger-border); + background: var(--color-danger-surface); + } + + .form-error-summary h2 { + font-size: 1.1rem; + } + + .form-error-summary p, + .form-error-summary ul { + margin-block-end: 0; + } + + .form-actions { + padding-block-start: 1rem; + border-top: 1px solid var(--color-border); + } + + .form-actions--sticky { + position: sticky; + z-index: 10; + bottom: 0; + padding: 0.75rem; + background: color-mix(in oklch, var(--color-panel) 94%, transparent); + } + + .status-page { + max-width: 48rem; + padding-block: 2rem; + } + + .status-page__actions { + justify-content: flex-start; + } + + .status-page__support { + color: var(--color-content-muted); + } +} diff --git a/src/presentation/templates/page-templates.tsx b/src/presentation/templates/page-templates.tsx index d6e423c1..de2890a9 100644 --- a/src/presentation/templates/page-templates.tsx +++ b/src/presentation/templates/page-templates.tsx @@ -2,6 +2,11 @@ import type { ReactNode } from "react"; import { PageHeader } from "../components/page-header.tsx"; import { Button } from "../components/ui/button.ts"; +import { + LinkButton, + type LinkTarget, +} from "../design-system/primitives/core.tsx"; +import { PaginationLandmarkContext } from "../design-system/primitives/navigation.tsx"; import { useLocale } from "../i18n/index.ts"; export type PageHeading = Readonly<{ @@ -18,12 +23,12 @@ export type PageActionDefinition = disabled?: boolean; variant?: "primary" | "secondary" | "danger" | "ghost"; }> - | Readonly<{ + | (Readonly<{ kind: "link"; label: string; - href: string; variant?: "primary" | "secondary" | "danger" | "ghost"; - }>; + }> & + LinkTarget); export type PageTemplateSlots = Readonly<{ heading: PageHeading; @@ -130,7 +135,9 @@ export function CollectionPage( className="collection-page__pagination" aria-label={message("template.pagination")} > - {props.pagination} + + {props.pagination} + ) : null} @@ -207,6 +214,10 @@ export function StatusPage( primaryAction?: PageActionDefinition; secondaryAction?: PageActionDefinition; supportReference?: string; + /** Names the answer for tests and telemetry, e.g. `invalid-route`. */ + surface?: string; + /** Extra content under the actions, such as a failure alert. */ + children?: ReactNode; }>, ) { const { message } = useLocale(); @@ -214,6 +225,7 @@ export function StatusPage(
    {props.primaryAction || props.secondaryAction ? ( @@ -226,6 +238,7 @@ export function StatusPage( } /> ) : null} + {props.children} {props.supportReference ? (

    {message("template.supportReference", { @@ -243,19 +256,23 @@ function PageActionBar(props: Readonly<{ }>) { return (

    - {props.actions.map((action) => + {/* Keyed by position: a label that changes while pending must not + remount the button the user just pressed. */} + {props.actions.map((action, index) => action.kind === "link" ? ( - {action.label} - + ) : ( + {form.result} + + ); + } + + render(); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Ready"); + await user.click(screen.getByRole("button", { name: "Submit" })); + await user.click(screen.getByRole("button", { name: "Submit" })); + releaseValidation(); + + await waitFor(() => + expect(screen.getByTestId("result")).toHaveTextContent("success"), + ); + expect(submit).toHaveBeenCalledOnce(); + }); + + it("does not ask to discard changes when navigating right after a save", async () => { + const user = userEvent.setup(); + + function SaveThenLeave() { + const navigate = useNavigate(); + const form = useAppForm({ + schema, + defaultValues: defaults, + allowedServerFields: ["name", "note"], + mapToCommand: (values) => ({ name: values.name }), + submit: async () => ({ ok: true as const, value: "saved" }), + }); + const guard = useDirtyNavigationGuard(form.dirty); + return ( +
    { + void form.submitForm(event).then((outcome) => { + if (outcome?.ok) void navigate("/done"); + }); + }} + pending={form.pending} + > + + + + + ); + } + + const router = createMemoryRouter( + [ + { path: "/", element: }, + { path: "/done", element:

    Done

    }, + ], + { initialEntries: ["/"] }, + ); + render(); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Ready"); + await user.click(screen.getByRole("button", { name: "Save" })); + + expect(await screen.findByRole("heading", { name: "Done" })).toBeVisible(); + expect( + screen.queryByRole("dialog", { name: "저장하지 않은 변경이 있습니다." }), + ).not.toBeInTheDocument(); + }); +}); diff --git a/tests/component/pagination.test.tsx b/tests/component/pagination.test.tsx new file mode 100644 index 00000000..a6bdc5b0 --- /dev/null +++ b/tests/component/pagination.test.tsx @@ -0,0 +1,80 @@ +// @vitest-environment jsdom + +import { render, screen, within } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import { Pagination } from "../../src/presentation/design-system/index.ts"; +import { CollectionPage } from "../../src/presentation/templates/index.ts"; + +function pagination(page: number, pageCount: number) { + return ( + {}} + page={page} + pageCount={pageCount} + pageLabel={(candidate) => `Page ${candidate}`} + previousLabel="Previous" + /> + ); +} + +function pageLinks(): string[] { + return screen + .getAllByRole("link") + .map((link) => link.textContent ?? ""); +} + +describe("Pagination windowing", () => { + it("links the first, last and neighbouring pages only", () => { + render(pagination(50, 5000)); + + expect(pageLinks()).toEqual([ + "Page 1", + "Page 49", + "Page 50", + "Page 51", + "Page 5000", + ]); + expect(screen.getByRole("link", { name: "Page 50" })).toHaveAttribute( + "aria-current", + "page", + ); + }); + + it("links a single skipped page instead of eliding it", () => { + render(pagination(3, 5000)); + expect(pageLinks()).toEqual([ + "Page 1", + "Page 2", + "Page 3", + "Page 4", + "Page 5000", + ]); + }); + + it("keeps every page of a short range", () => { + render(pagination(1, 3)); + expect(pageLinks()).toEqual(["Page 1", "Page 2", "Page 3"]); + }); +}); + +describe("Pagination landmarks", () => { + it("is a navigation landmark on its own", () => { + render(pagination(1, 2)); + expect(screen.getByRole("navigation", { name: "Pages" })).toBeVisible(); + }); + + it("does not nest a navigation landmark inside the collection page slot", () => { + render( + + Results + , + ); + + const slot = screen.getByRole("navigation", { name: "페이지 탐색" }); + expect(within(slot).queryAllByRole("navigation")).toHaveLength(0); + expect(within(slot).getByRole("group", { name: "Pages" })).toBeVisible(); + }); +}); diff --git a/tests/component/render-boundary.test.tsx b/tests/component/render-boundary.test.tsx index 829c8ff2..63208a00 100644 --- a/tests/component/render-boundary.test.tsx +++ b/tests/component/render-boundary.test.tsx @@ -10,6 +10,7 @@ import { deriveAsyncState } from "../../src/application/view-models/async-state. import { AsyncSurface } from "../../src/presentation/components/async-surface.tsx"; import { BootErrorShell } from "../../src/presentation/boundaries/boot-error-shell.tsx"; import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.tsx"; +import { LocaleProvider } from "../../src/presentation/i18n/index.ts"; function Defect(): ReactNode { throw new Error("raw render stack"); @@ -123,4 +124,18 @@ describe("render recovery boundaries", () => { ); expect(await screen.findByText("next route")).toBeVisible(); }); + + it("renders the default fallback in the current locale", () => { + render( + + + + + , + ); + expect(screen.getByRole("alert")).toHaveTextContent( + "The page could not be displayed.", + ); + expect(screen.getByRole("button", { name: "Try again" })).toBeVisible(); + }); }); diff --git a/tests/component/route-status-surfaces.test.tsx b/tests/component/route-status-surfaces.test.tsx new file mode 100644 index 00000000..0812572c --- /dev/null +++ b/tests/component/route-status-surfaces.test.tsx @@ -0,0 +1,205 @@ +// @vitest-environment jsdom + +import { render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { MemoryRouter } from "react-router-dom"; +import { describe, expect, it, vi } from "vitest"; + +import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts"; +import type { ApplicationOutputPorts } from "../../src/application/create-application.ts"; +import HomePage from "../../src/presentation/pages/home-page.tsx"; +import PlatformOverviewPage from "../../src/presentation/examples/platform-overview-page.tsx"; +import { LocaleProvider } from "../../src/presentation/i18n/index.ts"; +import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx"; +import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx"; +import { AppRouter } from "../../src/presentation/routes/app-router.tsx"; +import { createTestApplication } from "../helpers/create-test-application.ts"; + +function deferred() { + let reject: (error: unknown) => void = () => {}; + const promise = new Promise((_, fail) => { + reject = fail; + }); + return { promise, reject }; +} + +function renderApp( + url: string, + overrides: Partial = {}, + basename?: string, +) { + window.history.pushState({}, "", url); + return render( + + + + + , + ); +} + +function sessionWithSignIn(beginSignIn: (returnTo?: string) => Promise) { + return { ...createAnonymousSessionAdapter(), beginSignIn }; +} + +describe("route-level status surfaces", () => { + // First in the file: the home chunk has not been loaded yet, so the route + // suspends and shows its loading surface. + it("shows the busy route loading surface while a page chunk loads", async () => { + renderApp("/"); + + const copy = screen.getByText("화면을 준비하고 있습니다."); + expect(copy.closest('[aria-busy="true"]')).not.toBeNull(); + expect( + await screen.findByRole( + "heading", + { name: "Clean Architecture Frontend", level: 1 }, + { timeout: 5000 }, + ), + ).toBeVisible(); + }); + + it("keeps the auth-required surface, its pending label and its failure alert", async () => { + const user = userEvent.setup(); + const pending = deferred(); + const beginSignIn = vi.fn(() => pending.promise); + const { container } = renderApp("/examples/reference-resources#results", { + session: sessionWithSignIn(beginSignIn), + }); + + const heading = await screen.findByRole( + "heading", + { name: "세션이 필요합니다.", level: 1 }, + { timeout: 5000 }, + ); + const surface = container.querySelector( + '[data-surface="authentication-required"]', + ); + expect(surface).not.toBeNull(); + expect(surface).toContainElement(heading); + + await user.click(screen.getByRole("button", { name: "로그인 시작" })); + expect(beginSignIn).toHaveBeenCalledWith( + "/examples/reference-resources#results", + ); + expect(screen.getByRole("button", { name: "처리 중…" })).toBeDisabled(); + + pending.reject(new Error("identity provider unavailable")); + expect(await screen.findByRole("alert")).toHaveTextContent( + "세션 작업을 완료하지 못했습니다.", + ); + expect(screen.getByRole("button", { name: "로그인 시작" })).toBeEnabled(); + }); + + it("returns to the current URL with its hash from the shell session action", async () => { + const user = userEvent.setup(); + const pending = deferred(); + const beginSignIn = vi.fn(() => pending.promise); + renderApp("/examples/ui#buttons", { session: sessionWithSignIn(beginSignIn) }); + + const banner = screen.getByRole("banner"); + await user.click( + await within(banner).findByRole("button", { name: "로그인" }), + ); + expect(beginSignIn).toHaveBeenCalledWith("/examples/ui#buttons"); + expect(within(banner).getByRole("button", { name: "처리 중…" })).toBeDisabled(); + + pending.reject(new Error("identity provider unavailable")); + expect(await within(banner).findByRole("alert")).toHaveTextContent( + "세션 작업을 완료하지 못했습니다.", + ); + }); + + it("returns to the current URL with its hash from the auth example page", async () => { + const user = userEvent.setup(); + const beginSignIn = vi.fn(async () => {}); + renderApp("/examples/auth#session", { + session: sessionWithSignIn(beginSignIn), + }); + + await user.click( + await screen.findByRole( + "button", + { name: "로그인 시작" }, + { timeout: 5000 }, + ), + ); + expect(beginSignIn).toHaveBeenCalledWith("/examples/auth#session"); + }); + + it("answers an unknown address with a home link that keeps the basename", async () => { + renderApp("/app/missing", {}, "/app"); + + const heading = await screen.findByRole( + "heading", + { name: "페이지를 찾을 수 없습니다.", level: 1 }, + { timeout: 5000 }, + ); + const page = heading.closest("section"); + expect(page).not.toBeNull(); + expect( + within(page!).getByRole("link", { name: "홈으로 이동" }), + ).toHaveAttribute("href", "/app"); + }); +}); + +describe("temporary release loaders", () => { + function failingReleaseApplication() { + return createTestApplication({ + releaseInfo: { + getCurrent: async () => { + throw new Error("manifest unavailable"); + }, + refresh: async () => { + throw new Error("manifest unavailable"); + }, + }, + }); + } + + it("stops the home page release summary from loading forever", async () => { + window.history.pushState({}, "", "/"); + render( + + + + + , + ); + await waitFor(() => + expect( + screen.getByText("런타임 정보를 확인하지 못했습니다."), + ).toBeVisible(), + ); + expect( + screen.queryByText("검증된 런타임 정보를 확인하고 있습니다."), + ).not.toBeInTheDocument(); + }); + + it("stops the platform overview release metrics from loading forever", async () => { + render( + + + + + , + ); + await waitFor(() => + expect( + screen.getByText("런타임 정보를 확인하지 못했습니다."), + ).toBeVisible(), + ); + expect( + screen.queryByText("런타임 정보를 확인하고 있습니다."), + ).not.toBeInTheDocument(); + }); +}); + +/** HomePage renders router links, so it needs a router but not the app one. */ +function AppRouterlessHome() { + return ( + + + + ); +} diff --git a/tests/component/router.test.tsx b/tests/component/router.test.tsx index 161343fa..2e36b123 100644 --- a/tests/component/router.test.tsx +++ b/tests/component/router.test.tsx @@ -148,9 +148,9 @@ describe("generic application router", () => { }, { surface: "invalid-route", - url: "/examples/ui?unexpected=1", - routeId: "EXAMPLES_UI", - title: "UI 구성요소 · Frontend Skeleton", + url: "/examples/reference-resources?limit=invalid", + routeId: "REFERENCE_RESOURCE_LIST", + title: "Reference resources · Frontend Skeleton", disableFeature: false, }, { @@ -200,6 +200,28 @@ describe("generic application router", () => { }, ); + it("ignores unknown query parameters on a platform route and keeps the URL", async () => { + // D-16: `/?utm_source=x` or an OAuth callback parameter is not an invalid + // address. The `none` codec drops it from the parsed input only. + window.history.pushState({}, "", "/examples/ui?utm_source=mail#top"); + const { container } = renderRouter(); + + expect( + await screen.findByRole( + "heading", + { name: "UI 구성요소", level: 1 }, + { timeout: 5000 }, + ), + ).toBeVisible(); + expect(container.querySelector('[data-surface="invalid-route"]')).toBeNull(); + await waitFor(() => + expect(document.title).toBe("UI 구성요소 · Frontend Skeleton"), + ); + expect(`${window.location.pathname}${window.location.search}`).toBe( + "/examples/ui?utm_source=mail", + ); + }); + it("focuses the route heading again when the lazy chunk is already cached", async () => { // §9.7. The first visit resolves the route module asynchronously, so the // router lifecycle and the page header commit separately. A later visit diff --git a/tests/component/tooltip.test.tsx b/tests/component/tooltip.test.tsx new file mode 100644 index 00000000..24d4eebb --- /dev/null +++ b/tests/component/tooltip.test.tsx @@ -0,0 +1,63 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it } from "vitest"; + +import { Button, Tooltip } from "../../src/presentation/design-system/index.ts"; + +describe("Tooltip", () => { + it("describes the focusable trigger itself", async () => { + const user = userEvent.setup(); + render( + <> +

    Existing hint

    + + + + , + ); + + await user.tab(); + const trigger = screen.getByRole("button", { name: "Help" }); + expect(trigger).toHaveFocus(); + expect(trigger).toHaveAccessibleDescription("Existing hint Optional detail"); + }); + + it("closes with Escape and opens again on the next focus", async () => { + const user = userEvent.setup(); + render( + <> + + + + + , + ); + + await user.tab(); + const tooltip = screen.getByRole("tooltip"); + expect(tooltip).toBeVisible(); + + await user.keyboard("{Escape}"); + expect(tooltip).not.toBeVisible(); + expect(screen.getByRole("button", { name: "Help" })).toHaveFocus(); + + await user.tab(); + await user.tab({ shift: true }); + expect(screen.getByRole("tooltip")).toBeVisible(); + }); + + it("closes a hovered tooltip with Escape", async () => { + const user = userEvent.setup(); + render( + + + , + ); + + await user.hover(screen.getByRole("button", { name: "Help" })); + await user.keyboard("{Escape}"); + expect(screen.getByRole("tooltip", { hidden: true })).not.toBeVisible(); + }); +}); diff --git a/tests/contract/reusable-capability/feature-adapter-composition.test.ts b/tests/contract/reusable-capability/feature-adapter-composition.test.ts index 0db78193..945d8194 100644 --- a/tests/contract/reusable-capability/feature-adapter-composition.test.ts +++ b/tests/contract/reusable-capability/feature-adapter-composition.test.ts @@ -119,4 +119,43 @@ describe("feature adapter composition", () => { value: { draft, revision: 1 }, }); }); + + const http = Object.freeze({ + execute: async () => { + throw new Error("HTTP should not execute during composition"); + }, + }) as unknown as InstalledHttpOperationExecutor; + + it("rejects two contributions for the same feature id (Q-6.9-6)", () => { + // A feature copied from another without renaming its id. + const copied = defineFeatureAdapterContribution({ + ...TEST_HTTP_FEATURE_ADAPTER_CONTRIBUTION, + }); + expect(() => + composeFeatureAdapterInputs( + Object.freeze([TEST_HTTP_FEATURE_ADAPTER_CONTRIBUTION, copied] as const), + Object.freeze(["test-http-feature"]), + Object.freeze({ http }), + ), + ).toThrow(/duplicate.*test-http-feature/u); + }); + + it("rejects an input installed under another feature's id (Q-6.9-6)", () => { + const wrongId = defineFeatureAdapterContribution({ + featureId: "test-http-feature", + needs: ["http"] as const, + createInput: () => + Object.freeze({ + featureId: "local-draft", + input: {}, + }) as never, + }); + expect(() => + composeFeatureAdapterInputs( + Object.freeze([wrongId] as const), + Object.freeze(["test-http-feature"]), + Object.freeze({ http }), + ), + ).toThrow(/test-http-feature.*local-draft/u); + }); }); diff --git a/tests/features/reference-feature/reference-validator-protocol.test.ts b/tests/features/reference-feature/reference-validator-protocol.test.ts new file mode 100644 index 00000000..ed04cc2b --- /dev/null +++ b/tests/features/reference-feature/reference-validator-protocol.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from "vitest"; + +import { + CREATE_REFERENCE_RESOURCE_CONTRACT, + LIST_REFERENCE_RESOURCES_CONTRACT, +} from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts"; +import { + REFERENCE_RUNTIME_SCHEMA_CODECS, + validateReferencePayload, + validateReferenceRequest, +} from "../../../src/features/reference-feature/contracts/reference-schemas.ts"; + +/** + * Q-6.7-8 characterization. The reference feature exposes one schema through + * two protocols: the canonical `RuntimeValidator` (array paths) for the HTTP + * contract and the registry-facing `RuntimeSchemaCodec` (dotted paths). Both + * must keep answering exactly this after they share one zod wrapper. + */ +describe("reference validator protocols", () => { + const badList = [{ id: "unsafe", name: 42 }]; + + it("answers the canonical validator with array paths", () => { + expect( + LIST_REFERENCE_RESOURCES_CONTRACT.contract.outputValidator.safeParse( + badList, + ), + ).toEqual({ + success: false, + issues: [{ path: [0, "name"], code: "invalid_type" }], + }); + expect( + CREATE_REFERENCE_RESOURCE_CONTRACT.contract.inputValidator.safeParse({ + name: " Example ", + }), + ).toEqual({ success: true, data: { name: "Example" } }); + }); + + it("answers the schema codec with dotted paths", () => { + const codecs = REFERENCE_RUNTIME_SCHEMA_CODECS; + expect(codecs.ReferenceResourceListPayload.parse(badList)).toEqual({ + success: false, + issues: [{ path: "0.name", code: "invalid_type" }], + }); + expect( + codecs.CreateReferenceResourceCommand.parse({ name: "a", extra: 1 }), + ).toEqual({ + success: false, + issues: [{ path: "", code: "unrecognized_keys" }], + }); + expect( + codecs.ReferenceResourceListQuery.parse({ limit: "5", tags: "open" }), + ).toEqual({ success: true, data: { limit: 5, tags: ["open"] } }); + expect(Object.keys(codecs)).toEqual([ + "ReferenceResourceParams", + "ReferenceResourceListQuery", + "NoRequest", + "CreateReferenceResourceCommand", + "ReferenceResourceListPayload", + "ReferenceResourcePayload", + ]); + for (const [schemaId, codec] of Object.entries(codecs)) { + expect(codec.schemaId).toBe(schemaId); + } + }); + + it("keeps the payload and request lookups apart", () => { + expect(validateReferencePayload("ReferenceResourceListPayload", badList)) + .toEqual({ + success: false, + issues: [{ path: "0.name", code: "invalid_type" }], + }); + expect(validateReferencePayload("NoRequest", {})).toEqual({ + success: false, + issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }], + }); + expect( + validateReferenceRequest("CreateReferenceResourceCommand", { + name: " Example ", + }), + ).toEqual({ success: true, data: { name: "Example" } }); + expect( + validateReferenceRequest("ReferenceResourcePayload", {}), + ).toEqual({ + success: false, + issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }], + }); + }); +}); diff --git a/tests/fixtures/coverage/repository-omission.json b/tests/fixtures/coverage/repository-omission.json index ba04a728..ae2b8436 100644 --- a/tests/fixtures/coverage/repository-omission.json +++ b/tests/fixtures/coverage/repository-omission.json @@ -38,10 +38,10 @@ "src/contracts/compatibility.ts": { "lines": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "statements": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "functions": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "branches": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 } }, - "src/application/policies/performance-budgets.ts": { + "src/bootstrap/load-release-manifest.ts": { "lines": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "statements": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "functions": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "branches": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 } }, - "src/application/policies/promotion-readiness.ts": { + "src/bootstrap/read-bounded-boot-json.ts": { "lines": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "statements": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "functions": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "branches": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 } }, "src/application/use-cases/decide-chunk-recovery.ts": { diff --git a/tests/integration/auth-recovery.test.ts b/tests/integration/auth-recovery.test.ts index 3631b98f..05f66299 100644 --- a/tests/integration/auth-recovery.test.ts +++ b/tests/integration/auth-recovery.test.ts @@ -10,11 +10,11 @@ let responseStatuses: number[] = []; const server = setupServer( http.get("https://api.test/api/entities", () => { const status = responseStatuses.shift() ?? 200; - if (status === 401) { + if (status !== 200) { return HttpResponse.json( { success: false, - error: { code: "UNAUTHENTICATED" }, + error: { code: status === 401 ? "UNAUTHENTICATED" : "UNAVAILABLE" }, meta: { requestId: "request-1", traceId: "trace-1" }, }, { status }, @@ -104,6 +104,35 @@ describe("bounded 401 session recovery", () => { expect(notifyUnauthenticated).toHaveBeenCalledTimes(1); }); + // Q-6.3-11. Recovery is its own single replay, not a retry: an exhausted or + // disabled retry budget must not turn a recoverable 401 into a logout. + it.each([ + { label: "retries are disabled", statuses: [401, 200], maxRetryAttempts: 0 }, + { + label: "a 503 already used the retry budget", + statuses: [503, 401, 200], + maxRetryAttempts: 1, + }, + ])("recovers a 401 when $label", async ({ statuses, maxRetryAttempts }) => { + responseStatuses = [...statuses]; + const recoverSession = vi.fn(async () => "restored" as const); + const notifyUnauthenticated = vi.fn(); + const client = testClient({ + baseUrl: "https://api.test", + authSession: createExternalAuthSessionAdapter( + createOwner({ recoverSession, notifyUnauthenticated }), + ), + clock, + maxRetryAttempts, + }); + + await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({ + ok: true, + }); + expect(recoverSession).toHaveBeenCalledTimes(1); + expect(notifyUnauthenticated).not.toHaveBeenCalled(); + }); + it("normalizes attach and invalid recovery failures", async () => { const attachFailure = createExternalAuthSessionAdapter(createOwner({ attachCredential: async () => { diff --git a/tests/integration/http-client.test.ts b/tests/integration/http-client.test.ts index 348aeb3c..2390124f 100644 --- a/tests/integration/http-client.test.ts +++ b/tests/integration/http-client.test.ts @@ -145,7 +145,7 @@ describe("shared HTTP client", () => { server.use( http.get( "https://api.test/api/entities", - () => new HttpResponse("raw body", { status: 502 }), + () => new HttpResponse("raw body", { status: 200 }), ), ); const client = testClient({ baseUrl: "https://api.test", clock }); @@ -158,6 +158,43 @@ describe("shared HTTP client", () => { expect(JSON.stringify(result)).not.toContain("raw body"); }); + // Q-6.3-3b. A gateway 5xx/408/425 with an HTML, empty or broken body is a + // server outage, not a contract breach: it keeps its status and the V2 + // SERVER_FAILURE retry rule (502/503/504 only). + it.each([ + { status: 502, contentType: "text/html", body: "raw body", fetches: 3 }, + { status: 503, contentType: "application/json", body: "", fetches: 3 }, + { status: 504, contentType: "application/json", body: "{", fetches: 3 }, + { status: 408, contentType: "text/plain", body: "timeout", fetches: 1 }, + ])( + "keeps a $status gateway body as a server failure with its status", + async ({ status, contentType, body, fetches }) => { + let fetched = 0; + server.use( + http.get("https://api.test/api/entities", () => { + fetched += 1; + return new HttpResponse(body, { + status, + headers: { "Content-Type": contentType }, + }); + }), + ); + const client = testClient({ + baseUrl: "https://api.test", + clock, + random: () => 0, + }); + const result = await client.execute("LIST_ENTITIES"); + + expect(result).toMatchObject({ + ok: false, + error: { kind: "SERVER_FAILURE", httpStatus: status }, + }); + expect(fetched).toBe(fetches); + expect(JSON.stringify(result)).not.toContain("raw body"); + }, + ); + it("classifies malformed JSON and invalid payloads at the boundary", async () => { server.use( http.get( diff --git a/tests/platform/execution/execution-context.test.ts b/tests/platform/execution/execution-context.test.ts index aabd421d..c0e611de 100644 --- a/tests/platform/execution/execution-context.test.ts +++ b/tests/platform/execution/execution-context.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { createExecutionContext } from "../../../src/platform/execution/execution-context.ts"; @@ -69,6 +69,26 @@ describe("createExecutionContext", () => { expect(direct.cancellation.signal.aborted).toBe(true); }); + it("detaches from a long-lived owner signal when the interaction completes (Q-6.9-7)", () => { + const owner = new AbortController(); + const remove = vi.spyOn(owner.signal, "removeEventListener"); + const context = createExecutionContext({ + interactionId: "interaction-7", + deadlineMs: 1_000, + traffic: TRAFFIC, + signal: owner.signal, + }); + + context.complete(); + context.complete(); + expect(remove).toHaveBeenCalledOnce(); + expect(remove).toHaveBeenCalledWith("abort", expect.any(Function)); + + // A finished interaction is not cancelled by its owner afterwards. + owner.abort(); + expect(context.cancellation.signal.aborted).toBe(false); + }); + it.each([0, -1, Number.POSITIVE_INFINITY, 60_001, 1.5])( "rejects an unbounded or invalid deadline %s", (deadlineMs) => { diff --git a/tests/platform/telemetry/telemetry-buffer.test.ts b/tests/platform/telemetry/telemetry-buffer.test.ts index 4fbd5efa..dc25fc2c 100644 --- a/tests/platform/telemetry/telemetry-buffer.test.ts +++ b/tests/platform/telemetry/telemetry-buffer.test.ts @@ -62,6 +62,37 @@ describe("createTelemetryBuffer", () => { expect(buffer.dropped).toBe(1); }); + it("evicts nothing when eviction cannot make room for the incoming event (Q-6.9-11)", () => { + const at = (severity: TelemetryEvent["severity"]) => ({ + kind: `test.${severity}`, + severity, + }); + const evicted: string[] = []; + const buffer = createTelemetryBuffer({ + maxEvents: 10, + maxBytes: 300, + onEvict: (entry) => evicted.push(entry.event.severity), + }); + buffer.push(at("info"), 50); + buffer.push(at("error"), 240); + + // Dropping the info event frees 50 bytes; the warning needs 100. + expect(buffer.push(at("warning"), 100)).toBe(false); + expect(buffer.items.map((item) => item.severity)).toEqual(["info", "error"]); + expect(buffer.bytes).toBe(290); + expect(buffer.dropped).toBe(1); + expect(evicted).toEqual([]); + }); + + it("evicts the oldest event of the same severity to admit a new one", () => { + const buffer = createTelemetryBuffer({ maxEvents: 2, maxBytes: 1_024 }); + buffer.push(infoEvent("a")); + buffer.push(infoEvent("b")); + expect(buffer.push(infoEvent("c"))).toBe(true); + expect(buffer.items).toEqual([infoEvent("b"), infoEvent("c")]); + expect(buffer.dropped).toBe(1); + }); + it("enforces the byte ceiling independently of the event count", () => { const buffer = createTelemetryBuffer({ maxEvents: 100, maxBytes: 200 }); for (let i = 0; i < 50; i += 1) buffer.push(infoEvent(`event-${i}`)); diff --git a/tests/runtime-schema/runtime-config.test.ts b/tests/runtime-schema/runtime-config.test.ts index c277ace9..b7b71af0 100644 --- a/tests/runtime-schema/runtime-config.test.ts +++ b/tests/runtime-schema/runtime-config.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from "vitest"; -import { loadRuntimeConfig } from "../../src/bootstrap/load-runtime-config.ts"; +import { + BootConfigError, + loadRuntimeConfig, +} from "../../src/bootstrap/load-runtime-config.ts"; import { validateRuntimeConfig } from "../../src/bootstrap/runtime-config-schema.ts"; import { assertSafeConfigNames } from "../../src/contracts/env.ts"; @@ -228,6 +231,43 @@ describe("runtime configuration boundary", () => { expect(result.validationDurationMs).toBe(0); }); + it.each([ + [ + "an invalid field", + { ...validConfig, REQUEST_TIMEOUT_MS: -1, RELEASE_ID: "r".repeat(10_000) }, + { configSchemaVersion: "2.0" }, + ], + [ + "an unsupported version", + { ...validConfig, CONFIG_SCHEMA_VERSION: "v".repeat(10_000), RELEASE_ID: "release-a" }, + {}, + ], + ])( + "puts only validated config values into the safe error for %s (Q-6.9-10)", + async (_case, document, expected) => { + const failure = await loadRuntimeConfig({ + buildConfig: { + buildId: "build-a", + commitSha: "local", + routerBasePath: "/", + runtimeConfigUrl: "/config.json", + }, + fetcher: async () => + new Response(JSON.stringify(document), { + headers: { "content-type": "application/json" }, + }), + }).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(BootConfigError); + const safe = (failure as BootConfigError).safe; + expect(safe.code).toBe("CONFIG_SCHEMA_INVALID"); + expect({ + configSchemaVersion: safe.configSchemaVersion, + releaseId: safe.releaseId, + }).toEqual({ configSchemaVersion: undefined, releaseId: undefined, ...expected }); + }, + ); + it("returns only safe boot fields on failure", async () => { await expect( loadRuntimeConfig({ diff --git a/tests/unit/boundary-mapper.test.ts b/tests/unit/boundary-mapper.test.ts index 9ae6a330..6d3c6dc8 100644 --- a/tests/unit/boundary-mapper.test.ts +++ b/tests/unit/boundary-mapper.test.ts @@ -3,8 +3,11 @@ import { describe, expect, it } from "vitest"; import { mapOperationPayload } from "../../src/adapters/http/resource-mapper.ts"; import { composeBoundaryMapperRegistry, + mappingFailure, mappingSuccess, + toContractMappingResult, } from "../../src/contracts/boundary-mapper.ts"; +import { mappingViolation } from "../../src/contracts/external-contract-runtime.ts"; describe("platform DTO mapper boundary", () => { it("fails closed when no feature mapper was injected", () => { @@ -31,4 +34,14 @@ describe("platform DTO mapper boundary", () => { ]), ).toThrow("duplicate boundary mapper"); }); + + it("adapts a boundary result to the canonical mapping result (D-15)", () => { + expect(toContractMappingResult(mappingSuccess(1))).toEqual({ + ok: true, + value: 1, + }); + expect( + toContractMappingResult(mappingFailure("UNSUPPORTED_WIRE_VALUE")), + ).toEqual(mappingViolation("UNSUPPORTED_WIRE_VALUE")); + }); }); diff --git a/tests/unit/browser-file-content.test.ts b/tests/unit/browser-file-content.test.ts index 86fdf965..e1f1e36c 100644 --- a/tests/unit/browser-file-content.test.ts +++ b/tests/unit/browser-file-content.test.ts @@ -121,6 +121,31 @@ describe("browser file content policy", () => { ).toBe("d.bin"); }); + it("truncates a huge filename in linear time with the same result (Q-6.2-10)", () => { + const policy = { safeExtension: ".pdf", maxUtf8Bytes: 180 } as const; + expect( + sanitizeSuggestedFileName(`${"a".repeat(175)} bbbb.pdf`, policy), + ).toBe(`${"a".repeat(175)}.pdf`); + expect( + sanitizeSuggestedFileName(`${"가".repeat(100)}.pdf`, policy), + ).toBe(`${"가".repeat(58)}.pdf`); + expect( + sanitizeSuggestedFileName(`${"😀".repeat(50)}.pdf`, policy), + ).toBe(`${"😀".repeat(44)}.pdf`); + + // A server-supplied name used to be re-encoded whole once per dropped + // code point: O(n^2), so a 100k-character name froze the tab. + const encode = vi.spyOn(TextEncoder.prototype, "encode"); + try { + expect( + sanitizeSuggestedFileName("x".repeat(5_000), policy), + ).toBe(`${"x".repeat(176)}.pdf`); + expect(encode.mock.calls.length).toBeLessThan(10); + } finally { + encode.mockRestore(); + } + }); + it("keeps native files behind opaque refs and performs bounded reads", async () => { const policies = pngPolicies(); const vault = new BrowserFileVault({ @@ -755,4 +780,144 @@ describe("browser file content policy", () => { }, ]); }); + + it("keeps the shared token, limit and media-type checks (Q-6.2-12 characterization)", () => { + const policies = pngPolicies(); + const file = new File([new Uint8Array([1])], "a.png", { + type: "image/png", + lastModified: 1, + }); + expect( + new BrowserFileVault({ + policies, + createReference: () => "file with space", + }).captureFiles([file], pngSelectionPolicy), + ).toMatchObject({ ok: false, error: { code: "UNAVAILABLE" } }); + expect( + new BrowserFileVault({ + policies, + createReference: () => `file:${"x".repeat(123)}`, + }).captureFiles([file], pngSelectionPolicy), + ).toMatchObject({ ok: true }); + expect( + () => new BrowserFileVault({ policies, hardMaxRangeBytes: 0 }), + ).toThrow(TypeError); + + const revoked: string[] = []; + const registry = new ObjectUrlLeaseRegistry({ + createObjectURL: () => "", + revokeObjectURL: (url) => revoked.push(url), + }); + expect(() => registry.create(new Blob([new Uint8Array([1])]))).toThrow( + "Object URL allocation failed", + ); + expect(revoked).toEqual([]); + expect( + () => + new ObjectUrlLeaseRegistry(URL, { + hardMaxActiveLeases: 1.5, + hardMaxSingleLeaseBytes: 1, + hardMaxAggregateLeaseBytes: 1, + }), + ).toThrow(TypeError); + + const download = (mediaType: string, maxTransferBytes = 8) => + new BrowserFilePolicyRegistry({ + profiles: [ + { + reference: browserFilePolicyReference("files", "download"), + download: { + strategy: "BOUNDED_OBJECT_URL", + mediaType, + safeExtension: ".bin", + maxTransferBytes, + maxBufferedBytes: 8, + integrity: "OPTIONAL", + }, + }, + ], + hardLimits: { + maxInspectionBytes: 64, + maxRetainedFileBytes: 64, + maxPreviewBytes: 64, + maxObjectUrlBytes: 64, + maxTransferBytes: 64, + }, + }); + expect(() => download("application/octet-stream")).not.toThrow(); + expect(() => download("application/*")).toThrow(TypeError); + expect(() => download("application/octet-stream", 0)).toThrow(TypeError); + }); + + it("ends a pending native read on caller abort and on vault dispose", async () => { + const pendingStream = () => { + const state = { cancelled: 0 }; + const file = new File([new Uint8Array([1])], "slow.bin", { + lastModified: 1, + }); + Object.defineProperty(file, "stream", { + value: () => + new ReadableStream({ + pull: () => new Promise(() => {}), + cancel() { + state.cancelled += 1; + }, + }), + }); + return { file, state }; + }; + const open = async (vault: BrowserFileVault, file: File) => { + const captured = vault.captureFiles( + [file], + { ...pngSelectionPolicy, accept: Object.freeze([]) }, + ); + if (!captured.ok || !captured.value[0]) throw new Error("capture"); + const opened = await vault.openSource({ + ref: captured.value[0].ref, + signal: new AbortController().signal, + }); + if (!opened.ok) throw new Error("open"); + return opened.value; + }; + const collect = async ( + stream: AsyncIterable, + ): Promise => { + const results: unknown[] = []; + for await (const result of stream) results.push(result); + return results; + }; + + const aborted = pendingStream(); + const callerVault = new BrowserFileVault({ + policies: pngPolicies(), + createReference: () => "file:caller-abort", + }); + const controller = new AbortController(); + const callerRead = collect( + (await open(callerVault, aborted.file)).stream(controller.signal), + ); + await new Promise((resolve) => setTimeout(resolve, 0)); + controller.abort(); + expect(await callerRead).toMatchObject([ + { ok: false, error: { code: "ABORTED", operation: "FILE_READ" } }, + ]); + expect(aborted.state.cancelled).toBe(1); + + const disposed = pendingStream(); + const disposedVault = new BrowserFileVault({ + policies: pngPolicies(), + createReference: () => "file:vault-dispose", + }); + const disposedRead = collect( + (await open(disposedVault, disposed.file)).stream( + new AbortController().signal, + ), + ); + await new Promise((resolve) => setTimeout(resolve, 0)); + disposedVault.dispose(); + expect(await disposedRead).toMatchObject([ + { ok: false, error: { code: "UNAVAILABLE", operation: "FILE_READ" } }, + ]); + expect(disposed.state.cancelled).toBe(1); + }); }); diff --git a/tests/unit/browser-file-download.test.ts b/tests/unit/browser-file-download.test.ts index 0b40316f..933bb36b 100644 --- a/tests/unit/browser-file-download.test.ts +++ b/tests/unit/browser-file-download.test.ts @@ -1039,4 +1039,225 @@ describe("browser download delivery", () => { }, }); }); + + it("closes a lease that resolves in the same turn as the abort (Q-6.2-7)", async () => { + const controller = new AbortController(); + let releaseOpen: ((value: unknown) => void) | undefined; + const close = vi.fn(); + const adapter = createDownloadDeliveryAdapter({ + ...HARD_LIMITS, + policies, + host: { handoff: vi.fn() }, + browserManagedCapabilities: capabilityResolver(), + userActivation: { isActive: true }, + openAuthorizedSource: () => + new Promise((resolve) => { + releaseOpen = resolve; + }) as never, + }); + const capability = Object.freeze({ + capabilityReceipt: "capability-gap-1", + method: "GET" as const, + binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" }, + mediaType: "application/pdf", + byteLength: 3, + maxBytes: 3, + expectedSha256: "a".repeat(64), + expiresAtEpochMs: Number.MAX_SAFE_INTEGER, + }); + const delivering = adapter.deliver( + deliveryInput( + { + kind: "AUTHORIZED_STREAM_RESOURCE", + resourceId: "resource-1", + capability: capability as never, + }, + "BOUNDED_OBJECT_URL", + controller.signal, + ), + ); + await new Promise((resolve) => setTimeout(resolve, 0)); + // The lease lands after the abort but before the delivery's own cleanup. + controller.abort(); + releaseOpen?.({ + ok: true, + value: { + byteLength: 3, + integrity: "VERIFIED_ON_SUCCESSFUL_EXHAUSTION", + capability, + close, + async *stream() {}, + }, + }); + + await expect(delivering).resolves.toMatchObject({ + ok: false, + error: { code: "ABORTED" }, + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(close).toHaveBeenCalledOnce(); + }); + + it("aborts a writable that arrives after the delivery was aborted (Q-6.2-7)", async () => { + const controller = new AbortController(); + const events: string[] = []; + let createWritableCalled: (() => void) | undefined; + const writableRequested = new Promise((resolve) => { + createWritableCalled = resolve; + }); + let releaseWritable: + | ((writable: WritableStream) => void) + | undefined; + const adapter = createDownloadDeliveryAdapter({ + ...HARD_LIMITS, + policies, + host: { handoff: vi.fn() }, + browserManagedCapabilities: capabilityResolver(), + showSaveFilePicker: async () => ({ + createWritable() { + createWritableCalled?.(); + return new Promise>((resolve) => { + releaseWritable = resolve; + }); + }, + }), + userActivation: { isActive: true }, + }); + const delivering = adapter.deliver( + deliveryInput( + { + kind: "GENERATED", + bytes: byteSource([new Uint8Array([1])]), + }, + "PROMPT_AND_STREAM", + controller.signal, + ), + ); + await writableRequested; + controller.abort(); + await expect(delivering).resolves.toMatchObject({ + ok: false, + error: { code: "ABORTED" }, + }); + + // Chrome keeps a `.crswap` file for an open writable until it is aborted. + releaseWritable?.( + new WritableStream({ + abort() { + events.push("abort"); + }, + }), + ); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(events).toEqual(["abort"]); + }); + + it("keeps input validation failure codes (Q-6.2-11 characterization)", async () => { + const adapter = ( + overrides: Partial[0]> = {}, + ) => + createDownloadDeliveryAdapter({ + ...HARD_LIMITS, + policies, + host: { handoff: vi.fn() }, + browserManagedCapabilities: capabilityResolver( + (resourceId) => `/downloads/${resourceId}`, + ), + baseOrigin: "https://app.example", + showSaveFilePicker: async () => writableHandle([]), + userActivation: { isActive: true }, + ...overrides, + }); + const code = async ( + source: DownloadSource, + strategy: DownloadStrategy, + overrides: Partial[0]> = {}, + ): Promise => { + const result = await adapter(overrides).deliver( + deliveryInput(source, strategy), + ); + return result.ok ? result.value.kind : result.error.code; + }; + const generated = ( + bytes: FileByteSource = byteSource([new Uint8Array([1])]), + expectedSha256?: string, + ): DownloadSource => ({ + kind: "GENERATED", + bytes, + ...(expectedSha256 === undefined ? {} : { expectedSha256 }), + }); + const managed = (resourceId: string): DownloadSource => ({ + kind: "BROWSER_MANAGED_RESOURCE", + resourceId, + capabilityReceipt, + }); + + expect(await code(generated(), "BOUNDED_OBJECT_URL")).toBe( + "BROWSER_HANDOFF", + ); + expect( + await code({ kind: "UNKNOWN" } as never, "BOUNDED_OBJECT_URL"), + ).toBe("INVALID_INPUT"); + expect( + await code( + generated({ byteLength: 1, stream: "no" } as never), + "BOUNDED_OBJECT_URL", + ), + ).toBe("INVALID_INPUT"); + expect( + await code( + generated(byteSource([new Uint8Array([1])], -1)), + "BOUNDED_OBJECT_URL", + ), + ).toBe("INTEGRITY_FAILED"); + expect( + await code(generated(undefined, "not-a-digest"), "BOUNDED_OBJECT_URL"), + ).toBe("INVALID_INPUT"); + expect(await code(generated(), "BROWSER_MANAGED")).toBe( + "POLICY_REJECTED", + ); + expect(await code(managed("artifact-1"), "BOUNDED_OBJECT_URL")).toBe( + "POLICY_REJECTED", + ); + expect(await code(managed(""), "BROWSER_MANAGED")).toBe("INVALID_INPUT"); + expect(await code(managed("has space"), "BROWSER_MANAGED")).toBe( + "INVALID_INPUT", + ); + expect( + await code(generated(), "BOUNDED_OBJECT_URL", { + userActivation: { isActive: false }, + }), + ).toBe("PERMISSION_DENIED"); + expect( + await code(generated(), "BOUNDED_OBJECT_URL", { + filenameMaxUtf8Bytes: 2, + }), + ).toBe("INVALID_INPUT"); + expect( + await code(generated(), "BOUNDED_OBJECT_URL", { + createTransferId: () => "transfer with space", + }), + ).toBe("UNAVAILABLE"); + expect( + await code(managed("artifact-1"), "BROWSER_MANAGED", { + browserManagedCapabilities: capabilityResolver( + () => "https://user:secret@app.example/downloads/artifact-1", + ), + }), + ).toBe("POLICY_REJECTED"); + expect( + await code(managed("artifact-1"), "BROWSER_MANAGED", { + browserManagedCapabilities: capabilityResolver(undefined, { + expiresAtEpochMs: 1, + }), + }), + ).toBe("EXPIRED_RESOURCE"); + expect( + await code(managed("artifact-1"), "BROWSER_MANAGED", { + browserManagedCapabilities: capabilityResolver(undefined, { + mediaType: "text/html", + }), + }), + ).toBe("POLICY_REJECTED"); + }); }); diff --git a/tests/unit/browser-file-picker.test.ts b/tests/unit/browser-file-picker.test.ts index b43fd79e..d6ee8f81 100644 --- a/tests/unit/browser-file-picker.test.ts +++ b/tests/unit/browser-file-picker.test.ts @@ -263,6 +263,60 @@ describe("browser file pickers", () => { expect(vault.activeReferenceCount).toBe(1); }); + it("stops the focus fallback once a native cancel event was observed (Q-6.2-8)", async () => { + const input = labelledFileInput(); + const selected = new File(["slow"], "slow.txt", { + type: "text/plain", + lastModified: 1, + }); + let onClick = (): void => { + queueMicrotask(() => input.dispatchEvent(new Event("cancel"))); + }; + Object.defineProperty(input, "click", { + configurable: true, + value: vi.fn(() => onClick()), + }); + const scheduled: Array<() => void> = []; + const { policies, vault } = createHarness(policyDefinition, { + createReference: () => "file:slow", + }); + const picker = new NativeInputFilePicker({ + input, + vault, + policies, + userActivation: { isActive: true }, + scheduler: { + setTimeout(callback) { + scheduled.push(callback); + return scheduled.length; + }, + clearTimeout() {}, + }, + }); + + // This engine supports the native cancel event. + expect(await picker.select({ policy })).toEqual({ + ok: true, + value: { kind: "DISMISSED" }, + }); + + // A cloud provider returns focus first and dispatches change only after + // the file has been fetched, well past the focus grace. + onClick = () => window.dispatchEvent(new Event("focus")); + const pending = picker.select({ policy }); + for (const callback of scheduled.splice(0)) callback(); + Object.defineProperty(input, "files", { + configurable: true, + value: [selected], + }); + input.dispatchEvent(new Event("change")); + + expect(await pending).toMatchObject({ + ok: true, + value: { kind: "SELECTED", files: [{ displayName: "slow.txt" }] }, + }); + }); + it("lets the native cancel event settle before the focus fallback", async () => { const input = labelledFileInput(); let fallback: (() => void) | undefined; diff --git a/tests/unit/browser-rpc/browser-rpc-remediation.test.ts b/tests/unit/browser-rpc/browser-rpc-remediation.test.ts index fa10e33c..fa71da42 100644 --- a/tests/unit/browser-rpc/browser-rpc-remediation.test.ts +++ b/tests/unit/browser-rpc/browser-rpc-remediation.test.ts @@ -795,3 +795,229 @@ describe("RPC-03 registries are snapshotted before they are validated", () => { }); } }); + +/** + * Q-6.3-9. A command the transport already received may have been applied, a + * retry must not outlive the scope generation that started it, and a stream the + * consumer aborted without calling `return()` must not hold the operation in + * DRAINING forever. + */ +describe("Q-6.3-9 command effect, retry scope and abandoned streams", () => { + const COMMAND_KEY = "command-key-0001"; + const commandOperation = ( + overrides: Parameters[0] = {}, + ) => + unaryOperation({ + semantics: "COMMAND", + replayPolicy: "KEYED_COMMAND", + idempotencyKeyPolicy: "REQUIRED", + idempotencyLevel: "IDEMPOTENT", + serverStateProfileId: null, + ...overrides, + }); + + function commandRuntime( + invokeUnary: BrowserRpcTransport["invokeUnary"], + extra: Readonly<{ + operation?: ReturnType; + profile?: ReturnType; + generationFence?: Readonly<{ + capture(): unknown; + isCurrent(token: unknown): boolean; + }>; + }> = {}, + ) { + return createBrowserRpcRuntime({ + operations: { GET_RPC_RESOURCE: extra.operation ?? commandOperation() }, + profiles: { CONNECT_REFERENCE_UNARY: extra.profile ?? unaryProfile() }, + schemaCodecs: SCHEMA_CODECS, + mappers: MAPPERS, + requestEncoders: { RpcResourceRequestEncoder: UNARY_ENCODER }, + transports: { CONNECT_REFERENCE_UNARY: unaryTransport(invokeUnary) }, + ...(extra.generationFence === undefined + ? {} + : { generationFence: extra.generationFence }), + }).bindUnary("GET_RPC_RESOURCE", isResourceView); + } + + const afterSend: ReadonlyArray< + Readonly<{ + label: string; + invokeUnary: BrowserRpcTransport["invokeUnary"]; + operation?: ReturnType; + }> + > = [ + { + label: "answers UNAVAILABLE", + invokeUnary: async () => ({ + ok: false, + failure: { code: "UNAVAILABLE" }, + }), + }, + { + label: "throws", + invokeUnary: async () => { + throw new TypeError("connection reset"); + }, + }, + { + label: "never answers", + invokeUnary: () => new Promise(() => {}), + operation: commandOperation({ totalDeadlineMs: 25 }), + }, + ]; + + for (const { label, invokeUnary, operation } of afterSend) { + it(`reports MAYBE_APPLIED when a sent command's transport ${label}`, async () => { + const port = commandRuntime(invokeUnary, { + ...(operation === undefined ? {} : { operation }), + }); + + await expect( + port.execute({ resourceId: "r-1" }, { idempotencyKey: COMMAND_KEY }), + ).resolves.toMatchObject({ + ok: false, + error: { + effect: "MAYBE_APPLIED", + retryable: false, + action: "contact-support", + }, + }); + }); + } + + it("keeps a command rejected before send and a failed query effect-free", async () => { + const unsent = await commandRuntime(async () => { + throw new Error("must not be called"); + }).execute({ resourceId: "r-1" }); + expect(unsent).toMatchObject({ + ok: false, + error: { kind: "VALIDATION_REJECTED" }, + }); + expect(unsent.ok ? null : unsent.error).not.toHaveProperty("effect"); + + const query = await unaryRuntime( + unaryTransport(async () => ({ + ok: false, + failure: { code: "UNAVAILABLE" }, + })), + ) + .bindUnary("GET_RPC_RESOURCE", isResourceView) + .execute({ resourceId: "r-1" }); + expect(query).toMatchObject({ + ok: false, + error: { kind: "SERVER_FAILURE", retryable: true }, + }); + expect(query.ok ? null : query.error).not.toHaveProperty("effect"); + }); + + it("does not retry a command after its scope generation changed", async () => { + let calls = 0; + let generation = 1; + const port = commandRuntime( + async () => { + calls += 1; + // The session changes while the first attempt is in flight. + generation = 2; + return { ok: false, failure: { code: "UNAVAILABLE" } }; + }, + { + profile: unaryProfile({ + retryProfileId: "RPC_RETRY_TWO", + retryOwner: "FRONTEND_ADAPTER", + maxAttempts: 2, + backoffMs: [0], + retryableFailures: ["UNAVAILABLE"], + maxRetryAfterMs: 100, + }), + operation: commandOperation({ retryProfileId: "RPC_RETRY_TWO" }), + generationFence: { + capture: () => generation, + isCurrent: (token) => token === generation, + }, + }, + ); + + const result = await port.execute( + { resourceId: "r-1" }, + { idempotencyKey: COMMAND_KEY }, + ); + + expect(calls).toBe(1); + expect(result).toMatchObject({ + ok: false, + error: { + kind: "SCOPE_GENERATION_CHANGED", + effect: "MAYBE_APPLIED", + }, + }); + }); + + it("releases a stream the consumer aborted without calling return()", async () => { + const cancels: string[] = []; + let opened = 0; + const transport = defineBrowserRpcTransport({ + runtimeProfileId: "CONNECT_REFERENCE_STREAM", + providerId: "REFERENCE_RPC", + protocol: "CONNECT_HTTP", + rpcKind: "SERVER_STREAM", + openServerStream: () => { + opened += 1; + let closed: () => void = () => {}; + const closure = new Promise((resolve) => { + closed = resolve; + }); + let sent = false; + return { + streamId: `physical-${opened}`, + frames: { + [Symbol.asyncIterator]: () => + ({ + next: () => { + if (sent) return new Promise(() => {}); + sent = true; + return Promise.resolve({ + done: false, + value: { + kind: "MESSAGE", + message: { id: "r-1", name: "Resource" }, + encodedBytes: 16, + }, + }); + }, + }) as AsyncIterator, + }, + cancel(reason: string) { + cancels.push(reason); + closed(); + }, + waitClosed: () => closure, + }; + }, + }); + const stream = streamingRuntime(transport).bindServerStream( + "WATCH_RPC_RESOURCES", + isResourceView, + ); + const consumer = new AbortController(); + + const opening = stream.open( + { resourceId: "r-1" }, + { signal: consumer.signal }, + ); + const first = opening[Symbol.asyncIterator](); + await expect(first.next()).resolves.toMatchObject({ + value: { ok: true }, + }); + // The consumer walks away: it aborts but never calls next() or return(). + consumer.abort(); + await new Promise((resolve) => setTimeout(resolve, 5)); + + expect(cancels).toHaveLength(1); + const second = stream.open({ resourceId: "r-1" })[Symbol.asyncIterator](); + await expect(second.next()).resolves.toMatchObject({ + value: { ok: true }, + }); + expect(opened).toBe(2); + }); +}); diff --git a/tests/unit/chunk-recovery.test.ts b/tests/unit/chunk-recovery.test.ts index 7d0c8a12..7e29d6e1 100644 --- a/tests/unit/chunk-recovery.test.ts +++ b/tests/unit/chunk-recovery.test.ts @@ -37,6 +37,62 @@ describe("controlled chunk recovery", () => { }); }); + const storageError = { + kind: "STORAGE_UNAVAILABLE" as const, + code: "STORAGE_UNAVAILABLE", + retryable: false, + operationId: "STORAGE", + attemptCount: 1, + userMessageKey: "error.storage_unavailable", + action: "none" as const, + }; + const mismatch = { + failureKind: "CHUNK_LOAD_FAILURE", + manifestLoaded: true, + currentBuildId: "build-a", + currentReleaseId: "release-a", + activeBuildId: "build-b", + activeReleaseId: "release-b", + } as const; + + it("fails closed when the guard cannot be read", () => { + const storage: StoragePort = { + ...memoryStorage(), + read: () => ({ ok: false, error: storageError }), + }; + expect(decideChunkRecovery({ ...mismatch, storage })).toEqual({ + action: "support", + reason: "guard-read-failed", + }); + }); + + it("fails closed when the guard cannot be written", () => { + const storage: StoragePort = { + ...memoryStorage(), + write: () => ({ ok: false, error: storageError }), + }; + expect(decideChunkRecovery({ ...mismatch, storage })).toEqual({ + action: "support", + reason: "guard-write-failed", + }); + }); + + it("allows no second reload when replicas alternate the release pair (Q-6.9-9)", () => { + const storage = memoryStorage(); + expect(decideChunkRecovery({ ...mismatch, storage }).action).toBe("reload-once"); + // After the reload the page is on build-b while a replica still serves A. + expect( + decideChunkRecovery({ + ...mismatch, + currentBuildId: "build-b", + currentReleaseId: "release-b", + activeBuildId: "build-a", + activeReleaseId: "release-a", + storage, + }), + ).toEqual({ action: "support", reason: "reload-already-attempted" }); + }); + it.each([ [{ failureKind: "SERVER_FAILURE" }, "not-recoverable"], [{ manifestLoaded: false }, "manifest-unavailable"], diff --git a/tests/unit/conditional-validator-store.test.ts b/tests/unit/conditional-validator-store.test.ts index 9d4ccc62..df657455 100644 --- a/tests/unit/conditional-validator-store.test.ts +++ b/tests/unit/conditional-validator-store.test.ts @@ -79,6 +79,8 @@ describe("conditional validator CAS sidecar", () => { scope: firstScope.snapshot, }; expect(store.install(first, "raw-etag", 1)).toBe(false); + // Q-6.3-12. The opening quote of `W/"` is not also its closing quote. + expect(store.install(first, 'W/"', 1)).toBe(false); expect(store.install(first, 'W/"etag-a"', 1)).toBe(true); expect( store.install( diff --git a/tests/unit/contract-index-immutability.test.ts b/tests/unit/contract-index-immutability.test.ts new file mode 100644 index 00000000..52df5af1 --- /dev/null +++ b/tests/unit/contract-index-immutability.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it } from "vitest"; + +import { validateOfflineCommandContribution } from "../../src/contracts/offline-command.ts"; +import { + defineQueryInvalidationTopic, + indexInvalidationRegistry, + indexInvalidationTopicVersions, +} from "../../src/contracts/query-invalidation.ts"; +import { defineQueryNamespaceIdentity } from "../../src/contracts/query-keys.ts"; +import { validateRealtimeContributions } from "../../src/contracts/runtime-capabilities.ts"; +import { validateWebWorkerContributions } from "../../src/contracts/web-worker.ts"; + +/** + * Q-6.7-7. A validated index or registry is authority. `Object.freeze` on the + * outer wrapper leaves a returned `Map` clearable and leaves every row the + * caller's still-mutable object, so a later write changes what was validated. + */ + +function tryClear(map: unknown): void { + try { + (map as Map).clear(); + } catch { + // A read facade has no `clear`; that is the expected outcome. + } + try { + Map.prototype.clear.call(map as Map); + } catch { + // Borrowing the mutator must fail on the missing internal slot. + } +} + +describe("query invalidation index", () => { + const topic = defineQueryInvalidationTopic("qinv.orders.changed"); + const orders = defineQueryNamespaceIdentity("orders", 1); + const registry = { + topics: [topic], + namespaces: [orders], + edges: [{ topicId: topic, namespace: orders }], + }; + + it("cannot be cleared after indexing", () => { + const index = indexInvalidationRegistry(registry); + tryClear(index.namespacesForTopic); + tryClear(index.topicsForNamespace); + expect(index.namespacesForTopic.get(topic)).toEqual([orders]); + expect(index.topicsForNamespace.get('["orders",1]')).toEqual([topic]); + }); + + it("returns topic versions that cannot be cleared", () => { + const versions = indexInvalidationTopicVersions(registry, [ + { topicId: topic, topicVersion: 1 }, + ]); + tryClear(versions); + expect(versions.get(topic)).toBe(1); + }); +}); + +describe("runtime capability contributions", () => { + it("snapshots web worker task bounds", () => { + const task = { + taskId: "hash", + taskVersion: 1 as const, + maximumInputBytes: 1_024, + maximumOutputBytes: 1_024, + deadlineMs: 1_000, + }; + const [installed] = validateWebWorkerContributions([ + { taskGroupId: "crypto", tasks: [task], fallback: "UNSUPPORTED" }, + ]); + task.deadlineMs = 999_999; + expect(installed?.tasks[0]?.deadlineMs).toBe(1_000); + expect(Object.isFrozen(installed?.tasks[0])).toBe(true); + }); + + it("snapshots offline command operation bounds", () => { + const operation = { + operationId: "CREATE_ORDER", + contractPackageId: "@test/contracts", + maximumRequestBytes: 1_024, + retentionClass: "STANDARD_7D" as const, + }; + const installed = validateOfflineCommandContribution({ + datasetId: "OFFLINE_COMMANDS_V1", + operations: [operation], + }); + operation.maximumRequestBytes = 999_999_999; + expect(installed.operations[0]?.maximumRequestBytes).toBe(1_024); + expect(Object.isFrozen(installed.operations[0])).toBe(true); + }); + + it("snapshots realtime transport and effect rows", () => { + const transport = { + kind: "POLLING" as const, + operationId: "LIST_ORDERS", + intervalMs: 5_000, + }; + const topics = ["qinv.orders.changed"]; + const [installed] = validateRealtimeContributions([ + { + contributionId: "orders-realtime", + featureId: "orders", + contractSourcePackageId: "@test/contracts", + streamId: "ORDERS", + recoveryMode: "SESSION_REBUILD", + eventEffects: [ + { + eventType: "orders.changed", + mapperId: "OrdersChanged", + effect: "INVALIDATE_TOPICS", + invalidationTopics: topics, + }, + ], + transport, + }, + ]); + transport.intervalMs = 1; + topics.length = 0; + const effect = installed?.eventEffects[0]; + expect(installed?.transport).toMatchObject({ intervalMs: 5_000 }); + expect(effect?.invalidationTopics).toEqual(["qinv.orders.changed"]); + expect(Object.isFrozen(installed?.transport)).toBe(true); + expect(Object.isFrozen(effect?.invalidationTopics)).toBe(true); + }); +}); diff --git a/tests/unit/contract-registry-lookup.test.ts b/tests/unit/contract-registry-lookup.test.ts new file mode 100644 index 00000000..5762be27 --- /dev/null +++ b/tests/unit/contract-registry-lookup.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from "vitest"; + +import { getApiOperation } from "../../src/contracts/api-operations.ts"; +import { mapWithBoundaryRegistry } from "../../src/contracts/boundary-mapper.ts"; +import { + isAllowedOfflineTransition, + type OfflineCommandState, +} from "../../src/contracts/offline-command.ts"; +import { validateWithRuntimeSchemaRegistry } from "../../src/contracts/schema-registry.ts"; +import { getStorageDefinition } from "../../src/contracts/storage-keys.ts"; + +/** + * Q-6.7-11. A registry lookup answers only for its own keys. `registry[id]` + * walks the prototype chain, so `constructor` or `__proto__` resolved to + * `Object` / `Object.prototype` instead of "not registered". + */ +const INHERITED = ["constructor", "__proto__", "toString", "hasOwnProperty"]; + +describe("registry lookups ignore inherited keys", () => { + it("getApiOperation", () => { + for (const id of INHERITED) { + expect(() => getApiOperation(id), id).toThrow("Unregistered API operation"); + } + }); + + it("getStorageDefinition", () => { + for (const id of INHERITED) { + expect(() => getStorageDefinition(id), id).toThrow( + "Unregistered storage key", + ); + } + }); + + it("validateWithRuntimeSchemaRegistry", () => { + for (const id of INHERITED) { + expect(validateWithRuntimeSchemaRegistry(id, {}, {}), id).toEqual({ + success: false, + issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }], + }); + } + }); + + it("mapWithBoundaryRegistry", () => { + for (const id of INHERITED) { + expect(mapWithBoundaryRegistry(id, {}, {}), id).toEqual({ + ok: false, + code: "MAPPING_INVARIANT_REJECTED", + }); + } + }); +}); + +describe("offline command transitions", () => { + it("answers false for a state that is not listed", () => { + for (const from of ["UNKNOWN", ...INHERITED]) { + expect( + isAllowedOfflineTransition(from as OfflineCommandState, "PENDING"), + from, + ).toBe(false); + } + }); + + it("keeps the listed transitions", () => { + expect(isAllowedOfflineTransition("PENDING", "LEASED")).toBe(true); + expect(isAllowedOfflineTransition("ACKED", "PENDING")).toBe(false); + }); +}); diff --git a/tests/unit/contract-release-checks.test.ts b/tests/unit/contract-release-checks.test.ts new file mode 100644 index 00000000..e309dcba --- /dev/null +++ b/tests/unit/contract-release-checks.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from "vitest"; + +import { + CONTRACT_SET_ALGORITHM, + computeContractSetDigest, +} from "../../src/contracts/contract-set-canonical.ts"; +import { verifyContractSet } from "../../src/contracts/contract-set.ts"; +import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts"; +import { compareReleaseToRuntime } from "../../src/contracts/release-tokens.ts"; + +/** Q-6.7-12. Quiet passes and small defects in the release contracts. */ + +describe("release to runtime comparison", () => { + it("reports the asset manifest hash as unverified, not as compared", () => { + const result = compareReleaseToRuntime( + { + buildId: "build-a", + configSchemaVersion: "1.0", + apiContractVersion: "1.0", + assetManifestHash: "assets-a", + releaseId: "release-a", + }, + { + BUILD_ID: "build-a", + CONFIG_SCHEMA_VERSION: "1.0", + API_CONTRACT_VERSION: "1.0", + RELEASE_ID: "release-a", + }, + ); + expect(result).toMatchObject({ compatible: true, mismatches: [] }); + expect(result.unverified).toEqual(["assetManifestHash"]); + }); +}); + +describe("contract set verification", () => { + const accounts = Object.freeze({ + packageId: "@example/accounts", + version: "1.2.3", + digest: `sha256:${"1".repeat(64)}` as const, + runtimeProtocolVersion: 1 as const, + sourceRevision: "a".repeat(40), + }); + + it("returns a failure code for a duplicated expected package", async () => { + const manifest = { + setAlgorithm: CONTRACT_SET_ALGORITHM, + setDigest: await computeContractSetDigest([accounts]), + packages: [accounts], + }; + await expect( + verifyContractSet({ expected: [accounts, accounts], manifest }), + ).resolves.toEqual({ ok: false, code: "CONTRACT_SET_DUPLICATE_PACKAGE" }); + }); + + it("still admits a matching set", async () => { + const manifest = { + setAlgorithm: CONTRACT_SET_ALGORITHM, + setDigest: await computeContractSetDigest([accounts]), + packages: [accounts], + }; + await expect( + verifyContractSet({ expected: [accounts], manifest }), + ).resolves.toEqual({ ok: true }); + }); +}); + +describe("runtime identity registry eviction", () => { + it("evicts the least recently touched released row first", () => { + let sequence = 0; + const registry = createRuntimeIdentityRegistry({ + maxEntries: 2, + tokenFactory: () => `identity-token-${String(sequence++).padStart(4, "0")}`, + }); + const first = registry.intern({ resource: "first" }).token; + const second = registry.intern({ resource: "second" }).token; + // Touch "first" again so "second" becomes the eviction candidate. + expect(registry.intern({ resource: "first" }).token).toBe(first); + registry.intern({ resource: "third" }); + expect(registry.inspect().entries).toBe(2); + expect(registry.intern({ resource: "first" }).token).toBe(first); + expect(registry.intern({ resource: "second" }).token).not.toBe(second); + }); +}); diff --git a/tests/unit/contract-snapshot-bypass.test.ts b/tests/unit/contract-snapshot-bypass.test.ts new file mode 100644 index 00000000..cbc3825c --- /dev/null +++ b/tests/unit/contract-snapshot-bypass.test.ts @@ -0,0 +1,262 @@ +import { describe, expect, it } from "vitest"; + +import { installBrowserRpcContractBindings } from "../../src/contracts/browser-rpc.ts"; +import { parseCacheInvalidationWireEvent } from "../../src/contracts/cache-invalidation.ts"; +import { + composeContractContributions, + ContractContributionError, +} from "../../src/contracts/external-contract-runtime.ts"; +import { createRealtimePolicyRegistry } from "../../src/contracts/realtime-streams.ts"; +import { + installRestAuthProfileRegistry, + REST_AUTH_PROFILES, +} from "../../src/contracts/rest-profiles.ts"; +import { decodeStaticAssetManifest } from "../../src/contracts/service-worker-static-manifest.ts"; +import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts"; +import { + MAPPERS, + SCHEMA_CODECS, + UNARY_ENCODER, + unaryOperation, + unaryProfile, +} from "./browser-rpc/fixture.ts"; +import { + EFFECT_PROFILE_ID, + ENDPOINT_ID, + KILL_SWITCH_ID, + TEST_API_OPERATIONS, + TEST_MAPPERS, + TEST_SCHEMA_CODECS, + createTestRealtimeRegistry, +} from "./realtime/fixture.ts"; + +/** + * Q-6.7-6. Every contract that installs a caller-supplied row must validate + * and install one owned snapshot. An own `Symbol.iterator` on an array or an + * accessor on a row lets the value that was checked differ from the value + * that was installed. + */ + +/** An array whose length and indices say one thing and whose iterator says another. */ +function iteratorSmuggling(visible: readonly T[], smuggled: readonly T[]): T[] { + const array = [...visible]; + Object.defineProperty(array, Symbol.iterator, { + value: function* () { + yield* smuggled; + }, + }); + return array; +} + +const validator = Object.freeze({ + schemaId: "SmuggledSchema", + safeParse: (value: unknown) => + Object.freeze({ success: true as const, data: value }), +}); + +describe("external contract composition", () => { + it("does not install an event hidden behind an array iterator", () => { + const smuggled = Object.freeze({ + eventType: "test.smuggled", + envelopeValidator: validator, + payloadValidator: validator, + }); + let composed: ReturnType | undefined; + try { + composed = composeContractContributions([ + { + contributionId: "fixture-v1", + featureId: "test-feature", + source: { + kind: "TEMPLATE_FIXTURE", + fixtureId: "REFERENCE_FEATURE_V1", + revision: 1, + }, + http: [], + events: iteratorSmuggling([], [smuggled]), + }, + ] as never); + } catch (error) { + expect(error).toBeInstanceOf(ContractContributionError); + return; + } + expect(composed.eventByType.has("test.smuggled")).toBe(false); + }); + + it("reports a throwing reflection trap as a composition failure", () => { + const row = new Proxy( + { ...TEST_CONTRACT_CONTRIBUTION.http[0]! }, + { + ownKeys() { + throw new TypeError("hostile ownKeys trap"); + }, + }, + ); + expect(() => + composeContractContributions([ + { ...TEST_CONTRACT_CONTRIBUTION, http: [row] }, + ] as never), + ).toThrow(ContractContributionError); + }); +}); + +describe("realtime policy registry", () => { + it("rejects a limit accessor instead of reading it twice", () => { + const baseline = createTestRealtimeRegistry(); + const stream = baseline.listStreams()[0]!; + let reads = 0; + const limits = { ...stream.limits }; + Object.defineProperty(limits, "maxEventBytes", { + enumerable: true, + configurable: true, + get: () => { + reads += 1; + // Three reads validate it; the fourth is the install copy. + return reads <= 3 ? 1_024 : 999_999_999; + }, + }); + expect(() => + createRealtimePolicyRegistry({ + streams: [{ ...stream, limits }], + eventTypes: [baseline.listEventTypes()[0]!], + bindings: { + schemaCodecs: TEST_SCHEMA_CODECS, + mappers: TEST_MAPPERS, + apiOperations: TEST_API_OPERATIONS, + endpointIds: [ENDPOINT_ID], + effectProfileIds: [EFFECT_PROFILE_ID], + killSwitchIds: [KILL_SWITCH_ID], + rebuildInputIds: ["referenceRealtimeRebuild"], + }, + }), + ).toThrow(); + }); +}); + +describe("cache invalidation wire event", () => { + it("rejects an accessor field", () => { + const now = 1_000_000; + const event = { + protocolVersion: 1, + eventId: "remote-event-00000001", + sourceId: "remote-source-0000001", + sourceEpoch: "remote-epoch-0000001", + sequence: 1, + cacheEpoch: "cache-epoch-0001", + topicVersion: 1, + emittedAt: now, + expiresAt: now + 60_000, + }; + Object.defineProperty(event, "topic", { + enumerable: true, + get: () => "sample-topic-alpha", + }); + expect( + parseCacheInvalidationWireEvent(event, { + cacheEpoch: "cache-epoch-0001", + topicVersions: { "sample-topic-alpha": 1 }, + nowEpochMilliseconds: now, + }), + ).toEqual({ ok: false, reason: "INVALID_ENVELOPE" }); + }); +}); + +describe("static asset manifest", () => { + const row = { + url: "/assets/app-abcdefgh.js", + sha256: `sha256:${"a".repeat(64)}`, + bytes: 16, + contentType: "text/javascript", + }; + const manifest = (assets: unknown) => ({ + schemaVersion: 1, + buildId: "build-1", + releaseId: "release-1", + setDigest: `sha256:${"b".repeat(64)}`, + assets, + }); + + it("rejects an accessor on a row", () => { + const accessorRow = { ...row }; + Object.defineProperty(accessorRow, "bytes", { + enumerable: true, + get: () => 16, + }); + expect(decodeStaticAssetManifest(manifest([accessorRow])).ok).toBe(false); + }); + + it("does not decode rows hidden behind an array iterator", () => { + const decoded = decodeStaticAssetManifest( + manifest(iteratorSmuggling([], [row])), + ); + expect(decoded.ok && decoded.manifest.assets.length > 0).toBe(false); + }); +}); + +describe("browser RPC contract bindings", () => { + const install = (operations: Record) => + installBrowserRpcContractBindings({ + operations: operations as never, + profiles: { [unaryProfile().runtimeProfileId]: unaryProfile() }, + schemaCodecs: SCHEMA_CODECS, + mappers: MAPPERS, + requestEncoders: { RpcResourceRequestEncoder: UNARY_ENCODER }, + }); + + it("rejects a non-enumerable registry entry", () => { + const operations = {}; + Object.defineProperty(operations, "GET_RPC_RESOURCE", { + enumerable: false, + value: unaryOperation(), + }); + expect(() => install(operations)).toThrow(TypeError); + }); + + it("rejects a non-enumerable row field", () => { + const { totalDeadlineMs, ...rest } = unaryOperation(); + const operation = Object.defineProperty(rest, "totalDeadlineMs", { + enumerable: false, + value: totalDeadlineMs, + }); + expect(() => install({ GET_RPC_RESOURCE: operation })).toThrow(TypeError); + }); +}); + +describe("REST auth profile registry", () => { + it("rejects an accessor field", () => { + const profile = { ...REST_AUTH_PROFILES.ANONYMOUS }; + Object.defineProperty(profile, "transport", { + enumerable: true, + get: () => "ANONYMOUS", + }); + expect(() => installRestAuthProfileRegistry({ ANONYMOUS: profile })).toThrow( + TypeError, + ); + }); + + it("installs the header set it validated, not the one an iterator yields", () => { + let iterations = 0; + const allowed = ["authorization"]; + Object.defineProperty(allowed, Symbol.iterator, { + value: function* () { + iterations += 1; + yield "authorization"; + if (iterations > 1) yield* ["x-csrf-token", "x-csrf-token"]; + }, + }); + let installed: ReturnType | undefined; + try { + installed = installRestAuthProfileRegistry({ + REFERENCE_EXTERNAL_BEARER: { + ...REST_AUTH_PROFILES.REFERENCE_EXTERNAL_BEARER, + allowedCredentialHeaders: allowed as never, + }, + }); + } catch { + return; + } + expect( + installed.get("REFERENCE_EXTERNAL_BEARER")?.allowedCredentialHeaders, + ).toEqual(["authorization"]); + }); +}); diff --git a/tests/unit/cross-tab-invalidation.test.ts b/tests/unit/cross-tab-invalidation.test.ts index 88df5162..5ab6d474 100644 --- a/tests/unit/cross-tab-invalidation.test.ts +++ b/tests/unit/cross-tab-invalidation.test.ts @@ -4,12 +4,14 @@ import { CACHE_INVALIDATION_PROTOCOL_VERSION, CACHE_INVALIDATION_WIRE_LIMITS, decodeCacheInvalidationWireEvent, + isCacheInvalidationOpaqueIdentifier, parseCacheInvalidationWireEvent, type CacheInvalidationWireEvent, } from "../../src/contracts/cache-invalidation.ts"; import { createBrowserCrossContextInvalidation, createBrowserCrossContextInvalidationFromHost, + crossContextCacheEpochForRelease, type BroadcastChannelFacade, type BroadcastMessageListener, type BrowserCrossContextInvalidationDependencies, @@ -346,6 +348,66 @@ describe("browser cross-context host", () => { ).toBeUndefined(); expect(reads).toEqual([]); }); + + it("reports an inactive host through observe instead of failing silently (Q-6.2-9)", () => { + const observations: CrossContextInvalidationObservation[] = []; + const topics = [{ topic: TOPIC, topicVersion: 1 }]; + + expect( + createBrowserCrossContextInvalidationFromHost({ + host: {}, + cacheEpoch: CACHE_EPOCH, + topics, + observe: (observation) => observations.push(observation), + }), + ).toBeUndefined(); + expect( + createBrowserCrossContextInvalidationFromHost({ + host: { crypto: globalThis.crypto }, + cacheEpoch: "release.1.2.3+sha.abc", + topics, + observe: (observation) => observations.push(observation), + }), + ).toBeUndefined(); + expect(observations).toEqual([ + { + operation: "OPEN", + outcome: "FAILED", + transport: "NONE", + reason: "SECURE_RANDOM_UNAVAILABLE", + }, + { + operation: "OPEN", + outcome: "FAILED", + transport: "NONE", + reason: "INVALID_CACHE_EPOCH", + }, + ]); + }); + + it("derives a valid, stable cache epoch from any release id (Q-6.2-9)", () => { + const releaseIds = [ + "1.2.3+sha.abc", + "feature/x", + "app@1.2.3", + "x".repeat(500), + "1.2.3", + ]; + const epochs = releaseIds.map(crossContextCacheEpochForRelease); + for (const epoch of epochs) { + expect(isCacheInvalidationOpaqueIdentifier(epoch)).toBe(true); + } + expect(new Set(epochs).size).toBe(releaseIds.length); + expect(crossContextCacheEpochForRelease("feature/x")).toBe(epochs[1]); + + const runtime = createBrowserCrossContextInvalidationFromHost({ + host: { crypto: globalThis.crypto }, + cacheEpoch: crossContextCacheEpochForRelease("app@1.2.3"), + topics: [{ topic: TOPIC, topicVersion: 1 }], + }); + expect(runtime).toBeDefined(); + runtime?.close(); + }); }); describe("browser cross-context invalidation transport", () => { diff --git a/tests/unit/cursor-pagination-runtime.test.ts b/tests/unit/cursor-pagination-runtime.test.ts index eeb6fce6..ebb938ab 100644 --- a/tests/unit/cursor-pagination-runtime.test.ts +++ b/tests/unit/cursor-pagination-runtime.test.ts @@ -157,6 +157,67 @@ describe("bounded cursor pagination runtime", () => { error: { code: "PAGINATION_SNAPSHOT_CHANGED" }, }); }); + + // Q-6.3-12. The byte estimate serialized every accumulated item again on + // each page, and `push(...items)` spreads a page into call arguments. + it("serializes each page once", async () => { + const pages = [["a", "b"], ["c", "d"], ["e", "f"]]; + const stringify = vi.spyOn(JSON, "stringify"); + try { + const runtime = createCursorPaginationRuntime({ + definitionId: "LIST_ALL", + profile: { ...profile, maxTotalItems: 6 }, + loadPage: async (cursor) => { + const index = cursor === null ? 0 : Number(cursor); + const last = index === pages.length - 1; + return { + ok: true, + value: { + items: pages[index] ?? [], + nextCursor: last ? null : String(index + 1), + hasMore: !last, + snapshotToken: null, + }, + }; + }, + }); + const result = await runtime.loadAll({}); + const serializedItems = stringify.mock.calls + .map(([value]) => (Array.isArray(value) ? value.length : 0)) + .reduce((sum, length) => sum + length, 0); + stringify.mockRestore(); + expect(result).toEqual({ + ok: true, + value: ["a", "b", "c", "d", "e", "f"], + }); + expect(serializedItems).toBe(6); + } finally { + stringify.mockRestore(); + } + }); + + it("accepts a page larger than the call argument limit", async () => { + const large = new Array(1_000_000).fill(0); + const bulk = createCursorPaginationRuntime({ + definitionId: "LIST_ALL", + profile: { + ...profile, + maxTotalItems: large.length, + maxEstimatedBytes: 4 * large.length, + }, + loadPage: async () => ({ + ok: true, + value: { + items: large, + nextCursor: null, + hasMore: false, + snapshotToken: null, + }, + }), + }); + const result = await bulk.loadAll({}); + expect(result.ok && result.value.length).toBe(large.length); + }); }); /** diff --git a/tests/unit/deployment-admission.test.ts b/tests/unit/deployment-admission.test.ts index eb44038e..b0e71a39 100644 --- a/tests/unit/deployment-admission.test.ts +++ b/tests/unit/deployment-admission.test.ts @@ -80,13 +80,51 @@ describe("deployment admission", () => { } }); - it("permits a routable public host", () => { - expect( - findAdmissionViolations("production", { + it("refuses IPv6, mapped, CGNAT, 0/8 and internal-name hosts (Q-6.7-10)", () => { + for (const host of [ + "https://[::ffff:127.0.0.1]/", + "https://[::ffff:8.8.8.8]/", + "https://[fd00::1]/", + "https://[fc12:3456::1]/", + "https://[fe80::1]/", + "https://[febf::1]/", + "https://[0:0:0:0:0:0:0:1]/", + "https://100.64.0.1/", + "https://100.127.255.254/", + "https://0.1.2.3/", + "https://api.internal/", + "https://printer.local/", + "https://localhost./", + "https://api.internal./", + ]) { + const violations = findAdmissionViolations("production", { ...PRODUCTION_ARTIFACT, - API_BASE_URL: "https://api.172.16.example.com/", - } as AdmissionInput), - ).toEqual([]); + API_BASE_URL: host, + } as AdmissionInput); + expect(violations.map((violation) => violation.field), host).toContain( + "API_BASE_URL", + ); + } + }); + + it("permits a routable public host", () => { + for (const host of [ + "https://api.172.16.example.com/", + "https://100.128.0.1/", + "https://100.63.255.255/", + "https://[2001:db8::1]/", + "https://[fec0::1]/", + "https://internal.example.com/", + "https://local.example.com/", + ]) { + expect( + findAdmissionViolations("production", { + ...PRODUCTION_ARTIFACT, + API_BASE_URL: host, + } as AdmissionInput), + host, + ).toEqual([]); + } }); it("refuses a placeholder identity on a public target", () => { diff --git a/tests/unit/http-execution-v3.test.ts b/tests/unit/http-execution-v3.test.ts index 85df28f7..660e68c0 100644 --- a/tests/unit/http-execution-v3.test.ts +++ b/tests/unit/http-execution-v3.test.ts @@ -10,6 +10,10 @@ import { } from "../../src/adapters/http/http-execution-v3.ts"; import { mappingSuccess } from "../../src/contracts/boundary-mapper.ts"; import type { InstalledHttpContract } from "../../src/contracts/external-contract-runtime.ts"; +import { + createExecutionContext, + type ExecutionContext, +} from "../../src/platform/execution/execution-context.ts"; import { TEST_CREATE_HTTP_CONTRACT, TEST_LIST_HTTP_CONTRACT, @@ -842,3 +846,228 @@ describe("gateway failures without a usable problem body", () => { }, ); }); + +/** + * Q-6.3-6. Every wait the lifetime signal can end reports its owner the same + * way: the caller cancels, the deadline times out, and a scope fence ends as a + * scope abort — a transport abort before response headers, the stale-generation + * violation after them. A fence during a retry backoff used to read as TIMEOUT. + */ +describe("terminal owner classification at every wait", () => { + const phases = [ + "credentials", + "lease", + "dispatch", + "transport backoff", + "admission", + "retry backoff", + ] as const; + type Phase = (typeof phases)[number]; + type Owner = "CALLER" | "SCOPE_FENCE" | "DEADLINE"; + + const hang = () => new Promise(() => {}); + + async function endWaitAt(phase: Phase, owner: Owner) { + const caller = new AbortController(); + const fence = new AbortController(); + const fencedScope = Object.freeze({ + ...scope, + signal: fence.signal, + isCurrent: () => !fence.signal.aborted, + }); + let reached = false; + const reach = () => { + reached = true; + }; + let execution: ExecutionContext | undefined; + if (phase === "lease") { + execution = createExecutionContext({ + interactionId: "held-lease", + deadlineMs: 10_000, + traffic: { + maxPhysicalRequests: 4, + maxRetries: 2, + maxConcurrentRequests: 1, + maxQueuedRequests: 1, + }, + }); + await execution.traffic.concurrency.acquire(new AbortController().signal); + } + const observations: HttpExecutionObservation[] = []; + const executor = createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 2, + attachCredentials: () => + phase === "credentials" + ? (reach(), hang()) + : { kind: "READY", headers: {} }, + fetcher: vi.fn(async () => { + switch (phase) { + case "transport backoff": + throw new TypeError("network down"); + case "admission": + return new Response( + new ReadableStream({ + pull: () => (reach(), hang()), + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + case "retry backoff": + return Response.json( + { type: "about:blank", title: "temporary", status: 503 }, + { status: 503 }, + ); + default: + reach(); + return hang(); + } + }), + sleep: () => (reach(), hang()), + random: () => 0, + observe: (observation) => void observations.push(observation), + }); + + const pending = executor.execute( + operation({ deadlineMs: owner === "DEADLINE" ? 30 : 10_000 }), + { limit: 20 }, + { + routeId: ROUTE_ID, + scope: fencedScope, + signal: caller.signal, + ...(execution === undefined ? {} : { execution }), + }, + ); + if (owner !== "DEADLINE") { + await vi.waitFor(() => + expect(reached || execution?.traffic.concurrency.queued === 1).toBe( + true, + ), + ); + (owner === "CALLER" ? caller : fence).abort(); + } + const outcome = await pending; + return { + outcome, + cancellationOwner: observations.at(-1)?.cancellationOwner, + }; + } + + it.each(phases)( + "cancels at the %s wait when the caller aborts", + async (phase) => { + await expect(endWaitAt(phase, "CALLER")).resolves.toMatchObject({ + outcome: { kind: "CANCELLED", effect: "NOT_STARTED" }, + cancellationOwner: "CALLER", + }); + }, + ); + + it.each(phases)( + "times out at the %s wait when the deadline fires", + async (phase) => { + await expect(endWaitAt(phase, "DEADLINE")).resolves.toMatchObject({ + outcome: { kind: "TRANSPORT_FAILURE", failure: { kind: "TIMEOUT" } }, + cancellationOwner: "DEADLINE", + }); + }, + ); + + it.each(phases)( + "ends the %s wait as a scope abort when the scope is fenced", + async (phase) => { + await expect(endWaitAt(phase, "SCOPE_FENCE")).resolves.toMatchObject({ + outcome: + phase === "admission" + ? { + kind: "CONTRACT_VIOLATION", + violation: { kind: "SCOPE_FENCED" }, + } + : { + kind: "TRANSPORT_FAILURE", + failure: { kind: "ABORTED_BY_SCOPE" }, + }, + cancellationOwner: "SCOPE_FENCE", + }); + }, + ); +}); + +/** + * Q-6.3-7. A retried command's final effect joins what earlier attempts already + * established, and an answer that says the command may already be applied is + * not replayed. + */ +describe("command effect across retries", () => { + const idempotentCommand: InstalledHttpContract = { + ...createInstalled, + contract: { + ...createInstalled.contract, + retrySemantics: "IDEMPOTENT" as const, + }, + frontend: { ...createInstalled.frontend, retryBudget: 1 as const }, + }; + + async function runThenReject(first: () => Promise) { + const fetcher = vi + .fn() + .mockImplementationOnce(first) + .mockImplementation(async () => + // The fixture classifier reads a 400 problem as NOT_APPLIED. + Response.json( + { type: "about:blank", title: "rejected", status: 400 }, + { status: 400 }, + ), + ); + const executor = createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 1, + attachCredentials: () => ({ kind: "READY", headers: {} }), + fetcher, + sleep: async () => {}, + random: () => 0, + }); + const outcome = await executor.execute( + idempotentCommand, + { name: "created" }, + { + routeId: ROUTE_ID, + scope, + intent: mutationIntent({ idempotencyKey: null }), + }, + ); + return { outcome, attempts: fetcher.mock.calls.length }; + } + + it("keeps MAYBE_APPLIED when the retry after a lost response is rejected", async () => { + await expect( + runThenReject(async () => { + throw new TypeError("connection reset"); + }), + ).resolves.toMatchObject({ + attempts: 2, + outcome: { kind: "PROBLEM", effect: "MAYBE_APPLIED" }, + }); + }); + + it("keeps MAYBE_APPLIED when the retry after a rate limit is rejected", async () => { + await expect( + runThenReject(async () => new Response(null, { status: 429 })), + ).resolves.toMatchObject({ + attempts: 2, + outcome: { kind: "PROBLEM", effect: "MAYBE_APPLIED" }, + }); + }); + + it("does not replay a command whose gateway failure may already be applied", async () => { + await expect( + runThenReject(async () => new Response("", { status: 504 })), + ).resolves.toMatchObject({ + attempts: 1, + outcome: { + kind: "CONTRACT_VIOLATION", + metadata: { status: 504 }, + effect: "MAYBE_APPLIED", + }, + }); + }); +}); diff --git a/tests/unit/i18n-contract.test.ts b/tests/unit/i18n-contract.test.ts index 398a4b3f..42513ebd 100644 --- a/tests/unit/i18n-contract.test.ts +++ b/tests/unit/i18n-contract.test.ts @@ -52,10 +52,14 @@ describe("internationalization message contract", () => { expect(normalizeLocale("fr-FR")).toBe("ko-KR"); expect(resolveMessage("fr-FR", "action.retry")).toBe("다시 시도"); expect(resolveMessage("en-US", "action.login")).toBe("Sign in"); + // The fallback copy follows the requested locale. expect(resolveMessage("en-US", "backend.stack.trace")).toBe( - "요청한 문구를 표시할 수 없습니다.", + "This message is unavailable.", ); expect(resolveMessage("en-US", "action.closeNamed")).toBe( + "This message is unavailable.", + ); + expect(resolveMessage("ko-KR", "backend.stack.trace")).toBe( "요청한 문구를 표시할 수 없습니다.", ); expect(resolveMessage("en-US", "backend.stack.trace")).not.toContain( diff --git a/tests/unit/image-cdn-browser-probe.test.ts b/tests/unit/image-cdn-browser-probe.test.ts index 183c8de1..d7c09204 100644 --- a/tests/unit/image-cdn-browser-probe.test.ts +++ b/tests/unit/image-cdn-browser-probe.test.ts @@ -108,6 +108,40 @@ describe("browser image probe", () => { expect(close).toHaveBeenCalledTimes(samples.length); }); + // Q-6.1-8. The header parser reads pre-rotation dimensions, so the native + // decode must not apply EXIF/irot orientation either; otherwise an + // orientation 5-8 JPEG decodes with width and height swapped. + it("decodes with the default bitmap factory without applying orientation", async () => { + const bytes = jpegBytes(640, 360); + const exactUrl = imageUrl.replace("format=png", "format=jpeg"); + const nativeCreateImageBitmap = vi.fn(async () => ({ + width: 640, + height: 360, + close() {}, + })); + vi.stubGlobal("createImageBitmap", nativeCreateImageBitmap); + try { + const probe = createBrowserImageProbe({ + fetcher: (async () => + responseAt(exactUrl, bytes, { + status: 200, + headers: publicImageHeaders("image/jpeg", bytes.byteLength), + })) as typeof fetch, + }); + await expect( + probe.probe( + request({ absoluteUrl: exactUrl, expectedMediaType: "image/jpeg" }), + ), + ).resolves.toMatchObject({ ok: true }); + expect(nativeCreateImageBitmap).toHaveBeenCalledWith( + expect.any(Blob), + { imageOrientation: "none" }, + ); + } finally { + vi.unstubAllGlobals(); + } + }); + it("fails closed on duplicate/conflicting cache directives and oversized bodies", async () => { const png = pngBytes(640, 360); const createBitmap = vi.fn(async () => ({ diff --git a/tests/unit/image-cdn-runtime.test.ts b/tests/unit/image-cdn-runtime.test.ts index 29590d0d..1a851044 100644 --- a/tests/unit/image-cdn-runtime.test.ts +++ b/tests/unit/image-cdn-runtime.test.ts @@ -397,6 +397,40 @@ describe("production image CDN runtime", () => { expect(resolved.value.sources[0]?.type).toBe("image/avif"); }); + // Q-6.1-7 / D-12. The probe demands the exact primary pixel size, which a + // ratio-preserving fit (inside/outside) does not produce for an asset whose + // ratio differs, so that preset could only ever fail at probe time. + it("allows a PRIMARY_REQUIRED probe only with an exact-size fit", () => { + for (const fit of ["inside", "outside"] as const) { + expect(() => + createPolicies([ + createPreset(imageCdnPresetReference("probe", `fit-${fit}`), { + fit, + probeMode: "PRIMARY_REQUIRED", + }), + ]), + ).toThrow(/preset policy is invalid/u); + // Without the probe a ratio-preserving fit stays allowed. + expect(() => + createPolicies([ + createPreset(imageCdnPresetReference("probe", `none-${fit}`), { + fit, + }), + ]), + ).not.toThrow(); + } + for (const fit of ["cover", "contain", "fill"] as const) { + expect(() => + createPolicies([ + createPreset(imageCdnPresetReference("probe", `exact-${fit}`), { + fit, + probeMode: "PRIMARY_REQUIRED", + }), + ]), + ).not.toThrow(); + } + }); + it("rejects unsafe origins and preset budgets at composition time", () => { const preset = imageCdnPresetReference( "unsafe", diff --git a/tests/unit/indexeddb-connection.test.ts b/tests/unit/indexeddb-connection.test.ts index 068c59ca..636f0bf5 100644 --- a/tests/unit/indexeddb-connection.test.ts +++ b/tests/unit/indexeddb-connection.test.ts @@ -469,6 +469,65 @@ describe("shared IndexedDB connection mechanics", () => { }); }); + describe("Q-6.5-10 an upgrade that starts after the open settled", () => { + function openWithUpgrade( + stub: StubFactory, + options: Readonly<{ signal?: AbortSignal }> = {}, + ) { + const upgrade = vi.fn(() => ({ kind: "APPLIED" as const })); + const pending = openIndexedDbDatabase({ + factory: stub.factory, + databaseName: "kernel", + version: 2, + translate: recordingTranslate([]), + upgrade, + ...options, + }); + const request = stub.opened[0]; + if (!request) throw new Error("no open request"); + return { pending, request, upgrade }; + } + + function startUpgrade(request: StubOpenRequest) { + const abort = vi.fn(); + request.transaction = { abort } as unknown as IDBTransaction; + request.onupgradeneeded?.(versionChangeEvent(1, 2)); + return abort; + } + + it("is aborted instead of migrating after the caller gave up", async () => { + const stub = stubFactory(); + const controller = new AbortController(); + const { pending, request, upgrade } = openWithUpgrade(stub, { + signal: controller.signal, + }); + // No versionchange transaction exists yet, so there is nothing to abort. + controller.abort(); + await expect(pending).resolves.toEqual({ + ok: false, + error: { cause: "CALLER_ABORT" }, + }); + + const abort = startUpgrade(request); + expect(upgrade).not.toHaveBeenCalled(); + expect(abort).toHaveBeenCalledTimes(1); + }); + + it("is aborted after a terminal BLOCKED", async () => { + const stub = stubFactory(); + const { pending, request, upgrade } = openWithUpgrade(stub); + request.onblocked?.(versionChangeEvent(1, 2)); + await expect(pending).resolves.toMatchObject({ + ok: false, + error: { cause: "BLOCKED" }, + }); + + const abort = startUpgrade(request); + expect(upgrade).not.toHaveBeenCalled(); + expect(abort).toHaveBeenCalledTimes(1); + }); + }); + it("closes a connection that arrives after the caller gave up", async () => { const memory = new MemoryIndexedDbFactory(); const controller = new AbortController(); diff --git a/tests/unit/indexeddb-maintenance.test.ts b/tests/unit/indexeddb-maintenance.test.ts index 3fe8ea2a..13fd4999 100644 --- a/tests/unit/indexeddb-maintenance.test.ts +++ b/tests/unit/indexeddb-maintenance.test.ts @@ -35,7 +35,11 @@ const TEST_STORAGE_POLICY = Object.freeze({ unavailableFallback: "ONLINE_ONLY" as const, }); -function createSchemaRuntime(memory: MemoryIndexedDbFactory) { +function createSchemaRuntime( + memory: MemoryIndexedDbFactory, + measureStoredBytes: (value: CurrentPayload) => number = (value) => + new TextEncoder().encode(JSON.stringify(value)).byteLength, +) { return createIndexedDbRuntime({ scope: TEST_SCOPE, storagePolicy: TEST_STORAGE_POLICY, @@ -98,8 +102,7 @@ function createSchemaRuntime(memory: MemoryIndexedDbFactory) { codec: { currentVersion: 2, encode: (value) => ({ ok: true, value }), - measureStoredBytes: (value) => - new TextEncoder().encode(JSON.stringify(value)).byteLength, + measureStoredBytes, decode: (version, value) => version === 2 && value !== null && @@ -1008,3 +1011,115 @@ describe("IndexedDB bounded codec maintenance", () => { ).toBeDefined(); }); }); + +/** + * Q-6.5-7 characterization. The runtime, maintenance and the dataset binding + * each carried their own copy of the stored-row rules. These pin what every + * call site does today so merging the copies cannot move any of it. + */ +describe("Q-6.5-7 stored-row rules stay the same at every call site", () => { + const encodedBytes = (value: unknown) => + new TextEncoder().encode(JSON.stringify(value)).byteLength; + + it("measures a record as payload + 512 + 2 bytes per key character in both writers", async () => { + const memory = new MemoryIndexedDbFactory(); + const runtime = createSchemaRuntime(memory); + expect(await runtime.open()).toMatchObject({ ok: true }); + expect( + await runtime.compareAndSwap({ + key: "abc", + value: { label: "x" }, + expectedRevision: null, + idempotencyKey: "abc-create", + }), + ).toMatchObject({ ok: true }); + runtime.close(); + expect(memory.readRaw("retention", "abc")).toMatchObject({ + measuredBytes: encodedBytes({ label: "x" }) + 512 + 6, + }); + + seedLegacy(memory, "k1", "legacy"); + const maintenance = createMaintenance(memory, defaultPolicy()); + expect( + await maintenance.migrateCodecBatch({ + maxRows: 10, + maxDurationMs: 10_000, + }), + ).toMatchObject({ ok: true, value: { migratedRows: 1 } }); + expect(memory.readRaw("retention", "k1")).toMatchObject({ + measuredBytes: encodedBytes({ label: "legacy" }) + 512 + 4, + }); + }); + + it.each([ + ["NaN", Number.NaN], + ["a negative size", -1], + ["a size past the stored maximum", 2_147_483_647], + ])( + "rejects %s as INVALID_INPUT in the runtime and MIGRATION_FAILED in maintenance", + async (_label, measured) => { + const memory = new MemoryIndexedDbFactory(); + const runtime = createSchemaRuntime(memory, () => measured); + expect(await runtime.open()).toMatchObject({ ok: true }); + expect( + await runtime.compareAndSwap({ + key: "measured", + value: { label: "x" }, + expectedRevision: null, + idempotencyKey: "measured-create", + }), + ).toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } }); + runtime.close(); + + seedLegacy(memory, "legacy", "value"); + const maintenance = createMaintenance(memory, { + ...defaultPolicy(), + measureStoredBytes: () => measured, + }); + expect( + await maintenance.migrateCodecBatch({ + maxRows: 10, + maxDurationMs: 10_000, + }), + ).toMatchObject({ + ok: false, + error: { code: "MIGRATION_FAILED", recovery: "READ_ONLY" }, + }); + }, + ); + + it("bounds a stored budget by hardBudgetBytes when the dataset binding is verified", async () => { + const memory = new MemoryIndexedDbFactory(); + await prepareSchema(memory); + const budget = memory.readRaw("governance", "dataset-budget") as Record< + string, + unknown + >; + + memory.seed("governance", { + ...budget, + usedBytes: TEST_STORAGE_POLICY.hardBudgetBytes, + }); + const atLimit = createSchemaRuntime(memory); + expect(await atLimit.open()).toMatchObject({ ok: true }); + atLimit.close(); + + memory.seed("governance", { + ...budget, + usedBytes: TEST_STORAGE_POLICY.hardBudgetBytes + 1, + }); + const overLimit = createSchemaRuntime(memory); + const opened = await overLimit.open(); + overLimit.close(); + expect(opened).toMatchObject({ + ok: false, + error: { code: "POLICY_REJECTED" }, + }); + expect( + await createMaintenance(memory, defaultPolicy()).migrateCodecBatch({ + maxRows: 10, + maxDurationMs: 10_000, + }), + ).toMatchObject({ ok: false, error: { code: "POLICY_REJECTED" } }); + }); +}); diff --git a/tests/unit/indexeddb-runtime.test.ts b/tests/unit/indexeddb-runtime.test.ts index 6396a37d..dbe64ac8 100644 --- a/tests/unit/indexeddb-runtime.test.ts +++ b/tests/unit/indexeddb-runtime.test.ts @@ -449,7 +449,7 @@ describe("IndexedDB runtime", () => { expect(runtime.getStatus()).toEqual({ kind: "READY", schemaVersion: 1 }); }); - it("times out a blocked upgrade, then closes a late successful connection", async () => { + it("times out a blocked upgrade, then aborts the late upgrade instead of committing it", async () => { const memory = new MemoryIndexedDbFactory(); memory.blockNextOpen(); let timeout: (() => void) | undefined; @@ -484,7 +484,10 @@ describe("IndexedDB runtime", () => { memory.releaseBlockedOpen(); await Promise.resolve(); - expect(memory.isConnectionClosed()).toBe(true); + // Q-6.5-10. The upgrade that starts after the deadline is aborted, so no + // schema commits and no connection exists to leak. (This test used to + // expect the late upgrade to commit and its connection to be closed.) + expect(memory.hasStore("records")).toBe(false); expect(runtime.getStatus()).toEqual({ kind: "CLOSED", reason: "NOT_OPENED", diff --git a/tests/unit/indexeddb-transaction.test.ts b/tests/unit/indexeddb-transaction.test.ts index f36deb70..aa9acd93 100644 --- a/tests/unit/indexeddb-transaction.test.ts +++ b/tests/unit/indexeddb-transaction.test.ts @@ -383,12 +383,52 @@ describe("shared IndexedDB transaction mechanics", () => { transaction.error = new DOMException("aborted", "AbortError"); transaction.onabort?.(new Event("abort")); - const result = await pending; - expect(result.ok).toBe(false); - if (result.ok) return; - // The first candidate wins, so the later `fail` never becomes the value; - // an aborted transaction still cannot report the success it never kept. - expect(result.error.cause).toBe("NATIVE_EXCEPTION"); + // Q-6.5-10. A `fail` after `succeed` replaces the success candidate, so + // the caller's own failure is reported instead of an anonymous native + // abort. (This test used to expect NATIVE_EXCEPTION, which dropped it.) + expect(await pending).toEqual({ ok: false, error: { cause: "CLOSED" } }); + }); + + it("keeps the first failure when fail() is called twice", async () => { + const stub = stubDatabase(); + const pending = runIndexedDbTransaction({ + database: stub.database, + stores: ["rows"], + mode: "readwrite", + translate: recordingTranslate(), + queue: (_transaction, context) => { + context.fail({ cause: "CLOSED" }); + context.succeed("value"); + context.fail({ cause: "BLOCKED" }); + }, + }); + + stub.transactions[0]?.onabort?.(new Event("abort")); + expect(await pending).toEqual({ ok: false, error: { cause: "CLOSED" } }); + }); + + it("does not commit a write when fail() follows succeed()", async () => { + const { database, memory } = await seededDatabase(); + + const result = await runIndexedDbTransaction({ + database, + stores: ["rows"], + mode: "readwrite", + translate: recordingTranslate(), + queue: (transaction, context) => { + const store = transaction.objectStore("rows"); + onIndexedDbRequest(store.put({ id: "e", rank: 5 }), context, () => { + context.succeed("written"); + context.fail({ cause: "ADMISSION_REJECTED", detail: "late" }); + }); + }, + }); + + expect(result).toEqual({ + ok: false, + error: { cause: "ADMISSION_REJECTED", detail: "late" }, + }); + expect(memory.readRaw("rows", "e")).toBeUndefined(); }); }); diff --git a/tests/unit/installed-feature-messages.test.ts b/tests/unit/installed-feature-messages.test.ts new file mode 100644 index 00000000..b8e5ac18 --- /dev/null +++ b/tests/unit/installed-feature-messages.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; + +import { + composeInstalledMessageCatalogs, + INSTALLED_MESSAGE_CATALOGS, +} from "../../src/features/installed-feature-messages.ts"; +import { REFERENCE_MESSAGE_CATALOGS } from "../../src/features/reference-feature/contracts/reference-message-catalog.ts"; + +describe("installed feature message catalogs (Q-6.9-12)", () => { + it("keeps the installed ko-KR and en-US catalogs", () => { + expect(Object.keys(INSTALLED_MESSAGE_CATALOGS).sort()).toEqual(["en-US", "ko-KR"]); + expect(INSTALLED_MESSAGE_CATALOGS["ko-KR"]).toEqual(REFERENCE_MESSAGE_CATALOGS["ko-KR"]); + expect(INSTALLED_MESSAGE_CATALOGS["en-US"]).toEqual(REFERENCE_MESSAGE_CATALOGS["en-US"]); + }); + + it("composes every locale a feature declares, not a fixed list", () => { + const catalogs = composeInstalledMessageCatalogs([ + { messages: { "ko-KR": { a: "가" }, "ja-JP": { a: "あ" } } }, + { messages: { "ko-KR": { b: "나" } } }, + ]); + expect(catalogs).toEqual({ + "ko-KR": { a: "가", b: "나" }, + "ja-JP": { a: "あ" }, + }); + expect(Object.isFrozen(catalogs["ko-KR"])).toBe(true); + }); + + it("rejects a key two features define for the same locale", () => { + expect(() => + composeInstalledMessageCatalogs([ + { messages: { "en-US": { a: "A" } } }, + { messages: { "en-US": { a: "B" } } }, + ]), + ).toThrow("Duplicate en-US message key: a"); + }); +}); diff --git a/tests/unit/opfs-byte-store.test.ts b/tests/unit/opfs-byte-store.test.ts index 4a30a0dc..8586f2ef 100644 --- a/tests/unit/opfs-byte-store.test.ts +++ b/tests/unit/opfs-byte-store.test.ts @@ -697,6 +697,130 @@ describe("OPFS byte-store coordinator", () => { expect(rollback).not.toHaveBeenCalled(); }); + /** + * Q-6.5-9. A failed compensation leaves the journal row for reconciliation, + * but the caller still needs to know why the put failed: a cancel or a full + * disk must not turn into a bare CONFLICT. + */ + describe("Q-6.5-9 keeps the put's own failure when compensation fails", () => { + const quota = browserDataFailure("QUOTA_EXCEEDED", "OBJECT_WRITE", { + retryable: true, + recovery: "READ_ONLY", + }); + + async function putWith( + worker: Partial, + journal = createJournal(), + ) { + const adapter = createOpfsByteStoreAdapter({ + journal, + worker: createWorker(worker), + scope, + storagePolicy, + createTransactionId: () => "transaction_12345678", + now: () => 100, + }); + return await adapter.objects.put({ + objectId: "object_12345678", + expectedGeneration: null, + mediaType: "application/octet-stream", + source: sourceFrom(new Uint8Array([1])), + }); + } + + it.each([ + [ + "a failed cleanup", + async () => browserDataFailure("UNAVAILABLE", "OBJECT_RECONCILE"), + ], + [ + "an unknown cleanup effect", + async () => browserDataSuccess({ kind: "EFFECT_UNKNOWN" as const }), + ], + ])("after %s", async (_label, abortPreparedPut) => { + const journal = createJournal(); + expect( + await putWith( + { preparePut: async () => quota, abortPreparedPut }, + journal, + ), + ).toEqual({ + ok: false, + error: { + code: "QUOTA_EXCEEDED", + operation: "OBJECT_WRITE", + retryable: true, + recovery: "RECONCILE", + }, + }); + expect( + journal.transactions.get("transaction_12345678")?.phase, + ).toBe("PREPARING"); + }); + + it("keeps a caller cancel as ABORTED", async () => { + expect( + await putWith({ + preparePut: async () => + browserDataFailure("ABORTED", "OBJECT_WRITE"), + abortPreparedPut: async () => + browserDataFailure("UNAVAILABLE", "OBJECT_RECONCILE"), + }), + ).toMatchObject({ + ok: false, + error: { code: "ABORTED", recovery: "RECONCILE" }, + }); + }); + + it("after a failed journal rollback", async () => { + const journal = createJournal(); + vi.spyOn(journal, "rollback").mockResolvedValueOnce( + browserDataFailure("UNAVAILABLE", "OBJECT_RECONCILE"), + ); + expect( + await putWith({ preparePut: async () => quota }, journal), + ).toMatchObject({ + ok: false, + error: { + code: "QUOTA_EXCEEDED", + operation: "OBJECT_WRITE", + recovery: "RECONCILE", + }, + }); + }); + + it("after FILES_READY could not be recorded", async () => { + const journal = createJournal(); + vi.spyOn(journal, "markFilesReady").mockResolvedValueOnce( + browserDataFailure("UNAVAILABLE", "OBJECT_RECONCILE", { + retryable: true, + recovery: "REOPEN", + }), + ); + expect( + await putWith( + { + abortPreparedPut: async () => + browserDataSuccess({ kind: "EFFECT_UNKNOWN" as const }), + }, + journal, + ), + ).toEqual({ + ok: false, + error: { + code: "UNAVAILABLE", + operation: "OBJECT_WRITE", + retryable: true, + recovery: "RECONCILE", + }, + }); + }); + + it("returns the put's failure unchanged when compensation succeeds", async () => { + expect(await putWith({ preparePut: async () => quota })).toEqual(quota); + }); + }); + it("holds the OPFS mutation lease until exact physical cleanup completes", async () => { const journal = createJournal(); const observed: Array>> = []; diff --git a/tests/unit/opfs-worker-runtime.test.ts b/tests/unit/opfs-worker-runtime.test.ts index 65ef8b10..71f7a117 100644 --- a/tests/unit/opfs-worker-runtime.test.ts +++ b/tests/unit/opfs-worker-runtime.test.ts @@ -72,6 +72,7 @@ class MemoryFile { readonly kind = "file"; bytes = new Uint8Array(); lastModified = 0; + reads = 0; } class MemoryDirectory { @@ -152,6 +153,7 @@ function fileHandle(file: MemoryFile): FileSystemFileHandle { kind: "file", name: "memory", async getFile() { + file.reads += 1; const blob = new Blob([Uint8Array.from(file.bytes)]); Object.defineProperty(blob, "lastModified", { value: file.lastModified, @@ -1136,6 +1138,165 @@ describe("R-5.5 stored objects are checked against their own chunk size", () => }); }); +describe("Q-6.5-6 openObject checks the manifest up front and the bytes while streaming", () => { + const twoChunkPolicy = resolveOpfsRuntimePolicy({ + chunkSizeBytes: 64 * 1024, + maxObjectBytes: 128 * 1024, + maxChunkCount: 2, + orphanGracePeriodMs: 60_000, + }); + const payload = Uint8Array.from( + { length: 64 * 1024 + 1 }, + (_, index) => index % 251, + ); + + async function writeObject(bytes: Uint8Array) { + const root = new MemoryDirectory(); + const gateway = loopbackGateway( + createOpfsWorkerRuntime({ + root: root as unknown as FileSystemDirectoryHandle, + crypto: globalThis.crypto, + policy: twoChunkPolicy, + leaseManager: immediateLeases({ count: 0 }), + dedicatedWorker: true, + supportsSynchronousAccessHandles: false, + }), + twoChunkPolicy, + ); + const written = await gateway.preparePut( + putRequest("e", bytesSource(bytes)), + ); + if (!written.ok) throw new Error(written.error.code); + return { root, gateway, stored: written.value }; + } + + function filesNamed( + directory: MemoryDirectory, + matches: (name: string) => boolean, + ): MemoryFile[] { + const found: MemoryFile[] = []; + for (const [name, node] of directory.children) { + if (node instanceof MemoryDirectory) { + found.push(...filesNamed(node, matches)); + } else if (matches(name)) { + found.push(node); + } + } + return found; + } + + function chunkFile(root: MemoryDirectory, digestHex: string): MemoryFile { + const [file] = filesNamed(root, (name) => name === `${digestHex}.bin`); + if (!file) throw new Error("Chunk file is missing."); + return file; + } + + /** Rewrites the root digest in both the stored manifest and the caller's copy. */ + function withForgedRootDigest( + root: MemoryDirectory, + stored: OpfsPreparedObject, + ): OpfsPreparedObject { + const forged: OpfsPreparedObject = { + ...stored, + descriptor: { + ...stored.descriptor, + integrity: { + ...stored.descriptor.integrity, + rootDigestHex: "0".repeat(64), + }, + }, + }; + const [manifest] = filesNamed(root, (name) => name === "manifest.json"); + if (!manifest) throw new Error("Manifest is missing."); + manifest.bytes = new TextEncoder().encode(JSON.stringify(forged)); + return forged; + } + + async function drain(source: ByteSource) { + const results: Array<{ ok: true; bytes: number } | { ok: false; code: string }> = []; + for await (const chunk of source.stream(new AbortController().signal)) { + results.push( + chunk.ok + ? { ok: true, bytes: chunk.value.byteLength } + : { ok: false, code: chunk.error.code }, + ); + } + return results; + } + + it("opens without reading chunk bytes and reads each chunk once while streaming", async () => { + const { root, gateway, stored } = await writeObject(payload); + const chunks = stored.chunks.map((chunk) => + chunkFile(root, chunk.digestHex), + ); + expect(chunks).toHaveLength(2); + for (const file of chunks) file.reads = 0; + + const opened = await gateway.openObject(stored); + if (!opened.ok) throw new Error(opened.error.code); + expect(chunks.map((file) => file.reads)).toEqual([0, 0]); + + const bytes: number[] = []; + for await (const chunk of opened.value.stream( + new AbortController().signal, + )) { + if (!chunk.ok) throw new Error(chunk.error.code); + bytes.push(...chunk.value); + } + expect(bytes).toEqual([...payload]); + expect(chunks.map((file) => file.reads)).toEqual([1, 1]); + }); + + it("still fails the read at a corrupted chunk", async () => { + const { root, gateway, stored } = await writeObject(payload); + const second = chunkFile(root, stored.chunks[1]!.digestHex); + second.bytes = Uint8Array.from(second.bytes, (byte) => byte ^ 0xff); + + const opened = await gateway.openObject(stored); + if (!opened.ok) throw new Error(opened.error.code); + expect(await drain(opened.value)).toEqual([ + { ok: true, bytes: 64 * 1024 }, + { ok: false, code: "INTEGRITY_FAILED" }, + ]); + }); + + it("checks the root digest before the last chunk is released", async () => { + const { root, gateway, stored } = await writeObject(payload); + const forged = withForgedRootDigest(root, stored); + + const opened = await gateway.openObject(forged); + if (!opened.ok) throw new Error(opened.error.code); + expect(await drain(opened.value)).toEqual([ + { ok: true, bytes: 64 * 1024 }, + { ok: false, code: "INTEGRITY_FAILED" }, + ]); + }); + + it("checks the root digest of an empty object at open, where its stream ends", async () => { + const { root, gateway, stored } = await writeObject(new Uint8Array()); + expect(stored.chunks).toHaveLength(0); + const intact = await gateway.openObject(stored); + expect(intact.ok && (await drain(intact.value))).toEqual([]); + + const forged = withForgedRootDigest(root, stored); + expect(await gateway.openObject(forged)).toMatchObject({ + ok: false, + error: { code: "INTEGRITY_FAILED" }, + }); + }); + + it("keeps verifyObject a full byte check", async () => { + const { root, gateway, stored } = await writeObject(payload); + const second = chunkFile(root, stored.chunks[1]!.digestHex); + second.bytes = Uint8Array.from(second.bytes, (byte) => byte ^ 0xff); + + expect(await gateway.verifyObject(stored)).toEqual({ + ok: true, + value: false, + }); + }); +}); + describe("OPFS worker client lifecycle", () => { it("rejects a colliding concurrent request id without replacing the first RPC", async () => { let listener: ((event: MessageEvent) => void) | undefined; diff --git a/tests/unit/performance-budgets.test.ts b/tests/unit/performance-budgets.test.ts index 4e3ac585..8d33d5d8 100644 --- a/tests/unit/performance-budgets.test.ts +++ b/tests/unit/performance-budgets.test.ts @@ -5,7 +5,7 @@ import { evaluateFieldBudget, evaluateLabBudget, percentile75, -} from "../../src/application/policies/performance-budgets.ts"; +} from "../../scripts/lib/performance-budgets.ts"; describe("performance budgets", () => { it("rejects initial and lazy JavaScript above their named limits", () => { diff --git a/tests/unit/presigned-transfer-download.test.ts b/tests/unit/presigned-transfer-download.test.ts index 998897d9..c4fe0f72 100644 --- a/tests/unit/presigned-transfer-download.test.ts +++ b/tests/unit/presigned-transfer-download.test.ts @@ -177,6 +177,26 @@ describe("presigned download stream lifecycle", () => { }); } + // Q-6.1-11. The duplicate check read the issuer's object again after the + // snapshot, so a stateful object could show it a receipt the vault had + // never stored while the snapshot carried one it already held. + it("checks a duplicate receipt against the snapshot, not the issuer's object", () => { + const vault = freshVault(); + expect(vault.register(baseRegistration() as never).ok).toBe(true); + const replay = new Proxy(baseRegistration(), { + get(target, key, receiver) { + return key === "capabilityReceipt" + ? "capability-never-registered" + : Reflect.get(target, key, receiver); + }, + }); + expect(vault.register(replay as never)).toMatchObject({ + ok: false, + error: { code: "CONFLICT", recovery: "REISSUE_CAPABILITY" }, + }); + vault.dispose(); + }); + it("does not observe a mutation of the issuer's object after registration", () => { const vault = freshVault(); const registration = baseRegistration(); diff --git a/tests/unit/presigned-transfer.test.ts b/tests/unit/presigned-transfer.test.ts index ab260fc1..4eeb3cf5 100644 --- a/tests/unit/presigned-transfer.test.ts +++ b/tests/unit/presigned-transfer.test.ts @@ -565,6 +565,67 @@ describe("presigned transfer capability issuance and admission", () => { }); }); + // Q-6.1-9. `Number(declaredLength)` accepted "5e0", "0x5" and "+5" as 5. + it("rejects a download Content-Length that is not a plain decimal", async () => { + const bytes = new Uint8Array([1, 2, 3, 4, 5]); + const payload = downloadCapabilityPayload(bytes); + for (const declared of ["5e0", "0x5", "+5", "5.0"]) { + const fetcher = vi.fn(async (input: RequestInfo | URL) => + String(input) === CONTROL_ENDPOINT + ? jsonResponse(payload) + : downloadResponse(bytes.slice().buffer, payload, { + "Content-Length": declared, + }), + ) as unknown as typeof fetch; + const harness = createHarness({ fetcher }); + const issued = await harness.provider.issueDownload({ + resourceId: "resource-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + await expect( + firstStreamResult( + await harness.executor.downloadSources.open({ + resourceId: "resource-1", + capability: issued.value, + signal: new AbortController().signal, + }), + ), + declared, + ).resolves.toMatchObject({ + ok: false, + error: { code: "INTEGRITY_FAILED" }, + }); + } + }); + + // Q-6.1-9. The provider and the executor share one status table: a refused + // or failed capability HTTP exchange is recovered by a new capability. + it("maps capability endpoint statuses with the executor's recovery table", async () => { + for (const [status, code, retryable] of [ + [401, "PERMISSION_DENIED", false], + [403, "PERMISSION_DENIED", false], + [503, "UNAVAILABLE", true], + [429, "UNAVAILABLE", true], + ] as const) { + const fetcher = vi.fn(async () => + responseWithUrl(new Response(null, { status }), CONTROL_ENDPOINT), + ) as unknown as typeof fetch; + const { provider } = createHarness({ fetcher }); + expect( + await provider.issueDownload({ + resourceId: "resource-1", + signal: new AbortController().signal, + }), + String(status), + ).toMatchObject({ + ok: false, + error: { code, retryable, recovery: "REISSUE_CAPABILITY" }, + }); + } + }); + it("accepts a valid opaque UTF-8 path segment", async () => { const bytes = new Uint8Array([1, 2, 3]); // BT-PRE-05. Canonical uppercase percent-hex for a real UTF-8 segment. diff --git a/tests/unit/promotion-readiness.test.ts b/tests/unit/promotion-readiness.test.ts index 9b5e3631..0984ae69 100644 --- a/tests/unit/promotion-readiness.test.ts +++ b/tests/unit/promotion-readiness.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; import { evaluatePromotionReadiness, PROMOTION_FORMULA, -} from "../../src/application/policies/promotion-readiness.ts"; +} from "../../scripts/lib/promotion-readiness.ts"; const allGateIds = Object.values(PROMOTION_FORMULA).flat(); type GateResults = Parameters[0]; diff --git a/tests/unit/public-response-cache-codec.test.ts b/tests/unit/public-response-cache-codec.test.ts new file mode 100644 index 00000000..5d5d8573 --- /dev/null +++ b/tests/unit/public-response-cache-codec.test.ts @@ -0,0 +1,326 @@ +import { describe, expect, it } from "vitest"; + +import type { PublicCacheAsset } from "../../src/application/ports/browser-file-storage/cache-storage-ports.ts"; +import { createDefaultPublicCachePolicy } from "../../src/adapters/cache-storage/public-cache-policy.ts"; +import { createPublicResponseCacheAdapter } from "../../src/adapters/cache-storage/public-response-cache-adapter.ts"; +import { + MemoryCacheStorage, + digestHex, + immediateLock, + manifestFor, +} from "./public-response-cache-fixture.ts"; + +/** + * Q-6.2-11. Characterization of the manifest codec and response validation + * before they moved out of the adapter: every rejection keeps its code. + */ +const ORIGIN = "https://assets.example.test"; +const policy = createDefaultPublicCachePolicy(ORIGIN); +const BYTES = new Uint8Array([1, 2, 3, 4]); + +async function asset( + overrides: Partial = {}, +): Promise { + return { + absoluteUrl: `${ORIGIN}/app.js`, + expectedByteLength: BYTES.byteLength, + expectedContentType: "application/javascript", + integrity: { algorithm: "SHA-256", digestHex: await digestHex(BYTES) }, + ...overrides, + }; +} + +function adapterWith( + respond: () => Response = () => + new Response(Uint8Array.from(BYTES), { + headers: { + "cache-control": "public", + "content-type": "application/javascript", + }, + }), + cacheStorage = new MemoryCacheStorage(), +) { + return createPublicResponseCacheAdapter({ + cacheStorage: cacheStorage as unknown as CacheStorage, + crypto: globalThis.crypto, + mutationLock: immediateLock, + policy, + fetcher: async () => respond(), + }); +} + +async function stageCode( + assets: readonly PublicCacheAsset[], + respond?: () => Response, +): Promise { + const manifest = { + releaseRegistryId: "codec-release", + assets, + manifestDigestHex: "0".repeat(64), + }; + try { + Object.assign(manifest, await manifestFor("codec-release", assets, policy)); + } catch { + // An invalid manifest has no digest; staging must still reject it. + } + const result = await adapterWith(respond).admin.stageRelease(manifest); + return result.ok ? "OK" : result.error.code; +} + +describe("public cache codec and response validation (characterization)", () => { + it("keeps manifest normalization failure codes", async () => { + const valid = await asset(); + expect(await stageCode([])).toBe("LIMIT_EXCEEDED"); + expect(await stageCode([valid, valid])).toBe("CONFLICT"); + expect( + await stageCode([ + await asset({ + integrity: { algorithm: "SHA-1" as "SHA-256", digestHex: "0" }, + }), + ]), + ).toBe("INVALID_INPUT"); + expect( + await stageCode([await asset({ expectedByteLength: -1 })]), + ).toBe("INVALID_INPUT"); + for (const absoluteUrl of [ + "https://user:secret@assets.example.test/app.js", + "https://other.example.test/app.js", + `${ORIGIN}/app.js#fragment`, + `${ORIGIN}/app.js?token=secret`, + `${ORIGIN}/.well-known/ca-public-cache-v1/candidate`, + ]) { + expect(await stageCode([await asset({ absoluteUrl })])).toBe( + "POLICY_REJECTED", + ); + } + expect(await stageCode([await asset({ absoluteUrl: "not a url" })])).toBe( + "INVALID_INPUT", + ); + expect( + await stageCode([await asset({ expectedContentType: "text/html" })]), + ).toBe("POLICY_REJECTED"); + expect( + await stageCode([ + await asset({ requestHeaders: [["authorization", "Bearer x"]] }), + ]), + ).toBe("POLICY_REJECTED"); + expect( + await stageCode([ + await asset({ + requestHeaders: [["accept"] as unknown as readonly [string, string]], + }), + ]), + ).toBe("INVALID_INPUT"); + + const wrongDigest = await adapterWith().admin.stageRelease({ + releaseRegistryId: "codec-release", + assets: [valid], + manifestDigestHex: "0".repeat(64), + }); + expect(wrongDigest).toMatchObject({ + ok: false, + error: { code: "INTEGRITY_FAILED" }, + }); + const badRelease = await adapterWith().admin.stageRelease({ + ...(await manifestFor("codec-release", [valid], policy)), + releaseRegistryId: "bad release id", + }); + expect(badRelease).toMatchObject({ + ok: false, + error: { code: "INVALID_INPUT" }, + }); + }); + + it("keeps response validation failure codes", async () => { + const valid = await asset(); + const response = ( + headers: Record, + body: Uint8Array = BYTES, + init: ResponseInit = {}, + ) => () => + new Response(Uint8Array.from(body), { + ...init, + headers: { + "cache-control": "public", + "content-type": "application/javascript", + ...headers, + }, + }); + + expect(await stageCode([valid], response({}))).toBe("OK"); + expect( + await stageCode([valid], response({}, BYTES, { status: 203 })), + ).toBe("POLICY_REJECTED"); + expect( + await stageCode([valid], response({ "cache-control": "no-store" })), + ).toBe("POLICY_REJECTED"); + expect(await stageCode([valid], response({ pragma: "no-cache" }))).toBe( + "POLICY_REJECTED", + ); + expect( + await stageCode([valid], response({ "www-authenticate": "Basic" })), + ).toBe("POLICY_REJECTED"); + expect( + await stageCode([valid], response({ "content-type": "text/html" })), + ).toBe("POLICY_REJECTED"); + expect( + await stageCode([valid], response({ "content-type": "text/css" })), + ).toBe("INTEGRITY_FAILED"); + expect(await stageCode([valid], response({ vary: "Cookie" }))).toBe( + "POLICY_REJECTED", + ); + expect( + await stageCode([valid], response({ "content-length": "99999999999" })), + ).toBe("LIMIT_EXCEEDED"); + expect( + await stageCode([valid], response({}, new Uint8Array([1, 2, 3, 4, 5]))), + ).toBe("INTEGRITY_FAILED"); + expect( + await stageCode([valid], response({}, new Uint8Array([1, 2, 3]))), + ).toBe("INTEGRITY_FAILED"); + expect( + await stageCode([valid], response({}, new Uint8Array([4, 3, 2, 1]))), + ).toBe("INTEGRITY_FAILED"); + }); + + it("cancels a pending cached body read when the lookup is aborted", async () => { + const valid = await asset(); + const manifest = await manifestFor("codec-release", [valid], policy); + const storage = new MemoryCacheStorage(); + const adapter = adapterWith(undefined, storage); + expect(await adapter.admin.stageRelease(manifest)).toMatchObject({ + ok: true, + }); + expect( + await adapter.admin.activateRelease( + manifest.releaseRegistryId, + manifest.manifestDigestHex, + ), + ).toMatchObject({ ok: true }); + const name = [...storage.caches.keys()].find((key) => + key.includes(":codec-release:"), + )!; + const cache = storage.caches.get(name)!; + const match = cache.match.bind(cache); + let cancelled = 0; + let pulled: (() => void) | undefined; + const bodyRequested = new Promise((resolve) => { + pulled = resolve; + }); + cache.match = async (request: RequestInfo | URL) => { + if (request instanceof Request && request.url === valid.absoluteUrl) { + return new Response( + new ReadableStream({ + pull() { + pulled?.(); + return new Promise(() => {}); + }, + cancel() { + cancelled += 1; + }, + }), + { + headers: { + "cache-control": "public", + "content-type": "application/javascript", + }, + }, + ); + } + return await match(request); + }; + + const controller = new AbortController(); + const lookup = adapter.responses.matchActiveExact({ + absoluteUrl: valid.absoluteUrl, + signal: controller.signal, + }); + await bodyRequested; + controller.abort(); + expect(await lookup).toMatchObject({ + ok: false, + error: { code: "ABORTED" }, + }); + expect(cancelled).toBe(1); + }); + + it("keeps control JSON decoding failure codes", async () => { + const valid = await asset(); + const manifest = await manifestFor("codec-release", [valid], policy); + const lookupAfter = async ( + tamper: (storage: MemoryCacheStorage) => Promise, + ): Promise => { + const storage = new MemoryCacheStorage(); + const adapter = adapterWith(undefined, storage); + expect(await adapter.admin.stageRelease(manifest)).toMatchObject({ + ok: true, + }); + expect( + await adapter.admin.activateRelease( + manifest.releaseRegistryId, + manifest.manifestDigestHex, + ), + ).toMatchObject({ ok: true }); + await tamper(storage); + const result = await adapter.responses.matchActiveExact({ + absoluteUrl: valid.absoluteUrl, + }); + return result.ok ? "OK" : result.error.code; + }; + const replace = async ( + storage: MemoryCacheStorage, + path: "active" | "candidate", + body: BodyInit, + ): Promise => { + const name = [...storage.caches.keys()].find((key) => + path === "active" + ? key.endsWith(":control") + : key.includes(":codec-release:"), + )!; + await storage.caches + .get(name)! + .put( + new Request(`${ORIGIN}/.well-known/ca-public-cache-v1/${path}`), + new Response(body, { + headers: { "content-type": "application/json" }, + }), + ); + }; + + expect(await lookupAfter(async () => {})).toBe("OK"); + expect( + await lookupAfter((storage) => replace(storage, "active", "{not json")), + ).toBe("CORRUPT_DATA"); + expect( + await lookupAfter((storage) => + replace(storage, "active", new Uint8Array([0xff, 0xfe])), + ), + ).toBe("CORRUPT_DATA"); + expect( + await lookupAfter((storage) => + replace(storage, "active", JSON.stringify({ schemaVersion: 2 })), + ), + ).toBe("CORRUPT_DATA"); + expect( + await lookupAfter(async (storage) => { + const name = [...storage.caches.keys()].find((key) => + key.includes(":codec-release:"), + )!; + const cache = storage.caches.get(name)!; + const marker = await (await cache.match( + new Request(`${ORIGIN}/.well-known/ca-public-cache-v1/candidate`), + ))!.json(); + await replace( + storage, + "candidate", + JSON.stringify({ ...marker, entryCount: 2 }), + ); + }), + ).toBe("CORRUPT_DATA"); + expect( + await lookupAfter((storage) => + replace(storage, "candidate", JSON.stringify({ verified: false })), + ), + ).toBe("CORRUPT_DATA"); + }); +}); diff --git a/tests/unit/public-response-cache.test.ts b/tests/unit/public-response-cache.test.ts index 4ffb06b0..30dd1df8 100644 --- a/tests/unit/public-response-cache.test.ts +++ b/tests/unit/public-response-cache.test.ts @@ -1457,4 +1457,140 @@ describe("public response Cache Storage adapter", () => { expect(bodyCancelled).toBe(true); expect(await cacheStorage.keys()).toEqual([]); }); + + it("reuses a verified release marker across lookups (Q-6.2-6)", async () => { + const policy = createDefaultPublicCachePolicy( + "https://assets.example.test", + ); + const cacheStorage = new MemoryCacheStorage(); + let digests = 0; + const countingCrypto = { + subtle: { + digest: async ( + algorithm: AlgorithmIdentifier, + data: BufferSource, + ): Promise => { + digests += 1; + return await globalThis.crypto.subtle.digest(algorithm, data); + }, + }, + } as unknown as Crypto; + const bodies = new Map(); + const release = async ( + releaseRegistryId: string, + files: Readonly>, + ): Promise => { + const assets: PublicCacheAsset[] = []; + for (const [path, content] of Object.entries(files)) { + const bytes = Uint8Array.from(content); + const absoluteUrl = `https://assets.example.test/${path}`; + bodies.set(absoluteUrl, bytes); + assets.push({ + absoluteUrl, + expectedByteLength: bytes.byteLength, + expectedContentType: "application/javascript", + integrity: { + algorithm: "SHA-256", + digestHex: await digestHex(bytes), + }, + }); + } + return await manifestFor(releaseRegistryId, assets, policy); + }; + const adapter = createPublicResponseCacheAdapter({ + cacheStorage: cacheStorage as unknown as CacheStorage, + crypto: countingCrypto, + mutationLock: immediateLock, + policy, + fetcher: async (request) => + new Response(Uint8Array.from(bodies.get(request.url)!), { + headers: { + "cache-control": "public", + "content-type": "application/javascript", + }, + }), + }); + const publish = async (manifest: PublicCacheReleaseManifest) => { + expect(await adapter.admin.stageRelease(manifest)).toMatchObject({ + ok: true, + }); + expect( + await adapter.admin.activateRelease( + manifest.releaseRegistryId, + manifest.manifestDigestHex, + ), + ).toMatchObject({ ok: true }); + }; + const markerUrl = + "https://assets.example.test/.well-known/ca-public-cache-v1/candidate"; + let markerReads = 0; + const countMarkerReads = (releaseRegistryId: string): void => { + const name = [...cacheStorage.caches.keys()].find((key) => + key.includes(`:${releaseRegistryId}:`), + )!; + const cache = cacheStorage.caches.get(name)!; + const match = cache.match.bind(cache); + cache.match = async (request: RequestInfo | URL) => { + if (request instanceof Request && request.url === markerUrl) { + markerReads += 1; + } + return await match(request); + }; + }; + const lookup = async (path: string): Promise => { + const match = await adapter.responses.matchActiveExact({ + absoluteUrl: `https://assets.example.test/${path}`, + }); + if (!match.ok) throw new Error(match.error.code); + if (!match.value) return null; + const bytes: number[] = []; + for await (const chunk of match.value.body.stream( + new AbortController().signal, + )) { + if (chunk.ok) bytes.push(...chunk.value); + } + return bytes; + }; + + const first = await release("marker-reuse-1", { + "a.js": [1], + "b.js": [2, 2], + "c.js": [3, 3, 3], + }); + await publish(first); + countMarkerReads("marker-reuse-1"); + + digests = 0; + expect(await lookup("b.js")).toEqual([2, 2]); + // First lookup verifies the marker (manifest digest) and the body. + expect(markerReads).toBe(1); + expect(digests).toBe(2); + + digests = 0; + markerReads = 0; + expect(await lookup("c.js")).toEqual([3, 3, 3]); + expect(await lookup("a.js")).toEqual([1]); + expect(await lookup("missing.js")).toBeNull(); + // Later lookups neither re-read nor re-hash the verified marker; only + // each served body is still verified. + expect(markerReads).toBe(0); + expect(digests).toBe(2); + + // A newly activated release is never answered from the old marker. + const second = await release("marker-reuse-2", { "d.js": [4] }); + await publish(second); + expect(await lookup("d.js")).toEqual([4]); + expect(await lookup("a.js")).toBeNull(); + + // An evicted candidate is still reported even though its marker is known. + const secondName = [...cacheStorage.caches.keys()].find((key) => + key.includes(":marker-reuse-2:"), + )!; + cacheStorage.caches.delete(secondName); + expect( + await adapter.responses.matchActiveExact({ + absoluteUrl: "https://assets.example.test/d.js", + }), + ).toMatchObject({ ok: false, error: { code: "STORAGE_EVICTED" } }); + }); }); diff --git a/tests/unit/realtime/bounded-poll-coordinator.test.ts b/tests/unit/realtime/bounded-poll-coordinator.test.ts index 06cfd849..9f08f28b 100644 --- a/tests/unit/realtime/bounded-poll-coordinator.test.ts +++ b/tests/unit/realtime/bounded-poll-coordinator.test.ts @@ -835,6 +835,78 @@ describe("bounded poll coordinator", () => { }); }); + it("ends a run whose executor throws with a retryable OFFLINE", async () => { + const clock = new ManualClock(); + const coordinator = createBoundedPollCoordinator({ + policy, + operation, + environment: new MutableEnvironment(), + clock, + execute: async () => { + throw new TypeError("Failed to fetch"); + }, + }); + const running = coordinator.run(); + clock.advance(5_000); + await expect(running).resolves.toEqual({ + ok: false, + error: { kind: "OFFLINE", operation: "POLL", retryable: true }, + }); + }); + + it("reads attempt results with the shared realtime snapshot rules", async () => { + const runWith = async (result: unknown) => { + const clock = new ManualClock(); + const coordinator = createBoundedPollCoordinator({ + policy, + operation, + environment: new MutableEnvironment(), + clock, + execute: async () => result as BoundedPollAttemptResult, + }); + const running = coordinator.run(); + clock.advance(5_000); + return running; + }; + const terminalValue = () => ({ + kind: "VALUE", + value: "done", + responseBytes: 1, + state: "COMPLETED", + }); + + // A hidden (non-enumerable) field is not plain data: rejected. + await expect( + runWith( + Object.defineProperties( + {}, + { + ok: { enumerable: false, value: true }, + value: { enumerable: true, value: terminalValue() }, + }, + ), + ), + ).resolves.toMatchObject({ + ok: false, + error: { kind: "PROTOCOL_MISMATCH" }, + }); + // A null-prototype record is plain data: accepted. + await expect( + runWith( + Object.assign(Object.create(null) as object, { + ok: true, + value: Object.assign( + Object.create(null) as object, + terminalValue(), + ), + }), + ), + ).resolves.toMatchObject({ + ok: true, + value: { kind: "TERMINAL", value: "done" }, + }); + }); + it("fails closed on response ceilings, concurrent runs and close", async () => { const clock = new ManualClock(); const coordinator = createBoundedPollCoordinator({ diff --git a/tests/unit/realtime/event-codec.test.ts b/tests/unit/realtime/event-codec.test.ts index a344cbe9..d1c7fdd1 100644 --- a/tests/unit/realtime/event-codec.test.ts +++ b/tests/unit/realtime/event-codec.test.ts @@ -227,6 +227,24 @@ describe("REALTIME_EVENT_V1 codec", () => { ); }); + it("keeps a fixed-size semantic fingerprint however large the payload", () => { + const codec = createTestRealtimeCodec(); + const small = codec.decode(realtimeEventJson()); + const large = codec.decode( + realtimeEventJson({ payload: { value: "x".repeat(3_000) } }), + ); + + expect(small.ok && large.ok).toBe(true); + if (!small.ok || !large.ok) return; + expect(large.value.fingerprintBytes).toBe( + small.value.fingerprintBytes, + ); + expect(large.value.fingerprintBytes).toBeLessThanOrEqual(32); + expect(large.value.semanticFingerprint).not.toBe( + small.value.semanticFingerprint, + ); + }); + it("uses bounded uint64 sequence and header-safe cursor helpers", () => { expect(isCanonicalRealtimeSequence("0")).toBe(true); expect(isCanonicalRealtimeSequence(REALTIME_MAX_SEQUENCE)).toBe(true); diff --git a/tests/unit/realtime/fetch-sse-connection.test.ts b/tests/unit/realtime/fetch-sse-connection.test.ts index 79f7b1a8..de2e9c8e 100644 --- a/tests/unit/realtime/fetch-sse-connection.test.ts +++ b/tests/unit/realtime/fetch-sse-connection.test.ts @@ -526,6 +526,29 @@ describe("fetch SSE connection", () => { ); }); + it("dispatches a single chunk holding more events than the per-chunk item cap", async () => { + const chunk = Array.from( + { length: 300 }, + (_, index) => + `id: cursor-${index}\ndata: ${"x".repeat(300)}\n\n`, + ).join(""); + const runtime = connection( + (async () => eventStream([chunk])) as typeof fetch, + ); + const received: string[] = []; + await expect( + runtime.read({ + resumeCursor: null, + onEvent: (event) => { + received.push(event.id ?? ""); + return realtimeSuccess(SSE_CONTINUE); + }, + }), + ).resolves.toMatchObject({ ok: true, value: { kind: "EOF" } }); + expect(received).toHaveLength(300); + expect(received[299]).toBe("cursor-299"); + }); + it("rejects arbitrary endpoints and mode-incoherent cursors before fetch", async () => { expect(() => createFetchSseConnection({ diff --git a/tests/unit/realtime/live-poll-handoff-coordinator.test.ts b/tests/unit/realtime/live-poll-handoff-coordinator.test.ts index c60d77ff..f3c1f9c5 100644 --- a/tests/unit/realtime/live-poll-handoff-coordinator.test.ts +++ b/tests/unit/realtime/live-poll-handoff-coordinator.test.ts @@ -426,6 +426,41 @@ describe("live/poll authoritative writer handoff", () => { }); }); + it("bounds the probe by what is still buffered, not by all it ever accepted", async () => { + const firstLive = deferred>(); + const order: string[] = []; + const harness = createHarness({ + initial: "POLL", + limits: { ...limits, maxProbeBufferedEvents: 2 }, + apply: vi.fn(async ({ value }) => { + order.push(value); + if (value === "live-1") await firstLive.promise; + return realtimeSuccess(undefined); + }), + }); + const live = expectProbe(harness.coordinator.beginLiveProbe()); + await live.write("live-1", 3); + await live.write("live-2", 3); + + const activation = live.activate(); + // live-1 left the buffer for the drain, so one slot is free again. + await vi.waitFor(() => expect(order).toEqual(["live-1"])); + await expect(live.write("live-3", 3)).resolves.toMatchObject({ + ok: true, + value: { kind: "BUFFERED" }, + }); + await expect(live.write("live-4", 3)).resolves.toMatchObject({ + ok: false, + error: { kind: "QUEUE_OVERFLOW" }, + }); + + // Overflow during activation still fails closed. + firstLive.resolve(realtimeSuccess(undefined)); + await expect(activation).resolves.toMatchObject({ ok: false }); + expect(harness.coordinator.inspect().state).toBe("CLOSED"); + expect(order).toEqual(["live-1"]); + }); + it("drops an overflowing probe without displacing poll and never reuses its generation", async () => { const harness = createHarness({ initial: "POLL", diff --git a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts index 6d337439..8e3fd832 100644 --- a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts +++ b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts @@ -234,7 +234,8 @@ function deferred(): Readonly<{ } async function flush(): Promise { - for (let turn = 0; turn < 8; turn += 1) { + // Enough turns for a retry loop iteration: sleep, attempt and close races. + for (let turn = 0; turn < 16; turn += 1) { await Promise.resolve(); } } @@ -433,8 +434,8 @@ describe("realtime reconnect coordinator", () => { expect(result).toBe(terminal); }); - it("resets a spent retry only after policy eligibility", async () => { - const runScenario = async (markValid: boolean) => { + it("resets a spent retry only after a valid signal and a stable open", async () => { + const runScenario = async (markValid: boolean, openMs: number) => { const clock = new ManualClock(); const firstFailure = realtimeFailure( "CONNECT_TIMEOUT", @@ -452,6 +453,7 @@ describe("realtime reconnect coordinator", () => { false, ); const closeSession = vi.fn(); + const closing = deferred>(); let attempts = 0; const coordinator = createRealtimeReconnectCoordinator({ policy: policy({ maxAttempts: 1 }), @@ -474,8 +476,7 @@ describe("realtime reconnect coordinator", () => { receipt: RealtimeReconnectOutcome, ) => receipt, close: closeSession, - waitClosed: () => - failed(sessionFailure, 0), + waitClosed: () => closing.promise, }), ); } @@ -486,12 +487,12 @@ describe("realtime reconnect coordinator", () => { const running = coordinator.run(); await flush(); clock.advance(0); + await flushUntil(() => attempts === 2); await flush(); - if (markValid) { - await flushUntil(() => clock.sleepCalls.length === 2); - expect(clock.sleepCalls).toEqual([0, 0]); - clock.advance(0); - } + clock.advance(openMs); + closing.resolve(failed(sessionFailure, 0)); + await flushUntil(() => clock.sleepCalls.length === 2); + clock.advance(0); const result = await running; return { attempts, @@ -502,12 +503,20 @@ describe("realtime reconnect coordinator", () => { }; }; - const unstable = await runScenario(false); - expect(unstable.attempts).toBe(2); - expect(unstable.result).toBe(unstable.sessionFailure); - expect(unstable.closeSession).toHaveBeenCalledOnce(); + // A heartbeat on a short-lived connection, or a quiet long one, keeps + // the spent budget; only both together reset it. + for (const [markValid, openMs] of [ + [false, 0], + [true, 499], + [false, 500], + ] as const) { + const spent = await runScenario(markValid, openMs); + expect(spent.attempts).toBe(2); + expect(spent.result).toBe(spent.sessionFailure); + expect(spent.closeSession).toHaveBeenCalledOnce(); + } - const eligible = await runScenario(true); + const eligible = await runScenario(true, 500); expect(eligible.attempts).toBe(3); expect(eligible.result).toBe(eligible.terminal); expect(eligible.closeSession).toHaveBeenCalledOnce(); diff --git a/tests/unit/realtime/realtime-reconnect-policy.test.ts b/tests/unit/realtime/realtime-reconnect-policy.test.ts index 4e4de156..b95a6562 100644 --- a/tests/unit/realtime/realtime-reconnect-policy.test.ts +++ b/tests/unit/realtime/realtime-reconnect-policy.test.ts @@ -80,31 +80,19 @@ describe("realtime reconnect policy", () => { expect(parseRetryAfterDelay("-1", 0)).toBeNull(); }); - it("resets attempts only after stable open or a valid signal", () => { - expect( + it("resets attempts only after a valid signal on a stable open", () => { + const eligible = (nowMs: number, observed: boolean) => isReconnectAttemptResetEligible({ policy, openedAtMs: 10, - nowMs: 29_000, - observedValidHeartbeatOrEvent: false, - }), - ).toBe(false); - expect( - isReconnectAttemptResetEligible({ - policy, - openedAtMs: 10, - nowMs: 30_010, - observedValidHeartbeatOrEvent: false, - }), - ).toBe(true); - expect( - isReconnectAttemptResetEligible({ - policy, - openedAtMs: 10, - nowMs: 11, - observedValidHeartbeatOrEvent: true, - }), - ).toBe(true); + nowMs, + observedValidHeartbeatOrEvent: observed, + }); + expect(eligible(29_000, false)).toBe(false); + expect(eligible(30_010, false)).toBe(false); + expect(eligible(11, true)).toBe(false); + expect(eligible(30_009, true)).toBe(false); + expect(eligible(30_010, true)).toBe(true); expect(reconnectBudgetRemaining(policy, 1_000, 2_000)).toBe( 299_000, ); diff --git a/tests/unit/realtime/result.test.ts b/tests/unit/realtime/result.test.ts index 95036e13..7e2ed9b1 100644 --- a/tests/unit/realtime/result.test.ts +++ b/tests/unit/realtime/result.test.ts @@ -1,10 +1,12 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { isRealtimeResult, + raceRealtimeTask, realtimeFailure, realtimeSuccess, snapshotRealtimeResult, + timerDeadline, } from "../../../src/adapters/realtime/result.ts"; function isString(value: unknown): value is string { @@ -166,3 +168,78 @@ describe("realtime result boundary", () => { expect(snapshotRealtimeResult(source, isString)).toBeNull(); }); }); + +describe("realtime abort/deadline race", () => { + const never = () => new Promise(() => undefined); + + it("settles with the value, a rejection or a synchronous throw", async () => { + await expect(raceRealtimeTask(() => 7)).resolves.toEqual({ + kind: "VALUE", + value: 7, + }); + await expect( + raceRealtimeTask(() => Promise.reject(new Error("no"))), + ).resolves.toEqual({ kind: "REJECTED" }); + await expect( + raceRealtimeTask(() => { + throw new Error("sync"); + }), + ).resolves.toEqual({ kind: "REJECTED" }); + }); + + it("aborts without starting, or mid-flight with cleanup", async () => { + const task = vi.fn(never); + await expect( + raceRealtimeTask(task, AbortSignal.abort()), + ).resolves.toEqual({ kind: "ABORTED" }); + expect(task).not.toHaveBeenCalled(); + + const caller = new AbortController(); + const remove = vi.spyOn(caller.signal, "removeEventListener"); + let lease: AbortSignal | undefined; + const running = raceRealtimeTask((signal) => { + lease = signal; + return never(); + }, caller.signal); + caller.abort(); + await expect(running).resolves.toEqual({ kind: "ABORTED" }); + expect(lease?.aborted).toBe(true); + expect(remove).toHaveBeenCalledWith("abort", expect.any(Function)); + }); + + it("times out on the deadline and reports a broken deadline", async () => { + let deadlineSignal: AbortSignal | undefined; + await expect( + raceRealtimeTask(never, undefined, (signal) => { + deadlineSignal = signal; + return Promise.resolve(); + }), + ).resolves.toEqual({ kind: "TIMEOUT" }); + expect(deadlineSignal?.aborted).toBe(true); + + await expect( + raceRealtimeTask(never, undefined, () => Promise.reject(new Error())), + ).resolves.toEqual({ kind: "CLOCK_FAILED" }); + + // A deadline that throws still lets the task start (e.g. a cancel). + const task = vi.fn(never); + await expect( + raceRealtimeTask(task, undefined, () => { + throw new Error("clock"); + }), + ).resolves.toEqual({ kind: "CLOCK_FAILED" }); + expect(task).toHaveBeenCalledOnce(); + }); + + it("clears a host-timer deadline when the task wins", async () => { + vi.useFakeTimers(); + try { + await expect( + raceRealtimeTask(() => "done", undefined, timerDeadline(1_000)), + ).resolves.toEqual({ kind: "VALUE", value: "done" }); + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/tests/unit/realtime/sse-parser.test.ts b/tests/unit/realtime/sse-parser.test.ts index ea3685b9..3e14defe 100644 --- a/tests/unit/realtime/sse-parser.test.ts +++ b/tests/unit/realtime/sse-parser.test.ts @@ -46,6 +46,22 @@ describe("incremental SSE parser", () => { }); }); + it("strips exactly one leading BOM", () => { + const parser = createIncrementalSseParser(); + // The second BOM belongs to the field name, so the line is ignored. + expect( + pushText(parser, "\uFEFF\uFEFFdata: x\n\ndata: y\n\n"), + ).toEqual([ + { + kind: "EVENT", + eventType: "message", + data: "y", + id: null, + hasExplicitId: false, + }, + ]); + }); + it("preserves standard inherited ID state while marking direct IDs", () => { const parser = createIncrementalSseParser(); const items = pushText( @@ -159,18 +175,6 @@ describe("incremental SSE parser", () => { }, }); - const excessiveBatch = createIncrementalSseParser({ - maxItemsPerChunk: 2, - }); - expect(excessiveBatch.push(encoder.encode(":\n:\n:\n"))).toEqual({ - ok: false, - error: { - kind: "QUEUE_OVERFLOW", - operation: "DECODE", - retryable: false, - }, - }); - const oversizedChunk = createIncrementalSseParser({ maxChunkBytes: 65_536, }); @@ -186,6 +190,52 @@ describe("incremental SSE parser", () => { }); }); + it("hands items past the per-chunk cap to drain() instead of failing", () => { + const parser = createIncrementalSseParser({ maxItemsPerChunk: 1 }); + const comment = { kind: "COMMENT" }; + expect(pushText(parser, ":\r:\r\n:\ndata: a\r")).toEqual([comment]); + // The retained text resumes between CR and LF. + expect(parser.drain()).toEqual({ ok: true, value: [comment] }); + expect(parser.drain()).toEqual({ ok: true, value: [comment] }); + expect(parser.drain()).toEqual({ ok: true, value: [] }); + expect(parser.drain()).toEqual({ ok: true, value: [] }); + expect(pushText(parser, "\n\n")).toEqual([ + { + kind: "EVENT", + eventType: "message", + data: "a", + id: null, + hasExplicitId: false, + }, + ]); + + // A lone CR followed by another complete line still honours the cap. + const loneCarriageReturn = createIncrementalSseParser({ + maxItemsPerChunk: 1, + }); + expect(pushText(loneCarriageReturn, ":\r:\n")).toEqual([comment]); + expect(loneCarriageReturn.drain()).toEqual({ + ok: true, + value: [comment], + }); + + // Undrained items are a caller bug: fail closed instead of buffering. + const undrained = createIncrementalSseParser({ maxItemsPerChunk: 1 }); + expect(pushText(undrained, ":\n:\n")).toEqual([comment]); + const overflow = { + ok: false, + error: { + kind: "QUEUE_OVERFLOW", + operation: "DECODE", + retryable: false, + }, + }; + expect(undrained.push(encoder.encode(":\n"))).toEqual(overflow); + const unfinished = createIncrementalSseParser({ maxItemsPerChunk: 1 }); + expect(pushText(unfinished, ":\n:\n")).toEqual([comment]); + expect(unfinished.finish()).toEqual(overflow); + }); + it("parses the same items whether bytes arrive at once or one by one", () => { const stream = encoder.encode( "event: a\r\ndata: 한글\rdata: 😀 é\r\n\r\n" + diff --git a/tests/unit/realtime/stream-coordinator.test.ts b/tests/unit/realtime/stream-coordinator.test.ts index f3d154e8..671a8f96 100644 --- a/tests/unit/realtime/stream-coordinator.test.ts +++ b/tests/unit/realtime/stream-coordinator.test.ts @@ -707,7 +707,7 @@ describe("transport-independent realtime stream coordinator", () => { expect(harness.coordinator.inspect(STREAM_ID).freshness).toBe("STALE"); }); - it("recovers instead of evicting and continuing after dedupe capacity", async () => { + it("evicts the oldest dedupe entry and keeps applying at capacity", async () => { const harness = createHarness({ registry: createTestRealtimeRegistry({ limits: { @@ -718,24 +718,58 @@ describe("transport-independent realtime stream coordinator", () => { }); await harness.initialize(); await harness.coordinator.accept(harness.event()); + const second = { + eventId: "event-00000002", + sequence: "2", + resumeCursor: "cursor-00000002", + }; await expect( - harness.coordinator.accept( - harness.event({ - eventId: "event-00000002", - sequence: "2", - resumeCursor: "cursor-00000002", - }), - ), + harness.coordinator.accept(harness.event(second)), ).resolves.toMatchObject({ ok: true, - value: { - outcome: "RECOVERED", - reason: "DEDUPE_OVERFLOW", - }, + value: { outcome: "APPLIED" }, }); - expect(harness.effects).toHaveBeenCalledTimes(1); - expect(harness.coordinator.inspect(STREAM_ID).dedupeEntries).toBe(0); + expect(harness.effects).toHaveBeenCalledTimes(2); + expect(harness.recoveryReasons).toEqual(["INITIALIZE"]); + expect(harness.coordinator.inspect(STREAM_ID).dedupeEntries).toBe(1); + // The newest entry still catches its duplicate; the evicted one is stale. + await expect( + harness.coordinator.accept(harness.event(second)), + ).resolves.toMatchObject({ + ok: true, + value: { outcome: "DROPPED", reason: "DUPLICATE_EVENT" }, + }); + await expect( + harness.coordinator.accept(harness.event()), + ).resolves.toMatchObject({ + ok: true, + value: { outcome: "DROPPED", reason: "STALE_EVENT" }, + }); + }); + + it("expires dedupe entries by TTL oldest first", async () => { + let now = 10_000; + const harness = createHarness({ now: () => now }); + await harness.initialize(); + await harness.coordinator.accept(harness.event()); + now += TEST_LIMITS.dedupeTtlMs / 2; + await harness.coordinator.accept( + harness.event({ + eventId: "event-00000002", + sequence: "2", + resumeCursor: "cursor-00000002", + }), + ); + now += TEST_LIMITS.dedupeTtlMs / 2; + await harness.coordinator.accept( + harness.event({ + eventId: "event-00000003", + sequence: "3", + resumeCursor: "cursor-00000003", + }), + ); + expect(harness.coordinator.inspect(STREAM_ID).dedupeEntries).toBe(2); }); it("rejects a regressing same-epoch recovery checkpoint atomically", async () => { @@ -1122,6 +1156,7 @@ type HarnessOptions = Readonly<{ }>; scheduleTimeout?: (callback: () => void, delayMs: number) => unknown; clearScheduledTimeout?: (handle: unknown) => void; + now?: () => number; }>; function createHarness(options: HarnessOptions = {}) { @@ -1165,7 +1200,7 @@ function createHarness(options: HarnessOptions = {}) { scopeBinding: "scope-binding-0001", isCurrent: () => current, }, - now: () => 10_000, + now: options.now ?? (() => 10_000), observe: options.observe, ...(options.taskLimits ? { taskLimits: options.taskLimits } : {}), ...(options.scheduleTimeout diff --git a/tests/unit/rest-profile-contract.test.ts b/tests/unit/rest-profile-contract.test.ts index 6dd534be..fba5a25d 100644 --- a/tests/unit/rest-profile-contract.test.ts +++ b/tests/unit/rest-profile-contract.test.ts @@ -1,11 +1,19 @@ import { describe, expect, it } from "vitest"; import { defineRestOperation } from "../../src/contracts/api-operations.ts"; +import { + composeContractContributions, + ContractContributionError, +} from "../../src/contracts/external-contract-runtime.ts"; import { createRestProviderProfile, + INSTALLED_REST_AUTH_PROFILES, + installRestAuthProfileRegistry, resolveRestSecurityProfiles, + REST_AUTH_PROFILES, validateRestProfileBindings, } from "../../src/contracts/rest-profiles.ts"; +import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts"; /** * §24.12: the common REST profile contract must stay independently verifiable @@ -96,3 +104,71 @@ describe("REST provider/auth/CSRF profiles", () => { ).toThrow("Unregistered REST provider binding"); }); }); + +/** + * Q-6.7-9. Composition, the V3 executor and the V2 resolve must all answer + * from one validated installed registry. A raw record handed to resolve used + * to skip installation, so a bearer profile with ambient credentials passed. + */ +describe("one installed REST auth profile registry", () => { + const provider = createRestProviderProfile("PRIMARY_API", "https://api.test", [ + "omit", + "same-origin", + ]); + + it("rejects a raw profile record that installation would refuse", () => { + const incoherent = { + REFERENCE_EXTERNAL_BEARER: { + ...REST_AUTH_PROFILES.REFERENCE_EXTERNAL_BEARER, + credentials: "same-origin" as const, + }, + }; + expect(() => + resolveRestSecurityProfiles(SAMPLE_COMMAND, provider, incoherent), + ).toThrow(TypeError); + }); + + it("resolves through the installed registry", () => { + expect( + resolveRestSecurityProfiles( + SAMPLE_COMMAND, + provider, + INSTALLED_REST_AUTH_PROFILES, + ).auth, + ).toBe(INSTALLED_REST_AUTH_PROFILES.get("REFERENCE_EXTERNAL_BEARER")); + }); + + it("does not resolve an inherited profile id", () => { + expect(() => + resolveRestSecurityProfiles( + { ...SAMPLE_COMMAND, authProfileId: "toString" }, + provider, + REST_AUTH_PROFILES, + ), + ).toThrow("incoherent"); + }); + + it("composes contributions against the registry it is given", () => { + const registry = installRestAuthProfileRegistry({ + ...REST_AUTH_PROFILES, + CUSTOM_BEARER: { + ...REST_AUTH_PROFILES.REFERENCE_EXTERNAL_BEARER, + authProfileId: "CUSTOM_BEARER", + }, + }); + const row = TEST_CONTRACT_CONTRIBUTION.http[0]!; + const contribution = { + ...TEST_CONTRACT_CONTRIBUTION, + http: [ + { ...row, frontend: { ...row.frontend, authProfileId: "CUSTOM_BEARER" } }, + ], + }; + expect(() => composeContractContributions([contribution])).toThrow( + ContractContributionError, + ); + expect( + composeContractContributions([contribution], registry).httpByOperationId + .size, + ).toBe(1); + }); +}); diff --git a/tests/unit/resumable-upload-checkpoint.test.ts b/tests/unit/resumable-upload-checkpoint.test.ts index 88aca0bf..e96c8906 100644 --- a/tests/unit/resumable-upload-checkpoint.test.ts +++ b/tests/unit/resumable-upload-checkpoint.test.ts @@ -317,6 +317,43 @@ describe("IndexedDB resumable upload checkpoint", () => { }); }); + // Q-6.1-6. The revision-free delete exists only for rows this build cannot + // read; a readable checkpoint still needs the exact-revision remove. + it("removes only an unreadable row without a revision", async () => { + const memory = new MemoryIndexedDbFactory(); + const store = createIndexedDbResumableUploadCheckpointStore({ + scope, + factory: memory.factory, + }); + const readable = checkpoint(1); + expect( + await store.compareAndSwap({ expectedRevision: null, checkpoint: readable }), + ).toMatchObject({ ok: true }); + expect( + await store.removeUnreadable?.({ uploadKey: readable.uploadKey }), + ).toMatchObject({ + ok: false, + error: { code: "CONFLICT", recovery: "RECONCILE" }, + }); + expect(await store.read(readable.uploadKey)).toEqual({ + ok: true, + value: readable, + }); + + memory.seed("checkpoints", { ...readable, schemaVersion: 2 }); + expect(await store.read(readable.uploadKey)).toMatchObject({ + ok: false, + error: { code: "CORRUPT_DATA" }, + }); + expect( + await store.removeUnreadable?.({ uploadKey: readable.uploadKey }), + ).toEqual({ ok: true, value: undefined }); + expect(await store.read(readable.uploadKey)).toEqual({ + ok: true, + value: null, + }); + }); + it("closes the bound partition before successful lifecycle deletion", async () => { const memory = new MemoryIndexedDbFactory(); const runtime = createIndexedDbResumableUploadCheckpointRuntime({ diff --git a/tests/unit/resumable-upload-runtime-contract.test.ts b/tests/unit/resumable-upload-runtime-contract.test.ts new file mode 100644 index 00000000..8d20d545 --- /dev/null +++ b/tests/unit/resumable-upload-runtime-contract.test.ts @@ -0,0 +1,367 @@ +import { describe, expect, it } from "vitest"; + +import type { BrowserDataObservation } from "../../src/application/ports/browser-file-storage/shared.ts"; +import { + browserDataFailure, + browserDataSuccess, +} from "../../src/adapters/browser-file-storage/result.ts"; +import { + createResumableUploadRuntime, + type ResumableUploadRuntimeDependencies, +} from "../../src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts"; + +import { + activeSignal, + createControlHarness, + executorFor, + MemoryCheckpointStore, + noContentionLock, + rangeSource, + runtimePolicy, + type ControlHarness, + type TestCapability, +} from "./resumable-upload-runtime-fixture.ts"; + +/** + * Q-6.1-10. Characterization of the two blocks moved out of the runtime file: + * the dependency snapshot wrappers and the server response validators. The + * other runtime suites reach them only on their happy paths. + */ + +function dependencies( + harness: ControlHarness, + overrides: Partial> = {}, +): ResumableUploadRuntimeDependencies { + return { + controlPlane: harness.control, + partExecutor: executorFor(harness), + checkpoints: new MemoryCheckpointStore(), + mutationLock: noContentionLock, + crypto, + policy: runtimePolicy(), + now: () => 1_000, + random: () => 0, + sleep: async () => {}, + ...overrides, + }; +} + +async function upload( + input: ResumableUploadRuntimeDependencies, +) { + return await createResumableUploadRuntime(input).upload({ + uploadKey: "upload_key_contract", + purpose: "attachment", + mediaType: "application/octet-stream", + source: rangeSource(new Uint8Array([1, 2, 3, 4, 5])), + signal: activeSignal, + }); +} + +describe("resumable upload runtime dependency snapshots", () => { + it("rejects an invalid collaborator at composition", () => { + const harness = createControlHarness(); + const invalid: Partial< + ResumableUploadRuntimeDependencies + >[] = [ + { + controlPlane: { + ...harness.control, + abort: undefined, + } as unknown as typeof harness.control, + }, + { partExecutor: {} as never }, + { + checkpoints: { + read: async () => browserDataSuccess(null), + } as never, + }, + { + checkpoints: Object.assign(new MemoryCheckpointStore(), { + removeUnreadable: "not a function", + }) as never, + }, + { mutationLock: {} as never }, + { + crossContextCancellation: { + publish: () => true, + subscribe: () => () => {}, + } as never, + }, + { + crossContextCancellation: { + publish: () => true, + subscribe: () => "not a release", + close: () => {}, + } as never, + }, + { observer: {} as never }, + { now: 1_000 as never }, + { random: "0" as never }, + { sleep: 1 as never }, + ]; + for (const override of invalid) { + expect( + () => createResumableUploadRuntime(dependencies(harness, override)), + Object.keys(override).join(","), + ).toThrow(TypeError); + } + }); + + it("captures collaborator methods once at composition", async () => { + const harness = createControlHarness(); + const runtime = createResumableUploadRuntime(dependencies(harness)); + harness.control.createSession = async () => { + throw new Error("replaced after composition"); + }; + await expect( + runtime.upload({ + uploadKey: "upload_key_contract", + purpose: "attachment", + mediaType: "application/octet-stream", + source: rangeSource(new Uint8Array([1, 2, 3, 4, 5])), + signal: activeSignal, + }), + ).resolves.toMatchObject({ + ok: true, + value: { state: "QUARANTINED" }, + }); + }); + + it("hands the observer frozen copies and survives a throwing one", async () => { + const observations: BrowserDataObservation[] = []; + const harness = createControlHarness(); + await expect( + upload( + dependencies(harness, { + observer: { + record(observation) { + observations.push(observation); + throw new Error("observer failure"); + }, + }, + }), + ), + ).resolves.toMatchObject({ ok: true }); + expect(observations.length).toBeGreaterThan(0); + expect(observations.every((value) => Object.isFrozen(value))).toBe(true); + }); + + it("sleeps between retries with the default timer when none is injected", async () => { + const harness = createControlHarness(); + const create = harness.control.createSession.bind(harness.control); + let creates = 0; + harness.control.createSession = async (input) => { + creates += 1; + return creates === 1 + ? browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", { + retryable: true, + recovery: "RESUME", + }) + : await create(input); + }; + const { sleep: _injected, ...withoutSleep } = dependencies(harness); + await expect(upload(withoutSleep)).resolves.toMatchObject({ + ok: true, + value: { state: "QUARANTINED" }, + }); + expect(creates).toBe(2); + }); + + it("ends the default retry sleep when the caller aborts", async () => { + const harness = createControlHarness(); + let failed: () => void = () => {}; + const firstFailure = new Promise((resolve) => { + failed = resolve; + }); + harness.control.createSession = async () => { + failed(); + return browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", { + retryable: true, + recovery: "RESUME", + }); + }; + const { sleep: _injected, ...withoutSleep } = dependencies(harness, { + policy: runtimePolicy({ + retryBaseDelayMs: 60_000, + retryMaxDelayMs: 60_000, + }), + }); + const controller = new AbortController(); + const uploading = createResumableUploadRuntime(withoutSleep).upload({ + uploadKey: "upload_key_contract", + purpose: "attachment", + mediaType: "application/octet-stream", + source: rangeSource(new Uint8Array([1, 2, 3, 4, 5])), + signal: controller.signal, + }); + await firstFailure; + controller.abort(); + await expect(uploading).resolves.toMatchObject({ + ok: false, + error: { code: "ABORTED" }, + }); + }); + + it("treats a throwing clock as UNAVAILABLE", async () => { + const harness = createControlHarness(); + await expect( + upload( + dependencies(harness, { + now: () => { + throw new Error("clock"); + }, + }), + ), + ).resolves.toMatchObject({ + ok: false, + error: { code: "UNAVAILABLE", operation: "UPLOAD_SESSION" }, + }); + }); +}); + +describe("resumable upload runtime server response validation", () => { + it("rejects a created session with an unknown field", async () => { + const harness = createControlHarness(); + const create = harness.control.createSession.bind(harness.control); + harness.control.createSession = async (input) => { + const created = await create(input); + return created.ok + ? browserDataSuccess({ + ...created.value, + uploadUrl: "https://objects.invalid/secret", + }) + : created; + }; + await expect(upload(dependencies(harness))).resolves.toMatchObject({ + ok: false, + error: { + code: "INTEGRITY_FAILED", + operation: "UPLOAD_SESSION", + recovery: "RECONCILE", + }, + }); + }); + + it("rejects a session concurrency above the local policy", async () => { + const harness = createControlHarness({ serverMaxConcurrency: 4 }); + await expect(upload(dependencies(harness))).resolves.toMatchObject({ + ok: false, + error: { code: "INTEGRITY_FAILED", operation: "UPLOAD_SESSION" }, + }); + }); + + it("restarts a session whose lifetime exceeds the policy ceiling", async () => { + const harness = createControlHarness(); + const create = harness.control.createSession.bind(harness.control); + harness.control.createSession = async (input) => { + const created = await create(input); + return created.ok + ? browserDataSuccess({ + ...created.value, + expiresAtEpochMs: 1_000 + 20_000, + }) + : created; + }; + await expect(upload(dependencies(harness))).resolves.toMatchObject({ + ok: false, + error: { + code: "EXPIRED_RESOURCE", + operation: "UPLOAD_SESSION", + recovery: "RESTART", + }, + }); + }); + + it("rejects a part capability with an unknown field", async () => { + const harness = createControlHarness({ + issueCapability: (input) => + browserDataSuccess({ + capability: Object.freeze({ id: "cap" }), + uploadBindingSha256: input.uploadBindingSha256, + expiresAtEpochMs: 1_000 + 4_000, + href: "https://objects.invalid/secret", + } as never), + }); + await expect(upload(dependencies(harness))).resolves.toMatchObject({ + ok: false, + error: { + code: "CORRUPT_DATA", + operation: "UPLOAD_PART", + recovery: "REISSUE_CAPABILITY", + }, + }); + }); + + it("rejects a part capability that outlives its session", async () => { + const harness = createControlHarness({ + issueCapability: (input) => + browserDataSuccess({ + capability: Object.freeze({ id: "cap" }), + uploadBindingSha256: input.uploadBindingSha256, + expiresAtEpochMs: 1_000 + 5_000 + 1, + }), + }); + await expect(upload(dependencies(harness))).resolves.toMatchObject({ + ok: false, + error: { + code: "POLICY_REJECTED", + operation: "UPLOAD_PART", + recovery: "REISSUE_CAPABILITY", + }, + }); + }); + + it("rejects a status in a state outside the protocol", async () => { + const harness = createControlHarness(); + harness.control.getStatus = async (input) => + browserDataSuccess({ + state: "PAUSED", + protocol: input.protocol, + sessionId: input.sessionId, + requestBindingSha256: input.requestBindingSha256, + } as never); + await expect(upload(dependencies(harness))).resolves.toMatchObject({ + ok: false, + error: { + code: "INTEGRITY_FAILED", + operation: "UPLOAD_RECONCILE", + recovery: "RECONCILE", + }, + }); + }); + + it("rejects server receipts that are out of part order", async () => { + const harness = createControlHarness({ + statusParts: (_session, accepted) => + [...accepted.values()].sort( + (left, right) => right.partNumber - left.partNumber, + ), + }); + // The first status has no parts; once parts are accepted the reversed + // list is what the final reconcile reads. + await expect(upload(dependencies(harness))).resolves.toMatchObject({ + ok: false, + error: { code: "INTEGRITY_FAILED", operation: "UPLOAD_RECONCILE" }, + }); + }); + + it("treats a definitive not-found status as terminal and restarts", async () => { + const harness = createControlHarness({ + sessionId: (index) => `session_0${index}`, + }); + let statusCalls = 0; + const status = harness.control.getStatus.bind(harness.control); + harness.control.getStatus = async (input) => { + statusCalls += 1; + return statusCalls === 1 + ? browserDataFailure("NOT_FOUND", "UPLOAD_RECONCILE") + : await status(input); + }; + await expect(upload(dependencies(harness))).resolves.toMatchObject({ + ok: true, + value: { state: "QUARANTINED", replayed: false }, + }); + expect(harness.getSession()?.sessionId).toBe("session_02"); + }); +}); diff --git a/tests/unit/resumable-upload-runtime.test.ts b/tests/unit/resumable-upload-runtime.test.ts index dbc442fe..015c9431 100644 --- a/tests/unit/resumable-upload-runtime.test.ts +++ b/tests/unit/resumable-upload-runtime.test.ts @@ -23,6 +23,7 @@ import { browserDataFailure, browserDataSuccess, } from "../../src/adapters/browser-file-storage/result.ts"; +import { createIndexedDbResumableUploadCheckpointStore } from "../../src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts"; import { createPresignedUploadPartExecutor } from "../../src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts"; import { createResumableUploadRuntime } from "../../src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts"; import { resolveResumableUploadRuntimePolicy } from "../../src/adapters/browser-transfer/resumable-upload/runtime-policy.ts"; @@ -31,6 +32,7 @@ import type { UploadCancellationListener, } from "../../src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts"; import type { UploadMutationLock } from "../../src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts"; +import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts"; import { activeSignal, @@ -225,6 +227,61 @@ describe("production resumable upload runtime", () => { expect(serialized).not.toContain("etag-part"); }); + // Q-6.1-5. A sibling worker used to keep retrying its part until its own + // attempt deadline; the first failure now aborts the whole transfer. + it("aborts in-flight sibling workers as soon as one part fails", async () => { + const harness = createControlHarness({ serverMaxConcurrency: 2 }); + let secondStarted: () => void = () => {}; + const secondRunning = new Promise((resolve) => { + secondStarted = resolve; + }); + let siblingAborted = false; + const runtime = createResumableUploadRuntime({ + controlPlane: harness.control, + partExecutor: { + async uploadPart(input) { + if (input.part.partNumber === 1) { + await secondRunning; + return browserDataFailure("POLICY_REJECTED", "UPLOAD_PART"); + } + secondStarted(); + return await new Promise((resolve) => { + input.signal.addEventListener( + "abort", + () => { + siblingAborted = true; + resolve(browserDataFailure("ABORTED", "UPLOAD_PART")); + }, + { once: true }, + ); + }); + }, + }, + checkpoints: new MemoryCheckpointStore(), + mutationLock: noContentionLock, + crypto, + policy: runtimePolicy({ providerAttemptTimeoutMs: 60_000 }), + now: () => 1_000, + random: () => 0, + sleep: async () => {}, + }); + + const uploading = runtime.upload({ + uploadKey: "upload_key_01", + purpose: "attachment", + mediaType: "application/octet-stream", + source: rangeSource(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9])), + signal: activeSignal, + }); + + await vi.waitFor(() => expect(siblingAborted).toBe(true)); + // The caller sees the part that failed, not the sibling's ABORTED. + await expect(uploading).resolves.toMatchObject({ + ok: false, + error: { code: "POLICY_REJECTED", operation: "UPLOAD_PART" }, + }); + }); + it("supports replayable FileByteSource without retaining the whole file", async () => { const checkpoints = new MemoryCheckpointStore(); const harness = createControlHarness(); @@ -755,6 +812,56 @@ describe("production resumable upload runtime", () => { ); }); + // Q-6.1-6. A row this build cannot read (here a newer schemaVersion left by + // a rolled-back release) used to fail both upload and abort with + // CORRUPT_DATA until the whole partition was deleted. + it("removes an unreadable checkpoint row on abort and reports ORPHANED", async () => { + const memory = new MemoryIndexedDbFactory(); + const checkpoints = createIndexedDbResumableUploadCheckpointStore({ + scope: { + authorityToken: "authority_token_01", + namespaceToken: "namespace_token_01", + partitionToken: "partition_token_01", + }, + factory: memory.factory, + }); + // Opens the database so the object stores exist before seeding. + expect(await checkpoints.read("upload_key_unreadable")).toEqual({ + ok: true, + value: null, + }); + memory.seed("checkpoints", { + schemaVersion: 2, + uploadKey: "upload_key_unreadable", + revision: 7, + state: "PAUSED", + }); + const harness = createControlHarness(); + const serverAbort = vi.spyOn(harness.control, "abort"); + const runtime = createResumableUploadRuntime({ + controlPlane: harness.control, + partExecutor: executorFor(harness), + checkpoints, + mutationLock: noContentionLock, + crypto, + policy: runtimePolicy(), + now: () => 1_000, + sleep: async () => {}, + }); + + expect( + await runtime.abort({ + uploadKey: "upload_key_unreadable", + signal: activeSignal, + }), + ).toEqual({ ok: true, value: { state: "ORPHANED" } }); + // No session id can be read from the row, so the server is not called. + expect(serverAbort).not.toHaveBeenCalled(); + expect(memory.readRaw("checkpoints", "upload_key_unreadable")).toBe( + undefined, + ); + }); + it("interrupts a same-runtime active upload before explicit abort waits for the key lock", async () => { const checkpoints = new MemoryCheckpointStore(); const harness = createControlHarness(); @@ -976,8 +1083,10 @@ describe("production resumable upload runtime", () => { let forwardedUploadBinding = ""; let forwardedSessionId = ""; let forwardedRequestBinding = ""; + let forwardedBytes: Uint8Array | undefined; const port: PresignedUploadPartPort = { async put(input) { + forwardedBytes = input.bytes; forwardedUploadBinding = input.uploadBindingSha256; forwardedSessionId = input.sessionId; forwardedRequestBinding = input.requestBindingSha256; @@ -1008,6 +1117,7 @@ describe("production resumable upload runtime", () => { expectedSha256: "a".repeat(64), expiresAtEpochMs: 2_000, } as unknown as PresignedUploadPartCapability; + const partBytes = new Uint8Array([1, 2, 3, 4]); const result = await executor.uploadPart({ protocol: RESUMABLE_UPLOAD_PROTOCOL, capability, @@ -1028,7 +1138,7 @@ describe("production resumable upload runtime", () => { byteLength: 4, checksumSha256: "a".repeat(64), }, - bytes: new Uint8Array([1, 2, 3, 4]), + bytes: partBytes, idempotencyKey: "upload-part-idempotency-01", signal: activeSignal, }); @@ -1036,6 +1146,9 @@ describe("production resumable upload runtime", () => { ok: true, value: { receiptToken: "etag.response-01" }, }); + // Q-6.1-3b. The presigned port snapshots the bytes itself, so the bridge + // forwards the part buffer instead of adding a second copy per attempt. + expect(forwardedBytes).toBe(partBytes); expect(forwardedUploadBinding).toBe("b".repeat(64)); expect(forwardedSessionId).toBe("session_01"); expect(forwardedRequestBinding).toBe("c".repeat(64)); diff --git a/tests/unit/retry-policy.test.ts b/tests/unit/retry-policy.test.ts index f479e922..cf3da93c 100644 --- a/tests/unit/retry-policy.test.ts +++ b/tests/unit/retry-policy.test.ts @@ -15,11 +15,21 @@ describe("HTTP retry policy", () => { it("parses retry-after and chooses the longer bounded delay", () => { expect(parseRetryAfter("2", 0)).toBe(2_000); + expect(parseRetryAfter(" 2 ", 0)).toBe(2_000); + expect(parseRetryAfter("Thu, 01 Jan 1970 00:00:05 GMT", 1_000)).toBe( + 4_000, + ); expect(retryDelay({ kind: "RATE_LIMITED", retryAfterMs: 500 }, 0, () => 0)).toBe( 500, ); }); + it("rejects Retry-After values that are not delta-seconds or an HTTP date", () => { + for (const value of ["", " ", "1e3", "1.5", "-1", "0x10", "2024-01-01"]) { + expect(parseRetryAfter(value, 0)).toBeNull(); + } + }); + it("allows at most two retries for safe or keyed requests", () => { const failure = { kind: "SERVER_FAILURE" }; expect(shouldRetry({ idempotency: "safe" }, failure, 0)).toBe(true); diff --git a/tests/unit/runtime-adapters.test.ts b/tests/unit/runtime-adapters.test.ts index 0ffaeefb..2553a34c 100644 --- a/tests/unit/runtime-adapters.test.ts +++ b/tests/unit/runtime-adapters.test.ts @@ -5,6 +5,9 @@ import { createRuntimeHttpClient, } from "../../src/bootstrap/runtime-adapters.ts"; import { createBrowserMutationIntentFactory } from "../../src/adapters/platform/browser-mutation-intent-factory.ts"; +import { createApplication } from "../../src/application/create-application.ts"; +import type { ApplicationFeatureId } from "../../src/application/ports/in/application-api.ts"; +import { INSTALLED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-product-manifest.ts"; import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts"; type Runtime = Parameters[0]["runtime"]; @@ -278,6 +281,51 @@ describe("runtime adapter composition", () => { expect(serviceWorker?.active).toBe(0); }); + it("gives a feature switched off by FEATURE_OVERRIDES no application API (Q-6.9-5)", async () => { + const [disabledId, ...activeIds] = INSTALLED_PRODUCT_FEATURE_IDS; + const adapters = await createRuntimeAdapters({ + runtime: { + ...runtime, + config: { + ...runtime.config, + FEATURE_OVERRIDES: { [disabledId!]: "DISABLED" }, + }, + }, + release, + host: {}, + }); + const application = createApplication( + adapters.outputPorts, + adapters.featureInputs, + ); + + expect(adapters.outputPorts.productFeatures.isActive(disabledId!)).toBe(false); + expect(application.features.has(disabledId!)).toBe(false); + expect(() => + application.features.get(disabledId as ApplicationFeatureId), + ).toThrow(/not installed/u); + for (const featureId of activeIds) { + expect(application.features.has(featureId)).toBe(true); + } + adapters.infrastructure.dispose(); + }); + + it("still resolves every installed feature API when nothing is switched off", async () => { + const adapters = await createRuntimeAdapters({ runtime, release, host: {} }); + const application = createApplication( + adapters.outputPorts, + adapters.featureInputs, + ); + + for (const featureId of INSTALLED_PRODUCT_FEATURE_IDS) { + expect(application.features.has(featureId)).toBe(true); + expect( + application.features.get(featureId as ApplicationFeatureId), + ).toBeDefined(); + } + adapters.infrastructure.dispose(); + }); + it("states contract identity as a digest for a V2 release manifest", async () => { const adapters = await createRuntimeAdapters({ runtime, release, host: {} }); diff --git a/tests/unit/service-worker-runtime.test.ts b/tests/unit/service-worker-runtime.test.ts index c0de17ce..d0158758 100644 --- a/tests/unit/service-worker-runtime.test.ts +++ b/tests/unit/service-worker-runtime.test.ts @@ -4,6 +4,7 @@ import { createServiceWorkerPageController } from "../../src/adapters/service-wo import { createServiceWorkerRuntime } from "../../src/adapters/service-worker/service-worker-lifecycle.ts"; import { createServiceWorkerMessage } from "../../src/adapters/service-worker/service-worker-protocol.ts"; import { installStaticAssets } from "../../src/adapters/service-worker/service-worker-static-assets.ts"; +import { createServiceWorkerRuntimeHost } from "../../src/bootstrap/register-service-worker.ts"; import { SERVICE_WORKER_BOUNDS, SERVICE_WORKER_SCRIPT_PATH, @@ -289,6 +290,21 @@ describe("service worker static cache authority", () => { await expect(served?.text()).resolves.toBe("previous"); }); + it("serves an old build's hashed chunk that the current manifest does not list from the previous release cache (Q-6.6-6b)", async () => { + // The page still runs the previous build and lazy-loads a chunk the new + // manifest (and so the current cache) no longer has. + const oldChunk = "/assets/settings-page-Zz9Yy8Xx.js"; + const fixture = previousReleaseCaches(oldChunk); + const runtime = staticRuntime(fixture.caches, "/assets/app-Dq3x8Yk2.js"); + + const served = await runtime.onFetch({ + method: "GET", + url: `${ORIGIN}${oldChunk}`, + mode: "cors", + }); + await expect(served?.text()).resolves.toBe("previous"); + }); + it("never answers a non-hashed URL from the previous release cache (D-7)", async () => { const assetUrl = "/assets/app.js"; const fixture = previousReleaseCaches(assetUrl); @@ -587,6 +603,53 @@ describe("service worker worker-side protocol", () => { expect(markerPut).toHaveBeenCalledOnce(); }); + it("deletes stale caches before, and regardless of, the marker write (Q-6.6-9)", async () => { + const current = staticCacheName(identity.staticAssetSetDigest); + const stale = `${STATIC_CACHE_PREFIX}${"3".repeat(16)}`; + const previous = `${STATIC_CACHE_PREFIX}${"4".repeat(16)}`; + const order: string[] = []; + // Storage is full: the marker write fails. + const cache = { + match: vi.fn(async () => undefined), + put: vi.fn(async () => { + order.push("marker"); + throw new DOMException("full", "QuotaExceededError"); + }), + } as unknown as Cache; + const runtime = createServiceWorkerRuntime( + { + caches: { + open: vi.fn(async () => cache), + keys: vi.fn(async () => [stale, previous, current]), + delete: vi.fn(async (name: string) => { + order.push(`delete:${name}`); + return true; + }), + }, + clients: { matchAll: vi.fn(async () => []) }, + skipWaiting: vi.fn(async () => {}), + fetcher: vi.fn(), + digest: vi.fn(), + } as never, + { + identity, + handlers: ["PWA_STATIC_ASSETS"], + manifest: { + schemaVersion: 1, + buildId: identity.buildId, + releaseId: identity.releaseId, + setDigest: identity.staticAssetSetDigest as `sha256:${string}`, + assets: [], + }, + runtimeConfigUrl: "/runtime-config.json", + releaseManifestUrl: "/release-manifest.json", + }, + ); + + await expect(runtime.onActivate()).resolves.toBe(1); + expect(order).toEqual([`delete:${stale}`, "marker"]); + }); + it("waits for every exact client drain acknowledgement before activation", async () => { const fixture = workerScope(); const runtime = createServiceWorkerRuntime(fixture.scope as never, { @@ -996,6 +1059,52 @@ describe("service worker static asset install", () => { } }); + /** A failing install through the runtime, with `existing` caches present. */ + async function failInstall(existing: readonly string[]) { + const deleteCache = vi.fn(async (_name: string) => true); + const runtime = createServiceWorkerRuntime( + { + caches: { + open: vi.fn(async () => ({ put: vi.fn() }) as unknown as Cache), + keys: vi.fn(async () => existing), + delete: deleteCache, + }, + clients: { matchAll: vi.fn(async () => []) }, + registrationScope: `${ORIGIN}/`, + skipWaiting: vi.fn(async () => {}), + fetcher: vi.fn(async () => new Response(null, { status: 500 })), + digest: vi.fn(), + } as never, + { + identity, + handlers: ["PWA_STATIC_ASSETS"], + manifest, + runtimeConfigUrl: "/runtime-config.json", + releaseManifestUrl: "/release-manifest.json", + }, + ); + await expect(runtime.onInstall()).rejects.toThrow( + "STATIC_INSTALL_REJECTED:STATUS_INVALID", + ); + return deleteCache; + } + + it("keeps a candidate cache that already existed when install fails (Q-6.6-8)", async () => { + // Same asset set as the active worker (same build id, new worker code): + // the candidate name is the cache the active worker is serving from. + const candidate = staticCacheName(manifest.setDigest); + const deleteCache = await failInstall([candidate]); + expect(deleteCache).not.toHaveBeenCalled(); + }); + + it("still deletes a candidate cache that this install created (Q-6.6-8)", async () => { + const candidate = staticCacheName(manifest.setDigest); + const deleteCache = await failInstall([ + `${STATIC_CACHE_PREFIX}${"e".repeat(16)}`, + ]); + expect(deleteCache.mock.calls.map((call) => call[0])).toEqual([candidate]); + }); + it("accepts replies only from the captured waiting or controller source", async () => { const browser = pageContainer({ waiting: true }); const controller = pageController(browser.container); @@ -1097,6 +1206,42 @@ describe("service worker static asset install", () => { await controller.stop(); }); + it("skips update checks while the injected host document is hidden (Q-6.6-12)", async () => { + vi.useFakeTimers(); + try { + const browser = pageContainer({ controlled: true }); + const hostDocument = { visibilityState: "hidden" as DocumentVisibilityState }; + const host = createServiceWorkerRuntimeHost({ + capabilities: { + serviceWorker: { + mode: "ACTIVE", + scriptPath: SERVICE_WORKER_SCRIPT_PATH, + handlers: [], + }, + serviceWorkerDisabledCleanup: false, + } as never, + routerBasePath: "/", + buildId: "page-build", + host: { + location: { origin: ORIGIN }, + navigator: { serviceWorker: browser.container }, + document: hostDocument, + }, + }); + await expect(host?.start()).resolves.toMatchObject({ kind: "ACTIVE" }); + + await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.updateCheckIntervalMs); + expect(browser.registration.update).not.toHaveBeenCalled(); + + hostDocument.visibilityState = "visible"; + await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.updateCheckIntervalMs); + expect(browser.registration.update).toHaveBeenCalledOnce(); + await host?.stop(); + } finally { + vi.useRealTimers(); + } + }); + it("announces an update that finished installing as waiting (R-6.3)", async () => { const browser = pageContainer({ controlled: true }); const controller = pageController(browser.container); @@ -1328,13 +1473,54 @@ describe("page ↔ worker activation seam", () => { vi.useRealTimers(); } }); + + it("waits past the worker's drain window for its commit reply (Q-6.6-10b)", async () => { + vi.useFakeTimers(); + try { + const seam = activationSeam(["page-build-n", "page-build-n1"]); + for (const tab of seam.tabs) await tab.controller.start(); + // The last tab answers 1ms before the worker's drain deadline, and + // skipWaiting() then takes 50ms: the worker commits after 30s. + const slowTab = seam.tabs[0]!.waiting; + const deliver = slowTab.postMessage.bind(slowTab); + slowTab.postMessage = (message) => { + if (message.kind !== "CLIENT_DRAINED") return deliver(message); + setTimeout( + () => deliver(message), + SERVICE_WORKER_BOUNDS.clientDrainMs - 1, + ); + }; + const promote = seam.workerScope.skipWaiting.getMockImplementation()!; + seam.workerScope.skipWaiting.mockImplementation(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + await promote(); + }); + + const activation = seam.tabs[1]!.controller.requestActivation(); + await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.clientDrainMs + 100); + + await expect(activation).resolves.toEqual({ + kind: "ACTIVATED_RELOAD_REQUIRED", + }); + for (const tab of seam.tabs) await tab.controller.stop(); + } finally { + vi.useRealTimers(); + } + }); }); /** * Loads the real worker entry against stubbed worker globals and build-time * constants, and returns the listeners it registered on `self`. */ -async function loadWorkerEntry(handlers: readonly string[]) { +async function loadWorkerEntry( + handlers: readonly string[], + cacheStorage: unknown = { + open: async () => ({ match: async () => new Response("cached") }), + keys: async () => [], + delete: async () => true, + }, +) { const listeners = new Map void>(); vi.stubGlobal("self", { addEventListener: (type: string, listener: (event: unknown) => void) => { @@ -1362,11 +1548,7 @@ async function loadWorkerEntry(handlers: readonly string[]) { vi.stubGlobal("__CA_SERVICE_WORKER_HANDLERS__", handlers); vi.stubGlobal("__CA_RUNTIME_CONFIG_URL__", "/runtime-config.json"); vi.stubGlobal("__CA_RELEASE_MANIFEST_URL__", "/release-manifest.json"); - vi.stubGlobal("caches", { - open: async () => ({ match: async () => new Response("cached") }), - keys: async () => [], - delete: async () => true, - }); + vi.stubGlobal("caches", cacheStorage); vi.stubGlobal("fetch", async () => new Response("network")); vi.resetModules(); // A computed specifier keeps the WebWorker-lib entry out of the DOM-lib @@ -1376,12 +1558,12 @@ async function loadWorkerEntry(handlers: readonly string[]) { return listeners; } -describe("service worker entry fetch interception (R-6.6)", () => { +describe("service worker entry fetch interception (R-6.6, Q-6.6-6b)", () => { function fetchEvent(request: { method: string; url: string; mode: string }) { return { request, respondWith: vi.fn() }; } - it("answers only same-origin GETs for manifest assets", async () => { + it("answers manifest assets and leaves navigations, API, cross-origin and unhashed requests alone", async () => { try { const listeners = await loadWorkerEntry(["PWA_STATIC_ASSETS"]); const onFetch = listeners.get("fetch")!; @@ -1392,7 +1574,15 @@ describe("service worker entry fetch interception (R-6.6)", () => { { method: "POST", url: asset, mode: "cors" }, { method: "GET", url: `${ORIGIN}/api/users`, mode: "cors" }, { method: "GET", url: `${ORIGIN}/runtime-config.json`, mode: "cors" }, + // `-manifest.json` looks like a content hash; it is still network-only. + { method: "GET", url: `${ORIGIN}/release-manifest.json`, mode: "cors" }, { method: "GET", url: "https://cdn.example/assets/app-Dq3x8Yk2.js", mode: "cors" }, + { method: "GET", url: "https://cdn.example/assets/old-Zz9Yy8Xx.js", mode: "cors" }, + // Q-6.6-6b. Same-origin but not a content-hashed name. + { method: "GET", url: `${ORIGIN}/assets/app.js`, mode: "cors" }, + { method: "GET", url: `${ORIGIN}/favicon.ico`, mode: "no-cors" }, + { method: "POST", url: `${ORIGIN}/assets/old-Zz9Yy8Xx.js`, mode: "cors" }, + { method: "GET", url: `${ORIGIN}/assets/old-Zz9Yy8Xx.js`, mode: "navigate" }, ]; for (const request of passthrough) { const event = fetchEvent(request); @@ -1410,6 +1600,72 @@ describe("service worker entry fetch interception (R-6.6)", () => { } }); + /** + * Q-6.6-6b. The current cache is empty; the previous release cache (found by + * its activation marker) still holds the old build's lazy chunk. + */ + function previousReleaseStorage(oldChunk: string) { + const current = staticCacheName(identity.staticAssetSetDigest); + const previous = `${STATIC_CACHE_PREFIX}${"e".repeat(16)}`; + const marker = JSON.stringify({ + schemaVersion: 1, + cacheName: previous, + activationSequence: 1, + }); + return { + open: async (name: string) => ({ + match: async (url: string) => { + if (name !== previous) return undefined; + if (url === oldChunk) return new Response("previous"); + return url.startsWith("https://clean-architecture.invalid/") + ? new Response(marker) + : undefined; + }, + }), + keys: async () => [current, previous], + delete: async () => true, + }; + } + + it("serves an old build's hashed chunk from the previous release cache (Q-6.6-6b)", async () => { + try { + const oldChunk = `${ORIGIN}/assets/settings-Zz9Yy8Xx.js`; + const listeners = await loadWorkerEntry( + ["PWA_STATIC_ASSETS"], + previousReleaseStorage(oldChunk), + ); + const event = fetchEvent({ method: "GET", url: oldChunk, mode: "cors" }); + listeners.get("fetch")!(event); + + expect(event.respondWith).toHaveBeenCalledOnce(); + const response = (await event.respondWith.mock.calls[0]![0]) as Response; + await expect(response.text()).resolves.toBe("previous"); + } finally { + vi.unstubAllGlobals(); + } + }); + + it("falls back to the network when the previous release cache misses too (Q-6.6-6b)", async () => { + try { + const listeners = await loadWorkerEntry( + ["PWA_STATIC_ASSETS"], + previousReleaseStorage(`${ORIGIN}/assets/settings-Zz9Yy8Xx.js`), + ); + const event = fetchEvent({ + method: "GET", + url: `${ORIGIN}/assets/unknown-Qq1Ww2Ee.js`, + mode: "cors", + }); + listeners.get("fetch")!(event); + + expect(event.respondWith).toHaveBeenCalledOnce(); + const response = (await event.respondWith.mock.calls[0]![0]) as Response; + await expect(response.text()).resolves.toBe("network"); + } finally { + vi.unstubAllGlobals(); + } + }); + it("registers no fetch listener without the static asset handler", async () => { try { const listeners = await loadWorkerEntry(["WEB_PUSH"]); diff --git a/tests/unit/tanstack-cache-coordinator.test.ts b/tests/unit/tanstack-cache-coordinator.test.ts index 4a9603af..07ac65c1 100644 --- a/tests/unit/tanstack-cache-coordinator.test.ts +++ b/tests/unit/tanstack-cache-coordinator.test.ts @@ -212,6 +212,40 @@ describe("TanStack cross-context cache coordinator", () => { expect(invalidate).toHaveBeenCalledTimes(3); }); + it("starts every namespace refetch at once and reports each failure", async () => { + // Q-6.3-8. invalidateQueries resolves only after active refetches finish, + // so awaiting namespaces one by one added their refetch times together. + const client = createClient(); + const pending: Array<() => void> = []; + const invalidate = vi + .spyOn(client, "invalidateQueries") + .mockImplementationOnce( + () => new Promise((resolve) => pending.push(resolve)), + ) + .mockImplementationOnce(() => Promise.reject(new Error("refetch failed"))); + const record = vi.fn(); + const coordinator = createTanStackCacheCoordinator({ + queryClient: client, + invalidationIndex: invalidationIndex(), + topicVersions: topicVersions(), + diagnostics: { record } as never, + }); + + let settled = false; + const done = coordinator.invalidate([TOPIC_A]).then(() => { + settled = true; + }); + await vi.waitFor(() => expect(invalidate).toHaveBeenCalledTimes(2)); + expect(settled).toBe(false); + + pending.forEach((resolve) => resolve()); + await done; + expect(record).toHaveBeenCalledOnce(); + expect(record.mock.calls[0]?.[0]).toMatchObject({ + context: { operation: "invalidate" }, + }); + }); + it("coalesces remote hints while a local mutation lease is held", async () => { const client = createClient(); const harness = crossContextHarness(); diff --git a/tests/unit/telemetry.test.ts b/tests/unit/telemetry.test.ts index 4d501f6f..e1f8aa38 100644 --- a/tests/unit/telemetry.test.ts +++ b/tests/unit/telemetry.test.ts @@ -5,6 +5,11 @@ import { createTelemetryAdapter, safeTraceparent, } from "../../src/adapters/telemetry/best-effort-telemetry.ts"; +import { + createFeatureTelemetry, + createFetchTelemetryTransport, +} from "../../src/adapters/telemetry/feature-telemetry.ts"; +import { createTelemetryCollector } from "../../src/adapters/telemetry/telemetry-collector.ts"; import { TELEMETRY_REGISTRY, projectTelemetryEvent, @@ -357,6 +362,238 @@ describe("best-effort telemetry adapter", () => { ); }); +describe("telemetry collector payloads (Q-6.9-4)", () => { + function recordingFetcher() { + const calls: Array> = []; + const fetcher = vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => { + calls.push({ url: String(url), init: init ?? {} }); + return new Response(null, { status: 204 }); + }); + return { calls, fetcher: fetcher as unknown as typeof fetch }; + } + + it("posts the contract projection for the application port", async () => { + const { calls, fetcher } = recordingFetcher(); + const adapter = createTelemetryAdapter({ + enabled: true, + endpoint: "https://telemetry.test/events", + schedule: () => {}, + now: () => Date.parse("2026-09-24T00:00:00.000Z"), + fetcher, + }); + adapter.emit("api.request.failed", validAttributes); + await adapter.flush(); + + expect(calls).toHaveLength(1); + expect(calls[0]?.url).toBe("https://telemetry.test/events"); + expect(calls[0]?.init).toMatchObject({ + method: "POST", + headers: { "Content-Type": "application/json" }, + keepalive: true, + }); + expect(JSON.parse(String(calls[0]?.init.body))).toEqual({ + events: [ + { + eventName: "api.request.failed", + timestamp: "2026-09-24T00:00:00.000Z", + attributes: validAttributes, + }, + ], + }); + adapter.dispose(); + }); + + it("posts the pipeline projection for the feature port", async () => { + const { calls, fetcher } = recordingFetcher(); + const transport = createFetchTelemetryTransport({ + endpoint: "https://telemetry.test/events", + fetcher, + }); + await transport.send([ + { + event: { kind: "catalog.load.failed", severity: "error", featureId: "catalog" }, + fingerprint: "fp-1", + occurrences: 3, + }, + ]); + + expect(calls).toHaveLength(1); + expect(calls[0]?.url).toBe("https://telemetry.test/events"); + expect(calls[0]?.init).toMatchObject({ + method: "POST", + headers: { "Content-Type": "application/json" }, + keepalive: true, + credentials: "omit", + cache: "no-store", + }); + expect(JSON.parse(String(calls[0]?.init.body))).toEqual({ + events: [ + { + kind: "catalog.load.failed", + severity: "error", + featureId: "catalog", + fingerprint: "fp-1", + occurrences: 3, + }, + ], + }); + }); + + it("rejects a feature batch the collector refuses", async () => { + const transport = createFetchTelemetryTransport({ + endpoint: "https://telemetry.test/events", + fetcher: (async () => new Response(null, { status: 503 })) as typeof fetch, + }); + await expect(transport.send([])).rejects.toThrow(); + }); +}); + +describe("one collector transport for both telemetry ports (Q-6.9-4)", () => { + const featureEvent = { + kind: "catalog.load.failed", + severity: "error", + featureId: "catalog", + } as const; + const hungFetcher = () => { + const signals: AbortSignal[] = []; + // Never settles and ignores its signal: only the collector can end it. + const fetcher = vi.fn((_url: RequestInfo | URL, init?: RequestInit) => { + if (init?.signal) signals.push(init.signal); + return new Promise(() => {}); + }); + return { signals, fetcher: fetcher as unknown as typeof fetch, calls: fetcher }; + }; + + it("sends application telemetry without cookies or HTTP cache", async () => { + const fetcher = vi.fn(async () => new Response(null, { status: 204 })); + const adapter = createTelemetryAdapter({ + enabled: true, + endpoint: "https://telemetry.test/events", + schedule: () => {}, + fetcher: fetcher as unknown as typeof fetch, + }); + adapter.emit("api.request.failed", validAttributes); + await adapter.flush(); + + expect(fetcher).toHaveBeenCalledWith( + "https://telemetry.test/events", + expect.objectContaining({ credentials: "omit", cache: "no-store" }), + ); + adapter.dispose(); + }); + + it("times out a hung collector so later application flushes still send", async () => { + const { fetcher, calls } = hungFetcher(); + const collector = createTelemetryCollector({ + endpoint: "https://telemetry.test/events", + fetcher, + timeoutMs: 5, + }); + const adapter = createTelemetryAdapter({ + enabled: true, + endpoint: "https://telemetry.test/events", + schedule: () => {}, + collector, + }); + adapter.emit("api.request.failed", validAttributes); + await adapter.flush(); + expect(adapter.dropReasons()).toEqual({ "sink-failure": 1 }); + + adapter.emit("api.request.failed", validAttributes); + await adapter.flush(); + expect(calls).toHaveBeenCalledTimes(2); + adapter.dispose(); + }); + + it("times out a hung collector for feature telemetry", async () => { + const { fetcher } = hungFetcher(); + const telemetry = createFeatureTelemetry({ + enabled: true, + endpoint: "https://telemetry.test/events", + collector: createTelemetryCollector({ + endpoint: "https://telemetry.test/events", + fetcher, + timeoutMs: 5, + }), + }); + await telemetry.emit(featureEvent); + await telemetry.flush(); + expect(telemetry.stats()).toMatchObject({ sends: 1, failedSends: 1 }); + telemetry.dispose(); + }); + + it("shares one send-rate window between the two ports", async () => { + const fetcher = vi.fn(async () => new Response(null, { status: 204 })); + const collector = createTelemetryCollector({ + endpoint: "https://telemetry.test/events", + fetcher: fetcher as unknown as typeof fetch, + maxSendsPerMinute: 1, + }); + const adapter = createTelemetryAdapter({ + enabled: true, + endpoint: "https://telemetry.test/events", + schedule: () => {}, + setTimer: () => 0, + clearTimer: () => {}, + collector, + }); + const telemetry = createFeatureTelemetry({ + enabled: true, + endpoint: "https://telemetry.test/events", + collector, + }); + + adapter.emit("api.request.failed", validAttributes); + await adapter.flush(); + await telemetry.emit(featureEvent); + await telemetry.flush(); + + expect(fetcher).toHaveBeenCalledOnce(); + expect(telemetry.stats().buffered).toBe(1); + adapter.dispose(); + telemetry.dispose(); + }); + + it("flushes feature telemetry on page exit and stops listening on dispose", async () => { + const lifecycle = new EventTarget(); + const remove = vi.spyOn(lifecycle, "removeEventListener"); + const fetcher = vi.fn(async () => new Response(null, { status: 204 })); + const telemetry = createFeatureTelemetry({ + enabled: true, + endpoint: "https://telemetry.test/events", + collector: createTelemetryCollector({ + endpoint: "https://telemetry.test/events", + fetcher: fetcher as unknown as typeof fetch, + lifecycle, + }), + }); + await telemetry.emit(featureEvent); + await vi.waitFor(() => expect(fetcher).toHaveBeenCalledOnce()); + // A duplicate is held until the next flush; page exit is that flush. + await telemetry.emit(featureEvent); + expect(fetcher).toHaveBeenCalledOnce(); + + lifecycle.dispatchEvent(new Event("pagehide")); + await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2)); + telemetry.dispose(); + expect(remove).toHaveBeenCalledWith("pagehide", expect.any(Function)); + }); + + it("aborts an in-flight feature batch on dispose", async () => { + const { fetcher, signals } = hungFetcher(); + const telemetry = createFeatureTelemetry({ + enabled: true, + endpoint: "https://telemetry.test/events", + fetcher, + }); + await telemetry.emit(featureEvent); + await vi.waitFor(() => expect(signals).toHaveLength(1)); + + telemetry.dispose(); + expect(signals[0]?.aborted).toBe(true); + }); +}); + describe("telemetry adapter send-rate limit (spec §27)", () => { function harness(maxSendsPerMinute = 3) { let now = 0; diff --git a/tests/unit/web-push-codec.test.ts b/tests/unit/web-push-codec.test.ts index a0342b1e..4bd286b0 100644 --- a/tests/unit/web-push-codec.test.ts +++ b/tests/unit/web-push-codec.test.ts @@ -18,6 +18,13 @@ import { createWebPushRegistrationGateway, type WebPushRegistrationExecutor, } from "../../src/adapters/web-push/push-registration-gateway.ts"; +import { createPushAssociationFenceStore } from "../../src/adapters/web-push/push-association-fence-store.ts"; +import { createWebPushSubscriptionAdapter } from "../../src/adapters/web-push/push-subscription-adapter.ts"; +import { createFakePushControlStoreDependencies } from "../helpers/fake-push-control-repository.ts"; +import { + base64UrlDecode, + base64UrlEncode, +} from "../../src/adapters/web-push/codec-primitives.ts"; const now = Date.parse("2026-07-28T00:00:00.000Z"); @@ -130,6 +137,29 @@ describe("Web Push contracts", () => { }); }); + it("rejects duplicate keys at any depth without a nesting budget", () => { + const deepDeclarative = { + web_push: 8030, + notification: { title: "t", data: { a: [[[[{ b: 1 }]]]] } }, + }; + expect( + decodeWebPushHint(encoded(deepDeclarative), now), + ).toMatchObject({ + ok: false, + error: { code: "DECLARATIVE_PUSH_FORBIDDEN" }, + }); + const nestedDuplicate = JSON.stringify(deepDeclarative).replace( + '"title":"t"', + '"title":"t","title":"u"', + ); + expect( + decodeWebPushHint(new TextEncoder().encode(nestedDuplicate), now), + ).toMatchObject({ + ok: false, + error: { code: "CONTRACT_REJECTED" }, + }); + }); + it("uses an injected closed notification and route registry", async () => { const registry = createWebPushNotificationRegistry([ { @@ -253,3 +283,136 @@ describe("Web Push contracts", () => { }); }); }); + +/** + * Q-6.6-12. The web-push files each carried their own base64url decoder, + * opaque-id pattern, authority check and exact-record check. These pin what + * every caller observes, so merging them into one module cannot loosen any. + */ +describe("web-push codec primitives as seen by their callers (Q-6.6-12)", () => { + const authority = { + fenceGeneration: "fence_01", + sessionBindingEpoch: "session_01", + releaseEpoch: "release_01", + }; + const p256dhBytes = new Uint8Array(65); + p256dhBytes[0] = 4; + const material = { + endpoint: "https://push.example.test/subscription/opaque", + p256dh: Buffer.from(p256dhBytes).toString("base64url"), + auth: Buffer.from(new Uint8Array(16)).toString("base64url"), + expirationTime: null, + }; + /** 87 chars carry 2 spare bits and 22 chars carry 4; they must be zero. */ + const withSpareBitSet = (encoded: string) => + `${encoded.slice(0, -1)}${encoded.endsWith("A") ? "B" : "A"}`; + const registered: WebPushRegistrationExecutor = { + async execute() { + return webPushSuccess({ + protocol: WEB_PUSH_PROTOCOLS.registration, + associationEpoch: "association_01", + sessionBindingEpoch: "session_01", + }); + }, + }; + + it("rejects subscription keys whose spare base64url bits are set", async () => { + const gateway = createWebPushRegistrationGateway(registered); + for (const broken of [ + { ...material, p256dh: withSpareBitSet(material.p256dh) }, + { ...material, auth: withSpareBitSet(material.auth) }, + ]) { + expect( + await gateway.register({ + material: broken, + authority, + idempotencyKey: "idempotency_01", + }), + ).toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } }); + } + }); + + it("rejects a VAPID key whose spare base64url bits are set", () => { + const key = new Uint8Array(65); + key[0] = 4; + const valid = Buffer.from(key).toString("base64url"); + expect(() => + createWebPushSubscriptionAdapter({ + vapidPublicKey: withSpareBitSet(valid), + } as never), + ).toThrow(TypeError); + }); + + it("rejects a null authority as invalid input in the fence store", async () => { + const store = createPushAssociationFenceStore( + createFakePushControlStoreDependencies(), + ); + expect( + await store.prepare({ + authority: null as never, + updatedAt: "2026-07-28T00:00:00.000Z", + }), + ).toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } }); + }); + + it("rejects a null authority as invalid input in the gateway", async () => { + const gateway = createWebPushRegistrationGateway(registered); + await expect( + gateway.register({ + material, + authority: null as never, + idempotencyKey: "idempotency_01", + }), + ).resolves.toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } }); + await expect( + gateway.reconcile({ material, authority: null as never }), + ).resolves.toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } }); + }); + + it("rejects backend answers that are arrays or carry extra keys", async () => { + for (const answer of [ + [WEB_PUSH_PROTOCOLS.revoke, "REVOKED"], + { protocol: WEB_PUSH_PROTOCOLS.revoke, state: "REVOKED", extra: 1 }, + ]) { + const gateway = createWebPushRegistrationGateway({ + execute: async () => webPushSuccess(answer), + }); + expect( + await gateway.revoke({ associationEpoch: "association_01" }), + ).toMatchObject({ ok: false, error: { code: "CONTRACT_REJECTED" } }); + } + }); + + it("gives every accepted base64url string exactly one decoding", () => { + expect([...base64UrlDecode("AQID")!]).toEqual([1, 2, 3]); + expect([...base64UrlDecode("AQ")!]).toEqual([1]); + expect(base64UrlDecode("")?.byteLength).toBe(0); + // "AQIDA": a lone trailing character cannot finish a byte. The window + // adapter's old copy accepted it because its spare bits were zero. + for (const invalid of ["A", "AQIDA", "AR", "AQ==", "AQ+/", null, 7]) { + expect(base64UrlDecode(invalid), String(invalid)).toBeNull(); + } + }); + + it("encodes base64url exactly like Node and round-trips through the decoder", () => { + for (let length = 0; length <= 66; length += 1) { + const bytes = Uint8Array.from({ length }, (_, index) => (index * 37 + 11) & 255); + const encoded = base64UrlEncode(bytes); + expect(encoded).toBe(Buffer.from(bytes).toString("base64url")); + expect([...base64UrlDecode(encoded)!]).toEqual([...bytes]); + } + }); + + it("rejects opaque ids outside the shared pattern", async () => { + const gateway = createWebPushRegistrationGateway(registered); + for (const associationEpoch of ["", "-leading", "a b", "a".repeat(129)]) { + expect(await gateway.revoke({ associationEpoch })).toMatchObject({ + ok: false, + error: { code: "INVALID_INPUT" }, + }); + } + expect( + decodeWebPushHint(encoded(hint({ notificationId: "a b" })), now), + ).toMatchObject({ ok: false }); + }); +}); diff --git a/tests/unit/web-push-worker-runtime.test.ts b/tests/unit/web-push-worker-runtime.test.ts index 197bec38..ff9c8f58 100644 --- a/tests/unit/web-push-worker-runtime.test.ts +++ b/tests/unit/web-push-worker-runtime.test.ts @@ -346,6 +346,114 @@ describe("Web Push worker runtime", () => { expect(focus).not.toHaveBeenCalled(); }); + describe("a rejected click opens the app root (Q-6.6-11, D-14)", () => { + async function rejectedClick( + options: Readonly<{ at?: number; data?: unknown }>, + ) { + const store = await activeFence(); + const postMessage = vi.fn(); + const focus = vi.fn(async () => {}); + const openWindow = vi.fn(async (url: string) => ({ + url, + focus: async () => {}, + postMessage() {}, + })); + const observations: unknown[] = []; + const adapter = createNotificationClickAdapter({ + fenceStore: store, + registry, + origin: "https://app.example.test", + now: () => options.at ?? now, + observer: { + record(observation) { + observations.push(observation); + }, + }, + clients: { + async matchControlledWindowClients() { + return [ + { url: "https://app.example.test/current", focus, postMessage }, + ]; + }, + openWindow, + }, + }); + let waited: Promise | null = null; + const result = await adapter.handle({ + notification: { data: options.data ?? clickData(), close() {} }, + waitUntil(task) { + waited = task; + }, + }); + await waited; + return { result, openWindow, focus, postMessage, observations }; + } + + it("opens the root without handoff data for an expired click", async () => { + const click = await rejectedClick({ + at: Date.parse("2026-07-28T02:00:00.000Z"), + }); + + expect(click.result).toMatchObject({ + ok: false, + error: { code: "EXPIRED" }, + }); + expect(click.openWindow.mock.calls).toEqual([ + ["https://app.example.test/"], + ]); + expect(click.postMessage).not.toHaveBeenCalled(); + expect(click.focus).not.toHaveBeenCalled(); + expect(click.observations).toContainEqual({ + event: "web_push_click_dispatched", + outcome: "FAILED", + reason: "EXPIRED", + nativeEffect: "CONFIRMED", + }); + }); + + it("opens the root for a click from another release", async () => { + const click = await rejectedClick({ + data: { ...clickData(), releaseEpoch: "release_02" }, + }); + + expect(click.result).toMatchObject({ + ok: false, + error: { code: "RELEASE_MISMATCH" }, + }); + expect(click.openWindow.mock.calls).toEqual([ + ["https://app.example.test/"], + ]); + expect(click.postMessage).not.toHaveBeenCalled(); + }); + + it("does not retry the root after the browser refused the target window", async () => { + const store = await activeFence(); + const openWindow = vi.fn(async () => null); + const adapter = createNotificationClickAdapter({ + fenceStore: store, + registry, + origin: "https://app.example.test", + now: () => now, + clients: { + matchControlledWindowClients: async () => [], + openWindow, + }, + }); + + const result = await adapter.handle({ + notification: { data: clickData(), close() {} }, + waitUntil() {}, + }); + expect(result).toMatchObject({ + ok: false, + error: { code: "NATIVE_FAILURE" }, + }); + expect(openWindow.mock.calls).toEqual([ + ["https://app.example.test/inbox"], + ]); + }); + }); + it("aborts in-flight push work when the worker runtime is disposed", async () => { const store = await activeFence(); const listeners = new Map void>();