diff --git a/apps/pwa/middleware.py b/apps/pwa/middleware.py new file mode 100644 index 0000000..7231d76 --- /dev/null +++ b/apps/pwa/middleware.py @@ -0,0 +1,38 @@ +import hashlib +import hmac + +from django.conf import settings + +AUTH_MARKER_HEADER = "X-Evection-Auth" +ANONYMOUS_MARKER = "anon" + + +def auth_marker(user) -> str: + """An opaque, stable identifier for who is logged in — "anon" if no + one. Derived with an HMAC of the user's pk under SECRET_KEY, so it's + constant for one user but reveals neither the pk nor anything + guessable.""" + if user is None or not user.is_authenticated: + return ANONYMOUS_MARKER + digest = hmac.new( + settings.SECRET_KEY.encode(), f"evection-sw-auth:{user.pk}".encode(), hashlib.sha256 + ).hexdigest() + return digest[:16] + + +class AuthMarkerMiddleware: + """Stamps every HTML response with who it was rendered for. The service + worker (templates/pwa/sw.js) caches authenticated pages for offline + reading in a single cache; it compares this marker on every navigation + and purges that cache whenever it changes — session expiry (the login + page comes back as "anon"), logging in, switching accounts — so one + session's pages can't be served to the next (R2-S3).""" + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + response = self.get_response(request) + if response.get("Content-Type", "").startswith("text/html"): + response[AUTH_MARKER_HEADER] = auth_marker(getattr(request, "user", None)) + return response diff --git a/apps/pwa/tests.py b/apps/pwa/tests.py index 423698a..da8b053 100644 --- a/apps/pwa/tests.py +++ b/apps/pwa/tests.py @@ -66,3 +66,42 @@ def test_base_template_links_manifest_and_registers_service_worker(client, djang assert 'rel="manifest"' in content assert "register-sw.js" in content assert "apple-touch-icon" in content + + +@pytest.mark.django_db +def test_html_responses_are_stamped_with_who_they_were_rendered_for(client, django_user_model): + """R2-S3: the service worker purges its page cache whenever this marker + changes, so it has to be stable per user, different between users, + and "anon" when logged out.""" + django_user_model.objects.create_user("alice", password="pw-alice-123") + django_user_model.objects.create_user("bob", password="pw-bob-123") + + anon = client.get(reverse("accounts:login"))["X-Evection-Auth"] + assert anon == "anon" + + client.login(username="alice", password="pw-alice-123") + alice_1 = client.get(reverse("reader:stream"))["X-Evection-Auth"] + alice_2 = client.get(reverse("reader:stream"))["X-Evection-Auth"] + client.logout() + client.login(username="bob", password="pw-bob-123") + bob = client.get(reverse("reader:stream"))["X-Evection-Auth"] + + assert alice_1 == alice_2 + assert len({anon, alice_1, bob}) == 3 + assert "alice" not in alice_1 and not alice_1.isdigit() + + +@pytest.mark.django_db +def test_non_html_responses_are_not_stamped(client, django_user_model): + django_user_model.objects.create_user("alice", password="pw-alice-123") + client.login(username="alice", password="pw-alice-123") + + assert "X-Evection-Auth" not in client.get(reverse("core:health")) + + +def test_service_worker_purges_its_page_cache_when_the_auth_marker_changes(client): + body = client.get(reverse("pwa:service_worker")).content.decode() + + assert "X-Evection-Auth" in body + assert "caches.delete(PAGES_CACHE)" in body + assert "previous !== marker" in body diff --git a/config/settings/base.py b/config/settings/base.py index 7fe2f8b..5869f19 100644 --- a/config/settings/base.py +++ b/config/settings/base.py @@ -49,6 +49,7 @@ MIDDLEWARE = [ "django.middleware.clickjacking.XFrameOptionsMiddleware", "django_htmx.middleware.HtmxMiddleware", "apps.accounts.middleware.SetupWizardMiddleware", + "apps.pwa.middleware.AuthMarkerMiddleware", ] ROOT_URLCONF = "config.urls" diff --git a/templates/pwa/sw.js b/templates/pwa/sw.js index 424d127..f007326 100644 --- a/templates/pwa/sw.js +++ b/templates/pwa/sw.js @@ -42,12 +42,38 @@ async function trimCache(cacheName, 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 cache = await caches.open(PAGES_CACHE); - cache.put(request, response.clone()); - trimCache(PAGES_CACHE, MAX_CACHED_PAGES); + 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);