Files
Evection/templates/pwa/sw.js
T
ksmithandClaude Sonnet 5.5 aacb41d1d3 Purge the PWA page cache on every login/logout/expiry transition (R2-S3, #35)
The service worker cached authenticated pages in one origin-wide cache
and only purged it when the logout request itself passed through it —
not on session expiry, externally cleared cookies, or an account
switch, so a shared device could show the previous session's pages
offline.

Every HTML response now carries X-Evection-Auth: an opaque HMAC of the
user (or "anon"), via a small middleware. The service worker remembers
the marker its cached pages belong to and, whenever a navigation brings
a different one, deletes the pages cache before storing anything; "anon"
responses (the login page) are never cached. So the cache always holds
exactly one session's pages, and any transition the worker can observe
online clears it. (What no design can detect is a session ending while
the device stays offline.)

Verified in a real browser: pages cached after login; expiring the
session server-side (no logout request) and loading a page left the
cache deleted and the marker "anon"; logging in as a second user
afterward cached only that user's pages, none of the first user's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 12:05:45 -07:00

126 lines
4.4 KiB
JavaScript

{% load static %}const CACHE_VERSION = "{{ cache_version }}";
const SHELL_CACHE = `evection-shell-${CACHE_VERSION}`;
const PAGES_CACHE = `evection-pages-${CACHE_VERSION}`;
const MAX_CACHED_PAGES = 60;
const SHELL_URLS = [
"{% url 'pwa:offline' %}",
"{% url 'accounts:login' %}",
"{% static 'css/base.css' %}",
"{% static 'js/htmx.min.js' %}",
"{% static 'pwa/icons/icon-192.png' %}",
"{% static 'pwa/icons/icon-512.png' %}",
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL_URLS)).then(() => self.skipWaiting())
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((names) =>
Promise.all(
names
.filter((name) => name !== SHELL_CACHE && name !== PAGES_CACHE)
.map((name) => caches.delete(name))
)
)
.then(() => self.clients.claim())
);
});
async function trimCache(cacheName, maxItems) {
const cache = await caches.open(cacheName);
const keys = await cache.keys();
if (keys.length <= maxItems) return;
// Cache.keys() returns insertion order, so the oldest entries are first.
const toDelete = keys.slice(0, keys.length - maxItems);
await Promise.all(toDelete.map((key) => cache.delete(key)));
}
// Every HTML response carries X-Evection-Auth: an opaque id for who it was
// rendered for ("anon" when no one is logged in — see apps.pwa.middleware).
// PAGES_CACHE holds one person's pages; the marker it belongs to is kept in
// the shell cache (a service worker's own memory doesn't survive being
// stopped). Any change — session expired, logged in, switched accounts —
// purges the pages before anything new is stored, so one session's
// authenticated HTML can never be served to the next, whether or not the
// logout request itself passed through this worker.
const AUTH_MARKER_KEY = "/__evection-auth-marker__";
async function syncAuthMarker(response) {
const marker = response.headers.get("X-Evection-Auth");
if (marker === null) return null; // not an HTML page we can attribute
const shell = await caches.open(SHELL_CACHE);
const stored = await shell.match(AUTH_MARKER_KEY);
const previous = stored ? await stored.text() : null;
if (previous !== marker) {
await caches.delete(PAGES_CACHE);
await shell.put(AUTH_MARKER_KEY, new Response(marker));
}
return marker;
}
async function networkFirstForNavigation(request) {
try {
const response = await fetch(request);
const marker = await syncAuthMarker(response);
if (marker !== null && marker !== "anon") {
const cache = await caches.open(PAGES_CACHE);
cache.put(request, response.clone());
trimCache(PAGES_CACHE, MAX_CACHED_PAGES);
}
return response;
} catch (err) {
const cached = await caches.match(request);
if (cached) return cached;
const offline = await caches.match("{% url 'pwa:offline' %}");
return offline || Response.error();
}
}
async function cacheFirstForAsset(request) {
const cached = await caches.match(request);
if (cached) return cached;
const response = await fetch(request);
const cache = await caches.open(SHELL_CACHE);
cache.put(request, response.clone());
return response;
}
const LOGOUT_PATH = "{% url 'accounts:logout' %}";
self.addEventListener("fetch", (event) => {
const { request } = event;
const url = new URL(request.url);
// Logging out ends this device's session, so any authenticated HTML
// sitting in PAGES_CACHE must not outlive it — otherwise a later
// offline navigation (shared device, different account logging in
// next) could still serve a previous user's cached article pages.
// Purging it synchronously with the logout request itself, rather
// than via a postMessage from the page, means there's no race with
// the navigation that follows.
if (request.method === "POST" && url.pathname === LOGOUT_PATH) {
event.respondWith(caches.delete(PAGES_CACHE).then(() => fetch(request)));
return;
}
// Mutations (mark-read, star, OPML upload, forms...) are always
// network-only — never intercept anything but GET.
if (request.method !== "GET") return;
if (request.mode === "navigate") {
event.respondWith(networkFirstForNavigation(request));
return;
}
if (url.pathname.startsWith("/static/")) {
event.respondWith(cacheFirstForAsset(request));
}
});