diff --git a/README.md b/README.md index 4a1a137ee..392723cc0 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Try the [live demo](https://demo.healthlog.dev) to see a working install — sig - **AI insights you own.** Daily briefing, health scores, correlations, and a conversational coach grounded in your own measurements and interpreted against cited guideline reference bands — where a value sits and what that means in plain words, never a diagnosis. The coach proposes concrete if-then plans you accept or decline, and suppresses proactive check-ins when there's nothing genuine to say. Bring your own OpenAI or Anthropic key, or point at a local endpoint (Ollama, LM Studio, vLLM) so AI requests stay on your network. - **Clinician-ready output.** A doctor-report PDF rendered on your server, a read-only HL7 FHIR R4 API, and scoped, time-limited share links you revoke after the visit. - **Private by construction.** AES-256-GCM encryption at rest for notes and other free text, documents, questionnaire answers, AI-written text and credentials, with zero-downtime key rotation. Measurement values, lab values, medication names and mood scores are stored unencrypted in the database, so the database volume and its backups need the same protection as the host. Passkey login, server-side sessions, strict CSP, and no third-party tracking anywhere. -- **Built to be lived in.** Installable PWA with offline support, medication reminders over APNs, Telegram, ntfy, and Web Push, a sub-second dashboard on years of imported history — in English, German, Spanish, French, Italian, Polish, Korean, Dutch, and Brazilian Portuguese end to end. +- **Built to be lived in.** Installable PWA that keeps the open page readable when the connection drops, medication reminders over APNs, Telegram, ntfy, and Web Push, a sub-second dashboard on years of imported history — in English, German, Spanish, French, Italian, Polish, Korean, Dutch, and Brazilian Portuguese end to end. The full feature tour, integration guides, and API reference live at [docs.healthlog.dev](https://docs.healthlog.dev). diff --git a/e2e/pwa-offline.spec.ts b/e2e/pwa-offline.spec.ts index 28b34c16a..7276c786b 100644 --- a/e2e/pwa-offline.spec.ts +++ b/e2e/pwa-offline.spec.ts @@ -12,12 +12,14 @@ import { MOBILE_ROUTES_STORAGE_STATE_PATH } from "./setup/global-setup"; * * 1. A page that is open when the connection drops stays the app and says * so (the offline strip). - * 2. Opening a page without a connection gets the worker's offline page: - * the word "Offline" and a working retry control, never the browser's - * error. (Signed-in pages are never cached, by design: the proxy pins - * `private, no-store` on them because some carry the record in the - * HTML. So this is what an offline launch of the installed app shows.) - * 3. When the connection returns, that page reloads into the app by + * 2. A tap on a link to another page keeps the open page and repeats the + * hint, instead of trading the readable page for the offline one. + * 3. Opening a page without a connection (a typed URL, a cold start) gets + * the worker's offline page: the word "Offline" and a working retry + * control, never the browser's error. Signed-in pages are never cached: + * the proxy pins `private, no-store` on them because some carry the + * record in the HTML. + * 4. When the connection returns, that page reloads into the app by * itself. * * The account is the populated mobile-sweep account; nothing here writes. @@ -25,7 +27,7 @@ import { MOBILE_ROUTES_STORAGE_STATE_PATH } from "./setup/global-setup"; test.describe("offline, with the service worker", () => { test.use({ storageState: MOBILE_ROUTES_STORAGE_STATE_PATH }); - test("an open page says it is offline, a new one opens the offline page, and both recover @critical", async ({ + test("an open page stays readable offline, a new one opens the offline page, and both recover @critical", async ({ page, context, }) => { @@ -42,6 +44,16 @@ test.describe("offline, with the service worker", () => { await context.setOffline(true); await expect(page.locator('[data-slot="offline-banner"]')).toBeVisible(); + // A tap on the dashboard link stays on the open page. + await page.locator('a[href="/"]:visible').first().click(); + await expect( + page + .locator("[data-sonner-toast]") + .filter({ hasText: "other pages open once you're back online" }), + ).toBeVisible(); + expect(new URL(page.url()).pathname).toBe("/medications"); + await expect(page.locator("#main-content")).toBeVisible(); + const response = await page.goto("/timeline"); expect(response?.status()).toBe(503); await expect(page.getByText("Offline", { exact: true })).toBeVisible(); diff --git a/e2e/v137-record-session-fence-offline.spec.ts b/e2e/v137-record-session-fence-offline.spec.ts index 455df1581..23984fe43 100644 --- a/e2e/v137-record-session-fence-offline.spec.ts +++ b/e2e/v137-record-session-fence-offline.spec.ts @@ -4,45 +4,22 @@ import { expect, test } from "./setup/test"; import { FENCE_OFFLINE_STORAGE_STATE_PATH } from "./setup/test-helpers"; /** - * FENCE-AC-07 — the disk layers cannot serve one record's bytes inside - * another. + * FENCE-AC-07: no record's API answers are kept in CacheStorage, before or + * after a record switch. * - * ## Why this is a spec of its own + * Runs in the `chromium-service-worker` project with the worker allowed and + * no route mocks, because the claim is about what the worker itself stores. + * The worker passes every `/api/` request to the network and keeps none of + * them; the only per-account layer on disk is the IndexedDB snapshot, which + * refuses to write or restore inside another record (unit-tested in + * `query-persister-shared-record.test.ts`). * - * `playwright.config.ts` sets `serviceWorkers: "block"` for every other - * project, and for a good reason written there: a worker-originated `fetch` is - * not subject to `page.route`, so the SW would bypass the per-spec route mocks. - * - * This case is the exact inverse. Its whole claim is about what the - * `healthlog-data-*` cache can and cannot serve across a record switch — and - * with the worker blocked that cache is never populated at all, so the positive - * control ("the owner snapshot really WAS on disk before the switch") could - * never pass no matter what the application did. A check that cannot pass is - * worse than no check, so this runs in the `chromium-service-worker` project - * with the worker allowed, and uses no route mocks. - * - * ## What is asserted, in order - * - * 1. the owner's record reads really are on disk before the switch — a test - * that seeded nothing proves nothing; - * 2. only current-version caches exist, which is the eviction the fence's - * design relies on to make "a response with no echo" safe; - * 3. the switch empties the data cache before it reloads; - * 4. every response now on disk carries the TARGET's record scope and never - * the previous one — the claim, read off the disk layer itself rather - * than inferred from what a page did or did not paint; - * 5. and offline, that cache is what answers a record read, still carrying - * the target's context. The non-empty scope set is the paired positive - * control: an empty cache would satisfy "no previous-record bytes" while - * proving nothing. + * The positive control is the page cache: the worker is running and storing + * something (public pages, catalogs, icons), so "no API entry" is not the + * same sentence as "the worker did nothing". */ -/** - * Pages whose reads the service worker is configured to hold on disk - * (`sw-cache-policy.ts` allowlists `/api/dashboard/snapshot`, - * `/api/measurements` and `/api/medications`). Visited rather than fetched, so - * the requests are the app's own and carry the record-session assertion. - */ +/** Pages whose reads used to be kept on disk. Visited, so the reads are the app's own. */ const WARM_PAGES = ["/", "/measurements", "/medications"] as const; /** @@ -105,45 +82,27 @@ async function expectShellReady(page: Page) { }); } -/** What the `healthlog-data-*` caches hold right now. */ -async function dataCacheState(page: Page) { +/** Every HealthLog cache and the API answers it holds. */ +async function cacheState(page: Page) { return page.evaluate(async () => { - const names = await caches.keys(); - const data = names.filter((n) => n.startsWith("healthlog-data-")); + const names = (await caches.keys()).filter((n) => + n.startsWith("healthlog-"), + ); + const apiEntries: string[] = []; let entries = 0; - for (const name of data) { - entries += (await (await caches.open(name)).keys()).length; - } - return { names, dataCaches: data, entries }; - }); -} - -/** - * The record context every cached response was stored WITH. - * - * This is the disk-layer claim, read off the disk layer. A cached record - * response carries the echo it was served under, so if a previous record's - * bytes were still reachable they would show up here as that record's scope. - */ -async function cachedScopes(page: Page): Promise { - return page.evaluate(async () => { - const scopes: string[] = []; - for (const name of (await caches.keys()).filter((n) => - n.startsWith("healthlog-data-"), - )) { - const cache = await caches.open(name); - for (const request of await cache.keys()) { - const cached = await cache.match(request); - const scope = cached?.headers.get("x-healthlog-record-scope"); - if (scope) scopes.push(scope); + for (const name of names) { + for (const request of await (await caches.open(name)).keys()) { + entries += 1; + const { pathname } = new URL(request.url); + if (pathname.startsWith("/api/")) apiEntries.push(pathname); } } - return scopes; + return { names, entries, apiEntries }; }); } test.describe.serial("FENCE-AC-07 record-fence disk layers", () => { - test("FENCE-AC-07 the disk layers cannot serve one record's bytes inside another", async ({ + test("FENCE-AC-07 no record's API answers are kept on disk across a switch", async ({ browser, }) => { const context = await browser.newContext({ @@ -153,10 +112,6 @@ test.describe.serial("FENCE-AC-07 record-fence disk layers", () => { try { await page.goto("/"); - // The gate is spelled out here rather than left inside a helper because - // the next act is a one-shot `page.evaluate`, and - // `src/__tests__/e2e-measurement-gating-guard.test.ts` reads the source - // text between the navigation and the read. await expect( page.getByRole("button", { name: "User menu" }), ).toBeVisible(); @@ -168,148 +123,51 @@ test.describe.serial("FENCE-AC-07 record-fence disk layers", () => { await page.locator('[data-slot="shared-record-banner-exit"]').click(); await expect(banner).toHaveCount(0); } - - // Wait for the worker to control the page — until it does, nothing it - // would cache is going through it. await page.waitForFunction( () => navigator.serviceWorker?.controller !== null, undefined, { timeout: 20_000 }, ); - // Warm the disk cache by VISITING the pages, not by issuing bare - // fetches. A bare `fetch` in `page.evaluate` carries no record-session - // assertion, so on a session that has been inside a shared record the - // fence refuses it and nothing cacheable comes back — the cache filled - // from the app's own reads instead, and those were the ones that happened - // to resolve no record scope. Driving the app is what puts real, - // echo-carrying record responses on disk. for (const path of WARM_PAGES) { await page.goto(path); // Spelled out rather than left inside `expectShellReady`, because the // next act is a one-shot `page.evaluate` and // `src/__tests__/e2e-measurement-gating-guard.test.ts` reads the source - // text between the navigation and the read. A gate hidden in a helper - // is invisible to that guard and to the next reader. + // text between the navigation and the read. await expect( page.getByRole("button", { name: "User menu" }), ).toBeVisible(); await expectShellReady(page); } + + // POSITIVE CONTROL: the worker controls the page and keeps something. await expect - .poll(async () => (await dataCacheState(page)).entries, { + .poll(async () => (await cacheState(page)).entries, { timeout: 15_000, }) .toBeGreaterThan(0); - - // (1) POSITIVE CONTROL: the owner's bytes really are on disk. - const seeded = await dataCacheState(page); - expect(seeded.dataCaches.length).toBeGreaterThan(0); - expect(seeded.entries).toBeGreaterThan(0); - - // (2) Only current-version caches survive activation. This is the - // eviction the fence's "a response with no echo is served normally" rule - // depends on: a PRE-fence cached response carries no echo, and it can - // only be served if its cache is still there. - const version = seeded.dataCaches[0].replace("healthlog-data-", ""); - const stale = seeded.names.filter( - (n) => - /^healthlog-(static|pages|data)-/.test(n) && !n.endsWith(version), + const own = await cacheState(page); + expect(own.apiEntries).toEqual([]); + expect(own.names.filter((n) => n.startsWith("healthlog-data-"))).toEqual( + [], ); - expect(stale).toEqual([]); - await openSwitcher(page); - const entry = page.locator( - `[data-slot="account-switcher-entry"][data-account-username="${TARGET_USERNAME}"]`, - ); - await expect(entry).toBeVisible(); - const targetAccountId = await entry.getAttribute("data-account-id"); - expect(targetAccountId).not.toBeNull(); - await entry.click(); - await expect( - page.locator('[data-slot="shared-record-banner"]'), - ).toBeVisible(); - - // (3) NOT asserted: "the data cache is momentarily empty". - // - // The switch does wipe the disk layers — `clearOfflineCachesForRecordSwitch` - // runs before the reload — but the reload immediately refills them from - // the target's own reads, so an empty cache is a state that exists for a - // few milliseconds and cannot be sampled reliably. Polling for it made - // this case fail for a reason that had nothing to do with the claim. - // - // The claim is asserted directly below instead, and it is the stronger - // statement anyway: what matters is not that the cache was briefly empty - // but that nothing in it belongs to the previous record. - - // Visit inside the TARGET record so there is something of its own on - // disk to find. + await enterRecord(page); for (const path of WARM_PAGES) { await page.goto(path); - // Spelled out rather than left inside `expectShellReady`, because the - // next act is a one-shot `page.evaluate` and - // `src/__tests__/e2e-measurement-gating-guard.test.ts` reads the source - // text between the navigation and the read. A gate hidden in a helper - // is invisible to that guard and to the next reader. await expect( page.getByRole("button", { name: "User menu" }), ).toBeVisible(); await expectShellReady(page); } - await expect - .poll(async () => (await dataCacheState(page)).entries, { - timeout: 15_000, - }) - .toBeGreaterThan(0); - // (4) + (5) The disk layer now holds the TARGET's bytes and only those, - // read off the disk layer itself. - // - // The first draft asserted the shared-record banner after an offline - // reload. That could never pass and had nothing to do with the claim: - // `/api/auth/me` is not a cached read, so offline it fails, `useAuth` - // errors and the shell paints its offline gate rather than a banner. The - // banner's absence says nothing about what is on disk. - // - // What IS on disk is checkable, and it is the whole point: every cached - // record response carries the echo it was served under, so a previous - // record's bytes surviving the switch would appear here as that record's - // scope. - const scopes = await cachedScopes(page); - // POSITIVE CONTROL: something really is cached with a context, so the - // assertion below is about a non-empty set. - expect(scopes.length).toBeGreaterThan(0); - for (const scope of scopes) { - expect(scope).toBe(targetAccountId); - } - expect(scopes).not.toContain("self"); - - // And the target's own record read really is one of the entries on disk, - // so the scope assertion above is about the reads that matter rather - // than about some incidental cached response. - const cachedUrls = await page.evaluate(async () => { - const urls: string[] = []; - for (const name of (await caches.keys()).filter((n) => - n.startsWith("healthlog-data-"), - )) { - for (const request of await (await caches.open(name)).keys()) { - urls.push(new URL(request.url).pathname); - } - } - return urls; - }); - expect(cachedUrls).toContain("/api/measurements"); - - // NOT asserted: that a bare `fetch` from page context can read those - // bytes back while offline. Since v1.37.0 an echoing response also - // carries `Vary: x-healthlog-record-epoch, x-healthlog-record-scope`, and - // the Cache API honours `Vary` — so a request WITHOUT the fence headers - // does not match the stored entry at all. That is the correct behaviour - // and a second line of defence worth naming: bytes cached under one - // record context cannot be retrieved by a request asserting a different - // one, or none. The app's own reads carry the headers and do match. + const inside = await cacheState(page); + expect(inside.apiEntries).toEqual([]); + expect( + inside.names.filter((n) => n.startsWith("healthlog-data-")), + ).toEqual([]); } finally { - await context.setOffline(false); // Hand the shared session back to its own record; see the note in // `v137-record-session-fence.spec.ts`. await context.request @@ -318,185 +176,4 @@ test.describe.serial("FENCE-AC-07 record-fence disk layers", () => { await context.close(); } }); - - test("FENCE-AC-07 a cached record response cannot be SERVED under a different context", async ({ - browser, - }) => { - /** - * The serving path, which the case above does not exercise. - * - * The test above asserts what is IN the cache. That is worth asserting and - * it is not the same claim: an entry can sit on disk under one context and - * still be handed to a request made under another, and on the EXTERNAL - * switch path nothing wipes it — the app never initiated the switch, so - * `clearOfflineCachesForRecordSwitch` never runs. On that path `Vary` is - * the only thing standing between a cached delegated response and the next - * request for the same URL. - * - * So this asks the Cache API the question a service worker asks it: - * `cache.match(request)` honours the stored response's `Vary`, so a request - * whose fence headers differ from the ones the entry was stored with does - * not match at all. Remove the `Vary` block from `attachRecordContextEcho` - * and the second lookup starts hitting. - */ - const context = await browser.newContext({ - storageState: FENCE_OFFLINE_STORAGE_STATE_PATH, - }); - const page = await context.newPage(); - - try { - await page.goto("/"); - await expect( - page.getByRole("button", { name: "User menu" }), - ).toBeVisible(); - await expectShellReady(page); - const banner = page.locator('[data-slot="shared-record-banner"]'); - if ((await banner.count()) > 0) { - await page.locator('[data-slot="shared-record-banner-exit"]').click(); - await expect(banner).toHaveCount(0); - } - await page.waitForFunction( - () => navigator.serviceWorker?.controller !== null, - undefined, - { timeout: 20_000 }, - ); - - // Enter the record and let its reads land on disk. - await enterRecord(page); - await page.goto("/measurements"); - await expect( - page.getByRole("button", { name: "User menu" }), - ).toBeVisible(); - await expectShellReady(page); - - // The context those bytes were stored under, read off the entry itself. - // - // Polled, not sampled once. The service worker writes its `healthlog-data-*` - // entry AFTER the response has been handed to the page, so - // `expectShellReady` returning is not evidence that the write has landed — - // it is evidence that the read arrived. Sampling here read `null` on a - // loaded machine and failed the positive control below, which then said - // "there is no cache entry" about a cache that was about to have one. - // Waiting on the entry itself waits for the signal rather than for a - // number of milliseconds, and it still fails if the entry never appears. - const readStoredEntry = async () => - page.evaluate(async () => { - for (const name of (await caches.keys()).filter((n) => - n.startsWith("healthlog-data-"), - )) { - const cache = await caches.open(name); - for (const request of await cache.keys()) { - if ( - !new URL(request.url).pathname.startsWith("/api/measurements") - ) - continue; - const response = await cache.match(request); - if (!response) continue; - return { - cacheName: name, - url: request.url, - vary: response.headers.get("Vary"), - epoch: response.headers.get("x-healthlog-record-epoch"), - scope: response.headers.get("x-healthlog-record-scope"), - }; - } - } - return null; - }); - - // POSITIVE CONTROL: there really is an entry, stored with a context. - await expect.poll(readStoredEntry, { timeout: 20_000 }).not.toBeNull(); - const stored = await readStoredEntry(); - expect(stored).not.toBeNull(); - expect(stored!.epoch).toMatch(/^\d+$/); - expect(stored!.scope).not.toBe("self"); - - // The EXTERNAL switch: nothing in the app initiates it, so - // `clearOfflineCachesForRecordSwitch` never runs and the entry above - // survives — the positive control below is what proves that. - // - // Sent with the page's own `fetch` rather than through - // `context.request`. Both are outside the app: the switch UI is what runs - // the wipe, and a bare `fetch` is not it (the service worker returns - // without touching any non-GET, so the request reaches the network - // unaltered). What differs is the socket. Every Playwright API context in - // the runner shares one process-wide keep-alive agent, so this POST could - // be handed a connection the server had already closed on its five-second - // idle timeout, and a POST is never replayed on a fresh one — twice this - // line ended the spec with `read ECONNRESET`, on all three attempts. - const left = await page.evaluate(async () => { - const res = await fetch("/api/account/switch", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ accountId: null }), - }); - return res.status; - }); - expect(left).toBe(200); - // Read back through the page for the same reason the switch above goes - // that way. This was the last call in the file still using the shared - // API context, and it duly failed with `read ECONNRESET` on all three - // attempts once the pooled socket had gone stale. The browser opens its - // own connection, and a GET for the caller's own session is outside the - // app either way. - const now = (await page.evaluate(async () => { - const res = await fetch("/api/auth/me"); - return (await res.json()).data.recordSession; - })) as { - epoch: number; - scope: string | null; - }; - // The context genuinely moved, or the comparison below is vacuous. - expect(String(now.epoch)).not.toBe(stored!.epoch); - - const lookups = await page.evaluate( - async ({ - cacheName, - url, - storedEpoch, - storedScope, - nowEpoch, - nowScope, - }) => { - const cache = await caches.open(cacheName); - const ask = async (epoch: string, scope: string) => - (await cache.match( - new Request(url, { - headers: { - "x-healthlog-record-epoch": epoch, - "x-healthlog-record-scope": scope, - }, - }), - )) !== undefined; - return { - underStoredContext: await ask(storedEpoch, storedScope), - underNewContext: await ask(nowEpoch, nowScope), - withNoAssertion: - (await cache.match(new Request(url))) !== undefined, - }; - }, - { - cacheName: stored!.cacheName, - url: stored!.url, - storedEpoch: stored!.epoch!, - storedScope: stored!.scope!, - nowEpoch: String(now.epoch), - nowScope: now.scope ?? "self", - }, - ); - - // POSITIVE CONTROL: the entry IS servable to the context it belongs to. - // Without this, "the other context misses" would pass for an entry that - // was simply not there. - expect(lookups.underStoredContext).toBe(true); - // The claim. Remove the `Vary` and this starts hitting. - expect(lookups.underNewContext).toBe(false); - expect(lookups.withNoAssertion).toBe(false); - } finally { - await context.request - .post("/api/account/switch", { data: { accountId: null } }) - .catch(() => {}); - await context.close(); - } - }); }); diff --git a/messages/de.json b/messages/de.json index 721e72a42..3be20d373 100644 --- a/messages/de.json +++ b/messages/de.json @@ -452,7 +452,7 @@ "offlineBanner": { "message": "Keine Verbindung: Änderungen können erst gespeichert werden, wenn du wieder online bist.", "saveFailed": "Speichern fehlgeschlagen, du bist offline. Bitte versuche es erneut, sobald du wieder online bist.", - "showingCached": "Zeigt deine zuletzt synchronisierten Daten." + "stayOnPage": "Diese Seite bleibt lesbar, andere Seiten öffnen sich, sobald du wieder online bist." }, "demoBanner": { "message": "Demo-Modus: Änderungen werden nicht gespeichert." diff --git a/messages/en.json b/messages/en.json index 5212ca494..b97815674 100644 --- a/messages/en.json +++ b/messages/en.json @@ -452,7 +452,7 @@ "offlineBanner": { "message": "No connection: changes can't be saved until you're back online.", "saveFailed": "Couldn't save, you're offline. Please try again once you're back online.", - "showingCached": "Showing your last synced data." + "stayOnPage": "This page stays readable; other pages open once you're back online." }, "demoBanner": { "message": "Demo mode: changes are not saved." diff --git a/messages/es.json b/messages/es.json index 61217c9e8..29be29505 100644 --- a/messages/es.json +++ b/messages/es.json @@ -452,7 +452,7 @@ "offlineBanner": { "message": "Sin conexión: los cambios no se pueden guardar hasta que vuelvas a estar en línea.", "saveFailed": "No se pudo guardar porque estás sin conexión. Inténtalo de nuevo cuando vuelvas a estar en línea.", - "showingCached": "Mostrando tus últimos datos sincronizados." + "stayOnPage": "Esta página se puede seguir leyendo; las demás se abrirán cuando vuelvas a estar en línea." }, "demoBanner": { "message": "Modo demo: los cambios no se guardan." diff --git a/messages/fr.json b/messages/fr.json index 3f728eda2..b2abdab83 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -452,7 +452,7 @@ "offlineBanner": { "message": "Pas de connexion : les modifications ne peuvent pas être enregistrées tant que vous n'êtes pas de nouveau en ligne.", "saveFailed": "Enregistrement impossible : vous êtes hors ligne. Réessayez une fois de nouveau en ligne.", - "showingCached": "Affichage de vos dernières données synchronisées." + "stayOnPage": "Cette page reste lisible ; les autres s'ouvriront dès que vous serez de nouveau en ligne." }, "demoBanner": { "message": "Mode démo : les modifications ne sont pas enregistrées." diff --git a/messages/it.json b/messages/it.json index bfe254835..d1f8668de 100644 --- a/messages/it.json +++ b/messages/it.json @@ -452,7 +452,7 @@ "offlineBanner": { "message": "Nessuna connessione: le modifiche non possono essere salvate finché non torni online.", "saveFailed": "Impossibile salvare: sei offline. Riprova quando torni online.", - "showingCached": "Vengono mostrati i tuoi ultimi dati sincronizzati." + "stayOnPage": "Questa pagina resta leggibile; le altre si aprono quando torni online." }, "demoBanner": { "message": "Modalità demo: le modifiche non vengono salvate." diff --git a/messages/ko.json b/messages/ko.json index 501d360a3..b06904477 100644 --- a/messages/ko.json +++ b/messages/ko.json @@ -452,7 +452,7 @@ "offlineBanner": { "message": "연결이 없어요. 온라인으로 돌아올 때까지 저장할 수 없어요.", "saveFailed": "저장하지 못했어요. 오프라인 상태예요. 온라인으로 돌아온 뒤 다시 시도해 주세요.", - "showingCached": "마지막으로 동기화한 데이터를 보여주고 있어요." + "stayOnPage": "이 페이지는 계속 볼 수 있어요. 다른 페이지는 온라인으로 돌아오면 열려요." }, "demoBanner": { "message": "데모 모드: 변경 내용은 저장되지 않아요." diff --git a/messages/nl.json b/messages/nl.json index 09fb725ea..317568cd6 100644 --- a/messages/nl.json +++ b/messages/nl.json @@ -452,7 +452,7 @@ "offlineBanner": { "message": "Geen verbinding: wijzigingen kunnen pas worden opgeslagen als je weer online bent.", "saveFailed": "Opslaan is mislukt, je bent offline. Probeer het opnieuw zodra je weer online bent.", - "showingCached": "Je laatst gesynchroniseerde gegevens worden getoond." + "stayOnPage": "Deze pagina blijft leesbaar; andere pagina's openen zodra je weer online bent." }, "demoBanner": { "message": "Demomodus: wijzigingen worden niet opgeslagen." diff --git a/messages/pl.json b/messages/pl.json index 699081867..37dfdb6a5 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -452,7 +452,7 @@ "offlineBanner": { "message": "Brak połączenia: zmian nie można zapisać, dopóki nie wrócisz online.", "saveFailed": "Nie udało się zapisać, jesteś offline. Spróbuj ponownie, gdy wrócisz online.", - "showingCached": "Wyświetlane są ostatnio zsynchronizowane dane." + "stayOnPage": "Ta strona pozostaje czytelna, inne otworzą się, gdy wrócisz online." }, "demoBanner": { "message": "Tryb demo: zmiany nie są zapisywane." diff --git a/messages/pt-BR.json b/messages/pt-BR.json index 3da35552e..e7667561a 100644 --- a/messages/pt-BR.json +++ b/messages/pt-BR.json @@ -452,7 +452,7 @@ "offlineBanner": { "message": "Sem conexão: as alterações não podem ser salvas até você voltar a ficar online.", "saveFailed": "Não foi possível salvar, você está offline. Tente novamente quando voltar a ficar online.", - "showingCached": "Mostrando seus últimos dados sincronizados." + "stayOnPage": "Esta página continua legível; as outras abrem quando você voltar a ficar online." }, "demoBanner": { "message": "Modo demonstração: as alterações não são salvas." diff --git a/messages/ru.json b/messages/ru.json index 1703b52cb..659c95666 100644 --- a/messages/ru.json +++ b/messages/ru.json @@ -452,7 +452,7 @@ "offlineBanner": { "message": "Нет подключения: изменения нельзя сохранить, пока вы снова не в сети.", "saveFailed": "Не удалось сохранить, вы не в сети. Попробуйте снова, когда подключение вернётся.", - "showingCached": "Показаны последние синхронизированные данные." + "stayOnPage": "Эту страницу можно читать дальше, другие откроются, когда вы снова будете в сети." }, "demoBanner": { "message": "Деморежим: изменения не сохраняются." diff --git a/public/manifest.json b/public/manifest.json index d94dc7fe3..922540d9d 100644 --- a/public/manifest.json +++ b/public/manifest.json @@ -40,7 +40,7 @@ { "name": "Add measurement", "short_name": "Add", - "url": "/measurements?add=WEIGHT&source=shortcut", + "url": "/measurements?add=WEIGHT", "icons": [ { "src": "/logo-192.png", "sizes": "192x192", "type": "image/png" } ] @@ -48,15 +48,7 @@ { "name": "Today", "short_name": "Today", - "url": "/?source=shortcut", - "icons": [ - { "src": "/logo-192.png", "sizes": "192x192", "type": "image/png" } - ] - }, - { - "name": "Medications", - "short_name": "Meds", - "url": "/medications?source=shortcut", + "url": "/", "icons": [ { "src": "/logo-192.png", "sizes": "192x192", "type": "image/png" } ] diff --git a/public/sw.js b/public/sw.js index 19178159e..21cfb60a9 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1,159 +1,52 @@ /** - * Service Worker for HealthLog PWA. - * Handles Web Push notifications and offline caching. + * HealthLog service worker: Web Push, a page cache for public pages, and a + * static cache for catalogs and icons. API answers and app chunks are never + * stored here. */ -// v1.4.38.4 — `CACHE_VERSION` now tracks the app release tag. -// Bumped on every release so the `activate` step evicts every -// pre-release cache entry. Without this the precached root HTML and -// the cached `/_next/static/*` chunks survived across deploys, -// stale-shell-served the old chunk graph, and the running app then -// hit `ChunkLoadError` on the first lazy navigation. Pair with the -// `` client component (mounted in ``) that -// polls `/api/version`, compares against `NEXT_PUBLIC_APP_VERSION`, -// and triggers an SW-unregister + cache-wipe + hard reload when the -// server moves ahead of the running shell. -// -// v1.4.43 — read the active version from `self.__APP_VERSION__`, -// which the build step writes to `/public/sw-version.js` (loaded -// synchronously below via `importScripts`). Pre-fix the literal was -// hand-bumped per release and quietly drifted four releases stale, so -// every deploy between v1.4.38.4 → v1.4.42 served the previous shell's -// cache instead of evicting it on activate. The fallback literal stays -// in case the import is missing (legacy SW versions, dev mode without -// the build step), but the source of truth is now the generated file. +// Cache names carry the release, so `activate` drops every older cache. The +// build writes the release to `/sw-version.js`; the literal below is the +// fallback when that file is missing (dev without `prebuild`, a 404), and +// `scripts/generate-sw-version.mjs` rewrites it at the marker on every +// build. Do not edit it by hand. try { importScripts("/sw-version.js"); } catch { - // Fall through to the literal fallback below. + // Fall through to the fallback literal. } -// The `|| "..."` fallback literal is the value used only when the -// `importScripts('/sw-version.js')` above is absent (dev with no `prebuild` -// step, or a 404 on the generated file). `scripts/generate-sw-version.mjs` -// rewrites it to the current `package.json` version on every prebuild — the -// marker below is the rewrite anchor — so in any shipped image the literal -// matches the active release and can never drift stale the way it did across -// v1.4.38.4 → v1.4.42. Do not hand-edit; bump `package.json` and rebuild. const CACHE_VERSION = (typeof self !== "undefined" && self.__APP_VERSION__) || /* @sw-version-fallback */ "v1.47.2"; const STATIC_CACHE = `healthlog-static-${CACHE_VERSION}`; const PAGE_CACHE = `healthlog-pages-${CACHE_VERSION}`; -// v1.18.6 — read-only data cache for a curated allowlist of safe GET `/api/*` -// reads. Network-first: online callers always get the fresh server response -// (and the cache is refreshed behind it), so a read-after-write never serves a -// stale pre-mutation list. Offline (the network fetch throws) the LAST cached -// dashboard/series is served instead of empty skeletons forever. -// -// v1.18.6.x — reverted from stale-while-revalidate, which served the cached -// pre-mutation copy first and only revalidated in the background, so a list -// read straight after a create/update showed the old (or empty) data until the -// next paint. Network-first restores read-after-write freshness while keeping -// the offline fallback. -const DATA_CACHE = `healthlog-data-${CACHE_VERSION}`; -// Keep this ownership contract aligned with -// `clearOfflineCachesForSessionEnd()` in `query-persister.ts`. Cache cleanup -// must cover every current/legacy HealthLog cache without deleting unrelated -// CacheStorage namespaces owned by another app on the same origin. +// Every HealthLog cache, current and legacy, and nothing another app on the +// origin owns. `data` stays in the pattern so caches from releases that still +// kept API reads are deleted on activate. Same pattern as +// `HEALTHLOG_CACHE_NAME_RE` in `src/lib/pwa/sw-cache-policy.ts`. const HEALTHLOG_CACHE_NAME_RE = /^healthlog-(?:static|pages|data)-/; -const CURRENT_HEALTHLOG_CACHES = new Set([ - STATIC_CACHE, - PAGE_CACHE, - DATA_CACHE, -]); -// Presence marker `src/proxy.ts` sets on every HealthLog page response. See -// `isForeignNavigationResponse` for why the worker needs it and the proxy for -// why it carries no version. Keep the name in lockstep with -// `HEALTHLOG_PAGE_MARKER_HEADER` there. +const CURRENT_HEALTHLOG_CACHES = new Set([STATIC_CACHE, PAGE_CACHE]); +// Set by `src/proxy.ts` on every HealthLog page; same name as there. const HEALTHLOG_PAGE_MARKER_HEADER = "X-HealthLog-Page"; -// Set as soon as a navigation looks like another app (see -// `isForeignNavigationResponse`). While it is set the fetch handler declines -// every request, so the page and its assets come from the network. It is -// cleared again when `confirmForeignOrigin` finds HealthLog after all, and -// stays set for the rest of the worker's life when the origin is confirmed -// foreign and the worker retires. +// While set, the fetch handler declines every request. Set when a page looks +// like another app, cleared when `confirmForeignOrigin` finds HealthLog. let foreignOrigin = false; -// One confirmation at a time: a burst of navigations must not fire a burst of -// probes, or race one probe's "HealthLog after all" against another's retire. +// One confirmation at a time, shared by a burst of navigations. let foreignOriginCheck = null; const MAX_STATIC_ENTRIES = 150; const MAX_PAGE_ENTRIES = 30; -const MAX_DATA_ENTRIES = 60; -// Safe-GET read allowlist. ONLY idempotent reads that render the core views -// and carry NO secret-shaped body. Auth, mutations and token endpoints are -// never listed — and `isCacheableApiResponse` is a second, body-level guard -// (mirrors the idempotency cache's `hlk_`/`hlr_`/`sk-` refusal) so a future -// endpoint that slipped onto the list can still never persist a secret. -// Matched by exact path or `/` / `?` prefix. -// v1.18.6 — AI/clinical narrative surfaces (`/api/insights`, `/api/analytics`) -// are deliberately NOT cached: `/api/insights` prefix-matched the Coach chat -// endpoint into the disk cache, and neither belongs on a self-hosted health -// PWA's durable storage. Only the dashboard snapshot, the widget layout, the -// measurement reads (incl. the batched daily series), the medication reads, -// and the version probe are eligible. -const API_READ_ALLOWLIST = [ - "/api/dashboard/snapshot", - // v1.37.20 — daily digest: the Today rail's offline read. Keep in - // lockstep with src/lib/pwa/sw-cache-policy.ts. - "/api/daily/digest", - "/api/dashboard/widgets", - "/api/measurements", - "/api/medications", - "/api/version", -]; - -// Defence in depth: even an allowlisted path is refused if its pathname looks -// like an auth/token/secret surface. -const API_DENY_RE = /\/(auth|tokens?|sessions?|login|password|webauthn)(\/|$|\?)/i; - -function isAllowlistedApiRead(pathname) { - if (API_DENY_RE.test(pathname)) return false; - return API_READ_ALLOWLIST.some( - (p) => - pathname === p || - pathname.startsWith(p + "/") || - pathname.startsWith(p + "?"), - ); -} - -// Body-level secret refusal: never persist a body carrying a token/secret- -// shaped pattern even if the path was allowlisted by mistake. -const SECRET_BODY_RE = /(hlk_|hlr_|sk-)[A-Za-z0-9_-]/; - -function isCacheableApiResponse(response, bodyText) { - if (!response || !response.ok) return false; - const cacheControl = response.headers.get("Cache-Control") || ""; - if (/no-store/i.test(cacheControl)) return false; - if (typeof bodyText === "string" && SECRET_BODY_RE.test(bodyText)) { - return false; - } - return true; -} - -// Public immutable assets to precache on install. Never include `/`: installing -// while signed in would fetch the authenticated Dashboard document with the -// browser's session cookies and persist that health-bearing HTML in -// CacheStorage for replay after logout. +// Never `/`: installed while signed in, it would store the dashboard HTML. const PRECACHE_URLS = ["/logo-192.png", "/logo-512.png", "/favicon.svg"]; -// ── Install: precache public immutable assets ──────────────────────────────── self.addEventListener("install", (event) => { event.waitUntil( caches .open(STATIC_CACHE) - .then(async (cache) => { - // An updated worker can reuse the same release-scoped cache when its - // source changes without a version bump. Remove a root document left - // by the previous worker before adding the safe public asset set. - await cache.delete("/"); - await cache.addAll(PRECACHE_URLS); - }) + .then((cache) => cache.addAll(PRECACHE_URLS)) .then(() => self.skipWaiting()), ); }); -// ── Activate: clean up old caches ──────────────────────────────────────────── self.addEventListener("activate", (event) => { event.waitUntil( Promise.all([ @@ -170,10 +63,8 @@ self.addEventListener("activate", (event) => { .map((k) => caches.delete(k)), ), ), - // Navigation preload lets the browser start the navigation request - // in parallel with service-worker startup; `networkFirst` consumes - // it via `event.preloadResponse`, shaving SW boot latency off every - // page navigation. Guarded — older engines lack the API. + // The browser starts the navigation while the worker boots; + // `networkFirst` uses `event.preloadResponse`. self.registration.navigationPreload ? self.registration.navigationPreload.enable() : Promise.resolve(), @@ -181,31 +72,17 @@ self.addEventListener("activate", (event) => { ); }); -// ── Fetch: strategy per resource type ──────────────────────────────────────── self.addEventListener("fetch", (event) => { - // The origin serves another app now (see `retireFromForeignOrigin`): no - // `respondWith`, no cache, the browser's own fetch for everything. if (foreignOrigin) return; const { request } = event; const url = new URL(request.url); - - // Only handle same-origin GET requests if (request.method !== "GET" || url.origin !== self.location.origin) return; - // One-shot auth navigations must reach the server EXACTLY ONCE. The OIDC - // login + callback endpoints are top-level browser navigations (not - // `fetch`/XHR), so with navigation preload enabled (see `activate`) the - // browser has ALREADY dispatched the request by the time this handler runs. - // Returning early WITHOUT `event.respondWith()` — the general `/api/` path - // below does exactly that — makes the browser ALSO run its own default - // navigation fetch, so the request is sent twice. The OIDC authorization - // code is single-use: the first callback redeems it and sets the session, - // the second fails at the IdP and redirects to - // `/auth/login?error=oidc_failed` on an otherwise-successful sign-in. - // Consuming the preload response here (or fetching once when there is none) - // settles the event with a single network request. These responses are - // never cached. + // The OIDC login and callback are navigations the browser has already sent + // as a preload. Declining here would make it send them a second time, and + // the single-use code fails on the second. Answer with the preload (or one + // fetch) and store nothing. if (url.pathname.startsWith("/api/auth/")) { event.respondWith( (async () => (await event.preloadResponse) || fetch(request))(), @@ -213,52 +90,28 @@ self.addEventListener("fetch", (event) => { return; } - // API calls. Allowlisted safe GET reads use network-first so the installed - // PWA always renders fresh server data online (and falls back to the last - // cached copy only when the network fails); everything else (auth, - // mutations, anything not on the list) stays network-only. - if (url.pathname.startsWith("/api/")) { - if (isAllowlistedApiRead(url.pathname)) { - event.respondWith(networkFirstApi(request)); - } - return; - } + // Every other API request goes to the network untouched: no API answer is + // kept on this device. + if (url.pathname.startsWith("/api/")) return; - // Next.js static assets — cache-first (immutable hashed filenames) - if (url.pathname.startsWith("/_next/static/")) { - event.respondWith(cacheFirst(request, STATIC_CACHE)); - return; - } - - // Locale-catalog boot script — cache-first. The URL is versioned by the - // catalogs' content hash (`/i18n/?v=`, `next.config.ts`), - // so a changed catalog is a new URL and cache-first is - // correct and keeps the catalog available on an offline relaunch (the - // cached shell HTML references the same versioned URL it was rendered - // with). Carries no user data — same public strings as the repository's - // messages/*.json. + // Locale catalog: the URL carries the catalogs' content hash, so a change + // is a new URL. Public strings only. if (url.pathname.startsWith("/i18n/")) { event.respondWith(cacheFirst(request, STATIC_CACHE)); return; } - // Static files (fonts, icons, images) — cache-first with long TTL if (/\.(png|svg|jpg|jpeg|gif|webp|ico|woff2?|ttf|eot)$/i.test(url.pathname)) { event.respondWith(cacheFirst(request, STATIC_CACHE)); return; } - // HTML pages — network-first with cache fallback. The whole event is - // passed so `networkFirst` can consume the navigation-preload response. if (request.headers.get("accept")?.includes("text/html")) { event.respondWith(networkFirst(event, PAGE_CACHE)); return; } }); -/** - * Cache-first: serve from cache, fall back to network and cache the response. - */ async function cacheFirst(request, cacheName) { const cached = await caches.match(request); if (cached) return cached; @@ -276,80 +129,13 @@ async function cacheFirst(request, cacheName) { } /** - * Network-first for allowlisted safe GET `/api/*` reads. - * - * Always tries the network first so an online caller gets the fresh server - * response — critical for read-after-write: a list fetched straight after a - * create/update must reflect the mutation, not a stale pre-mutation copy. On a - * cacheable response the data cache is refreshed behind it. Only when the - * network fails (offline) is the last cached copy served; with neither, a JSON - * 503 lets the client's TanStack Query cache / IndexedDB persister supply data. - * - * Caching is gated twice: `isAllowlistedApiRead` already filtered the path, - * and `isCacheableApiResponse` inspects the actual body so a `no-store` or - * secret-shaped (`hlk_`/`hlr_`/`sk-`) response is never persisted — the same - * refusal discipline the idempotency cache uses. - */ -async function networkFirstApi(request) { - - try { - const response = await fetch(request); - // Read the body once to body-screen it, then reconstruct a fresh Response - // so both the cache.put and the return value have an unconsumed body. - const bodyText = await response - .clone() - .text() - .catch(() => undefined); - if (isCacheableApiResponse(response, bodyText)) { - await bestEffortCacheWrite( - DATA_CACHE, - request, - new Response(bodyText, { - status: response.status, - statusText: response.statusText, - headers: response.headers, - }), - MAX_DATA_ENTRIES, - ); - } - return response; - } catch { - // Network failed (offline) — serve the last cached copy if we have one. - const cache = await caches.open(DATA_CACHE); - const cached = await cache.match(request); - if (cached) return cached; - - return new Response( - JSON.stringify({ data: null, error: "offline", meta: { offline: true } }), - { - status: 503, - headers: { "Content-Type": "application/json; charset=utf-8" }, - }, - ); - } -} - -/** - * Privacy gate for the navigation page cache. Most app routes are - * client-fetch-only shells with no server-rendered PII (health JSON loads - * over `/api/*`, which is network-only here), so caching their HTML is - * safe. Two carve-outs: - * - * 1. A `Cache-Control: no-store` response opts itself out — the - * principled, future-proof rule for any current/future server RSC - * that renders user data and sets the header. - * 2. `/c/*` (the clinician-share view) renders health values + wellness - * scores straight into the HTML and emits `no-store`; the explicit - * path skip is belt-and-braces so a revoked share can never linger in - * CacheStorage and render back offline. - * - * In practice rule 1 covers every signed-in page: `src/proxy.ts` pins - * `private, no-store` on all of them, because several server-prefetch one - * account's record into the HTML. Only the public pages (sign-in, legal) - * land in this cache, so a navigation to an app page without a connection - * gets the offline page below, never somebody's cached record. A page that - * is already open keeps working offline from the cached chunks and the - * allowlisted data reads. + * Which navigation responses may land in the page cache. Signed-in pages + * never do: the proxy sends them `private, no-store` because some carry one + * account's record in the HTML. Two paths are skipped by name as well: the + * clinician share view `/c/*` (no-store too; a revoked share must never + * render back offline) and `/onboarding/*`. What is left are the public + * pages (sign-in, legal), so a navigation to an app page without a + * connection gets the offline page, never somebody's cached record. */ function isCacheableNavigation(request, response) { const cacheControl = response.headers.get("Cache-Control") || ""; @@ -357,6 +143,11 @@ function isCacheableNavigation(request, response) { try { const { pathname } = new URL(request.url); if (pathname === "/c" || pathname.startsWith("/c/")) return false; + // Public to the proxy, so not no-store, but rendered for a signed-in + // account during its setup. + if (pathname === "/onboarding" || pathname.startsWith("/onboarding/")) { + return false; + } } catch { // Unparseable URL — fall through; the no-store check already ran. } @@ -364,30 +155,11 @@ function isCacheableNavigation(request, response) { } /** - * Does this navigation response come from something other than HealthLog? - * - * The worker is registered with scope `/` because HealthLog serves everything - * from `/`. When HealthLog is stopped and a different app starts on the same - * origin (the usual case is `localhost:3000` on a developer machine), this - * worker kept answering: `/_next/static/*` is cache-first, so the other app - * ran on HealthLog's cached chunks, and the only way out was unregistering by - * hand in the browser's developer tools. - * - * Only a response that positively looks like another app counts: - * - * - a redirect is opaque to the worker (`opaqueredirect`, status 0, no - * readable headers), and HealthLog redirects every signed-out page, so it - * proves nothing; status 0 fails the `ok` check below; - * - a non-2xx answer proves nothing either: a reverse proxy or auth gateway - * in front of a stopped HealthLog answers 502 or 401 without the marker, - * and unregistering there would also drop the Web Push subscription; - * - a network failure never reaches this check (it throws into the offline - * fallback in `networkFirst`). - * - * What is left is a successful page without the marker HealthLog's proxy puts - * on every page response. That is a suspicion, not a verdict: a reverse proxy - * with a response-header allowlist strips the marker from every genuine page. - * `confirmForeignOrigin` settles it before anything is deleted. + * Does this page come from another app on the same origin (a developer's + * `localhost:3000`, say)? Only a successful page without the proxy's marker + * counts: a redirect is opaque, and a 401 or 502 from a gateway in front of a + * stopped HealthLog proves nothing. Still only a suspicion, because a proxy + * with a header allowlist strips the marker; `confirmForeignOrigin` decides. */ function isForeignNavigationResponse(response) { if (!response || !response.ok) return false; @@ -395,30 +167,15 @@ function isForeignNavigationResponse(response) { } /** - * Is the origin positively not HealthLog? Asked of `/api/version`, which is - * public (on the proxy's `PUBLIC_PATHS` list, no session needed) and answers - * `{ data: { version, buildSha, ... } }`. A body check survives any proxy that - * rewrites headers. + * Is the origin positively not HealthLog? Asks the public `/api/version`, + * whose body (`data.version` a string, `data.buildSha` present, possibly + * null) survives any header rewriting. A 404, non-JSON or another shape is + * foreign; a thrown fetch, a 5xx, a 401 or a redirect proves nothing. * - * Retire only on a positive answer from something else: a 404, a 2xx that is - * not JSON (another app's HTML fallback), or JSON without the HealthLog shape. - * `buildSha` is `null` on an image not built by the release workflow, so the - * shape is "`version` is a string and `buildSha` is present", not "both are - * strings". Anything that is not an answer (a thrown fetch, a 5xx, a 401 from - * an auth gateway, a redirect) proves nothing, and the worker resumes normal - * service. - * - * One gateway shape still reads as "another app": a same-origin auth gateway - * that answers an expired session with its sign-in page and status 200 (nginx - * `auth_request` with `error_page 401 = /oauth2/sign_in` does this). Both the - * navigation and this probe then come back as HTML. The probe sends the - * gateway cookie (`credentials: "same-origin"`), so a valid gateway session - * reaches HealthLog; with an expired one the verdict is wrong, which is why - * `retireFromForeignOrigin` never unregisters while a push subscription exists. - * - * The probe is the worker's own `fetch`, which never passes through this - * worker's fetch handler; `no-store` keeps the HTTP cache out of it and - * `redirect: "manual"` keeps a login redirect from reading as an answer. + * An auth gateway that answers an expired session with a 200 sign-in page + * still reads as foreign, which is why `retireFromForeignOrigin` keeps a + * worker that holds a push subscription. The gateway cookie is sent, so a + * valid gateway session reaches HealthLog. */ async function confirmForeignOrigin() { let response; @@ -448,9 +205,7 @@ async function confirmForeignOrigin() { return !isHealthlog; } -/** - * Confirm, then either retire or resume. Shared by concurrent navigations. - */ +/** Confirm, then retire or resume. Shared by concurrent navigations. */ function checkForeignOrigin() { if (!foreignOriginCheck) { foreignOriginCheck = (async () => { @@ -464,8 +219,7 @@ function checkForeignOrigin() { await retireFromForeignOrigin(); return; } - // HealthLog after all, or no answer: serve normally again, and let a - // later suspicious navigation ask again. + // HealthLog after all, or no answer: resume, and ask again next time. foreignOrigin = false; foreignOriginCheck = null; })(); @@ -474,11 +228,9 @@ function checkForeignOrigin() { } /** - * Whether this registration holds a Web Push subscription. Unregistering - * destroys the subscription and nothing in the app re-creates it (the push - * card only reads it), so reminders would stop without notice. A missing - * `pushManager` or a throwing lookup counts as "has one": keeping a worker - * that only passes requests through costs nothing, losing reminders does. + * Whether this registration holds a Web Push subscription, which + * unregistering would destroy without notice. When unsure, yes: a + * pass-through worker costs nothing, lost reminders do. */ async function hasPushSubscription() { try { @@ -493,18 +245,11 @@ async function hasPushSubscription() { } /** - * Leave an origin that no longer serves HealthLog: delete every HealthLog - * cache (only ours, matched by name, never another app's CacheStorage) and - * unregister, so the next load of that origin runs without this worker. The - * `foreignOrigin` flag set by the caller stays set, so the requests the - * current page still makes go to the network. Each step is best-effort and - * independent: a failed cache delete must not keep the worker registered. - * - * With a push subscription the worker does not unregister: the verdict may - * be a gateway's 200 sign-in page (see `confirmForeignOrigin`), and - * unregistering would destroy the subscription. It deletes the caches and - * stays in pass-through for the rest of its life instead, so another app on - * the origin still gets network content. The next worker start probes again. + * Leave an origin that no longer serves HealthLog: delete HealthLog's caches + * (never another app's) and unregister. With a push subscription it stays + * registered in pass-through instead (`foreignOrigin` stays set), and the + * next worker start probes again. Each step is independent: a failed delete + * must not keep the worker registered. */ async function retireFromForeignOrigin() { try { @@ -515,7 +260,7 @@ async function retireFromForeignOrigin() { .map((k) => caches.delete(k)), ); } catch { - // CacheStorage unavailable; unregistering still matters more. + // CacheStorage unavailable; unregistering matters more. } if (await hasPushSubscription()) return; try { @@ -526,14 +271,11 @@ async function retireFromForeignOrigin() { } /** - * Network-first: try network (preferring the navigation-preload response - * when the browser already started it), fall back to cache. - * - * The offline fallback only serves a shell cached under the CURRENT - * `CACHE_VERSION` cache names. The previous global `caches.match()` could - * resolve from a stale pre-update cache in the activation gap and serve a - * shell whose `/_next/static/*` chunk graph no longer exists - * (`ChunkLoadError` on the first lazy navigation). + * Network-first for pages: the navigation-preload response when the browser + * already started it, else a fetch. Without a connection, a page from this + * release's page cache (only public pages are there), else the offline page. + * The lookup is scoped to this release's cache name: a page from an older + * release would reference chunks that no longer exist. */ async function networkFirst(event, cacheName) { const { request } = event; @@ -542,8 +284,7 @@ async function networkFirst(event, cacheName) { (event.preloadResponse ? await event.preloadResponse : null) || (await fetch(request)); if (isForeignNavigationResponse(response)) { - // Step aside at once (declining a request only sends it to the - // network), but delete nothing until the origin is confirmed foreign. + // Step aside at once; delete nothing until it is confirmed. foreignOrigin = true; event.waitUntil(checkForeignOrigin()); return response; @@ -560,28 +301,8 @@ async function networkFirst(event, cacheName) { } return response; } catch { - // Version-scoped fallback: the page cache first, then the precached - // app shell — both names embed CACHE_VERSION, so a stale shell from a - // previous release can never be served here. - const pageCache = await caches.open(cacheName); - const cachedPage = await pageCache.match(request); + const cachedPage = await (await caches.open(cacheName)).match(request); if (cachedPage) return cachedPage; - const staticCache = await caches.open(STATIC_CACHE); - const precached = await staticCache.match(request); - if (precached) return precached; - - // Offline fallback. F-7 (mobile security audit, 2026-05-16): the - // previous fallback rendered hard-coded German body copy, which is - // wrong for any en/* user reaching it offline. The replacement is - // language-neutral — wordmark + the universally understood - // "Offline" token + a generic retry hint expressed as an icon - // (the round-trip arrow), so the page does the right thing in any - // locale without shipping a translation bundle into the worker. - // - // v1.42 — the arrow is a real control now (a link to the same URL, - // 64 px), the page reloads by itself as soon as the connection is - // back, it follows the device's light or dark scheme, and it keeps - // clear of the notch and home indicator of an installed app. return new Response(OFFLINE_PAGE, { status: 503, headers: { "Content-Type": "text/html; charset=utf-8" }, @@ -589,6 +310,9 @@ async function networkFirst(event, cacheName) { } } +// Language-neutral, because the worker ships no catalog: the wordmark, the +// word "Offline" and a 64 px retry link. It reloads itself when the +// connection returns, follows the device scheme and keeps clear of the notch. const OFFLINE_PAGE = 'HealthLog — Offline