Files
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

39 lines
1.4 KiB
Python

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