cipher/public/sw.js
maverick bd112d07fe Fix: namespace encrypted store per-account so two accounts can coexist on one browser
Root cause of 'two users can't chat': all accounts on one browser shared a
single IndexedDB, so the second registration overwrote the first's Signal
identity keys, corrupting both. Verified via two-isolated-client integration
test (real crypto.js + store.js) that the protocol itself is correct.

- store.js: useAccount(username) namespaces IndexedDB as cipher:<username>;
  keys generated at registration now persist under the right account
- accounts.js: localStorage-backed account registry + active pointer
- app.js: multi-account boot/activate, account-switch/add/logout menu,
  error toasts on send/decrypt failures (no more silent failures)
- login guards against missing on-device keys (multi-device linking still TODO)
- SW cache v2->v3 + precache accounts.js

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 02:48:00 +10:00

60 lines
1.6 KiB
JavaScript

// Service worker: offline app shell + Web Push wake-up.
// It never touches message plaintext — decryption happens only in the page.
const CACHE = "cipher-v3";
const SHELL = [
"/",
"/index.html",
"/manifest.webmanifest",
"/js/app.js",
"/js/api.js",
"/js/crypto.js",
"/js/store.js",
"/js/accounts.js",
"/js/vendor/libsignal.js",
"/icons/icon.svg",
];
self.addEventListener("install", (e) => {
e.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting()));
});
self.addEventListener("activate", (e) => {
e.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
).then(() => self.clients.claim())
);
});
self.addEventListener("fetch", (e) => {
const url = new URL(e.request.url);
// Never cache API or WebSocket traffic.
if (url.pathname.startsWith("/api/")) return;
// Cache-first for the shell, network fallback.
e.respondWith(
caches.match(e.request).then((hit) => hit || fetch(e.request))
);
});
// Payloadless push: just wake the client, which pulls ciphertext over the socket.
self.addEventListener("push", (e) => {
e.waitUntil(
self.registration.showNotification("Cipher", {
body: "New encrypted message",
icon: "/icons/icon.svg",
badge: "/icons/icon.svg",
tag: "cipher-msg",
})
);
});
self.addEventListener("notificationclick", (e) => {
e.notification.close();
e.waitUntil(
self.clients.matchAll({ type: "window" }).then((cl) => {
for (const c of cl) if ("focus" in c) return c.focus();
return self.clients.openWindow("/");
})
);
});