diff --git a/docs/architecture/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index 4707fa4f..434db1d3 100644 --- a/docs/architecture/optional-adapter-recipes.md +++ b/docs/architecture/optional-adapter-recipes.md @@ -106,6 +106,22 @@ type은 facade 밖으로 노출하지 않는다. SSOT다. 문서와 catalog가 다르면 gate가 검사하는 catalog를 우선 고치고 이 표도 같이 갱신한다. +Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·2·6만 갖고 있다. + +1. `src/features/installed-runtime-capabilities.ts`의 `SERVICE_WORKER`를 + `ACTIVE`로 바꾼다. `scripts/build-frontend.ts`가 worker 빌드를 추가로 돈다. +2. 관측: `createRuntimeComposition`이 텔레메트리 포트를 optional host에 넘긴다. + 시작 결과가 `FAILED`나 `INCOMPATIBLE`이면 `service-worker.start.failed`가 1건 + 남는다(`src/bootstrap/optional-runtime-host.ts`). 업데이트 설치 실패와 page + controller의 `observe`는 아직 어디에도 연결되지 않는다. +3. blockers: 저장하지 않은 편집이 있는 탭이 활성화를 거절하게 + `createOptionalRuntimeHost`에 `blockers`를 넘긴다. 템플릿은 넘기지 않는다. +4. 활성화 UI: `ServiceWorkerRuntimeHost.onUpdateWaiting`을 구독하고, 사용자가 + 동의하면 `requestActivation()`을 부른다(`src/contracts/service-worker.ts`). +5. reload 처리: `onReloadRequired`를 구독해 reload를 안내한다. +6. 끄기·롤백·제거: `docs/operations/release-cache-rollback.md`의 Service Worker + 절차. `service-worker.js`는 `Cache-Control: no-cache`로 서빙한다. + Web Push target은 현재 13번째 설치 recipe가 아니다. 기존 `realtime`, `service-worker-pwa`, `browser-permission`의 인접 경계를 조합해야 하는 별도 `NOT_SELECTED` capability다. 실제 선택 전 VD-10 amendment와 machine-readable 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 216e4af1..d284c036 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -1316,6 +1316,16 @@ user opt-in `matchAll()`이 signal을 따르지 않거나 `waitUntil()`이 동기 예외를 내도 늦은 `postMessage`를 허용하지 않고 degraded observation으로 닫는다. - re-subscribe가 실패하면 notification을 끄고 foreground fallback을 유지한다. +- 여러 tab은 native subscription(worker registration당 1개)과 origin의 fence + record를 공유한다. 그래서 `enable`·`reconcile`·`revoke`는 origin 단위 Web Lock + `web-push-control` 안에서 하나씩 실행한다. `inspect`는 읽기만 하므로 lock을 + 잡지 않는다. composition이 `navigator.locks`를 `lockManager`로 넘기고, Web + Locks가 없으면 `PUSH_UNSUPPORTED`로 보고한다 + (`src/adapters/web-push/push-subscription-adapter.ts`의 `exclusive`, + `supportReadiness`). activate 실패나 session binding 불일치의 보상은 backend + association을 revoke하지만 native `unsubscribe()`는 그 호출이 새로 만든 + subscription에만 한다. 이미 있던 subscription은 다른 tab의 association일 수 + 있다(`activateCommit`, 06-02). `associationEpoch`은 backend registration authority가 발급한다. `releaseEpoch`은 signed/verified release manifest에서 온다. backend registration @@ -1335,6 +1345,26 @@ logout/account switch: 찾아 best-effort close한다. 6. 새 account opt-in은 기존 consent와 association 정책을 다시 평가한다. +logout 없이 account가 바뀐 경우(session 만료, cookie 삭제, logout 중 crash)에는 +새 session이 이전 authority를 모른다. 그래서 `revoke`를 부를 수 없고, `enable`과 +`reconcile`은 `STALE_AUTHORITY`로 막힌다. 이때는 `revokeForeign({ nextAuthority })` +를 한 번 부른다(`src/application/ports/out/web-push-control.ts`). 다른 +`fenceGeneration`이 가진 fence를 `nextAuthority`의 `REVOKED`로 회전하고, 그 fence가 +갖던 association을 revoke하고, native subscription과 그 association의 notification을 +위 1~5 순서로 정리한다. 그 뒤 새 account의 opt-in이 가능하다. `nextAuthority`의 +`fenceGeneration`이 이미 가진 fence(같은 session의 다른 tab이 opt-in한 경우 등)는 +건드리지 않고 `inspect` 결과를 돌려준다(`push-subscription-adapter.ts` +`revokeForeign`, 06-06). 이 연산은 저장된 authority를 증명으로 요구하지 않는다. +그래서 BFF가 방금 확인한 현재 session의 authority로만 부른다. 오래된 session을 가진 +tab이 부르면 현재 account의 association을 revoke하게 된다. + +Web Push를 채택하려면 server 쪽에 다음 두 가지가 있어야 한다. 비정상 전환에서 +client revoke가 늦거나 실패해도 이전 account의 push를 막는 것은 이 둘뿐이다. + +- 짧은 association TTL: 갱신되지 않은 association은 server가 스스로 만료시킨다. +- send-time authorization: 보낼 때마다 association의 account와 session binding이 + 아직 유효한지 확인한다. + backend revoke가 ambiguous하면 server subscription은 짧은 association TTL, session/account epoch 확인과 send-time authorization으로 추가 방어한다. local `REVOKED` transaction이 실패하면 “late push를 반드시 drop했다”고 주장하지 @@ -1491,7 +1521,10 @@ worker가 종료·재시작된 뒤에도 click을 처리할 수 있도록 이 bo envelope만 `NotificationOptions.data`에 넣는다. click handler는 codec/size/expiry, current local `ACTIVE` fence와 release epoch를 다시 검증한다. unknown/mismatch (만료, fence·release 불일치, fence 읽기 실패, 모르는 route)는 notification을 닫고 -요청한 route 대신 **앱 루트(`/`)를 handoff 데이터 없이 연다**(D-14). +요청한 route 대신 **앱 루트를 handoff 데이터 없이 연다**(D-14). 앱 루트는 worker의 +`registration.scope`, 즉 router base path다(예: `/app/`). scope를 모르면 +`/`을 쓴다(`src/adapters/web-push/service-worker-scope-host.ts`, +`inbound/notification-click-adapter.ts`의 `appRootUrl`, 06-09). 사용자의 탭이 아무 반응 없이 사라지지 않게 하되, 거절된 click의 route와 notification 정보는 페이지로 넘기지 않는다. 결과는 여전히 실패로 보고하고 (`web_push_click_dispatched` `FAILED` + reason, `nativeEffect`는 루트 창의 diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md index b2e8d014..81765b77 100644 --- a/docs/operations/browser-file-storage-recovery.md +++ b/docs/operations/browser-file-storage-recovery.md @@ -460,8 +460,11 @@ committed object를 sync handle로 in-place repair하지 않는다. 새 generati ## 8. Cache Storage/Service Worker stale or poisoned release public static Cache release runtime은 존재하지만 cursor/count/deadline이 있는 -bounded inspect/cleanup과 Service Worker waiting/client-drain controller는 아직 -없다. Service Worker는 제품이 PWA/offline fetch를 별도로 선택한 경우에만 아래 +bounded inspect/cleanup은 아직 없다. Service Worker의 waiting/client-drain +활성화는 page controller의 `requestActivation()` 핸드셰이크로 구현돼 있다 +(`src/adapters/service-worker/service-worker-page-controller.ts`). 템플릿에는 이를 +부르는 화면이 없다. Service Worker는 제품이 static selection +(`src/features/installed-runtime-capabilities.ts`)을 `ACTIVE`로 바꾼 경우에만 아래 worker 절차를 적용한다. ### 신호 @@ -506,12 +509,38 @@ static Cache-only 조합: invocation을 추가 budget으로 반복 실행하지 않는다. VD-15 bounded cursor runtime 구현 전에는 큰 namespace를 자동 sweep하지 않는다. -Service Worker를 별도 선택한 조합에서만 추가: +Service Worker를 별도 선택한 조합에서만 추가. 워커의 fetch 가로채기만 끄는 +스위치는 없다. 끄는 경로는 아래 둘이다. -- fetch interception을 network-only kill switch로 전환 -- new worker activation 중지 -- 필요하면 unregister + 다음 navigation cleanup migration -- old controlled client가 drain되기 전 해당 release cleanup 금지 +- 페이지가 부팅하면: runtime config에 `CAPABILITY_OVERRIDES.SERVICE_WORKER: + "DISABLED"`를 넣는다. 재빌드는 필요 없다. 다음 부팅 때 page controller가 scope와 + script가 정확히 일치하는 등록만 unregister하고, 새 등록은 하지 않는다 + (`src/contracts/runtime-capabilities.ts` `resolveRuntimeCapabilities`, + `service-worker-page-controller.ts` `start()`의 `disabledCleanup` 분기). 소유 + 캐시는 지우지 않는다. unregister는 이미 열린 탭의 제어를 끊지 않으므로, 그 탭은 + 닫히거나 다시 load될 때까지 현재 워커를 쓴다. +- 워커 때문에 페이지가 부팅하지 못하면: static selection을 + `{ mode: "REMOVE_REGISTRATION", scriptPath: "service-worker.js" }`로 바꾼 + release를 배포한다. 이 release는 같은 URL에 자기 해제 `service-worker.js`를 낸다 + (`scripts/build-frontend.ts`, `scripts/lib/self-unregistering-service-worker.ts`). + 페이지 코드가 돌지 않아도 브라우저 update 검사(내비게이션 때, 등록은 + `updateViaCache: "none"`)가 이 파일을 받아 설치한다. 설치 즉시 + `skipWaiting()`하고, 활성화 때 `registration.unregister()`한다. fetch handler가 + 없어서 그동안의 요청은 모두 네트워크로 간다. 다음 load부터는 제어받지 않는다. + 브라우저 확인: `tests/e2e/service-worker-recovery.spec.ts`. +- 이 경로가 동작하려면 `service-worker.js`를 `Cache-Control: no-cache`로 서빙해야 + 한다. `verify:hosting-headers`는 파일이 있는지만 보고 이 헤더는 보지 않는다 + (`scripts/lib/hosting-probe.ts` `checkPublicServiceWorkers`). +- 새 워커는 install에서 `skipWaiting()`하지 않는다(`service-worker-entry.ts`). + 활성화는 페이지의 `requestActivation()`으로만 일어나므로, 새 worker 활성화를 + 멈추려고 따로 할 일은 없다. +- 제거는 `ACTIVE → REMOVE_REGISTRATION → PURGE_OWNED_RESOURCES → null` 순서로 + release를 나눈다(`src/contracts/service-worker.ts` + `InstalledServiceWorkerSelection`). 소유 캐시는 `PURGE_OWNED_RESOURCES` release의 + page controller가 지운다(`service-worker-removal.ts` `purgeOwnedResources`). + old controlled client가 drain되기 전에는 이 release를 배포하지 않는다. 캐시가 + 사라지면 그 탭의 워커는 요청을 네트워크로 넘기고(`service-worker-entry.ts` + fetch 리스너의 `cached ?? fetch(request)`), 서버에 없는 옛 청크는 404가 된다. hosting/CDN purge는 두 branch와 분리된 provider 절차로 실행한다. diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md index aa18c558..c09e7f54 100644 --- a/docs/operations/release-cache-rollback.md +++ b/docs/operations/release-cache-rollback.md @@ -45,8 +45,10 @@ The provider-independent cache defaults are: - runtime config and release manifest: `no-store` - public source maps: disabled - service worker/offline cache: disabled, unless the static selection in - `src/features/installed-runtime-capabilities.ts` is `ACTIVE`; then `dist` - holds exactly the selected `service-worker.js` + `src/features/installed-runtime-capabilities.ts` is `ACTIVE` or + `REMOVE_REGISTRATION`; then `dist` holds exactly the selected + `service-worker.js`, served `no-cache` so the browser's update check sees + each release's worker HTML, JSON config/manifest, and hashed JavaScript MIME types are also compared to the declared allowlist; a cache-correct response with a mismatched @@ -73,3 +75,35 @@ request them. The minimum is the previous release while the next one is active (the rolling window modeled in `tests/release/release-fixture.ts`). Size it to the longest session the product supports; a tab older than that depends on the reload-once recovery (FE-RB-002). + +## Service Worker steps (only when the static selection is not `null`) + +The worker is part of the release tuple: `service-worker.js` comes from the +same build as the HTML and assets it caches. + +1. **Rollback N+1 → N.** Switching the tuple serves N's `service-worker.js`. + The browser's update check installs it; the worker never calls + `skipWaiting()` on install (`src/adapters/service-worker/service-worker-entry.ts`), + so it waits until every tab of the scope closes or a page calls + `requestActivation()`. The template has no page that calls it. The cache + name is the asset-set digest, so if N's cache is still there as the + retained previous cache, the install reuses it and never deletes it on + failure (`service-worker-static-assets.ts` `installStaticAssets`). Tabs still on N+1 keep worker N+1, so N+1's assets + stay reachable for the rolling window above. +2. **Turn the worker off without a rebuild.** Set + `CAPABILITY_OVERRIDES.SERVICE_WORKER: "DISABLED"` in the runtime config. The + next boot unregisters the owned registration and registers nothing; owned + caches stay (`src/contracts/runtime-capabilities.ts` + `resolveRuntimeCapabilities`, `service-worker-page-controller.ts` `start()`). + This needs a page that boots. +3. **A worker stops the page from booting.** Deploy a release whose static + selection is `REMOVE_REGISTRATION`. It ships a self-unregistering + `service-worker.js` (`scripts/build-frontend.ts`, + `scripts/lib/self-unregistering-service-worker.ts`): the update check + installs it over the broken worker, it skips waiting, unregisters on + activation and answers no fetch. The next load is uncontrolled + (`tests/e2e/service-worker-recovery.spec.ts`). Runbook: + `docs/operations/browser-file-storage-recovery.md` §8. +4. **Removing the worker** takes three releases: + `REMOVE_REGISTRATION` → `PURGE_OWNED_RESOURCES` (deletes owned caches) → + `null` (`src/contracts/service-worker.ts` `InstalledServiceWorkerSelection`). diff --git a/scripts/build-frontend.ts b/scripts/build-frontend.ts index 8158b9e8..d77ba74b 100644 --- a/scripts/build-frontend.ts +++ b/scripts/build-frontend.ts @@ -1,9 +1,11 @@ import { spawnSync } from "node:child_process"; -import { rm } from "node:fs/promises"; +import { rm, writeFile } from "node:fs/promises"; import process from "node:process"; +import { SERVICE_WORKER_SCRIPT_PATH } from "../src/contracts/service-worker.ts"; import { INSTALLED_RUNTIME_CAPABILITIES } from "../src/features/installed-runtime-capabilities.ts"; import { makeDistFilesPublic } from "./lib/dist-permissions.ts"; +import { SELF_UNREGISTERING_SERVICE_WORKER } from "./lib/self-unregistering-service-worker.ts"; /** * §17.2.2. Deterministic two-pass build. @@ -17,17 +19,22 @@ import { makeDistFilesPublic } from "./lib/dist-permissions.ts"; * 4. materialize dist/config.json from the declared APP_PROFILE * 5. scan app dist and generate the static asset source * 6. ACTIVE only: Vite Service Worker build (emptyOutDir = false) + * REMOVE_REGISTRATION only: write the self-unregistering worker (06-03) * 7. generate Release Manifest V2 and the build manifest * 8. make every dist file readable by other users (13-02) * * Steps 5 and 6 are skipped for `REMOVE_REGISTRATION`, `PURGE_OWNED_RESOURCES` * and `null`: those modes never run an active worker build. + * `REMOVE_REGISTRATION` still ships a `service-worker.js` so the browser's + * update check can replace a worker that stops the page from booting (D-5). * * Step 4 has to follow the Vite build. Vite copies `public/` verbatim, so * without it every build — including a production one — ships the local * runtime document. The Service Worker asset scan excludes `config.json` * (`scripts/generate-service-worker-assets.ts`), so the order against step 5 - * is not what keeps the profile out of the worker cache (13-15). + * is not what keeps the profile out of the worker cache (13-15). Step 6 reads + * the release manifest URL from the `dist/config.json` step 4 wrote, and fails + * if its `APP_ENV` is not `APP_PROFILE` (06-10). */ const selection = INSTALLED_RUNTIME_CAPABILITIES.serviceWorker; @@ -62,13 +69,19 @@ if (buildsActiveWorker) { run("node", ["scripts/generate-service-worker-assets.ts", "dist"]); // 6. service worker build run("npx", ["vite", "build", "--config", "vite.service-worker.config.ts"]); +} else if (selection?.mode === "REMOVE_REGISTRATION") { + // 6. self-unregistering worker in place of the active one + await writeFile( + `dist/${SERVICE_WORKER_SCRIPT_PATH}`, + SELF_UNREGISTERING_SERVICE_WORKER, + ); } else { process.stdout.write( `service worker mode ${selection?.mode ?? "null"}: skipping worker build\n`, ); } -// 6. release + build manifest +// 7. release + build manifest run("node", ["scripts/generate-build-manifest.ts"]); // 8. publishable permissions: the validated writer creates 0600 files diff --git a/scripts/check-diagnostics.ts b/scripts/check-diagnostics.ts index 62a1ac29..8c535246 100644 --- a/scripts/check-diagnostics.ts +++ b/scripts/check-diagnostics.ts @@ -33,6 +33,7 @@ const telemetryProducerFiles: Readonly> = { "api.request.failed": "src/adapters/http/client.ts", "ui.render.failed": "src/application/create-application.ts", "release.mismatch.detected": "src/application/create-application.ts", + "service-worker.start.failed": "src/bootstrap/optional-runtime-host.ts", "telemetry.delivery.dropped": "src/adapters/telemetry/best-effort-telemetry.ts", }; diff --git a/scripts/lib/hosting-probe.ts b/scripts/lib/hosting-probe.ts index 4aa752f7..4122d1b6 100644 --- a/scripts/lib/hosting-probe.ts +++ b/scripts/lib/hosting-probe.ts @@ -32,7 +32,8 @@ const PUBLIC_SERVICE_WORKER = /(?:^|\/)(?:service-worker|sw)(?:[.-][^/]*)?\.js$/ /** * A built `dist` may ship a worker script only when the static selection is - * `ACTIVE`, and then only the selected script at the app root. + * `ACTIVE` or `REMOVE_REGISTRATION` (the self-unregistering worker, 06-03), and + * then only the selected script at the app root. */ export function checkPublicServiceWorkers( distFiles: readonly string[], @@ -40,7 +41,9 @@ export function checkPublicServiceWorkers( ) { const found = distFiles.filter((file) => PUBLIC_SERVICE_WORKER.test(file)); const allowed: string[] = - selection?.mode === "ACTIVE" ? [selection.scriptPath] : []; + selection?.mode === "ACTIVE" || selection?.mode === "REMOVE_REGISTRATION" + ? [selection.scriptPath] + : []; const passed = found.length === allowed.length && found.every((file) => allowed.includes(file)); diff --git a/scripts/lib/self-unregistering-service-worker.ts b/scripts/lib/self-unregistering-service-worker.ts new file mode 100644 index 00000000..f223a505 --- /dev/null +++ b/scripts/lib/self-unregistering-service-worker.ts @@ -0,0 +1,17 @@ +/** + * 06-03 (D-5). The emergency exit for a worker that stops the page from + * booting. A `REMOVE_REGISTRATION` release writes this as `service-worker.js`. + * The browser's own update check (navigation, `updateViaCache: "none"`) then + * installs it over any worker of this scope without a page: it skips waiting, + * and on activation unregisters the registration. It has no fetch handler, so + * every request goes to the network. Owned caches stay for the + * `PURGE_OWNED_RESOURCES` release, as with the page-side removal. + */ +export const SELF_UNREGISTERING_SERVICE_WORKER = `// Generated by scripts/build-frontend.ts (REMOVE_REGISTRATION). +self.addEventListener("install", (event) => { + event.waitUntil(self.skipWaiting()); +}); +self.addEventListener("activate", (event) => { + event.waitUntil(self.registration.unregister()); +}); +`; diff --git a/scripts/lib/service-worker-build-input.ts b/scripts/lib/service-worker-build-input.ts index 2315f317..65db5023 100644 --- a/scripts/lib/service-worker-build-input.ts +++ b/scripts/lib/service-worker-build-input.ts @@ -29,7 +29,10 @@ export function resolveServiceWorkerBuildInput(input: Readonly<{ selection: InstalledServiceWorkerSelection | null; assets: unknown; contractSet: unknown; + /** `dist/config.json`, materialized from the build's profile (06-10). */ runtimeConfig: unknown; + /** The build's `APP_PROFILE`; the runtime document must be for it. */ + appProfile: string; buildId: string; releaseId: string; }>): ServiceWorkerBuildInput { @@ -70,7 +73,14 @@ export function resolveServiceWorkerBuildInput(input: Readonly<{ throw new TypeError("Generated contract set digest is invalid."); } const runtimeConfig = record(input.runtimeConfig); - const releaseManifestUrl = runtimeConfig?.RELEASE_MANIFEST_URL; + // 06-10 / F-8. `public/config.json` is the local profile; a worker built from + // it for another profile would carry that profile's URLs. + if (runtimeConfig?.APP_ENV !== input.appProfile) { + throw new TypeError( + `Service Worker runtime config APP_ENV ${String(runtimeConfig?.APP_ENV)} does not match APP_PROFILE ${input.appProfile}.`, + ); + } + const releaseManifestUrl = runtimeConfig.RELEASE_MANIFEST_URL; if ( typeof releaseManifestUrl !== "string" || releaseManifestUrl.length === 0 || diff --git a/src/adapters/service-worker/service-worker-lifecycle.ts b/src/adapters/service-worker/service-worker-lifecycle.ts index 7b633be9..61ece109 100644 --- a/src/adapters/service-worker/service-worker-lifecycle.ts +++ b/src/adapters/service-worker/service-worker-lifecycle.ts @@ -119,10 +119,12 @@ export function createServiceWorkerRuntime( ), ); const consumedNonces = new Set(); + /** 06-07. Why a drain ended, so the requester is told the real reason. */ + type DrainOutcome = "DRAINED" | "REJECTED" | "TIMED_OUT"; type PendingActivation = Readonly<{ expectedClientIds: ReadonlySet; acknowledgedClientIds: Set; - resolve(drained: boolean): void; + resolve(outcome: DrainOutcome): void; timer: ReturnType; }>; const pendingActivations = new Map(); @@ -263,7 +265,8 @@ export function createServiceWorkerRuntime( /** * 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; + * content-hashed URL under the build asset directory (an old build's chunk, + * 06-08) is answered; * navigations, API calls, cross-origin and unhashed URLs are left alone. */ function intercepts(request: FetchRequest): boolean { @@ -346,8 +349,12 @@ export function createServiceWorkerRuntime( isClientWithinRegistrationScope(client.url, scope.registrationScope), ); const drained = await drainClients(clients, nonce); - if (!drained) { - notifyClients(clients, "ACTIVATE_REJECTED", nonce); + if (drained !== "DRAINED") { + notifyClients( + clients, + drained === "REJECTED" ? "ACTIVATE_REJECTED" : "ACTIVATE_DRAIN_TIMEOUT", + nonce, + ); return "REJECTED"; } @@ -357,7 +364,7 @@ export function createServiceWorkerRuntime( try { await scope.skipWaiting(); } catch { - notifyClients(clients, "ACTIVATE_REJECTED", nonce); + notifyClients(clients, "ACTIVATE_COMMIT_FAILED", nonce); return "REJECTED"; } // Post-commit notifications are per-client best effort. @@ -375,7 +382,12 @@ export function createServiceWorkerRuntime( */ function notifyClients( clients: readonly WorkerClientLike[], - kind: "ACTIVATE_REJECTED" | "ACTIVATE_ACCEPTED" | "ACTIVATED_RELOAD_REQUIRED", + kind: + | "ACTIVATE_REJECTED" + | "ACTIVATE_DRAIN_TIMEOUT" + | "ACTIVATE_COMMIT_FAILED" + | "ACTIVATE_ACCEPTED" + | "ACTIVATED_RELOAD_REQUIRED", nonce: string, ): void { for (const client of clients) { @@ -396,14 +408,14 @@ export function createServiceWorkerRuntime( async function drainClients( clients: readonly WorkerClientLike[], nonce: string, - ): Promise { + ): Promise { // SW-07. No in-scope client means nothing dirty to drain, so the set is // vacuously drained. A `clients.matchAll()` failure still rejects upstream. - if (clients.length === 0) return true; - const drained = new Promise((resolve) => { + if (clients.length === 0) return "DRAINED"; + const drained = new Promise((resolve) => { const timer = setTimeout(() => { pendingActivations.delete(nonce); - resolve(false); + resolve("TIMED_OUT"); }, SERVICE_WORKER_BOUNDS.clientDrainMs); pendingActivations.set( nonce, @@ -417,7 +429,7 @@ export function createServiceWorkerRuntime( }); // SW-08. A client that cannot receive the drain request can never // acknowledge it, so it fails immediately instead of holding the pending - // state until the timeout. + // state until the timeout. Like a silent client it did not refuse (06-07). // R-6.2. Clients run whatever build they loaded, which is usually not the // requester's. The request is untargeted; replies are paired by this // worker's buildId, the nonce and the exact client id. @@ -432,7 +444,7 @@ export function createServiceWorkerRuntime( ); } catch { const pending = pendingActivations.get(nonce); - if (pending) settlePendingActivation(nonce, pending, false); + if (pending) settlePendingActivation(nonce, pending, "TIMED_OUT"); return await drained; } } @@ -454,14 +466,14 @@ export function createServiceWorkerRuntime( return; } if (parsed.message.kind === "ACTIVATE_REJECTED") { - settlePendingActivation(parsed.message.nonce, pending, false); + settlePendingActivation(parsed.message.nonce, pending, "REJECTED"); return; } pending.acknowledgedClientIds.add(sourceClientId); if ( pending.acknowledgedClientIds.size === pending.expectedClientIds.size ) { - settlePendingActivation(parsed.message.nonce, pending, true); + settlePendingActivation(parsed.message.nonce, pending, "DRAINED"); } } @@ -516,11 +528,11 @@ export function createServiceWorkerRuntime( function settlePendingActivation( nonce: string, pending: PendingActivation, - drained: boolean, + outcome: DrainOutcome, ): void { clearTimeout(pending.timer); pendingActivations.delete(nonce); - pending.resolve(drained); + pending.resolve(outcome); } } diff --git a/src/adapters/service-worker/service-worker-page-controller.ts b/src/adapters/service-worker/service-worker-page-controller.ts index 5f33b034..c9c5f1e1 100644 --- a/src/adapters/service-worker/service-worker-page-controller.ts +++ b/src/adapters/service-worker/service-worker-page-controller.ts @@ -417,6 +417,8 @@ export function createServiceWorkerPageController( if ( parsed.message.nonce !== nonce || (kind !== "ACTIVATE_REJECTED" && + kind !== "ACTIVATE_DRAIN_TIMEOUT" && + kind !== "ACTIVATE_COMMIT_FAILED" && kind !== "ACTIVATE_ACCEPTED" && kind !== "ACTIVATED_RELOAD_REQUIRED") ) { @@ -438,7 +440,9 @@ export function createServiceWorkerPageController( } // R-6.1. ACCEPTED and RELOAD_REQUIRED are sent after skipWaiting(), // so the registration may already show this worker as active. - const committed = kind !== "ACTIVATE_REJECTED"; + const committed = + kind === "ACTIVATE_ACCEPTED" || + kind === "ACTIVATED_RELOAD_REQUIRED"; if ( registration?.waiting !== waiting && !(committed && registration?.active === waiting) @@ -446,10 +450,18 @@ export function createServiceWorkerPageController( finish(Object.freeze({ kind: "PROTOCOL_MISMATCH" as const })); return; } + // 06-07. Only a client's explicit refusal is a dirty client. finish( committed ? Object.freeze({ kind: "ACTIVATED_RELOAD_REQUIRED" as const }) - : Object.freeze({ kind: "BLOCKED_DIRTY_CLIENT" as const }), + : kind === "ACTIVATE_DRAIN_TIMEOUT" + ? Object.freeze({ kind: "CLIENT_DRAIN_TIMEOUT" as const }) + : kind === "ACTIVATE_COMMIT_FAILED" + ? Object.freeze({ + kind: "FAILED" as const, + code: "ACTIVATION_COMMIT_FAILED", + }) + : Object.freeze({ kind: "BLOCKED_DIRTY_CLIENT" as const }), ); }; const onStop = () => diff --git a/src/adapters/service-worker/service-worker-protocol.ts b/src/adapters/service-worker/service-worker-protocol.ts index 74d86d03..45ebec3b 100644 --- a/src/adapters/service-worker/service-worker-protocol.ts +++ b/src/adapters/service-worker/service-worker-protocol.ts @@ -19,6 +19,8 @@ const MESSAGE_KINDS: ReadonlySet = new Set([ "ACTIVATE_REQUEST", "ACTIVATE_ACCEPTED", "ACTIVATE_REJECTED", + "ACTIVATE_DRAIN_TIMEOUT", + "ACTIVATE_COMMIT_FAILED", "CLIENT_DRAIN_REQUEST", "CLIENT_DRAINED", "ACTIVATED_RELOAD_REQUIRED", diff --git a/src/adapters/service-worker/service-worker-static-assets.ts b/src/adapters/service-worker/service-worker-static-assets.ts index 2a594a5a..d96eb4e0 100644 --- a/src/adapters/service-worker/service-worker-static-assets.ts +++ b/src/adapters/service-worker/service-worker-static-assets.ts @@ -20,9 +20,10 @@ export type FetchClassification = | "NETWORK_ONLY" | "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. + * Q-6.6-6b. A content-hashed URL under the build asset directory that 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"; @@ -57,11 +58,18 @@ export function classifyFetch(input: ClassificationInput): FetchClassification { return "NETWORK_PASSTHROUGH"; } +/** + * 06-08. Vite's default `build.assetsDir`, under the app base that is also the + * registration scope. A hashed-looking API or download name elsewhere is not an + * old build chunk and is left to the browser. + */ +const BUILD_ASSET_DIRECTORY = "assets/"; + function isSameOriginHashedAsset(requestUrl: string, scopeUrl: string): boolean { try { const request = new URL(requestUrl); return ( - request.origin === new URL(scopeUrl).origin && + request.href.startsWith(new URL(BUILD_ASSET_DIRECTORY, scopeUrl).href) && HASHED_STATIC_ASSET_NAME.test(request.pathname) ); } catch { diff --git a/src/adapters/web-push/inbound/notification-click-adapter.ts b/src/adapters/web-push/inbound/notification-click-adapter.ts index b49fe4d1..dba1d551 100644 --- a/src/adapters/web-push/inbound/notification-click-adapter.ts +++ b/src/adapters/web-push/inbound/notification-click-adapter.ts @@ -84,6 +84,11 @@ export function createNotificationClickAdapter(dependencies: Readonly<{ fenceStore: PushAssociationFenceStore; clients: WorkerClientsFacade; origin: string; + /** + * 06-09. Where a refused click opens: the registration scope, which is the + * router base path. Defaults to the origin root; must be same-origin. + */ + appRootUrl?: string; now?: () => number; handlerDeadlineMs?: number; scheduler?: TimeoutScheduler; @@ -104,6 +109,11 @@ export function createNotificationClickAdapter(dependencies: Readonly<{ throw new TypeError("Web Push click adapter configuration is invalid."); } const origin: string = parsedOrigin; + const parsedAppRootUrl = safeTarget(origin, dependencies.appRootUrl ?? "/"); + if (!parsedAppRootUrl) { + throw new TypeError("Web Push click adapter configuration is invalid."); + } + const appRootUrl: string = parsedAppRootUrl; return Object.freeze({ handle(event) { @@ -246,9 +256,10 @@ export function createNotificationClickAdapter(dependencies: Readonly<{ /** * 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. + * the app at its root (06-09: the router base path) 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, @@ -265,8 +276,7 @@ export function createNotificationClickAdapter(dependencies: Readonly<{ ) { return result; } - // `origin` is already a parsed origin, so this is its root URL. - await openWindowBounded(`${origin}/`, signal, effect).catch(() => { + await openWindowBounded(appRootUrl, signal, effect).catch(() => { // The native call threw: whether a window opened is unknown. }); return result; diff --git a/src/adapters/web-push/push-subscription-adapter.ts b/src/adapters/web-push/push-subscription-adapter.ts index 418c2297..88ab8506 100644 --- a/src/adapters/web-push/push-subscription-adapter.ts +++ b/src/adapters/web-push/push-subscription-adapter.ts @@ -88,6 +88,13 @@ export function createWebPushSubscriptionAdapter( backendOperationDeadlineMs?: number; scheduler?: TimeoutScheduler; observer?: WebPushObserver; + /** + * 06-02 (D-4). The composition passes `navigator.locks`. Every tab shares + * one native subscription and one origin fence, so enable, reconcile and + * revoke run under the origin-wide `web-push-control` lock. Without Web + * Locks the adapter reports `PUSH_UNSUPPORTED`. + */ + lockManager?: Pick; }>, ): WebPushControlPort { const decodedVapidPublicKey = decodeVapidPublicKey( @@ -119,6 +126,11 @@ export function createWebPushSubscriptionAdapter( } const idempotencyKeyFactory = dependencies.idempotencyKeyFactory ?? (() => globalThis.crypto.randomUUID()); + const lockManager = dependencies.lockManager; + const requestLock = + typeof lockManager?.request === "function" + ? lockManager.request.bind(lockManager) + : null; let closed = false; let busy = false; let lifecycleGeneration = 0; @@ -131,33 +143,8 @@ export function createWebPushSubscriptionAdapter( return exclusive( "SUBSCRIPTION_INSPECT", input.signal, - async (generation, operationSignal) => { - const supported = supportReadiness(); - if (supported) return webPushSuccess(supported); - const permission = permissionReadiness(); - if (permission) return webPushSuccess(permission); - const native = await getSubscription(operationSignal, generation); - if (!native.ok) return native; - if (!native.value) { - return webPushSuccess( - unavailable("NATIVE_SUBSCRIPTION_MISSING"), - ); - } - if (!subscriptionUsesKey(native.value, vapidPublicKey)) { - return webPushSuccess( - unavailable("SUBSCRIPTION_KEY_MISMATCH"), - ); - } - const control = await dependencies.fenceStore.read({ - signal: operationSignal, - }); - if (!control.ok) return control; - return webPushSuccess( - isActiveFor(control.value?.control ?? null, input.authority) - ? readiness("PUSH_READY") - : unavailable("SESSION_AUTHORITY_CHANGED"), - ); - }, + (generation, operationSignal) => + inspectReadiness(input.authority, generation, operationSignal), ); }, @@ -383,6 +370,7 @@ export function createWebPushSubscriptionAdapter( commit: reconciled.value, signal: operationSignal, generation, + created: false, }); }, ); @@ -408,62 +396,54 @@ export function createWebPushSubscriptionAdapter( ) { return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE")); } - const capturedNative = await captureNativeForCleanup( + return await revokeReceipt( + current.value, + input.previousAuthority, + input.nextAuthority, + generation, operationSignal, - generation, ); - const previousAssociation = - current.value.control.association.state === "UNASSOCIATED" - ? null - : current.value.control.association.associationEpoch; - const fenced = await dependencies.fenceStore.rotateAndRevoke({ - expectedRevision: current.value.revision, - previousAuthority: input.previousAuthority, - nextAuthority: input.nextAuthority, - updatedAt: instantNow(), - signal: operationSignal, - }); - if (!fenced.ok) { - if (previousAssociation) { - await boundedBackendRevoke(previousAssociation); - } - return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE")); - } + }, + ); + }, - let revokeAmbiguous = false; - if (previousAssociation) { - const backend = await boundedBackendRevoke( - previousAssociation, + revokeForeign(input) { + return exclusive( + "SUBSCRIPTION_REVOKE", + input.signal, + async (generation, operationSignal) => { + const current = await dependencies.fenceStore.read({ + signal: operationSignal, + }); + if (!current.ok) { + return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE")); + } + // 06-06. Only another session generation's fence is foreign. The + // next authority's own fence (another tab of the same session opted + // in, or a new release of it) keeps its association. + if ( + !current.value || + current.value.control.fenceGeneration === + input.nextAuthority.fenceGeneration + ) { + return await inspectReadiness( + input.nextAuthority, + generation, + operationSignal, + ); + } + const stored = current.value.control; + return await revokeReceipt( + current.value, + Object.freeze({ + fenceGeneration: stored.fenceGeneration, + sessionBindingEpoch: stored.sessionBindingEpoch, + releaseEpoch: stored.releaseEpoch, + }), + input.nextAuthority, + generation, + operationSignal, ); - revokeAmbiguous = !backend.ok; - } - const nativeClean = await cleanupNative( - previousAssociation, - generation, - capturedNative, - fenced.value, - ); - observeWebPush(dependencies.observer, { - event: "web_push_association_revoked", - outcome: - revokeAmbiguous || !nativeClean ? "DEGRADED" : "SUCCEEDED", - ...(revokeAmbiguous - ? { reason: "BACKEND_REVOKE_AMBIGUOUS" } - : !nativeClean - ? { reason: "NATIVE_UNSUBSCRIBE_AMBIGUOUS" } - : {}), - }); - if (revokeAmbiguous) { - return webPushSuccess( - unavailable("BACKEND_REVOKE_AMBIGUOUS"), - ); - } - if (!nativeClean) { - return webPushSuccess( - unavailable("NATIVE_UNSUBSCRIBE_AMBIGUOUS"), - ); - } - return webPushSuccess(unavailable("REVOKED")); }, ); }, @@ -507,15 +487,22 @@ export function createWebPushSubscriptionAdapter( const generation = lifecycleGeneration; const operation = createLinkedAbortController(signal); inFlight.add(operation); + const run = () => task(generation, operation.signal); try { try { - return await task(generation, operation.signal); + // 06-02 (D-4). Inspection only reads; mutations wait for other tabs. + return failureOperation === "SUBSCRIPTION_INSPECT" || !requestLock + ? await run() + : await requestLock( + WEB_PUSH_CONTROL_LOCK, + { signal: operation.signal }, + run, + ); } catch { - return webPushFailure( - "NATIVE_FAILURE", - failureOperation, - true, - ); + // An abort while waiting for the lock rejects the request. + return operation.signal.aborted + ? webPushFailure("ABORTED", failureOperation) + : webPushFailure("NATIVE_FAILURE", failureOperation, true); } } finally { operation.dispose(); @@ -524,8 +511,99 @@ export function createWebPushSubscriptionAdapter( } } + async function inspectReadiness( + authority: PushAuthoritySnapshot, + generation: number, + operationSignal: AbortSignal, + ): Promise> { + const supported = supportReadiness(); + if (supported) return webPushSuccess(supported); + const permission = permissionReadiness(); + if (permission) return webPushSuccess(permission); + const native = await getSubscription(operationSignal, generation); + if (!native.ok) return native; + if (!native.value) { + return webPushSuccess(unavailable("NATIVE_SUBSCRIPTION_MISSING")); + } + if (!subscriptionUsesKey(native.value, vapidPublicKey)) { + return webPushSuccess(unavailable("SUBSCRIPTION_KEY_MISMATCH")); + } + const control = await dependencies.fenceStore.read({ + signal: operationSignal, + }); + if (!control.ok) return control; + return webPushSuccess( + isActiveFor(control.value?.control ?? null, authority) + ? readiness("PUSH_READY") + : unavailable("SESSION_AUTHORITY_CHANGED"), + ); + } + + /** + * Logout order: rotate the fence to REVOKED first, then revoke the captured + * association, unsubscribe the captured native subscription and close its + * notifications. + */ + async function revokeReceipt( + current: PushControlReceipt, + previousAuthority: PushAuthoritySnapshot, + nextAuthority: PushAuthoritySnapshot, + generation: number, + operationSignal: AbortSignal, + ): Promise> { + const capturedNative = await captureNativeForCleanup( + operationSignal, + generation, + ); + const previousAssociation = + current.control.association.state === "UNASSOCIATED" + ? null + : current.control.association.associationEpoch; + const fenced = await dependencies.fenceStore.rotateAndRevoke({ + expectedRevision: current.revision, + previousAuthority, + nextAuthority, + updatedAt: instantNow(), + signal: operationSignal, + }); + if (!fenced.ok) { + if (previousAssociation) { + await boundedBackendRevoke(previousAssociation); + } + return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE")); + } + + let revokeAmbiguous = false; + if (previousAssociation) { + const backend = await boundedBackendRevoke(previousAssociation); + revokeAmbiguous = !backend.ok; + } + const nativeClean = await cleanupNative( + previousAssociation, + generation, + capturedNative, + fenced.value, + ); + observeWebPush(dependencies.observer, { + event: "web_push_association_revoked", + outcome: revokeAmbiguous || !nativeClean ? "DEGRADED" : "SUCCEEDED", + ...(revokeAmbiguous + ? { reason: "BACKEND_REVOKE_AMBIGUOUS" } + : !nativeClean + ? { reason: "NATIVE_UNSUBSCRIBE_AMBIGUOUS" } + : {}), + }); + if (revokeAmbiguous) { + return webPushSuccess(unavailable("BACKEND_REVOKE_AMBIGUOUS")); + } + if (!nativeClean) { + return webPushSuccess(unavailable("NATIVE_UNSUBSCRIBE_AMBIGUOUS")); + } + return webPushSuccess(unavailable("REVOKED")); + } + function supportReadiness(): WebPushReadiness | null { - if (!dependencies.secureContext) { + if (!dependencies.secureContext || !requestLock) { return readiness("PUSH_UNSUPPORTED"); } if (!dependencies.registration.active) { @@ -703,6 +781,7 @@ export function createWebPushSubscriptionAdapter( commit: registered.value, signal: input.signal, generation: input.generation, + created: input.created, }); } @@ -713,13 +792,17 @@ export function createWebPushSubscriptionAdapter( commit: WebPushRegistrationCommit; signal: AbortSignal | undefined; generation: number; + created: boolean; }>): Promise> { + // 06-02 (D-4). A subscription this call did not create may carry another + // tab's association, so compensation leaves it in place. + const createdSubscription = input.created ? input.subscription : null; if ( input.commit.sessionBindingEpoch !== input.authority.sessionBindingEpoch || stale(input.signal, input.generation) ) { - await compensate(input.subscription, input.commit.associationEpoch); + await compensate(createdSubscription, input.commit.associationEpoch); return webPushSuccess( unavailable("SESSION_AUTHORITY_CHANGED"), ); @@ -732,21 +815,23 @@ export function createWebPushSubscriptionAdapter( signal: input.signal, }); if (!activated.ok) { - await compensate(input.subscription, input.commit.associationEpoch); + await compensate(createdSubscription, input.commit.associationEpoch); return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE")); } return webPushSuccess(readiness("PUSH_READY")); } async function compensate( - subscription: WindowPushSubscriptionFacade, + createdSubscription: WindowPushSubscriptionFacade | null, associationEpoch: string, ): Promise { await withAbortableDeadline( async (signal) => { await Promise.allSettled([ boundedBackendRevoke(associationEpoch, signal), - safeUnsubscribe(subscription), + createdSubscription + ? safeUnsubscribe(createdSubscription) + : Promise.resolve(true), ]); return webPushSuccess(undefined); }, @@ -1007,6 +1092,9 @@ export function createWebPushSubscriptionAdapter( } } +/** 06-02 (D-4). Origin-wide Web Lock name shared by every tab. */ +const WEB_PUSH_CONTROL_LOCK = "web-push-control"; + function readiness( state: WebPushReadiness["state"], ): WebPushReadiness { diff --git a/src/adapters/web-push/service-worker-runtime.ts b/src/adapters/web-push/service-worker-runtime.ts index 4182c241..ffafb6e1 100644 --- a/src/adapters/web-push/service-worker-runtime.ts +++ b/src/adapters/web-push/service-worker-runtime.ts @@ -60,6 +60,8 @@ type ServiceWorkerClientsFacade = Readonly<{ */ export type ServiceWorkerEventHost = Readonly<{ origin: string; + /** 06-09. `registration.scope`, the app root a refused click opens. */ + scope?: string; registration: ServiceWorkerRegistrationFacade; clients: ServiceWorkerClientsFacade; addEventListener(type: string, listener: (event: unknown) => void): void; @@ -118,6 +120,9 @@ export function createWebPushServiceWorkerRuntime( }, }, origin: dependencies.host.origin, + ...(dependencies.host.scope === undefined + ? {} + : { appRootUrl: dependencies.host.scope }), now: dependencies.now, scheduler: dependencies.scheduler, observer: dependencies.observer, @@ -273,7 +278,9 @@ function notificationClickEventFacade( typeof value.waitUntil !== "function" || !isRecord(value.notification) || typeof value.notification.close !== "function" || - !Object.hasOwn(value.notification, "data") + // 06-01. `data` is a WebIDL getter on `Notification.prototype`, never an + // own property, so the check must follow the prototype chain. + !("data" in value.notification) ) { return null; } diff --git a/src/adapters/web-push/service-worker-scope-host.ts b/src/adapters/web-push/service-worker-scope-host.ts index dda28aac..4b12343c 100644 --- a/src/adapters/web-push/service-worker-scope-host.ts +++ b/src/adapters/web-push/service-worker-scope-host.ts @@ -19,6 +19,7 @@ type MatchAllOptions = Parameters< export type NativeWorkerScope = Readonly<{ location: Readonly<{ origin: string }>; registration: Readonly<{ + scope: string; showNotification(title: string, options: unknown): Promise; }>; clients: Readonly<{ @@ -36,6 +37,7 @@ export function createServiceWorkerScopeHost( ): ServiceWorkerEventHost { return Object.freeze({ origin: scope.location.origin, + scope: scope.registration.scope, registration: Object.freeze({ showNotification: (title: string, options: NotificationOptions) => scope.registration.showNotification(title, { diff --git a/src/application/ports/out/web-push-control.ts b/src/application/ports/out/web-push-control.ts index bd27b8f0..fe80fbb3 100644 --- a/src/application/ports/out/web-push-control.ts +++ b/src/application/ports/out/web-push-control.ts @@ -26,6 +26,21 @@ export interface WebPushControlPort { signal?: AbortSignal; }>): Promise>; + /** + * 06-06. The session changed without `revoke` (expiry, cleared cookies, a + * crash during logout), so the caller cannot name the stored authority. A + * fence held by another `fenceGeneration` is rotated to `nextAuthority` as + * REVOKED and the association it held is revoked, as `revoke` does. A fence + * `nextAuthority`'s generation already holds is left alone and reported as + * `inspect` reports it. Call it only with the authority the BFF has just + * confirmed for the current session: a tab holding a stale session would + * otherwise revoke the current account's association. + */ + revokeForeign(input: Readonly<{ + nextAuthority: PushAuthoritySnapshot; + signal?: AbortSignal; + }>): Promise>; + dispose(): void; } diff --git a/src/bootstrap/create-runtime-composition.ts b/src/bootstrap/create-runtime-composition.ts index 8d1b712a..9240c6b3 100644 --- a/src/bootstrap/create-runtime-composition.ts +++ b/src/bootstrap/create-runtime-composition.ts @@ -1,5 +1,6 @@ import { resolveRuntimeCapabilities } from "../contracts/runtime-capabilities.ts"; import { INSTALLED_RUNTIME_CAPABILITIES } from "../features/installed-runtime-capabilities.ts"; +import type { TelemetryPort } from "../application/ports/telemetry-port.ts"; import { createCompositionRoot } from "./composition-root.ts"; import { loadReleaseManifest } from "./load-release-manifest.ts"; import { loadRuntimeConfig } from "./load-runtime-config.ts"; @@ -23,17 +24,23 @@ export type RuntimeCompositionDependencies = Readonly<{ export async function createRuntimeComposition( dependencies: RuntimeCompositionDependencies = {}, ) { + // 06-05. The optional host reports a Service Worker that did not start + // through the same telemetry port as the application. + let telemetry: TelemetryPort | undefined; const root = await createCompositionRoot({ loadConfig: () => loadRuntimeConfig({ fetcher: dependencies.fetcher }), loadRelease: (runtime) => loadReleaseManifest(runtime, { fetcher: dependencies.fetcher }), - createAdapters: ({ config: runtime, release }) => - createRuntimeAdapters({ + createAdapters: async ({ config: runtime, release }) => { + const adapters = await createRuntimeAdapters({ runtime, release, fetcher: dependencies.fetcher, host: dependencies.host, - }), + }); + telemetry = adapters.outputPorts.telemetry; + return adapters; + }, }); const capabilities = resolveRuntimeCapabilities( @@ -44,6 +51,7 @@ export async function createRuntimeComposition( capabilities, routerBasePath: root.config.build.routerBasePath, buildId: root.release.buildId, + ...(telemetry ? { telemetry } : {}), ...(dependencies.host ? { host: dependencies.host as Parameters< diff --git a/src/bootstrap/optional-runtime-host.ts b/src/bootstrap/optional-runtime-host.ts index 2ace8938..916ac188 100644 --- a/src/bootstrap/optional-runtime-host.ts +++ b/src/bootstrap/optional-runtime-host.ts @@ -8,6 +8,7 @@ import type { RuntimeStopReason, } from "../contracts/runtime-capabilities.ts"; import type { ServiceWorkerRuntimeHost } from "../contracts/service-worker.ts"; +import type { TelemetryPort } from "../application/ports/telemetry-port.ts"; import { createServiceWorkerRuntimeHost } from "./register-service-worker.ts"; /** @@ -39,6 +40,8 @@ export type OptionalRuntimeHostInput = Readonly<{ host?: Parameters[0]["host"]; blockers?: readonly (() => boolean)[]; observe?: (observation: Readonly<{ event: string; outcome: string }>) => void; + /** 06-05. Receives `service-worker.start.failed`. */ + telemetry?: TelemetryPort; }>; export function createOptionalRuntimeHost( @@ -107,6 +110,13 @@ export function createOptionalRuntimeHost( : outcome.kind === "INCOMPATIBLE" ? "INCOMPATIBLE" : "DEGRADED"; + if (outcome.kind === "FAILED" || outcome.kind === "INCOMPATIBLE") { + input.telemetry?.emit("service-worker.start.failed", { + error_kind: + outcome.kind === "FAILED" ? outcome.code : outcome.kind, + build_id: input.buildId, + }); + } } } if (!stopRequested) started = true; diff --git a/src/contracts/service-worker.ts b/src/contracts/service-worker.ts index 51004f16..b0f1f62a 100644 --- a/src/contracts/service-worker.ts +++ b/src/contracts/service-worker.ts @@ -70,6 +70,12 @@ export type ServiceWorkerMessageKind = | "ACTIVATE_REQUEST" | "ACTIVATE_ACCEPTED" | "ACTIVATE_REJECTED" + /** + * 06-07. Worker replies that are not a client's refusal. A page of an older + * build does not know them and ends at its own CLIENT_DRAIN_TIMEOUT. + */ + | "ACTIVATE_DRAIN_TIMEOUT" + | "ACTIVATE_COMMIT_FAILED" | "CLIENT_DRAIN_REQUEST" | "CLIENT_DRAINED" | "ACTIVATED_RELOAD_REQUIRED" diff --git a/src/contracts/telemetry.ts b/src/contracts/telemetry.ts index ad8c90fc..6b2cfdcb 100644 --- a/src/contracts/telemetry.ts +++ b/src/contracts/telemetry.ts @@ -85,6 +85,13 @@ export const TELEMETRY_REGISTRY = Object.freeze({ "release tuple mismatch", ["build_id", "active_release_id", "mismatch_kind"], ), + // 06-05. An ACTIVE worker that did not start (install failure, ownership + // mismatch) is otherwise visible nowhere. + "service-worker.start.failed": event( + "service-worker.start.failed", + "Service Worker start ended FAILED or INCOMPATIBLE", + ["error_kind", "build_id"], + ), "telemetry.delivery.dropped": event( "telemetry.delivery.dropped", "queue or sink failure", diff --git a/tests/e2e/service-worker-recovery.spec.ts b/tests/e2e/service-worker-recovery.spec.ts new file mode 100644 index 00000000..57406d7c --- /dev/null +++ b/tests/e2e/service-worker-recovery.spec.ts @@ -0,0 +1,151 @@ +import path from "node:path"; + +import { expect, test, type Page } from "../support/browser/strict-browser-test.ts"; +import { + ACTIVE_SELECTION, + prepareServiceWorkerBuilds, + removeServiceWorkerBuilds, + replaceOnce, + startBuildServer, + type ServiceWorkerBuilds, +} from "./support/service-worker-builds.ts"; + +/** + * 06-03 (D-5). The emergency exit for a worker that stops the page from + * booting. Page code cannot help then: the page never runs. Build A is the + * ACTIVE worker with its fetch handler broken (every intercepted request is a + * network error, the entry script included). Build B is a + * `REMOVE_REGISTRATION` release, which ships the self-unregistering + * `service-worker.js` (`scripts/lib/self-unregistering-service-worker.ts`). + * The browser's update check alone replaces A with it, and the next load boots + * B from the network. + */ + +type Probe = typeof globalThis & { + __caServiceWorkerTest?: { events: string[] }; +}; + +let builds: ServiceWorkerBuilds | undefined; + +test.beforeAll(async () => { + test.setTimeout(180_000); + builds = await prepareServiceWorkerBuilds({ + async beforeBuild(name, root) { + if (name === "a") { + await replaceOnce( + path.join(root, "src/adapters/service-worker/service-worker-entry.ts"), + "runtime.onFetch(described).then((cached) => cached ?? fetch(request)),", + "Promise.resolve(Response.error()),", + ); + return; + } + await replaceOnce( + path.join(root, "src/features/installed-runtime-capabilities.ts"), + ACTIVE_SELECTION, + `const SERVICE_WORKER: InstalledServiceWorkerSelection | null = { + mode: "REMOVE_REGISTRATION", + scriptPath: "service-worker.js", +};`, + ); + }, + }); +}); + +test.afterAll(async () => { + await removeServiceWorkerBuilds(builds); +}); + +async function startOutcome(page: Page): Promise { + await page.waitForFunction( + () => + (globalThis as Probe).__caServiceWorkerTest?.events.some((event) => + event.startsWith("start:"), + ) === true, + undefined, + { timeout: 60_000 }, + ); + const event = await page.evaluate(() => + (globalThis as Probe).__caServiceWorkerTest!.events.find((entry) => + entry.startsWith("start:"), + )!, + ); + return JSON.parse(event.slice("start:".length)); +} + +test("a REMOVE_REGISTRATION release unregisters a worker that blocks boot", async ({ + browser, + browserName, +}) => { + // Same quarantine as service-worker-update.spec.ts. + // quarantine(owner=frontend-platform, defect=playwright-firefox-no-sw-control, expires=2027-03-31) + test.skip( + browserName === "firefox", + "Playwright Firefox pages are never controlled by a service worker.", + ); + if (!builds) throw new Error("Service Worker builds were not prepared."); + const server = await startBuildServer(builds.dist); + // The broken phase fails requests on purpose, so this test drives its own + // context instead of the strict `page` fixture and checks the recovered + // load for browser errors itself. + const context = await browser.newContext(); + try { + const page = await context.newPage(); + await page.goto(`${server.origin}/`); + expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" }); + await page.evaluate(async () => { + await navigator.serviceWorker.ready; + }); + + // Worker A controls the next load and fails the entry script. + await page.goto(`${server.origin}/`); + const blocked = await page.evaluate(async () => { + const entry = document.querySelector( + 'script[type="module"][src]', + ); + if (!entry) return "no entry script"; + try { + await fetch(entry.src); + return "loaded"; + } catch { + return navigator.serviceWorker.controller ? "blocked" : "uncontrolled"; + } + }); + expect(blocked).toBe("blocked"); + + // Release B. Only the browser's update check runs; no code of B does. + server.serve("b"); + await page.evaluate(async () => { + await (await navigator.serviceWorker.getRegistration())?.update(); + }); + await expect + .poll( + () => + page.evaluate( + async () => + (await navigator.serviceWorker.getRegistration()) === undefined, + ), + { timeout: 30_000 }, + ) + .toBe(true); + + const failures: string[] = []; + page.on("console", (message) => { + if (["error", "warning"].includes(message.type())) { + failures.push(`console:${message.type()}:${message.text()}`); + } + }); + page.on("pageerror", (error) => failures.push(`pageerror:${error.name}`)); + page.on("requestfailed", (request) => + failures.push(`requestfailed:${new URL(request.url()).pathname}`), + ); + await page.goto(`${server.origin}/`); + expect(await startOutcome(page)).toEqual({ kind: "DISABLED" }); + expect( + await page.evaluate(() => navigator.serviceWorker.controller === null), + ).toBe(true); + expect(failures).toEqual([]); + } finally { + await context.close(); + await server.close(); + } +}); diff --git a/tests/e2e/support/service-worker-builds.ts b/tests/e2e/support/service-worker-builds.ts index 8c07feae..9481cbb9 100644 --- a/tests/e2e/support/service-worker-builds.ts +++ b/tests/e2e/support/service-worker-builds.ts @@ -52,7 +52,7 @@ export type ServiceWorkerBuilds = Readonly<{ dist: Readonly>; }>; -const ACTIVE_SELECTION = `const SERVICE_WORKER: InstalledServiceWorkerSelection | null = { +export const ACTIVE_SELECTION = `const SERVICE_WORKER: InstalledServiceWorkerSelection | null = { mode: "ACTIVE", scriptPath: "service-worker.js", handlers: ["PWA_STATIC_ASSETS"], @@ -80,7 +80,7 @@ export function createServiceWorkerRuntimeHost( } `; -async function replaceOnce( +export async function replaceOnce( file: string, search: string, replacement: string, @@ -105,7 +105,16 @@ function run(cwd: string, script: string, buildId: string): void { } } -export async function prepareServiceWorkerBuilds(): Promise { +/** + * `beforeBuild` edits the temp copy right before build `name` (06-03: a + * broken worker A, then a `REMOVE_REGISTRATION` release B). Edits persist + * into the later build. + */ +export async function prepareServiceWorkerBuilds( + options: Readonly<{ + beforeBuild?: (name: BuildName, root: string) => Promise; + }> = {}, +): Promise { const root = await mkdtemp(path.join(tmpdir(), "ca-sw-builds-")); await cp(repoRoot, root, { recursive: true, @@ -128,6 +137,7 @@ export async function prepareServiceWorkerBuilds(): Promise const dist = { a: path.join(root, "dist-a"), b: path.join(root, "dist-b") }; for (const name of ["a", "b"] as const) { + await options.beforeBuild?.(name, root); run(root, "scripts/generate-product-feature-index.ts", `sw-e2e-${name}`); run(root, "scripts/build-frontend.ts", `sw-e2e-${name}`); await rename(path.join(root, "dist"), dist[name]); diff --git a/tests/unit/hosting-probe.test.ts b/tests/unit/hosting-probe.test.ts index df5668c1..5f796756 100644 --- a/tests/unit/hosting-probe.test.ts +++ b/tests/unit/hosting-probe.test.ts @@ -15,6 +15,7 @@ describe("public service worker in dist", () => { handlers: ["PWA_STATIC_ASSETS"], } as const; const removal = { mode: "REMOVE_REGISTRATION", scriptPath: "service-worker.js" } as const; + const purge = { mode: "PURGE_OWNED_RESOURCES", scriptPath: "service-worker.js" } as const; it("accepts the selected worker when the selection is ACTIVE", () => { expect( @@ -22,6 +23,13 @@ describe("public service worker in dist", () => { ).toMatchObject({ expected: true, observed: true, passed: true }); }); + // 06-03 (D-5). REMOVE_REGISTRATION ships the self-unregistering worker. + it("accepts the selected worker when the selection is REMOVE_REGISTRATION", () => { + expect( + checkPublicServiceWorkers([...app, "service-worker.js"], removal), + ).toMatchObject({ expected: true, observed: true, passed: true }); + }); + it("accepts a worker-free dist when no worker is selected", () => { expect(checkPublicServiceWorkers(app, null)).toMatchObject({ expected: false, @@ -31,7 +39,8 @@ describe("public service worker in dist", () => { it.each([ ["no selection", [...app, "service-worker.js"], null], - ["a non-ACTIVE selection", [...app, "service-worker.js"], removal], + ["a PURGE_OWNED_RESOURCES selection", [...app, "service-worker.js"], purge], + ["REMOVE_REGISTRATION without the worker", app, removal], ["ACTIVE without the worker", app, active], ["ACTIVE with an extra worker", [...app, "service-worker.js", "assets/sw.js"], active], ["ACTIVE with the worker off the root", [...app, "assets/service-worker.js"], active], diff --git a/tests/unit/optional-runtime-host.test.ts b/tests/unit/optional-runtime-host.test.ts index b6d5f4b2..7087c022 100644 --- a/tests/unit/optional-runtime-host.test.ts +++ b/tests/unit/optional-runtime-host.test.ts @@ -87,4 +87,62 @@ describe("optional runtime host", () => { expect(runtime.health().serviceWorker).toBe("DISABLED"); expect(runtime.browserLifecycle()).toBeNull(); }); + + // 06-05. An ACTIVE selection whose worker install fails must be visible to + // operators, not only in `health()`, which nothing reads. + it.each([ + { + outcome: { kind: "FAILED", code: "INSTALL_FAILED" } as const, + events: [ + [ + "service-worker.start.failed", + { error_kind: "INSTALL_FAILED", build_id: "build-1" }, + ], + ], + }, + { + outcome: { kind: "INCOMPATIBLE" } as const, + events: [ + [ + "service-worker.start.failed", + { error_kind: "INCOMPATIBLE", build_id: "build-1" }, + ], + ], + }, + { outcome: { kind: "ACTIVE", buildId: "build-1" } as const, events: [] }, + { outcome: { kind: "RELOAD_TO_ENABLE" } as const, events: [] }, + ])( + "records $outcome.kind as $events.length telemetry event(s)", + async ({ outcome, events }) => { + const emit = vi.fn(); + const runtime = createOptionalRuntimeHost({ + capabilities: { + ...capabilities, + serviceWorker: { + mode: "ACTIVE", + scriptPath: "service-worker.js", + handlers: ["PWA_STATIC_ASSETS"], + }, + }, + routerBasePath: "/", + buildId: "build-1", + serviceWorkerHost: { + start: vi.fn(async (): Promise => outcome), + requestActivation: vi.fn(), + resetOwnedCaches: vi.fn(), + stop: vi.fn(async () => {}), + }, + browserLifecycleHost: { + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + }, + telemetry: { emit }, + }); + + await runtime.startAfterMount(); + + expect(emit.mock.calls).toEqual(events); + await runtime.stop(); + }, + ); }); diff --git a/tests/unit/service-worker-build-input.test.ts b/tests/unit/service-worker-build-input.test.ts index 5900d451..1169ce42 100644 --- a/tests/unit/service-worker-build-input.test.ts +++ b/tests/unit/service-worker-build-input.test.ts @@ -1,7 +1,9 @@ import { createHash } from "node:crypto"; +import { runInNewContext } from "node:vm"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; +import { SELF_UNREGISTERING_SERVICE_WORKER } from "../../scripts/lib/self-unregistering-service-worker.ts"; import { resolveServiceWorkerBuildInput } from "../../scripts/lib/service-worker-build-input.ts"; import { canonicalStaticManifestBytes, @@ -26,6 +28,12 @@ const ASSET_ROWS: readonly StaticAssetRow[] = Object.freeze([ }), ]); +/** The shape `scripts/generate-runtime-config.ts` writes to `dist/config.json`. */ +const LOCAL_RUNTIME_CONFIG = Object.freeze({ + APP_ENV: "local", + RELEASE_MANIFEST_URL: "/release-manifest.json", +}); + describe("service worker build input", () => { const selection = { mode: "ACTIVE" as const, @@ -46,7 +54,8 @@ describe("service worker build input", () => { selection: null, assets, contractSet: { setDigest: digest("b") }, - runtimeConfig: { RELEASE_MANIFEST_URL: "/release-manifest.json" }, + runtimeConfig: LOCAL_RUNTIME_CONFIG, + appProfile: "local", buildId: "build-1", releaseId: "release-1", }), @@ -56,7 +65,8 @@ describe("service worker build input", () => { selection, assets: null, contractSet: { setDigest: digest("b") }, - runtimeConfig: { RELEASE_MANIFEST_URL: "/release-manifest.json" }, + runtimeConfig: LOCAL_RUNTIME_CONFIG, + appProfile: "local", buildId: "build-1", releaseId: "release-1", }), @@ -69,7 +79,8 @@ describe("service worker build input", () => { selection, assets: { ...assets, buildId: "old-build" }, contractSet: { setDigest: digest("b") }, - runtimeConfig: { RELEASE_MANIFEST_URL: "/release-manifest.json" }, + runtimeConfig: LOCAL_RUNTIME_CONFIG, + appProfile: "local", buildId: "build-1", releaseId: "release-1", }), @@ -82,7 +93,8 @@ describe("service worker build input", () => { selection: { ...selection, handlers: ["WEB_PUSH"] }, assets, contractSet: { setDigest: digest("b") }, - runtimeConfig: { RELEASE_MANIFEST_URL: "/release-manifest.json" }, + runtimeConfig: LOCAL_RUNTIME_CONFIG, + appProfile: "local", buildId: "build-1", releaseId: "release-1", }), @@ -95,7 +107,8 @@ describe("service worker build input", () => { selection, assets, contractSet: { setDigest: digest("b") }, - runtimeConfig: { RELEASE_MANIFEST_URL: "/release-manifest.json" }, + runtimeConfig: LOCAL_RUNTIME_CONFIG, + appProfile: "local", buildId: "build-1", releaseId: "release-1", }), @@ -111,7 +124,8 @@ describe("service worker build input", () => { const base = { selection, contractSet: { setDigest: digest("b") }, - runtimeConfig: { RELEASE_MANIFEST_URL: "/release-manifest.json" }, + runtimeConfig: LOCAL_RUNTIME_CONFIG, + appProfile: "local", buildId: "build-1", releaseId: "release-1", }; @@ -180,16 +194,72 @@ describe("service worker build input", () => { } }); + // 06-10 / F-8. The worker build read `public/config.json`, the local + // profile, for every build. It now reads the profile document the build + // materialized, and a document for another profile fails the build. + it("rejects a runtime document for a profile other than the build's", () => { + const build = (appProfile: string) => + resolveServiceWorkerBuildInput({ + selection, + assets, + contractSet: { setDigest: digest("b") }, + runtimeConfig: LOCAL_RUNTIME_CONFIG, + appProfile, + buildId: "build-1", + releaseId: "release-1", + }); + + expect(() => build("production")).toThrow( + /APP_ENV local does not match APP_PROFILE production/u, + ); + expect(build("local").releaseManifestUrl).toBe("/release-manifest.json"); + }); + it("accepts generator-shaped output unchanged", () => { expect(() => resolveServiceWorkerBuildInput({ selection, assets, contractSet: { setDigest: digest("b") }, - runtimeConfig: { RELEASE_MANIFEST_URL: "/release-manifest.json" }, + runtimeConfig: LOCAL_RUNTIME_CONFIG, + appProfile: "local", buildId: "build-1", releaseId: "release-1", }), ).not.toThrow(); }); }); + +/** + * 06-03 (D-5). A REMOVE_REGISTRATION release ships this as + * `service-worker.js`, so a browser update check replaces even a worker that + * stops the page from booting. The context has no `caches` and no `fetch`: a + * reference to either throws. + */ +describe("self-unregistering service worker", () => { + it("takes over at once, unregisters itself and handles no fetch", async () => { + const listeners = new Map void>(); + const skipWaiting = vi.fn(async () => {}); + const unregister = vi.fn(async () => true); + runInNewContext(SELF_UNREGISTERING_SERVICE_WORKER, { + self: { + addEventListener(type: string, listener: (event: unknown) => void) { + listeners.set(type, listener); + }, + skipWaiting, + registration: { unregister }, + }, + }); + expect([...listeners.keys()].sort()).toEqual(["activate", "install"]); + + const pending: Promise[] = []; + const event = { waitUntil: (task: Promise) => pending.push(task) }; + listeners.get("install")!(event); + expect(skipWaiting).toHaveBeenCalledOnce(); + expect(unregister).not.toHaveBeenCalled(); + listeners.get("activate")!(event); + await Promise.all(pending); + expect(pending).toHaveLength(2); + expect(unregister).toHaveBeenCalledOnce(); + }); +}); diff --git a/tests/unit/service-worker-runtime.test.ts b/tests/unit/service-worker-runtime.test.ts index d0158758..64cb3fd5 100644 --- a/tests/unit/service-worker-runtime.test.ts +++ b/tests/unit/service-worker-runtime.test.ts @@ -3,8 +3,12 @@ import { describe, expect, it, vi } from "vitest"; import { createServiceWorkerPageController } from "../../src/adapters/service-worker/service-worker-page-controller.ts"; 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 { + classifyFetch, + installStaticAssets, +} from "../../src/adapters/service-worker/service-worker-static-assets.ts"; import { createServiceWorkerRuntimeHost } from "../../src/bootstrap/register-service-worker.ts"; +import { resolveRuntimeCapabilities } from "../../src/contracts/runtime-capabilities.ts"; import { SERVICE_WORKER_BOUNDS, SERVICE_WORKER_SCRIPT_PATH, @@ -292,8 +296,9 @@ describe("service worker static cache authority", () => { 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"; + // manifest (and so the current cache) no longer has. The fixture scope is + // `/app/`, so the build's asset directory is `/app/assets/` (06-08). + const oldChunk = "/app/assets/settings-page-Zz9Yy8Xx.js"; const fixture = previousReleaseCaches(oldChunk); const runtime = staticRuntime(fixture.caches, "/assets/app-Dq3x8Yk2.js"); @@ -459,6 +464,73 @@ describe("service worker exact ownership and truthful removal", () => { expect(foreign.unregister).not.toHaveBeenCalled(); }); + // 06-04. The runtime kill switch: `CAPABILITY_OVERRIDES.SERVICE_WORKER = + // "DISABLED"` over a static ACTIVE worker unregisters the owned registration + // without registering anything. + it("resolves runtime DISABLED over a static ACTIVE worker to disabled cleanup", () => { + expect( + resolveRuntimeCapabilities( + { + realtime: [], + webWorkers: [], + serviceWorker: { + mode: "ACTIVE", + scriptPath: SERVICE_WORKER_SCRIPT_PATH, + handlers: [], + }, + offlineCommands: null, + }, + { + REALTIME: "DEFAULT", + WEB_WORKER: "DEFAULT", + SERVICE_WORKER: "DISABLED", + OFFLINE_COMMANDS: "DEFAULT", + }, + ), + ).toMatchObject({ serviceWorker: null, serviceWorkerDisabledCleanup: true }); + }); + + it.each([ + { owner: "owned", scriptURL: SCRIPT_URL, unregisters: 1, expected: "DISABLED" }, + { + owner: "foreign", + scriptURL: `${ORIGIN}/someone-else.js`, + unregisters: 0, + expected: "INCOMPATIBLE", + }, + ])( + "runtime DISABLED unregisters only an $owner registration", + async ({ scriptURL, unregisters, expected }) => { + const registration = { + scope: `${ORIGIN}/`, + installing: null, + waiting: null, + active: { scriptURL }, + unregister: vi.fn(async () => true), + update: vi.fn(async () => {}), + } as unknown as ServiceWorkerRegistration; + const container = { + controller: null, + register: vi.fn(), + getRegistration: vi.fn(async () => registration), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + }; + const controller = createServiceWorkerPageController({ + selection: null, + disabledCleanup: true, + routerBasePath: "/", + origin: ORIGIN, + buildId: "page-build", + container: container as unknown as ServiceWorkerContainer, + }); + + await expect(controller.start()).resolves.toEqual({ kind: expected }); + expect(container.register).not.toHaveBeenCalled(); + expect(container.getRegistration).toHaveBeenCalledOnce(); + expect(registration.unregister).toHaveBeenCalledTimes(unregisters); + }, + ); }); describe("service worker page protocol", () => { @@ -1507,6 +1579,79 @@ describe("page ↔ worker activation seam", () => { vi.useRealTimers(); } }); + + // 06-07. A window without a page controller (a tab showing /config.json, a + // frozen background tab) never answers the drain. That is a timeout, not a + // tab with unsaved edits. + it("reports a window that never answers as CLIENT_DRAIN_TIMEOUT", async () => { + vi.useFakeTimers(); + try { + const seam = activationSeam(["page-build-n", "page-build-n1"]); + for (const tab of seam.tabs) await tab.controller.start(); + seam.workerScope.clients.matchAll.mockResolvedValue([ + ...seam.tabs.map((tab) => tab.client), + { id: "raw-json", url: `${ORIGIN}/config.json`, postMessage() {} }, + ]); + + const activation = seam.tabs[1]!.controller.requestActivation(); + await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.clientDrainMs); + + await expect(activation).resolves.toEqual({ + kind: "CLIENT_DRAIN_TIMEOUT", + }); + expect(seam.workerScope.skipWaiting).not.toHaveBeenCalled(); + for (const tab of seam.tabs) await tab.controller.stop(); + } finally { + vi.useRealTimers(); + } + }); + + it("reports a failed skipWaiting() as FAILED, not as a dirty tab", async () => { + vi.useFakeTimers(); + try { + const seam = activationSeam(["page-build-n", "page-build-n1"]); + for (const tab of seam.tabs) await tab.controller.start(); + seam.workerScope.skipWaiting.mockRejectedValue(new Error("commit")); + + const activation = seam.tabs[1]!.controller.requestActivation(); + await vi.advanceTimersByTimeAsync(0); + + await expect(activation).resolves.toEqual({ + kind: "FAILED", + code: "ACTIVATION_COMMIT_FAILED", + }); + for (const tab of seam.tabs) await tab.controller.stop(); + } finally { + vi.useRealTimers(); + } + }); + + it("still reports a tab that refuses the drain as BLOCKED_DIRTY_CLIENT", async () => { + vi.useFakeTimers(); + try { + const seam = activationSeam(["page-build-n", "page-build-n1"]); + for (const tab of seam.tabs) await tab.controller.start(); + // Tab 0 answers the drain with an explicit rejection (unsaved edits). + const dirtyTab = seam.tabs[0]!.waiting; + const deliver = dirtyTab.postMessage.bind(dirtyTab); + dirtyTab.postMessage = (message) => + deliver( + message.kind === "CLIENT_DRAINED" + ? { ...message, kind: "ACTIVATE_REJECTED" } + : message, + ); + + const activation = seam.tabs[1]!.controller.requestActivation(); + await vi.advanceTimersByTimeAsync(0); + + await expect(activation).resolves.toEqual({ + kind: "BLOCKED_DIRTY_CLIENT", + }); + for (const tab of seam.tabs) await tab.controller.stop(); + } finally { + vi.useRealTimers(); + } + }); }); /** @@ -1813,3 +1958,42 @@ describe("SW-01 the activation marker read is bounded in bytes", () => { expect(fixture.response.body?.locked).toBe(false); }); }); + +/** + * 06-08. The previous-release fallback is for old build chunks only. A hashed + * looking API or download name outside the build asset directory is left to + * the browser. + */ +describe("fetch classification of hashed-looking URLs", () => { + const classify = (path: string, scopeUrl = `${ORIGIN}/`) => + classifyFetch({ + method: "GET", + requestUrl: `${ORIGIN}${path}`, + isNavigation: false, + runtimeConfigUrl: `${ORIGIN}/config.json`, + releaseManifestUrl: `${ORIGIN}/release-manifest.json`, + manifestUrls: new Set(), + scopeUrl, + }); + + it.each([ + "/api/v1/user-profiles.json", + "/api/reports/monthly-summary2026.csv", + "/media/onboarding-video-final.mp4", + "/downloads/release-notes-20260925.pdf", + ])("passes %s through", (path) => { + expect(classify(path)).toBe("NETWORK_PASSTHROUGH"); + }); + + it("falls back only for a hashed name under the build asset directory", () => { + expect(classify("/assets/route-chunk-AbCd1234.js")).toBe( + "PREVIOUS_RELEASE_FALLBACK", + ); + expect(classify("/app/assets/route-chunk-AbCd1234.js", `${ORIGIN}/app/`)).toBe( + "PREVIOUS_RELEASE_FALLBACK", + ); + expect(classify("/assets/route-chunk-AbCd1234.js", `${ORIGIN}/app/`)).toBe( + "NETWORK_PASSTHROUGH", + ); + }); +}); diff --git a/tests/unit/web-push-subscription-adapter.test.ts b/tests/unit/web-push-subscription-adapter.test.ts index 1c01f76f..7d0541ad 100644 --- a/tests/unit/web-push-subscription-adapter.test.ts +++ b/tests/unit/web-push-subscription-adapter.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it, vi } from "vitest"; -import { WEB_PUSH_PROTOCOLS, webPushSuccess } from "../../src/contracts/web-push.ts"; +import { + WEB_PUSH_PROTOCOLS, + webPushSuccess, + type PushAuthoritySnapshot, +} from "../../src/contracts/web-push.ts"; import { createPushAssociationFenceStore } from "../../src/adapters/web-push/push-association-fence-store.ts"; import { createWebPushSubscriptionAdapter, @@ -153,6 +157,7 @@ describe("Web Push window subscription adapter", () => { fenceStore, gateway: gateway({ register }), vapidPublicKey, + lockManager: navigator.locks, now: () => now, idempotencyKeyFactory: () => "idempotency_01", }); @@ -207,6 +212,7 @@ describe("Web Push window subscription adapter", () => { fenceStore, gateway: gateway({ register }), vapidPublicKey, + lockManager: navigator.locks, now: () => now, }); @@ -224,7 +230,12 @@ describe("Web Push window subscription adapter", () => { expect(await fenceStore.read()).toEqual({ ok: true, value: null }); }); - it("compensates a stale backend session binding without activating local authority", async () => { + // 06-02 (D-4). Only a subscription this call created is unsubscribed; an + // existing one may belong to another tab's association. + it.each([ + { existing: true, unsubscribeCalls: 0 }, + { existing: false, unsubscribeCalls: 1 }, + ])("compensates a stale backend session binding without activating local authority (existing native: $existing)", async ({ existing, unsubscribeCalls }) => { const fenceStore = createPushAssociationFenceStore( createFakePushControlStoreDependencies(), ); @@ -241,7 +252,7 @@ describe("Web Push window subscription adapter", () => { registration: { active: true, pushManager: { - getSubscription: async () => native, + getSubscription: async () => (existing ? native : null), subscribe: async () => native, }, getNotifications: async () => [], @@ -256,6 +267,7 @@ describe("Web Push window subscription adapter", () => { revoke, }), vapidPublicKey, + lockManager: navigator.locks, now: () => now, idempotencyKeyFactory: () => "idempotency_01", }); @@ -276,7 +288,7 @@ describe("Web Push window subscription adapter", () => { associationEpoch: "association_stale", signal: expect.any(AbortSignal), }); - expect(unsubscribe).toHaveBeenCalledOnce(); + expect(unsubscribe).toHaveBeenCalledTimes(unsubscribeCalls); expect(await fenceStore.read()).toMatchObject({ ok: true, value: { @@ -346,6 +358,7 @@ describe("Web Push window subscription adapter", () => { fenceStore, gateway: gateway({ revoke }), vapidPublicKey, + lockManager: navigator.locks, now: () => now, }); @@ -417,6 +430,7 @@ describe("Web Push window subscription adapter", () => { fenceStore, gateway: gateway(), vapidPublicKey, + lockManager: navigator.locks, now: () => now, }); @@ -486,6 +500,7 @@ describe("Web Push window subscription adapter", () => { fenceStore, gateway: gateway({ revoke }), vapidPublicKey, + lockManager: navigator.locks, now: () => now, }); @@ -553,6 +568,7 @@ describe("Web Push window subscription adapter", () => { fenceStore, gateway: gateway({ revoke }), vapidPublicKey, + lockManager: navigator.locks, now: () => now, }); @@ -609,6 +625,7 @@ describe("Web Push window subscription adapter", () => { fenceStore, gateway: gateway({ revoke }), vapidPublicKey, + lockManager: navigator.locks, now: () => now, }); @@ -658,6 +675,7 @@ describe("Web Push window subscription adapter", () => { fenceStore, gateway: gateway(), vapidPublicKey, + lockManager: navigator.locks, nativeOperationDeadlineMs: 1, scheduler: clock.scheduler, }); @@ -694,6 +712,7 @@ describe("Web Push window subscription adapter", () => { fenceStore, gateway: gateway(), vapidPublicKey, + lockManager: navigator.locks, }); const inspection = adapter.inspect({ authority }); @@ -729,6 +748,7 @@ describe("Web Push window subscription adapter", () => { fenceStore, gateway: gateway(), vapidPublicKey, + lockManager: navigator.locks, }); for (let attempt = 0; attempt < 2; attempt += 1) { @@ -792,6 +812,7 @@ describe("Web Push window subscription adapter", () => { revoke, }), vapidPublicKey, + lockManager: navigator.locks, backendOperationDeadlineMs: 1, scheduler: clock.scheduler, idempotencyKeyFactory: () => "idempotency_01", @@ -862,6 +883,7 @@ describe("Web Push reconcile with a server ABSENT association (R-6.7)", () => { reconcile: async () => webPushSuccess({ state: "ABSENT" as const }), }), vapidPublicKey, + lockManager: navigator.locks, now: () => now, idempotencyKeyFactory: () => "idempotency_02", }); @@ -943,3 +965,342 @@ describe("Web Push reconcile with a server ABSENT association (R-6.7)", () => { }, ); }); + +/** + * 06-02 (D-4). The native subscription is one per service worker registration + * and the fence record one per origin, so every tab shares both. enable, + * reconcile and revoke hold the origin-wide `web-push-control` Web Lock + * (Node's `navigator.locks` here, shared by both adapters like two tabs), and + * a compensation unsubscribes only a subscription its own call created. + */ +describe("06-02 two tabs share one native subscription and one fence", () => { + function sharedTabs( + reconcileAnswer: ( + serverAssociation: string | null, + ) => Promise<"WAIT_FOR_REGISTER" | "NOW">, + lockManager: Pick | null = navigator.locks, + ) { + const dependencies = createFakePushControlStoreDependencies(); + const unsubscribe = vi.fn(async () => { + current = null; + return true; + }); + const native = subscription(unsubscribe); + let current: WindowPushSubscriptionFacade | null = null; + const server: { association: string | null } = { association: null }; + let releaseRegister!: () => void; + const registerGate = new Promise((resolve) => { + releaseRegister = resolve; + }); + let registerReached!: () => void; + const registerStarted = new Promise((resolve) => { + registerReached = resolve; + }); + const shared: WebPushRegistrationGateway = { + async register() { + registerReached(); + await registerGate; + server.association = "association_01"; + return webPushSuccess({ + associationEpoch: "association_01", + sessionBindingEpoch: "session_01", + }); + }, + async reconcile() { + if ((await reconcileAnswer(server.association)) === "WAIT_FOR_REGISTER") { + await registerGate; + } + return webPushSuccess( + server.association + ? { + state: "ACTIVE" as const, + associationEpoch: server.association, + sessionBindingEpoch: "session_01", + } + : { state: "ABSENT" as const }, + ); + }, + async revoke(input) { + if (server.association === input.associationEpoch) { + server.association = null; + } + return webPushSuccess({ state: "REVOKED" as const }); + }, + }; + function tab(activation: boolean) { + return createWebPushSubscriptionAdapter({ + secureContext: true, + userActivationIsActive: () => activation, + permission: { + permission: () => "granted", + requestPermission: async () => "granted", + }, + registration: { + active: true, + pushManager: { + getSubscription: async () => current, + subscribe: async () => { + current = native; + return native; + }, + }, + getNotifications: async () => [], + }, + fenceStore: createPushAssociationFenceStore(dependencies), + gateway: shared, + vapidPublicKey, + now: () => now, + ...(lockManager ? { lockManager } : {}), + }); + } + return { + tab, + server, + unsubscribe, + registerStarted, + releaseRegister: () => releaseRegister(), + nativeAlive: () => current === native, + fence: async () => + await createPushAssociationFenceStore(dependencies).read(), + }; + } + + async function raceEnableWithReconcile( + tabs: ReturnType, + ) { + const tab1 = tabs.tab(true); + const tab2 = tabs.tab(false); + const enabling = tab1.enable({ + authority, + signal: new AbortController().signal, + }); + // Tab 1 prepared the fence, subscribed and is waiting on register. + await tabs.registerStarted; + const reconciling = tab2.reconcile({ authority }); + await new Promise((resolve) => setTimeout(resolve, 0)); + tabs.releaseRegister(); + return await Promise.all([enabling, reconciling]); + } + + function expectReadyTabsStillReceive( + tabs: ReturnType, + results: readonly unknown[], + ) { + const ready = { ok: true, value: { state: "PUSH_READY" } }; + expect(results).toContainEqual(ready); + expect(tabs.unsubscribe).not.toHaveBeenCalled(); + expect(tabs.nativeAlive()).toBe(true); + expect(tabs.server.association).toBe("association_01"); + } + + it("keeps the shared state when the reconciling tab would win the fence CAS", async () => { + // Order 1: the server commits tab 1's register, tab 2 sees it first. + const tabs = sharedTabs(async () => "WAIT_FOR_REGISTER"); + const results = await raceEnableWithReconcile(tabs); + + expect(results).toEqual([ + { ok: true, value: { state: "PUSH_READY" } }, + { ok: true, value: { state: "PUSH_READY" } }, + ]); + expectReadyTabsStillReceive(tabs, results); + expect(await tabs.fence()).toMatchObject({ + ok: true, + value: { + control: { + association: { + state: "ACTIVE", + associationEpoch: "association_01", + }, + }, + }, + }); + }); + + it("keeps the shared state when a tab reconciles during another tab's unfinished opt-in", async () => { + // Order 2: the server still answers ABSENT while tab 1's register runs. + const tabs = sharedTabs(async () => "NOW"); + const results = await raceEnableWithReconcile(tabs); + + expect(results[0]).toEqual({ ok: true, value: { state: "PUSH_READY" } }); + expectReadyTabsStillReceive(tabs, results); + }); + + it("aborts a tab that is still waiting for another tab's lock", async () => { + const tabs = sharedTabs(async () => "NOW"); + const enabling = tabs.tab(true).enable({ + authority, + signal: new AbortController().signal, + }); + await tabs.registerStarted; + const waiting = new AbortController(); + const reconciling = tabs.tab(false).reconcile({ + authority, + signal: waiting.signal, + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + waiting.abort(); + + expect(await reconciling).toMatchObject({ + ok: false, + error: { code: "ABORTED", operation: "SUBSCRIPTION_RECONCILE" }, + }); + tabs.releaseRegister(); + expect(await enabling).toEqual({ + ok: true, + value: { state: "PUSH_READY" }, + }); + expect(tabs.unsubscribe).not.toHaveBeenCalled(); + }); + + it("reports PUSH_UNSUPPORTED without side effects when Web Locks are missing", async () => { + const tabs = sharedTabs(async () => "NOW", null); + expect( + await tabs.tab(true).enable({ + authority, + signal: new AbortController().signal, + }), + ).toEqual({ ok: true, value: { state: "PUSH_UNSUPPORTED" } }); + expect(tabs.nativeAlive()).toBe(false); + expect(await tabs.fence()).toEqual({ ok: true, value: null }); + }); +}); + +/** + * 06-06. The session changed from A to B without `revoke` (expiry, cleared + * cookies, a crash during logout). B cannot name A's stored authority, so + * `revokeForeign` rotates a fence another fence generation holds. A fence B + * already holds, for example because another tab of B opted in, is left alone. + */ +describe("06-06 account switch without logout", () => { + async function fenceFor(owner: PushAuthoritySnapshot, associationEpoch: string) { + const store = createPushAssociationFenceStore( + createFakePushControlStoreDependencies(), + ); + const prepared = await store.prepare({ + authority: owner, + updatedAt: "2026-07-28T00:00:00.000Z", + }); + if (!prepared.ok) throw new Error("expected prepared control"); + const active = await store.activate({ + expectedRevision: prepared.value.revision, + authority: owner, + associationEpoch, + updatedAt: "2026-07-28T00:00:01.000Z", + }); + if (!active.ok) throw new Error("expected active control"); + return store; + } + + function adapterOver( + fenceStore: ReturnType, + ) { + const unsubscribe = vi.fn(async () => { + current = null; + return true; + }); + let current: WindowPushSubscriptionFacade | null = subscription(unsubscribe); + const revoke = vi.fn(gateway().revoke); + const register = vi.fn(async () => + webPushSuccess({ + associationEpoch: "association_02", + sessionBindingEpoch: nextAuthority.sessionBindingEpoch, + }), + ); + const adapter = createWebPushSubscriptionAdapter({ + secureContext: true, + userActivationIsActive: () => true, + permission: { + permission: () => "granted", + requestPermission: async () => "granted", + }, + registration: { + active: true, + pushManager: { + getSubscription: async () => current, + subscribe: async () => { + current = subscription(); + return current; + }, + }, + getNotifications: async () => [], + }, + fenceStore, + gateway: gateway({ register, revoke }), + vapidPublicKey, + lockManager: navigator.locks, + now: () => now, + }); + return { adapter, unsubscribe, revoke, register }; + } + + it("lets B take over A's ACTIVE fence in one call and opt in again", async () => { + const fenceStore = await fenceFor(authority, "association_01"); + const tab = adapterOver(fenceStore); + // Without it B is stuck: the fence still belongs to A. + expect( + await tab.adapter.enable({ + authority: nextAuthority, + signal: new AbortController().signal, + }), + ).toMatchObject({ ok: false, error: { code: "STALE_AUTHORITY" } }); + + expect( + await tab.adapter.revokeForeign({ nextAuthority }), + ).toEqual({ + ok: true, + value: { state: "PUSH_UNAVAILABLE", reason: "REVOKED" }, + }); + expect(tab.revoke.mock.calls).toEqual([ + [{ associationEpoch: "association_01", signal: expect.any(AbortSignal) }], + ]); + expect(tab.unsubscribe).toHaveBeenCalledOnce(); + expect(await fenceStore.read()).toMatchObject({ + ok: true, + value: { + control: { + ...nextAuthority, + association: { state: "REVOKED", associationEpoch: "association_01" }, + }, + }, + }); + + expect( + await tab.adapter.enable({ + authority: nextAuthority, + signal: new AbortController().signal, + }), + ).toEqual({ ok: true, value: { state: "PUSH_READY" } }); + }); + + it("leaves a fence B already holds alone and reports it like inspect", async () => { + const fenceStore = await fenceFor(nextAuthority, "association_02"); + const before = await fenceStore.read(); + const tab = adapterOver(fenceStore); + + expect(await tab.adapter.revokeForeign({ nextAuthority })).toEqual({ + ok: true, + value: { state: "PUSH_READY" }, + }); + expect(tab.revoke).not.toHaveBeenCalled(); + expect(tab.unsubscribe).not.toHaveBeenCalled(); + expect(await fenceStore.read()).toEqual(before); + }); + + it("does not treat a new release of the same session as another account", async () => { + const fenceStore = await fenceFor(authority, "association_01"); + const before = await fenceStore.read(); + const tab = adapterOver(fenceStore); + + expect( + await tab.adapter.revokeForeign({ + nextAuthority: { ...authority, releaseEpoch: "release_02" }, + }), + ).toEqual({ + ok: true, + value: { state: "PUSH_UNAVAILABLE", reason: "SESSION_AUTHORITY_CHANGED" }, + }); + expect(tab.revoke).not.toHaveBeenCalled(); + expect(tab.unsubscribe).not.toHaveBeenCalled(); + expect(await fenceStore.read()).toEqual(before); + }); +}); diff --git a/tests/unit/web-push-worker-runtime.test.ts b/tests/unit/web-push-worker-runtime.test.ts index ff9c8f58..0e3bc6d2 100644 --- a/tests/unit/web-push-worker-runtime.test.ts +++ b/tests/unit/web-push-worker-runtime.test.ts @@ -106,6 +106,25 @@ function manualScheduler(): Readonly<{ }; } +/** + * 06-01. WebIDL shape of a real `Notification`: `data` is a getter and + * `close` a method on the prototype, so the instance has no own keys + * (checked in Chromium, Firefox and WebKit). + */ +class WebIdlNotification { + readonly #data: unknown; + closed = 0; + constructor(data: unknown) { + this.#data = data; + } + get data(): unknown { + return this.#data; + } + close(): void { + this.closed += 1; + } +} + describe("Web Push worker runtime", () => { it("waits for strict hint handling and shows only registry-owned safe copy", async () => { const store = await activeFence(); @@ -426,6 +445,59 @@ describe("Web Push worker runtime", () => { expect(click.postMessage).not.toHaveBeenCalled(); }); + // 06-09. Under a router base path the app root is the registration + // scope, not the origin root. + it("opens the registration scope under a base path", async () => { + const store = await activeFence(); + const listeners = new Map void>(); + const openWindow = vi.fn(async () => null); + const runtime = createWebPushServiceWorkerRuntime({ + fenceStore: store, + registry, + now: () => Date.parse("2026-07-28T02:00:00.000Z"), + host: { + origin: "https://app.example.test", + scope: "https://app.example.test/app/", + registration: { async showNotification() {} }, + clients: { matchAll: async () => [], openWindow }, + addEventListener(type, listener) { + listeners.set(type, listener); + }, + removeEventListener() {}, + }, + }); + let waited: Promise | null = null; + listeners.get("notificationclick")?.({ + notification: new WebIdlNotification(clickData()), + waitUntil(task: Promise) { + waited = task; + }, + }); + await waited; + + expect(openWindow.mock.calls).toEqual([ + ["https://app.example.test/app/"], + ]); + runtime.dispose(); + }); + + it("refuses an app root outside the origin", async () => { + expect(() => + createNotificationClickAdapter({ + fenceStore: createPushAssociationFenceStore( + createFakePushControlStoreDependencies(), + ), + registry, + origin: "https://app.example.test", + appRootUrl: "https://other.example.test/app/", + clients: { + matchControlledWindowClients: async () => [], + openWindow: async () => null, + }, + }), + ).toThrow(TypeError); + }); + it("does not retry the root after the browser refused the target window", async () => { const store = await activeFence(); const openWindow = vi.fn(async () => null); @@ -703,13 +775,18 @@ describe("Web Push worker runtime", () => { "pushsubscriptionchange", ]); let clickWait: Promise | null = null; + const notification = new WebIdlNotification(clickData()); + expect(Object.keys(notification)).toEqual(["closed"]); + expect(Object.hasOwn(notification, "data")).toBe(false); listeners.get("notificationclick")?.({ - notification: { data: clickData(), close() {} }, + notification, waitUntil(task: Promise) { clickWait = task; }, }); + expect(clickWait).not.toBeNull(); await clickWait; + expect(notification.closed).toBe(1); let subscriptionWait: Promise | null = null; listeners.get("pushsubscriptionchange")?.({ waitUntil(task: Promise) { diff --git a/vite.service-worker.config.ts b/vite.service-worker.config.ts index 28eeb96e..9ecce64b 100644 --- a/vite.service-worker.config.ts +++ b/vite.service-worker.config.ts @@ -48,8 +48,10 @@ const contractSet = await readGenerated<{ setDigest?: string }>( "./.generated/frontend-runtime/contract-set.ts", "BUILD_CONTRACT_SET", ); +// 06-10 / F-8. The profile document `scripts/generate-runtime-config.ts` wrote +// in step 4, not `public/config.json`, which is always the local profile. const runtimeConfig = JSON.parse( - await readFile("public/config.json", "utf8"), + await readFile("dist/config.json", "utf8"), ) as Record; const buildId = process.env.VITE_BUILD_ID ?? "local-build"; @@ -59,6 +61,7 @@ const buildInput = resolveServiceWorkerBuildInput({ assets, contractSet, runtimeConfig, + appProfile: process.env.APP_PROFILE ?? "local", buildId, releaseId, });