fix(service-worker): intercept only manifest asset GETs (R-6.6)

The fetch listener called respondWith() for every request, so every
navigation, API call and cross-origin request went through
onFetch -> fetch(request) inside the worker, even when only WEB_PUSH was
selected.

The listener now decides synchronously and calls respondWith() only for
a non-navigation GET whose URL is in runtime.manifestUrls; everything
else returns without touching the event. The fetch listener is only
registered when PWA_STATIC_ASSETS is selected, so a push-only worker is
not booted for fetches at all.

RED before fix:
- "service worker entry fetch interception (R-6.6) > answers only
  same-origin GETs for manifest assets": respondWith was called for a
  navigation.
- "... > registers no fetch listener without the static asset handler":
  a fetch listener was registered.
The test loads the real entry module against stubbed worker globals and
build-time constants.
Gates: check:architecture, check:types:{app,test,service-worker}, lint,
test:component pass. test:unit passes except the pre-existing
removal-fixture.test.ts case that needs generated release evidence
under artifacts/ (absent in a fresh worktree; unrelated to this diff).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-24 12:28:38 +09:00
co-authored by Claude Opus 5.5
parent 793d54b4a9
commit 37fc009601
2 changed files with 116 additions and 12 deletions
@@ -89,18 +89,32 @@ self.addEventListener("activate", (event) => {
event.waitUntil(runtime.onActivate());
});
self.addEventListener("fetch", (event) => {
const request = event.request;
event.respondWith(
runtime
.onFetch({
method: request.method,
url: request.url,
mode: request.mode,
})
.then((cached) => cached ?? fetch(request)),
);
});
// R-6.6. Without the static asset handler there is nothing to answer, and
// no fetch listener means the browser never boots this worker for a fetch.
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;
}
event.respondWith(
runtime
.onFetch({
method: request.method,
url: request.url,
mode: request.mode,
})
.then((cached) => cached ?? fetch(request)),
);
});
}
self.addEventListener("message", (event) => {
const parsed = parseServiceWorkerMessage(event.data);
+90
View File
@@ -1330,6 +1330,96 @@ describe("page ↔ worker activation seam", () => {
});
});
/**
* 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[]) {
const listeners = new Map<string, (event: unknown) => void>();
vi.stubGlobal("self", {
addEventListener: (type: string, listener: (event: unknown) => void) => {
listeners.set(type, listener);
},
registration: { scope: `${ORIGIN}/` },
clients: { matchAll: async () => [] },
skipWaiting: async () => {},
});
vi.stubGlobal("__CA_SERVICE_WORKER_BUILD_INFO__", identity);
vi.stubGlobal("__CA_SERVICE_WORKER_ASSETS__", {
schemaVersion: 1,
buildId: identity.buildId,
releaseId: identity.releaseId,
setDigest: identity.staticAssetSetDigest,
assets: [
{
url: "/assets/app-Dq3x8Yk2.js",
sha256: `sha256:${"d".repeat(64)}`,
bytes: 6,
contentType: "text/javascript",
},
],
});
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("fetch", async () => new Response("network"));
vi.resetModules();
// A computed specifier keeps the WebWorker-lib entry out of the DOM-lib
// test type program.
const entry = "../../src/adapters/service-worker/service-worker-entry.ts";
await import(/* @vite-ignore */ entry);
return listeners;
}
describe("service worker entry fetch interception (R-6.6)", () => {
function fetchEvent(request: { method: string; url: string; mode: string }) {
return { request, respondWith: vi.fn() };
}
it("answers only same-origin GETs for manifest assets", async () => {
try {
const listeners = await loadWorkerEntry(["PWA_STATIC_ASSETS"]);
const onFetch = listeners.get("fetch")!;
const asset = `${ORIGIN}/assets/app-Dq3x8Yk2.js`;
const passthrough = [
{ method: "GET", url: `${ORIGIN}/`, mode: "navigate" },
{ method: "GET", url: asset, mode: "navigate" },
{ method: "POST", url: asset, mode: "cors" },
{ method: "GET", url: `${ORIGIN}/api/users`, mode: "cors" },
{ method: "GET", url: `${ORIGIN}/runtime-config.json`, mode: "cors" },
{ method: "GET", url: "https://cdn.example/assets/app-Dq3x8Yk2.js", mode: "cors" },
];
for (const request of passthrough) {
const event = fetchEvent(request);
onFetch(event);
expect(event.respondWith, `${request.method} ${request.url} ${request.mode}`).not.toHaveBeenCalled();
}
const event = fetchEvent({ method: "GET", url: asset, mode: "cors" });
onFetch(event);
expect(event.respondWith).toHaveBeenCalledOnce();
const response = (await event.respondWith.mock.calls[0]![0]) as Response;
await expect(response.text()).resolves.toBe("cached");
} finally {
vi.unstubAllGlobals();
}
});
it("registers no fetch listener without the static asset handler", async () => {
try {
const listeners = await loadWorkerEntry(["WEB_PUSH"]);
expect(listeners.has("fetch")).toBe(false);
} finally {
vi.unstubAllGlobals();
}
});
});
/**
* SW-01. The marker read must be bounded in bytes, not only in logic. Adding a
* whole chunk and *then* comparing the running total meant a corrupt body could