|
| 1 | +"""PWA surface: web app manifest + service worker (Issue #86). |
| 2 | +
|
| 3 | +Wire/UX contract: ``docs/ux/pwa.md``. The Security lane owns this |
| 4 | +surface because its load-bearing properties are security ones: |
| 5 | +
|
| 6 | +- The **manifest** (``<mount>/web.manifest``) is served unauthenticated |
| 7 | + (the install prompt fires before login) and is computed at request |
| 8 | + time, but it carries **no per-user data** — only static/global values |
| 9 | + (mount-derived ``start_url``/``scope``, the AdminSite header, icons, |
| 10 | + theme colours from the client hint). An anonymous reader learns |
| 11 | + nothing they couldn't get from the static bundle. |
| 12 | +- The **service worker** (``<mount>/sw.js``) is served with |
| 13 | + ``Service-Worker-Allowed: <mount>`` so its scope is exactly the mount |
| 14 | + and **never** sibling Django views. It honours ``Cache-Control: |
| 15 | + no-store`` (so the package's no-store API reads are never cached), |
| 16 | + never caches non-GET requests (mutation safety), and exposes a |
| 17 | + cache-purge message used on logout so read-cached payloads can't |
| 18 | + outlive the session (``pwa.md`` §5 — defense-in-depth atop session |
| 19 | + expiry). |
| 20 | +
|
| 21 | +Both views live **outside** ``api/`` because they're served at the |
| 22 | +mount root, not under ``api/v1/``, and the manifest is intentionally |
| 23 | +anonymous (unlike every API endpoint, which is staff-gated). |
| 24 | +""" |
| 25 | + |
| 26 | +from __future__ import annotations |
| 27 | + |
| 28 | +from typing import Any |
| 29 | + |
| 30 | +from django.http import HttpRequest |
| 31 | +from django.http import HttpResponse |
| 32 | +from django.http import JsonResponse |
| 33 | +from django.shortcuts import render |
| 34 | +from django.views.generic import View |
| 35 | + |
| 36 | +from django_admin_react import conf as dar_conf |
| 37 | +from django_admin_react.api.registry import get_admin_site |
| 38 | + |
| 39 | +# Theme colours keyed by the resolved colour scheme. Kept here (not in |
| 40 | +# the SPA's CSS-var system) because the manifest is rendered server-side |
| 41 | +# before any CSS loads; these are the install-banner / splash colours |
| 42 | +# Android uses, and they only need to *approximate* the SPA theme. |
| 43 | +_THEME_COLOURS = { |
| 44 | + "light": {"background": "#ffffff", "theme": "#2563eb"}, |
| 45 | + "dark": {"background": "#0b0f19", "theme": "#3b82f6"}, |
| 46 | +} |
| 47 | + |
| 48 | +_DEFAULT_ICONS: list[dict[str, str]] = [ |
| 49 | + {"src": "static/dar/icons/icon-192.png", "sizes": "192x192", "type": "image/png"}, |
| 50 | + {"src": "static/dar/icons/icon-512.png", "sizes": "512x512", "type": "image/png"}, |
| 51 | + { |
| 52 | + "src": "static/dar/icons/icon-512-maskable.png", |
| 53 | + "sizes": "512x512", |
| 54 | + "type": "image/png", |
| 55 | + "purpose": "maskable", |
| 56 | + }, |
| 57 | +] |
| 58 | + |
| 59 | + |
| 60 | +def _mount(request: HttpRequest, suffix: str) -> str: |
| 61 | + """Reconstruct the consumer's mount prefix from ``request.path``. |
| 62 | +
|
| 63 | + The view is routed at ``<mount>/<suffix>`` (e.g. ``web.manifest``), |
| 64 | + so stripping the known suffix off ``request.path`` yields the mount. |
| 65 | + Mirrors ``views._mount_from_request`` but is local so this module |
| 66 | + has no import dependency on the SPA index view. |
| 67 | + """ |
| 68 | + path = request.path |
| 69 | + idx = path.rfind(suffix) |
| 70 | + if idx == -1: |
| 71 | + return "/" |
| 72 | + return path[:idx] or "/" |
| 73 | + |
| 74 | + |
| 75 | +def _resolved_scheme(request: HttpRequest) -> str: |
| 76 | + """Resolve light/dark from the ``Sec-CH-Prefers-Color-Scheme`` hint. |
| 77 | +
|
| 78 | + Pairs with the theming client-hint path (``theming.md`` §2). Any |
| 79 | + value other than a case-insensitive ``"dark"`` resolves to light — |
| 80 | + the safe, neutral default when the hint is absent or unexpected. |
| 81 | + """ |
| 82 | + hint = (request.headers.get("Sec-CH-Prefers-Color-Scheme") or "").strip().lower() |
| 83 | + return "dark" if hint == "dark" else "light" |
| 84 | + |
| 85 | + |
| 86 | +class ManifestView(View): |
| 87 | + """``GET <mount>/web.manifest`` — the PWA web app manifest. |
| 88 | +
|
| 89 | + Unauthenticated by design (the install prompt needs it pre-login). |
| 90 | + Carries no per-user data; every field is static or mount-/header- |
| 91 | + derived. ``Cache-Control: no-store`` is **not** set — the manifest |
| 92 | + is deliberately cacheable/network-first (``pwa.md`` §2.1). |
| 93 | + """ |
| 94 | + |
| 95 | + http_method_names = ["get"] |
| 96 | + |
| 97 | + def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: |
| 98 | + mount = _mount(request, "web.manifest") |
| 99 | + scheme = _resolved_scheme(request) |
| 100 | + colours = _THEME_COLOURS[scheme] |
| 101 | + |
| 102 | + admin_site = get_admin_site() |
| 103 | + site_header = getattr(admin_site, "site_header", None) |
| 104 | + name = dar_conf.PWA_NAME or (str(site_header) if site_header else "Django admin") |
| 105 | + short_name = dar_conf.PWA_SHORT_NAME or "Admin" |
| 106 | + icons = dar_conf.PWA_ICONS or _DEFAULT_ICONS |
| 107 | + |
| 108 | + manifest = { |
| 109 | + "name": name, |
| 110 | + "short_name": short_name, |
| 111 | + "start_url": mount, |
| 112 | + "scope": mount, |
| 113 | + "display": "standalone", |
| 114 | + "orientation": "any", |
| 115 | + "background_color": colours["background"], |
| 116 | + "theme_color": colours["theme"], |
| 117 | + "icons": icons, |
| 118 | + } |
| 119 | + response = JsonResponse(manifest, content_type="application/manifest+json") |
| 120 | + # Vary on the client hint so a light/dark cache entry doesn't |
| 121 | + # serve the wrong splash colours to the other scheme. |
| 122 | + response["Vary"] = "Sec-CH-Prefers-Color-Scheme" |
| 123 | + return response |
| 124 | + |
| 125 | + |
| 126 | +class ServiceWorkerView(View): |
| 127 | + """``GET <mount>/sw.js`` — the hand-rolled service worker. |
| 128 | +
|
| 129 | + Served with ``Service-Worker-Allowed: <mount>`` so the SW can claim |
| 130 | + the whole mount as its scope (a SW's default scope is its own path; |
| 131 | + the header widens it to the mount root). The JS is rendered from a |
| 132 | + template with the mount injected so the SW's fetch interception is |
| 133 | + bounded to the mount and never touches sibling Django views. |
| 134 | + """ |
| 135 | + |
| 136 | + http_method_names = ["get"] |
| 137 | + |
| 138 | + def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: |
| 139 | + mount = _mount(request, "sw.js") |
| 140 | + response = render( |
| 141 | + request, |
| 142 | + "admin_react/sw.js", |
| 143 | + {"mount": mount}, |
| 144 | + content_type="application/javascript", |
| 145 | + ) |
| 146 | + # Allow the SW to control the entire mount, not just ``<mount>/sw.js``. |
| 147 | + response["Service-Worker-Allowed"] = mount |
| 148 | + # The SW script itself should not be cached aggressively — a new |
| 149 | + # deploy must be able to ship a new SW. ``no-cache`` (revalidate) |
| 150 | + # not ``no-store`` so the browser's SW update check still works. |
| 151 | + response["Cache-Control"] = "no-cache" |
| 152 | + return response |
0 commit comments