Merge branch 'fix/v1474-offline' into release/v1.47.4

# Conflicts:
#	src/__tests__/baselines/version-stamp-comments.json
This commit is contained in:
Marc-André Bombeck committed 2026-11-11 21:32:11 +01:00
commit 188d21d6ac
30 files changed
+813 -1319

No files matched your search

+1 -1
View File
@@ -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).
+19 -7
View File
@@ -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();
+39 -362
View File
@@ -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<string[]> {
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();
}
});
});
+1 -1
View File
@@ -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."
+1 -1
View File
@@ -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."
+1 -1
View File
@@ -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."
+1 -1
View File
@@ -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."
+1 -1
View File
@@ -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."
+1 -1
View File
@@ -452,7 +452,7 @@
"offlineBanner": {
"message": "연결이 없어요. 온라인으로 돌아올 때까지 저장할 수 없어요.",
"saveFailed": "저장하지 못했어요. 오프라인 상태예요. 온라인으로 돌아온 뒤 다시 시도해 주세요.",
"showingCached": "마지막으로 동기화한 데이터를 보여주고 있어요."
"stayOnPage": "이 페이지는 계속 볼 수 있어요. 다른 페이지는 온라인으로 돌아오면 열려요."
},
"demoBanner": {
"message": "데모 모드: 변경 내용은 저장되지 않아요."
+1 -1
View File
@@ -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."
+1 -1
View File
@@ -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."
+1 -1
View File
@@ -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."
+1 -1
View File
@@ -452,7 +452,7 @@
"offlineBanner": {
"message": "Нет подключения: изменения нельзя сохранить, пока вы снова не в сети.",
"saveFailed": "Не удалось сохранить, вы не в сети. Попробуйте снова, когда подключение вернётся.",
"showingCached": "Показаны последние синхронизированные данные."
"stayOnPage": "Эту страницу можно читать дальше, другие откроются, когда вы снова будете в сети."
},
"demoBanner": {
"message": "Деморежим: изменения не сохраняются."
+2 -10
View File
@@ -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" }
]
+103 -410
View File
@@ -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
// `<VersionPoller>` client component (mounted in `<Providers>`) 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 `<path>/` / `<path>?` 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/<locale>?v=<hash>`, `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 =
'<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="color-scheme" content="dark light"><title>HealthLog — Offline</title><style>' +
":root{--bg:#282a36;--fg:#f8f8f2;--accent:#bd93f9;--muted:#a4a9c9;color-scheme:dark}" +
@@ -600,10 +324,8 @@ const OFFLINE_PAGE =
'<script>addEventListener("online",function(){location.reload()})</script></body></html>';
/**
* Cache a successful network response without making CacheStorage
* availability part of the fetch contract. Quota, eviction, or trim failures
* are intentionally swallowed: caching may improve a later request, but it
* must never replace this request's already-successful network response.
* Store a response, then trim. Failures (quota, eviction) are swallowed: a
* cache write must never replace a response that already succeeded.
*/
async function bestEffortCacheWrite(
cacheName,
@@ -616,15 +338,11 @@ async function bestEffortCacheWrite(
await cache.put(request, response);
await trimCache(cacheName, maxEntries);
} catch {
// CacheStorage is an optional optimization.
// Optional.
}
}
/**
* Trim cache to maxEntries by removing oldest entries. `keys()` returns
* insertion order, so one read + a single pass over the excess prefix
* replaces the previous re-fetch-keys-per-deletion loop (O(n²) reads).
*/
/** Drop the oldest entries past `maxEntries`; `keys()` is insertion order. */
async function trimCache(cacheName, maxEntries) {
const cache = await caches.open(cacheName);
const keys = await cache.keys();
@@ -634,11 +352,8 @@ async function trimCache(cacheName, maxEntries) {
}
}
// ── App badge helper (PWA Badging API) ───────────────────────────────────────
// v1.18.4 — reflect the server-authoritative outstanding-dose count on the
// installed PWA icon. Feature-detected + best-effort: unsupported engines
// (most desktop Firefox, older Safari) silently no-op. A count of 0 clears the
// badge; a positive count sets it. `undefined`/non-number leaves it untouched.
// The outstanding-dose count on the app icon, where the Badging API exists.
// 0 clears it; anything that is not a number leaves it alone.
function applyAppBadge(count) {
if (typeof count !== "number" || !isFinite(count)) return;
try {
@@ -650,12 +365,10 @@ function applyAppBadge(count) {
self.navigator.clearAppBadge();
}
} catch {
// Badging API can reject (permission / unsupported) — never let it
// break the push handler.
// Never let the badge break the push handler.
}
}
// ── Push Notifications ───────────────────────────────────────────────────────
self.addEventListener("push", (event) => {
if (!event.data) return;
@@ -666,27 +379,6 @@ self.addEventListener("push", (event) => {
payload = { title: "HealthLog", body: event.data.text() };
}
// v1.18.4 — `type:"clear"` is the PWA equivalent of ending an iOS Live
// Activity: the server sends it when a dose is logged so the still-pending
// dose-due reminder for that slot is closed here (matched on its stable
// `tag`), and the app badge re-reflects the outstanding-dose count. No new
// notification is shown.
if (payload && payload.type === "clear") {
event.waitUntil(
(async () => {
const tagToClear = payload.tag;
if (tagToClear) {
const matches = await self.registration.getNotifications({
tag: tagToClear,
});
for (const n of matches) n.close();
}
applyAppBadge(payload.badge);
})(),
);
return;
}
const {
title = "HealthLog",
body = "",
@@ -701,12 +393,9 @@ self.addEventListener("push", (event) => {
self.registration.showNotification(title, {
body,
tag,
// `renotify` lets a re-fired reminder for the same `tag` re-alert the
// user instead of silently replacing the existing notification.
// A re-sent reminder with the same tag alerts again.
renotify: true,
// v1.18.4 — urgent events (the web-push sender sets this) keep the
// notification on screen until the user acts, where the browser
// honours it.
// Set by the sender for urgent events, where the browser honours it.
requireInteraction: requireInteraction === true,
icon: "/logo-192.png",
badge: "/logo-192.png",
@@ -720,12 +409,8 @@ self.addEventListener("push", (event) => {
self.addEventListener("notificationclick", (event) => {
event.notification.close();
// F-7 (mobile security audit, 2026-05-16): validate the destination
// resolves to the same origin before navigating any client. Push
// payloads are VAPID-signed by our own server, but a server-side bug
// (or compromised admin issuing pushes) could ship an off-origin URL
// into `data.url` and use the focused PWA as a redirect-driven phish.
// Reject anything that doesn't match our origin and fall back to "/".
// Only ever navigate within this origin: a server bug or a compromised
// sender must not turn a tap into a redirect elsewhere.
const rawUrl = event.notification.data?.url || "/";
let safeUrl = "/";
try {
@@ -737,17 +422,25 @@ self.addEventListener("notificationclick", (event) => {
safeUrl = "/";
}
const target = new URL(safeUrl, self.location.origin).href;
event.waitUntil(
self.clients
.matchAll({ type: "window", includeUncontrolled: true })
.then((clientList) => {
for (const client of clientList) {
if (client.url.includes(self.location.origin) && "focus" in client) {
client.navigate(safeUrl);
return client.focus();
}
}
return self.clients.openWindow(safeUrl);
const windows = clientList.filter(
(c) => c.url.startsWith(self.location.origin + "/") && "focus" in c,
);
// A window already on the target only needs focus: navigating it
// would reload the app and drop whatever is open there.
const there = windows.find((c) => c.url === target);
if (there) return there.focus();
const client = windows[0];
if (!client) return self.clients.openWindow(safeUrl);
// Focus first, while the tap still counts as user activation.
return client
.focus()
.then(() => client.navigate(safeUrl))
.catch(() => self.clients.openWindow(safeUrl));
}),
);
});
@@ -1,7 +1,7 @@
{
"$comment": "tests that read a source file by path, per test file under src/. Maintained by src/__tests__/test-realism-ratchet.test.ts.",
"count": 337,
"total": 337,
"count": 336,
"total": 336,
"entries": {
"__tests__/account-payload-consumer-guard.test.ts": 1,
"__tests__/admin-data-wipe-completeness.test.ts": 1,
@@ -334,7 +334,6 @@
"lib/modules/__tests__/surface-module-registry.test.ts": 1,
"lib/mood/__tests__/context-vocabulary.test.ts": 1,
"lib/notifications/__tests__/event-defaults.test.ts": 1,
"lib/pwa/__tests__/sw-cache-policy.test.ts": 1,
"lib/record-activity/__tests__/verb-map-covers-routes.test.ts": 1,
"lib/sharing/__tests__/record-session-fence.test.ts": 1,
"lib/sources/__tests__/source-priority-whoop-applehealth.test.ts": 1,
@@ -1,7 +1,7 @@
{
"$comment": "Comment lines that open with a release version, per file under src/. Maintained by src/__tests__/version-stamp-ratchet.test.ts.",
"count": 2890,
"total": 9215,
"count": 2885,
"total": 9198,
"entries": {
"__tests__/account-payload-consumer-guard.test.ts": 2,
"__tests__/acting-account-boundary-guard.test.ts": 7,
@@ -55,7 +55,6 @@
"__tests__/recurrence-course-anchor-guard.test.ts": 1,
"__tests__/relation-links-backup-completeness.test.ts": 1,
"__tests__/resolved-field-consumer-guard.test.ts": 1,
"__tests__/service-worker.test.ts": 2,
"__tests__/session-surface-guard.test.ts": 7,
"__tests__/settings-legacy-routes.test.ts": 1,
"__tests__/shared-record-navigation.test.tsx": 1,
@@ -1092,7 +1091,6 @@
"components/layout/__tests__/capture-picker-discard.test.tsx": 1,
"components/layout/__tests__/capture-picker.test.tsx": 1,
"components/layout/__tests__/nav-model.test.ts": 7,
"components/layout/__tests__/offline-banner.test.tsx": 3,
"components/layout/__tests__/shared-record-chrome.test.tsx": 1,
"components/layout/__tests__/sidebar-nav.test.tsx": 3,
"components/layout/account-switcher-menu.tsx": 1,
@@ -1100,7 +1098,6 @@
"components/layout/bottom-nav.tsx": 8,
"components/layout/capture-picker.tsx": 5,
"components/layout/nav-model.ts": 17,
"components/layout/offline-banner.tsx": 3,
"components/layout/record-session-fence-bridge.tsx": 1,
"components/layout/shared-record-banner.tsx": 1,
"components/layout/shared-record-grant-loss-bridge.tsx": 1,
@@ -1279,7 +1276,7 @@
"components/onboarding/welcome-screen.tsx": 1,
"components/profile/__tests__/height-entry-surfaces.test.tsx": 1,
"components/profile/height-field-control.tsx": 1,
"components/providers.tsx": 3,
"components/providers.tsx": 2,
"components/records/about-me-note-manager.tsx": 3,
"components/records/ai-profile-inclusion-manager.tsx": 1,
"components/records/allergy-form.tsx": 1,
@@ -2678,10 +2675,8 @@
"lib/profile/life-circumstances.ts": 1,
"lib/profile/life-derived.ts": 1,
"lib/profile/life-report-rows.ts": 1,
"lib/pwa/__tests__/sw-cache-policy.test.ts": 3,
"lib/pwa/query-client-options.ts": 1,
"lib/pwa/query-persister.ts": 3,
"lib/pwa/sw-cache-policy.ts": 2,
"lib/pwa/query-persister.ts": 2,
"lib/queries/__tests__/use-achievements-query.test.tsx": 1,
"lib/queries/__tests__/use-dashboard-snapshot.test.tsx": 4,
"lib/queries/__tests__/use-medication-compliance-summary.test.ts": 1,
+169 -151
View File
@@ -1,19 +1,20 @@
/**
* v1.15.20 — service-worker cache behaviour, evaluated in a `vm` sandbox.
* Service-worker behaviour, evaluated in a `vm` sandbox.
*
* `public/sw.js` is plain script (no module system), so the test boots it
* inside a vm context with a fake CacheStorage and dispatches the captured
* event listeners. Four behaviours are pinned:
* event listeners. Pinned here:
*
* 1. cache write and trim failures never replace a successful network
* response for API, navigation, or static-asset requests;
* 2. the offline HTML fallback only serves a shell cached under the
* CURRENT `CACHE_VERSION` cache names (a stale pre-update shell would
* reference a chunk graph that no longer exists);
* 3. `activate` enables navigation preload and `networkFirst` consumes
* `event.preloadResponse` when the browser supplies it;
* 4. `trimCache` reads the key list once and deletes the excess prefix
* in a single pass (the previous loop re-fetched all keys per delete).
* 1. API requests and `/_next/static/` chunks go to the network untouched,
* and nothing of them lands in CacheStorage;
* 2. cache write and trim failures never replace a successful network
* response for navigation or static-asset requests;
* 3. the offline HTML fallback only serves a page cached under the
* CURRENT `CACHE_VERSION` cache names;
* 4. `activate` deletes every other HealthLog cache, enables navigation
* preload, and `networkFirst` consumes `event.preloadResponse`;
* 5. `trimCache` reads the key list once and deletes the excess prefix
* in a single pass.
*
* A HealthLog page response carries the `X-HealthLog-Page` marker the proxy
* sets, so the navigation fixtures below build pages with `healthlogPage()`.
@@ -41,7 +42,10 @@ const FALLBACK_VERSION = /\/\* @sw-version-fallback \*\/\s*"(v[^"]*)"/.exec(
)![1];
const CURRENT_PAGE_CACHE = `healthlog-pages-${FALLBACK_VERSION}`;
const CURRENT_STATIC_CACHE = `healthlog-static-${FALLBACK_VERSION}`;
const CURRENT_DATA_CACHE = `healthlog-data-${FALLBACK_VERSION}`;
// The API cache older releases kept, under the current version's name.
const LEGACY_DATA_CACHE = `healthlog-data-${FALLBACK_VERSION}`;
// A cache-first static asset: the locale catalog boot script.
const CATALOG = "/i18n/en.js?v=abc123";
const PAGE_MARKER = "X-HealthLog-Page";
@@ -154,8 +158,8 @@ function bootServiceWorker(): SwHarness {
navPreload.enabled = true;
},
};
// v1.18.4 — push-handler fakes: a notification store the `getNotifications`
// / `showNotification` calls read/write, and a Badging-API spy.
// Push-handler fakes: the notifications `showNotification` shows, and a
// Badging-API spy.
const shown: Array<{ title: string; tag?: string; closed: boolean }> = [];
const badge = { value: undefined as number | undefined, cleared: false };
const selfObj = {
@@ -176,14 +180,6 @@ function bootServiceWorker(): SwHarness {
showNotification: async (title: string, opts: { tag?: string }) => {
shown.push({ title, tag: opts?.tag, closed: false });
},
getNotifications: async ({ tag }: { tag?: string }) =>
shown
.filter((n) => !n.closed && (tag === undefined || n.tag === tag))
.map((n) => ({
close: () => {
n.closed = true;
},
})),
},
navigator: {
setAppBadge: (n: number) => {
@@ -277,18 +273,6 @@ function dispatchNavigationFetch(
return captured;
}
function dispatchApiFetch(harness: SwHarness, path: string): Promise<Response> {
let captured: Promise<Response> | null = null;
harness.listeners.get("fetch")!({
request: new Request(`${ORIGIN}${path}`),
respondWith: (p: Promise<Response>) => {
captured = p;
},
});
if (!captured) throw new Error("fetch handler did not respond");
return captured;
}
function dispatchAssetFetch(
harness: SwHarness,
path: string,
@@ -386,43 +370,37 @@ describe("sw.js — one-shot auth navigations", () => {
await dispatchAuthNavigation(harness, url).response;
await Promise.all(harness.lifetimePromises);
const pages = await harness.cacheStorage.open(CURRENT_PAGE_CACHE);
expect(await pages.match(`${ORIGIN}${url}`)).toBeUndefined();
const data = await harness.cacheStorage.open(CURRENT_DATA_CACHE);
expect(await data.match(`${ORIGIN}${url}`)).toBeUndefined();
expect(await harness.cacheStorage.match(`${ORIGIN}${url}`)).toBeUndefined();
});
});
describe("sw.js — what stays off the device", () => {
it.each([
"/api/dashboard/snapshot",
"/api/measurements?type=WEIGHT",
"/api/medications",
"/api/daily/digest",
"/api/version",
"/_next/static/chunks/app.js",
])("leaves %s to the network and stores nothing", async (path) => {
const harness = bootServiceWorker();
let fetchCalls = 0;
harness.context.fetch = async () => {
fetchCalls += 1;
return new Response(JSON.stringify({ data: { weightKg: 80 } }));
};
const { responded } = dispatchAnyFetch(harness, path);
await Promise.all(harness.lifetimePromises);
// Declined: the browser fetches it itself, the worker never sees the body.
expect(responded).toBe(false);
expect(fetchCalls).toBe(0);
expect(harness.cacheStorage.stores.size).toBe(0);
});
});
describe("sw.js — best-effort cache writes", () => {
it("returns the original successful API response when cache.put rejects", async () => {
const harness = bootServiceWorker();
const dataCache = await harness.cacheStorage.open(CURRENT_DATA_CACHE);
dataCache.putError = new Error("CacheStorage quota exceeded");
const networkResponse = new Response(
JSON.stringify({ data: { weightKg: 80 }, error: null }),
{
status: 200,
headers: {
"Content-Type": "application/json",
"X-Network-Response": "original",
},
},
);
harness.context.fetch = async () => networkResponse;
const response = await dispatchApiFetch(
harness,
"/api/measurements?type=WEIGHT",
);
expect(response).toBe(networkResponse);
expect(response.status).toBe(200);
expect(response.headers.get("X-Network-Response")).toBe("original");
expect(await response.text()).toBe(
JSON.stringify({ data: { weightKg: 80 }, error: null }),
);
});
it("returns the original successful navigation response when cache.put rejects", async () => {
const harness = bootServiceWorker();
const pageCache = await harness.cacheStorage.open(CURRENT_PAGE_CACHE);
@@ -477,39 +455,16 @@ describe("sw.js — best-effort cache writes", () => {
const harness = bootServiceWorker();
const staticCache = await harness.cacheStorage.open(CURRENT_STATIC_CACHE);
staticCache.putError = new Error("CacheStorage quota exceeded");
const networkResponse = new Response("immutable chunk", {
const networkResponse = new Response("immutable catalog", {
headers: { "X-Network-Response": "original" },
});
harness.context.fetch = async () => networkResponse;
const response = await dispatchAssetFetch(
harness,
"/_next/static/chunks/app.js",
);
const response = await dispatchAssetFetch(harness, CATALOG);
expect(response).toBe(networkResponse);
expect(response.headers.get("X-Network-Response")).toBe("original");
expect(await response.text()).toBe("immutable chunk");
});
it("returns the original successful API response when cache trimming rejects", async () => {
const harness = bootServiceWorker();
const dataCache = await harness.cacheStorage.open(CURRENT_DATA_CACHE);
dataCache.keysError = new Error("CacheStorage keys unavailable");
const networkResponse = new Response(
JSON.stringify({ data: { weightKg: 80 }, error: null }),
{ headers: { "Content-Type": "application/json" } },
);
harness.context.fetch = async () => networkResponse;
const response = await dispatchApiFetch(harness, "/api/measurements");
expect(response).toBe(networkResponse);
expect(response.status).toBe(200);
expect(await response.text()).toBe(
JSON.stringify({ data: { weightKg: 80 }, error: null }),
);
expect(dataCache.keysCalls).toBe(1);
expect(await response.text()).toBe("immutable catalog");
});
});
@@ -519,13 +474,16 @@ describe("sw.js — activate", () => {
const stale = await harness.cacheStorage.open("healthlog-pages-v0.0.1");
await stale.put(`${ORIGIN}/`, new Response("stale shell"));
await harness.cacheStorage.open(CURRENT_PAGE_CACHE);
// API answers an older worker kept, under this version's name and an old one.
await harness.cacheStorage.open(LEGACY_DATA_CACHE);
await harness.cacheStorage.open("healthlog-data-v0.0.1");
await harness.cacheStorage.open("next-app-runtime");
await dispatchActivate(harness);
expect(harness.cacheStorage.stores.has("healthlog-pages-v0.0.1")).toBe(
false,
expect([...harness.cacheStorage.stores.keys()].sort()).toEqual(
[CURRENT_PAGE_CACHE, "next-app-runtime"].sort(),
);
expect(harness.cacheStorage.stores.has(CURRENT_PAGE_CACHE)).toBe(true);
expect(harness.navPreload.enabled).toBe(true);
});
});
@@ -590,15 +548,6 @@ describe("sw.js — networkFirst offline fallback", () => {
expect(await res.text()).toBe("current shell");
});
it("falls back to the current-version precached shell when the page cache misses", async () => {
const harness = bootServiceWorker();
const statics = await harness.cacheStorage.open(CURRENT_STATIC_CACHE);
await statics.addAll(["/"]);
const res = await dispatchNavigationFetch(harness, "/");
expect(await res.text()).toBe("precached:/");
});
it("consumes the navigation-preload response instead of re-fetching", async () => {
const harness = bootServiceWorker();
let fetchCalls = 0;
@@ -664,6 +613,22 @@ describe("sw.js — networkFirst privacy gate", () => {
expect(await pages.match(`${ORIGIN}/c/hls_abc123`)).toBeUndefined();
});
it.each(["/onboarding", "/onboarding/who"])(
"does not cache the signed-in onboarding page %s",
async (path) => {
const harness = bootServiceWorker();
harness.context.fetch = async () => healthlogPage("onboarding step");
const res = await dispatchNavigationFetch(harness, path);
expect(await res.clone().text()).toBe("onboarding step");
await Promise.all(harness.lifetimePromises);
expect(
await harness.cacheStorage.match(`${ORIGIN}${path}`),
).toBeUndefined();
},
);
it("still caches an ordinary navigation response", async () => {
const harness = bootServiceWorker();
harness.context.fetch = async () => healthlogPage("app shell");
@@ -734,10 +699,7 @@ const foreignHtml = () =>
async function seedHealthlogCaches(harness: SwHarness): Promise<void> {
const statics = await harness.cacheStorage.open(CURRENT_STATIC_CACHE);
await statics.put(
`${ORIGIN}/_next/static/chunks/app.js`,
new Response("healthlog chunk"),
);
await statics.put(`${ORIGIN}${CATALOG}`, new Response("healthlog catalog"));
const pages = await harness.cacheStorage.open(CURRENT_PAGE_CACHE);
await pages.put(`${ORIGIN}/`, healthlogPage("healthlog shell"));
const legacy = await harness.cacheStorage.open("healthlog-data-v0.0.1");
@@ -759,9 +721,9 @@ describe("sw.js — foreign origin (#847)", () => {
expect(await res.text()).toBe("fresh shell");
expect(harness.unregisterCalls.count).toBe(0);
expect(harness.cacheStorage.stores.has(CURRENT_STATIC_CACHE)).toBe(true);
const asset = dispatchAnyFetch(harness, "/_next/static/chunks/app.js");
const asset = dispatchAnyFetch(harness, CATALOG);
expect(asset.responded).toBe(true);
expect(await (await asset.response!).text()).toBe("healthlog chunk");
expect(await (await asset.response!).text()).toBe("healthlog catalog");
});
it("retires when the page lacks the marker and the version probe finds another app's HTML", async () => {
@@ -775,9 +737,7 @@ describe("sw.js — foreign origin (#847)", () => {
// The other app's page is returned untouched, and the worker declines
// requests at once, before the probe has answered.
expect(res).toBe(foreignPage);
expect(
dispatchAnyFetch(harness, "/_next/static/chunks/app.js").responded,
).toBe(false);
expect(dispatchAnyFetch(harness, CATALOG).responded).toBe(false);
await Promise.all(harness.lifetimePromises);
@@ -790,9 +750,7 @@ describe("sw.js — foreign origin (#847)", () => {
// Still declining after the retire: static, HTML and API all go to the
// network through the browser.
expect(
dispatchAnyFetch(harness, "/_next/static/chunks/app.js").responded,
).toBe(false);
expect(dispatchAnyFetch(harness, CATALOG).responded).toBe(false);
expect(
dispatchAnyFetch(harness, "/about", { accept: "text/html" }).responded,
).toBe(false);
@@ -877,10 +835,10 @@ describe("sw.js — foreign origin (#847)", () => {
expect(harness.unregisterCalls.count).toBe(0);
expect(harness.cacheStorage.stores.has(CURRENT_STATIC_CACHE)).toBe(true);
// Normal service resumed: the cached chunk is served cache-first again.
const asset = dispatchAnyFetch(harness, "/_next/static/chunks/app.js");
// Normal service resumed: the cached catalog is served cache-first again.
const asset = dispatchAnyFetch(harness, CATALOG);
expect(asset.responded).toBe(true);
expect(await (await asset.response!).text()).toBe("healthlog chunk");
expect(await (await asset.response!).text()).toBe("healthlog catalog");
});
it.each([
@@ -905,9 +863,7 @@ describe("sw.js — foreign origin (#847)", () => {
expect(harness.unregisterCalls.count).toBe(0);
expect(harness.cacheStorage.stores.has(CURRENT_STATIC_CACHE)).toBe(true);
expect(
dispatchAnyFetch(harness, "/_next/static/chunks/app.js").responded,
).toBe(true);
expect(dispatchAnyFetch(harness, CATALOG).responded).toBe(true);
},
);
@@ -970,9 +926,7 @@ describe("sw.js — foreign origin (#847)", () => {
expect([...harness.cacheStorage.stores.keys()]).toEqual([
"next-app-runtime",
]);
expect(
dispatchAnyFetch(harness, "/_next/static/chunks/app.js").responded,
).toBe(false);
expect(dispatchAnyFetch(harness, CATALOG).responded).toBe(false);
expect(
dispatchAnyFetch(harness, "/about", { accept: "text/html" }).responded,
).toBe(false);
@@ -1056,9 +1010,7 @@ describe("sw.js — foreign origin (#847)", () => {
expect(res).toBe(response);
expect(harness.unregisterCalls.count).toBe(0);
expect(
dispatchAnyFetch(harness, "/_next/static/chunks/app.js").responded,
).toBe(true);
expect(dispatchAnyFetch(harness, CATALOG).responded).toBe(true);
});
it("does not treat an opaque redirect (a signed-out HealthLog page) as foreign", async () => {
@@ -1127,7 +1079,7 @@ describe("sw.js — trimCache", () => {
});
});
// ── push handler (v1.18.4: clear-on-taken tag close + app badge) ─────────────
// ── push handler ─────────────────────────────────────────────────────────────
async function dispatchPush(harness: SwHarness, data: unknown): Promise<void> {
let settled: Promise<unknown> = Promise.resolve();
harness.listeners.get("push")!({
@@ -1164,36 +1116,102 @@ describe("sw.js — push handler", () => {
expect(shown[0].tag).toBe(tag);
expect(badge.value).toBe(3);
});
});
it("a type:clear push closes the matching-tag notification (no new one) and updates the badge", async () => {
// ── notification tap ─────────────────────────────────────────────────────────
interface FakeWindow {
url: string;
focused: number;
navigatedTo: string[];
focus: () => Promise<FakeWindow>;
navigate: (url: string) => Promise<FakeWindow>;
}
function fakeWindow(path: string, navigateFails = false): FakeWindow {
const win: FakeWindow = {
url: `${ORIGIN}${path}`,
focused: 0,
navigatedTo: [],
focus: async () => {
win.focused += 1;
return win;
},
navigate: async (url: string) => {
if (navigateFails) throw new TypeError("not controlled");
win.navigatedTo.push(url);
return win;
},
};
return win;
}
async function tapNotification(
harness: SwHarness,
windows: FakeWindow[],
url: string,
): Promise<string[]> {
const opened: string[] = [];
(harness.context.self as { clients: unknown }).clients = {
claim: async () => {},
matchAll: async () => windows,
openWindow: async (target: string) => {
opened.push(target);
return null;
},
};
let settled: Promise<unknown> = Promise.resolve();
harness.listeners.get("notificationclick")!({
notification: { close: () => {}, data: { url } },
waitUntil: (p: Promise<unknown>) => {
settled = p;
},
});
await settled;
return opened;
}
describe("sw.js — notification tap", () => {
it("only focuses a window that is already on the target", async () => {
const harness = bootServiceWorker();
const { shown, badge } = swFakes(harness);
const tag = "med:med-1:2026-06-18T07:00:00.000Z";
const win = fakeWindow("/medications");
await dispatchPush(harness, { title: "dose", tag, badge: 1 });
expect(shown.filter((n) => !n.closed)).toHaveLength(1);
const opened = await tapNotification(harness, [win], "/medications");
await dispatchPush(harness, { type: "clear", tag, badge: 0 });
// The pending reminder for that slot is closed; no new notification shown.
expect(shown).toHaveLength(1);
expect(shown[0].closed).toBe(true);
// badge: 0 clears the app badge.
expect(badge.cleared).toBe(true);
expect(win.focused).toBe(1);
expect(win.navigatedTo).toEqual([]);
expect(opened).toEqual([]);
});
it("a type:clear push only closes its own slot's tag", async () => {
it("prefers the window on the target over the first one", async () => {
const harness = bootServiceWorker();
const { shown } = swFakes(harness);
const other = fakeWindow("/");
const there = fakeWindow("/mood?add=1");
await dispatchPush(harness, { title: "a", tag: "med:a:t1" });
await dispatchPush(harness, { title: "b", tag: "med:b:t2" });
await tapNotification(harness, [other, there], "/mood?add=1");
await dispatchPush(harness, { type: "clear", tag: "med:a:t1" });
expect(there.focused).toBe(1);
expect(other.focused).toBe(0);
expect(other.navigatedTo).toEqual([]);
});
const a = shown.find((n) => n.tag === "med:a:t1")!;
const b = shown.find((n) => n.tag === "med:b:t2")!;
expect(a.closed).toBe(true);
expect(b.closed).toBe(false);
it("focuses and navigates a window that is elsewhere", async () => {
const harness = bootServiceWorker();
const win = fakeWindow("/");
const opened = await tapNotification(harness, [win], "/medications");
expect(win.focused).toBe(1);
expect(win.navigatedTo).toEqual(["/medications"]);
expect(opened).toEqual([]);
});
it("opens a window when none is open or navigating fails", async () => {
const harness = bootServiceWorker();
expect(await tapNotification(harness, [], "/medications")).toEqual([
"/medications",
]);
expect(
await tapNotification(harness, [fakeWindow("/", true)], "/medications"),
).toEqual(["/medications"]);
});
});
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { surfaceModule } from "@/lib/modules/surface";
/**
* F-7 (mobile security audit, 2026-05-16): three regressions to lock
* in for `public/sw.js`.
@@ -107,3 +109,25 @@ describe("public/manifest.json PWA identity hygiene (F-7, 2026-05-16)", () => {
expect(manifest.start_url).toBe("/");
});
});
describe("public/manifest.json shortcuts", () => {
const manifest = JSON.parse(readFileSync(MANIFEST_PATH, "utf-8")) as {
shortcuts: Array<{ name: string; url: string }>;
};
it("open only pages no module can switch off", () => {
// The manifest is static: a shortcut into a module would open the
// "switched off" notice for everyone who turned that module off.
expect(manifest.shortcuts.length).toBeGreaterThan(0);
for (const { name, url } of manifest.shortcuts) {
const { pathname } = new URL(url, "https://app.example");
expect(surfaceModule(`nav:${pathname}`), name).toBeUndefined();
}
});
it("carry no query parameter the app does not read", () => {
for (const { name, url } of manifest.shortcuts) {
expect(url, name).not.toContain("source=");
}
});
});
+10
View File
@@ -724,6 +724,16 @@ body,
}
}
/*
* The installed iOS app runs with `black-translucent` (`layout.tsx`), which
* always draws the clock and battery in white. Over the light theme's card
* colour they disappear, so the light theme paints the strip in its dark
* ink instead.
*/
:root.light .shell-safe-area {
background-image: linear-gradient(var(--foreground), var(--foreground));
}
/*
* The on-screen keyboard. iOS Safari, and Chrome on Android by default,
* shrink only the visual viewport when the keyboard opens: everything
@@ -1,5 +1,5 @@
/**
* v1.4.43 — `<OfflineBanner>` SSR contract.
* `<OfflineBanner>` SSR contract and copy.
*
* The banner reads `navigator.onLine` + subscribes to `online`/`offline`
* window events inside a `useEffect`. SSR markup is therefore always
@@ -13,7 +13,6 @@ import { join } from "node:path";
import { describe, it, expect } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import { OfflineBanner } from "../offline-banner";
@@ -22,20 +21,16 @@ const ROOT = join(__dirname, "../../../..");
const SHELL_PATH = join(ROOT, "src/components/layout/auth-shell.tsx");
const BANNER_PATH = join(ROOT, "src/components/layout/offline-banner.tsx");
function loadMessages(locale: string): { offlineBanner: { message: string } } {
function loadMessages(locale: string): {
offlineBanner: { message: string; stayOnPage: string };
} {
const path = join(ROOT, "messages", `${locale}.json`);
return JSON.parse(readFileSync(path, "utf8"));
}
function render(node: React.ReactNode, locale: "en" | "de" = "en") {
// v1.18.6 — the banner now reads the cached dashboard snapshot to decide
// whether to append the "showing last synced data" hint, so it needs a
// QueryClient in context.
const queryClient = new QueryClient();
return renderToStaticMarkup(
<QueryClientProvider client={queryClient}>
<I18nProvider initialLocale={locale}>{node}</I18nProvider>
</QueryClientProvider>,
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
);
}
@@ -65,6 +60,16 @@ describe("<OfflineBanner>", () => {
);
});
it("says what still works: the open page, not the rest of the app", () => {
// The banner used to promise "your last synced data" although one tap
// on another page ended on the worker's offline page.
const en = loadMessages("en");
expect(en.offlineBanner.stayOnPage).toBe(
"This page stays readable; other pages open once you're back online.",
);
expect(en.offlineBanner).not.toHaveProperty("showingCached");
});
it("ships the message key in every supported locale", () => {
for (const locale of [
"en",
@@ -76,9 +81,11 @@ describe("<OfflineBanner>", () => {
"ko",
"nl",
"pt-BR",
"ru",
] as const) {
const m = loadMessages(locale);
expect(m.offlineBanner.message.length, locale).toBeGreaterThan(0);
expect(m.offlineBanner.stayOnPage.length, locale).toBeGreaterThan(0);
}
});
@@ -89,12 +96,10 @@ describe("<OfflineBanner>", () => {
});
});
// v1.4.43 — also pin the client-side branch: when
// `isOnline === false` the banner paints with the i18n message,
// the WifiOff icon, and the `role="status"` aria-live region. We
// can't easily fire window events from a node-environment vitest
// suite, but we can read the component source and assert the
// branch carries the expected affordances.
// The client-side branch: when `isOnline === false` the banner paints with
// the i18n message, the WifiOff icon, and the `role="status"` aria-live
// region. Window events cannot fire in this node-environment suite, so the
// branch is read from the source.
describe("<OfflineBanner> rendered branch (source-level)", () => {
const source = readFileSync(BANNER_PATH, "utf8");
+29 -43
View File
@@ -2,37 +2,28 @@
import { useEffect, useState } from "react";
import { WifiOff } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { isOfflineNavigationClick } from "@/lib/pwa/offline-navigation";
/**
* v1.4.43 — slim banner that surfaces "you're offline" while
* `navigator.onLine` reads false. The PWA service worker already
* serves the read paths from cache (`public/sw.js`), but pre-fix a
* user toggling airplane mode mid-form-fill saw blank tiles and no
* explanation. This banner closes the explanation gap.
* The strip that says the connection is down, and the guard that keeps the
* open page while it is.
*
* Mount strategy: rendered once at the top of `<AuthShell>` so every
* authenticated route inherits it. The component is mount-time SSR-
* safe — it never paints during the initial server render (the
* `online`/`offline` window events only fire client-side); a `useEffect`
* subscribes to the events once and toggles the visible state from
* there. Honours `prefers-reduced-motion` via the absence of any
* animation.
* Signed-in pages are never cached, so a navigation without a connection ends
* on the service worker's offline page and drops the page that was still
* readable. While the browser is offline, a tap on a link to another page of
* the app stays where it is and repeats the hint in a toast.
*
* Copy lives in `messages/*.json` under `offlineBanner.message`; all
* six locales ship today.
* Rendered once at the top of `<AuthShell>`. Hidden during SSR and the first
* client render (no hydration mismatch); the effect reads `navigator.onLine`
* after mount.
*/
export function OfflineBanner() {
const { t } = useTranslations();
const queryClient = useQueryClient();
// Initialise to `true` so the banner stays hidden during SSR + the
// first client render. The effect below flips it true/false after
// mount based on `navigator.onLine`. (We do NOT read navigator on
// the very first render to keep the SSR markup hydration-stable.)
const [isOnline, setIsOnline] = useState(true);
const stayOnPage = t("offlineBanner.stayOnPage");
useEffect(() => {
function handleOnline() {
@@ -41,17 +32,10 @@ export function OfflineBanner() {
function handleOffline() {
setIsOnline(false);
}
// Subscribe to the live transition events; both handlers route
// through the React setState pathway via the listener callback
// rather than a synchronous in-effect setState so the strict
// `react-hooks/set-state-in-effect` rule stays happy.
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
// Sync the initial state from `navigator.onLine` — deferred to a
// microtask so React sees this as an external-system bridge
// rather than a render-cascade setState. The legacy in-effect
// setState path tripped the strict lint rule, the queueMicrotask
// shape is the documented escape hatch.
// Deferred so the initial read is an external-system bridge, not a
// synchronous setState in the effect body.
queueMicrotask(() => {
if (typeof navigator !== "undefined" && navigator.onLine === false) {
setIsOnline(false);
@@ -63,18 +47,21 @@ export function OfflineBanner() {
};
}, []);
if (isOnline) return null;
useEffect(() => {
// Capture phase on `window`: runs before React's handlers on the
// document, so `next/link` sees the prevented default and stays put.
function keepOpenPage(event: MouseEvent) {
if (!isOfflineNavigationClick(event, window.location, navigator.onLine)) {
return;
}
event.preventDefault();
toast(stayOnPage, { id: "offline-navigation" });
}
window.addEventListener("click", keepOpenPage, true);
return () => window.removeEventListener("click", keepOpenPage, true);
}, [stayOnPage]);
// v1.18.6 — when an offline install is showing last-synced data (the SW's
// allowlisted read cache + the IndexedDB query persister hydrated the
// dashboard snapshot), say so honestly rather than implying a blank screen.
// v1.21.3 (b) — the snapshot cell is now locale-keyed, so match on the
// `["dashboard","snapshot"]` PREFIX (`getQueriesData`) rather than the
// exact zero-arg slot — any hydrated locale's snapshot proves cached data
// is present.
const hasCachedData = queryClient
.getQueriesData({ queryKey: queryKeys.dashboardSnapshot() })
.some(([, data]) => data != null);
if (isOnline) return null;
return (
<div
@@ -85,8 +72,7 @@ export function OfflineBanner() {
>
<WifiOff className="size-3.5 shrink-0" aria-hidden="true" />
<span className="text-center">
{t("offlineBanner.message")}
{hasCachedData ? ` ${t("offlineBanner.showingCached")}` : ""}
{t("offlineBanner.message")} {stayOnPage}
</span>
</div>
);
+8 -8
View File
@@ -278,18 +278,18 @@ function QueryVisibilityRefreshBridge() {
return null;
}
// ── Offline query persistence ────────────────────────
// ── Dashboard snapshot persistence ───────────────────
//
// v1.18.6 — hydrate the last-synced query cache from IndexedDB before the
// first authenticated paint, then debounce-persist successful reads back.
// Combined with the service worker's allowlisted stale-while-revalidate API
// branch, an installed PWA opened offline renders last-known data instead of
// empty skeletons. Build-version + age gated; cleared on logout.
// Fill the dashboard reads from the IndexedDB snapshot as a warm start, then
// debounce-persist them back. The restore waits for `/api/auth/me`: the
// snapshot belongs to one account, and only a known account can be compared
// with its owner. Build-version + age gated; cleared at every session end.
function QueryPersistenceBridge() {
const queryClient = useQueryClient();
const transition = useRecordSessionTransition();
const userId = useAuth().user?.id ?? null;
useEffect(() => {
if (transition.phase !== "ready") return;
if (transition.phase !== "ready" || userId === null) return;
let stop: (() => void) | undefined;
let cancelled = false;
void restorePersistedQueryCache(
@@ -305,7 +305,7 @@ function QueryPersistenceBridge() {
cancelled = true;
stop?.();
};
}, [queryClient, transition.phase]);
}, [queryClient, transition.phase, userId]);
return null;
}
@@ -0,0 +1,96 @@
import { describe, expect, it } from "vitest";
import { isOfflineNavigationClick } from "@/lib/pwa/offline-navigation";
const HERE = {
origin: "https://app.example",
pathname: "/medications",
search: "",
};
interface AnchorInit {
href: string;
target?: string;
download?: boolean;
}
/** A click on an element inside an anchor, the way a nav icon is tapped. */
function clickOn(
anchor: AnchorInit | null,
overrides: Partial<Parameters<typeof isOfflineNavigationClick>[0]> = {},
) {
const link = anchor && {
href: new URL(anchor.href, HERE.origin).href,
target: anchor.target ?? "",
hasAttribute: (name: string) => name === "download" && !!anchor.download,
};
return {
defaultPrevented: false,
button: 0,
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
target: {
closest: (selector: string) => (selector === "a[href]" ? link : null),
} as unknown as EventTarget,
...overrides,
};
}
describe("isOfflineNavigationClick", () => {
it("holds a tap on a link to another page while offline", () => {
expect(isOfflineNavigationClick(clickOn({ href: "/" }), HERE, false)).toBe(
true,
);
expect(
isOfflineNavigationClick(
clickOn({ href: "/measurements?add=WEIGHT" }),
HERE,
false,
),
).toBe(true);
// Same path, different query: a different page for the router.
expect(
isOfflineNavigationClick(
clickOn({ href: "/medications?tab=history" }),
HERE,
false,
),
).toBe(true);
});
it("lets every link through while online", () => {
expect(isOfflineNavigationClick(clickOn({ href: "/" }), HERE, true)).toBe(
false,
);
});
it("leaves links within the open page alone", () => {
expect(
isOfflineNavigationClick(
clickOn({ href: "/medications#main-content" }),
HERE,
false,
),
).toBe(false);
});
it("leaves clicks the browser handles itself alone", () => {
const offline = (click: ReturnType<typeof clickOn>) =>
isOfflineNavigationClick(click, HERE, false);
expect(offline(clickOn({ href: "https://elsewhere.example/" }))).toBe(
false,
);
expect(offline(clickOn({ href: "/", target: "_blank" }))).toBe(false);
expect(offline(clickOn({ href: "/export.csv", download: true }))).toBe(
false,
);
expect(offline(clickOn({ href: "/" }, { metaKey: true }))).toBe(false);
expect(offline(clickOn({ href: "/" }, { button: 1 }))).toBe(false);
expect(offline(clickOn({ href: "/" }, { defaultPrevented: true }))).toBe(
false,
);
expect(offline(clickOn(null))).toBe(false);
});
});
@@ -133,8 +133,13 @@ afterEach(() => {
}
});
/** A client signed in as the caller: the persister binds to that account. */
function appClient(): QueryClient {
return new QueryClient({ defaultOptions: QUERY_CLIENT_DEFAULT_OPTIONS });
const client = new QueryClient({
defaultOptions: QUERY_CLIENT_DEFAULT_OPTIONS,
});
client.setQueryData(queryKeys.authMe(), { id: "acct-delegate" });
return client;
}
describe("persisting while inside another record", () => {
@@ -207,7 +212,13 @@ describe("restoring while inside another record", () => {
// hash already makes a snapshot written in one record unreadable in
// another; asserting only that would be a check that cannot fail for the
// control it names. This one counts what landed in the cache, so removing
// the guard leaves exactly one entry here and turns it red.
expect(reader.getQueryCache().getAll()).toHaveLength(0);
// the guard leaves exactly one entry here and turns it red. The only
// entry is the reader's own `/api/auth/me`.
expect(
reader
.getQueryCache()
.getAll()
.map((q) => q.queryKey[0]),
).toEqual(["auth"]);
});
});
+134 -2
View File
@@ -98,7 +98,7 @@ describe("session-end CacheStorage cleanup", () => {
}
});
it("deletes current and legacy HealthLog static/page/data caches only", async () => {
it("deletes current and legacy HealthLog page and data caches only", async () => {
const cacheNames = [
"healthlog-static-v1.34.0",
"healthlog-static-v1.15.20",
@@ -124,9 +124,11 @@ describe("session-end CacheStorage cleanup", () => {
.soft(deleted.sort())
.toEqual(
cacheNames
.filter((name) => /^healthlog-(?:static|pages|data)-/.test(name))
.filter((name) => /^healthlog-(?:pages|data)-/.test(name))
.sort(),
);
// The static cache holds catalogs and icons, nothing of an account.
expect(deleted).not.toContain("healthlog-static-v1.34.0");
expect(deleted).not.toContain("unrelated-app-static-v7");
expect(deleted).not.toContain("workbox-precache-healthlog");
});
@@ -193,6 +195,7 @@ describe("persister round-trips through a fake IndexedDB", () => {
};
const source = new QueryClient();
source.setQueryData(["auth", "me"], { id: "user-a" });
source.setQueryData(["dashboard", "snapshot"], { weightKg: 81 });
const stop = startPersistingQueryCache(source, "v1.18.6");
// Force a flush by advancing past the 1s debounce. The trigger write uses
@@ -205,6 +208,7 @@ describe("persister round-trips through a fake IndexedDB", () => {
stop();
const matchingBuild = new QueryClient();
matchingBuild.setQueryData(["auth", "me"], { id: "user-a" });
await restorePersistedQueryCache(matchingBuild, "v1.18.6");
expect(matchingBuild.getQueryData(["dashboard", "snapshot"])).toEqual({
weightKg: 81,
@@ -220,6 +224,7 @@ describe("persister round-trips through a fake IndexedDB", () => {
expect(restored?.isStale()).toBe(true);
const foreignBuild = new QueryClient();
foreignBuild.setQueryData(["auth", "me"], { id: "user-a" });
await restorePersistedQueryCache(foreignBuild, "v9.9.9");
expect(
foreignBuild.getQueryData(["dashboard", "snapshot"]),
@@ -278,6 +283,7 @@ describe("persister round-trips through a fake IndexedDB", () => {
// Persist a STALE (empty) chart series under an allowlisted family.
const source = new QueryClient();
source.setQueryData(["auth", "me"], { id: "user-a" });
source.setQueryData(["chart-data", "WEIGHT"], []);
const stop = startPersistingQueryCache(source, "v1.18.6");
vi.useFakeTimers();
@@ -289,6 +295,7 @@ describe("persister round-trips through a fake IndexedDB", () => {
// The live client already fetched the FRESH (post-mutation) series.
const live = new QueryClient();
live.setQueryData(["auth", "me"], { id: "user-a" });
live.setQueryData(["chart-data", "WEIGHT"], [{ id: "fresh-row" }]);
await restorePersistedQueryCache(live, "v1.18.6");
@@ -297,6 +304,15 @@ describe("persister round-trips through a fake IndexedDB", () => {
expect(live.getQueryData(["chart-data", "WEIGHT"])).toEqual([
{ id: "fresh-row" },
]);
// A query the page has started but not answered has no data: filled.
const mounting = new QueryClient();
mounting.setQueryData(["auth", "me"], { id: "user-a" });
mounting
.getQueryCache()
.build(mounting, { queryKey: ["chart-data", "WEIGHT"] });
await restorePersistedQueryCache(mounting, "v1.18.6");
expect(mounting.getQueryData(["chart-data", "WEIGHT"])).toEqual([]);
});
it("discards a snapshot stamped with a different account id", async () => {
@@ -370,8 +386,124 @@ describe("persister round-trips through a fake IndexedDB", () => {
// restore can't resurrect it either.
expect(store.get("react-query")).toBeUndefined();
});
it("restores nothing until the live account is known", async () => {
installRoundTripIdb();
const source = new QueryClient();
source.setQueryData(["auth", "me"], { id: "user-a" });
await persistOnce(source);
// A cold start: the snapshot is on disk, `/api/auth/me` has not answered.
const booting = new QueryClient();
await restorePersistedQueryCache(booting, "v1.18.6");
expect(booting.getQueryData(["dashboard", "snapshot"])).toBeUndefined();
// Not discarded either: the account may well turn out to be its owner.
expect(roundTripStore.get("react-query")).toBeDefined();
booting.setQueryData(["auth", "me"], { id: "user-a" });
await restorePersistedQueryCache(booting, "v1.18.6");
expect(booting.getQueryData(["dashboard", "snapshot"])).toEqual({
weightKg: 81,
});
});
it("writes the dashboard snapshot without the model-written briefing", async () => {
installRoundTripIdb();
const source = new QueryClient();
source.setQueryData(["auth", "me"], { id: "user-a" });
const briefing = { headline: "Your pressure ran high this week." };
const briefingMemory = { recall: "Last week: steady.", forward: "Calm." };
source.setQueryData(["dashboard", "snapshot", "en"], {
weightKg: 81,
briefing,
briefingMemory,
briefingState: "ready",
});
await persistOnce(source);
const written = JSON.stringify(roundTripStore.get("react-query"));
expect(written).toContain('"weightKg":81');
expect(written).not.toContain(briefing.headline);
expect(written).not.toContain(briefingMemory.recall);
// The live cache keeps what the server sent.
expect(
source.getQueryData<{ briefing: unknown }>([
"dashboard",
"snapshot",
"en",
])?.briefing,
).toBe(briefing);
});
it("discards a snapshot written before any account was known", async () => {
installRoundTripIdb();
await persistOnce(new QueryClient());
const live = new QueryClient();
live.setQueryData(["auth", "me"], { id: "user-b" });
await restorePersistedQueryCache(live, "v1.18.6");
expect(live.getQueryData(["dashboard", "snapshot"])).toBeUndefined();
expect(roundTripStore.get("react-query")).toBeUndefined();
});
});
// ── shared fake IndexedDB for the account cases above ───────────────────────
const roundTripStore = new Map<string, unknown>();
function installRoundTripIdb(): void {
roundTripStore.clear();
const makeReq = (result?: unknown) => {
const req: Record<string, unknown> = { result };
queueMicrotask(() => (req.onsuccess as (() => void) | undefined)?.());
return req;
};
const fakeDb = {
close() {},
transaction() {
return {
objectStore() {
return {
put(value: unknown, key: string) {
roundTripStore.set(key, value);
return makeReq();
},
get(key: string) {
return makeReq(roundTripStore.get(key));
},
delete(key: string) {
roundTripStore.delete(key);
return makeReq();
},
};
},
set oncomplete(fn: () => void) {
queueMicrotask(fn);
},
set onerror(_fn: () => void) {},
};
},
};
(globalThis as { indexedDB?: unknown }).indexedDB = {
open() {
const req: Record<string, unknown> = { result: fakeDb };
queueMicrotask(() => (req.onsuccess as () => void)?.());
return req;
},
};
}
/** Write one dashboard snapshot from `source` through the 1 s debounce. */
async function persistOnce(source: QueryClient): Promise<void> {
source.setQueryData(["dashboard", "snapshot"], { weightKg: 81 });
const stop = startPersistingQueryCache(source, "v1.18.6");
vi.useFakeTimers();
source.setQueryData(["chart-data", "WEIGHT"], [{ v: 81 }]);
vi.advanceTimersByTime(1100);
vi.useRealTimers();
await new Promise((r) => setTimeout(r, 0));
stop();
}
describe("persister is bounded and surfaces quota failures", () => {
const original = (globalThis as { indexedDB?: unknown }).indexedDB;
@@ -1,149 +0,0 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
isAllowlistedApiRead,
isCacheableApiResponse,
} from "@/lib/pwa/sw-cache-policy";
const SW_SOURCE = readFileSync(join(process.cwd(), "public", "sw.js"), "utf8");
describe("isAllowlistedApiRead — offline read boundary", () => {
it("caches the curated safe GET read endpoints", () => {
expect(isAllowlistedApiRead("/api/dashboard/snapshot")).toBe(true);
expect(isAllowlistedApiRead("/api/dashboard/widgets")).toBe(true);
// v1.37.20 — the Today rail's offline read. Watched red before the
// allowlist entry landed.
expect(isAllowlistedApiRead("/api/daily/digest")).toBe(true);
expect(isAllowlistedApiRead("/api/measurements")).toBe(true);
expect(
isAllowlistedApiRead("/api/measurements/series-batch?types=WEIGHT"),
).toBe(true);
expect(isAllowlistedApiRead("/api/medications")).toBe(true);
expect(isAllowlistedApiRead("/api/version")).toBe(true);
});
// v1.18.6 — AI/clinical narrative surfaces are never disk-cached. `/api/insights`
// previously prefix-matched the Coach chat list (`/api/insights/chat`, which
// returns decrypted conversation content) into the data cache; `/api/analytics`
// carries clinical aggregates. Both are off the allowlist.
it("never caches the AI / clinical narrative surfaces", () => {
expect(isAllowlistedApiRead("/api/insights")).toBe(false);
expect(isAllowlistedApiRead("/api/insights/chat")).toBe(false);
expect(isAllowlistedApiRead("/api/insights/generate")).toBe(false);
expect(isAllowlistedApiRead("/api/analytics")).toBe(false);
expect(isAllowlistedApiRead("/api/analytics/range")).toBe(false);
});
it("never caches auth / session / token / login surfaces", () => {
expect(isAllowlistedApiRead("/api/auth/me")).toBe(false);
expect(isAllowlistedApiRead("/api/auth/logout")).toBe(false);
expect(isAllowlistedApiRead("/api/sessions")).toBe(false);
expect(isAllowlistedApiRead("/api/tokens")).toBe(false);
expect(isAllowlistedApiRead("/api/login")).toBe(false);
expect(isAllowlistedApiRead("/api/webauthn/options")).toBe(false);
});
it("refuses an auth/token segment nested under an allowlisted prefix", () => {
expect(isAllowlistedApiRead("/api/medications/tokens")).toBe(false);
expect(isAllowlistedApiRead("/api/measurements/auth")).toBe(false);
});
it("does not cache endpoints outside the allowlist", () => {
expect(isAllowlistedApiRead("/api/admin/users")).toBe(false);
expect(isAllowlistedApiRead("/api/devices")).toBe(false);
expect(isAllowlistedApiRead("/api/withings/callback")).toBe(false);
});
it("never caches the cycle calendar feed or its management routes (#1350)", () => {
// The feed URL is a credential and its body is a record's cycle dates;
// neither belongs in a browser's durable storage.
const feed = `/api/cycle/feed/hlf_${"1f".repeat(24)}.ics`;
expect(isAllowlistedApiRead(feed)).toBe(false);
expect(isAllowlistedApiRead("/api/cycle/feed-subscription")).toBe(false);
expect(SW_SOURCE).not.toContain("/api/cycle");
});
it("does not match a prefix that is only a partial path segment", () => {
// `/api/measurements-export` must NOT match `/api/measurements`.
expect(isAllowlistedApiRead("/api/measurements-export")).toBe(false);
});
});
describe("isCacheableApiResponse — body/header refusal", () => {
it("caches a successful read with a plain body", () => {
expect(
isCacheableApiResponse({
ok: true,
cacheControl: "private, max-age=0",
bodyText: JSON.stringify({ data: { weightKg: 80 }, error: null }),
}),
).toBe(true);
});
it("refuses non-ok responses", () => {
expect(isCacheableApiResponse({ ok: false, bodyText: "{}" })).toBe(false);
});
it("refuses a no-store response", () => {
expect(
isCacheableApiResponse({
ok: true,
cacheControl: "no-store",
bodyText: "{}",
}),
).toBe(false);
});
it("refuses secret-shaped bodies (hlk_ / hlr_ / sk-)", () => {
expect(
isCacheableApiResponse({
ok: true,
bodyText: JSON.stringify({ data: { token: "hlk_abc123def" } }),
}),
).toBe(false);
expect(
isCacheableApiResponse({
ok: true,
bodyText: JSON.stringify({ data: { refresh: "hlr_xyz789ghi" } }),
}),
).toBe(false);
expect(
isCacheableApiResponse({
ok: true,
bodyText: JSON.stringify({ data: { key: "sk-livesecret00" } }),
}),
).toBe(false);
});
});
// v1.18.6.x regression guard. The first v1.18.6 cut cached allowlisted API
// reads with stale-while-revalidate, which served the pre-mutation copy first
// and broke read-after-write (a list fetched straight after a create showed
// the old/empty data). The strategy must be network-first: always fetch fresh
// online, fall back to cache ONLY when the network throws (offline).
describe("public/sw.js — allowlisted API reads are network-first", () => {
it("routes the allowlisted API branch through a network-first handler", () => {
expect(SW_SOURCE).toContain("networkFirstApi(request)");
expect(SW_SOURCE).toContain("async function networkFirstApi(request)");
});
it("no longer uses stale-while-revalidate for API reads", () => {
expect(SW_SOURCE).not.toContain("staleWhileRevalidateApi");
});
it("falls back to the cached copy only inside the network-failure catch", () => {
const handler = SW_SOURCE.slice(
SW_SOURCE.indexOf("async function networkFirstApi(request)"),
);
const tryIdx = handler.indexOf("await fetch(request)");
const catchIdx = handler.indexOf("} catch {");
const cacheMatchIdx = handler.indexOf("cache.match(request)");
// fetch comes first; the cache read lives after the catch boundary.
expect(tryIdx).toBeGreaterThan(-1);
expect(catchIdx).toBeGreaterThan(tryIdx);
expect(cacheMatchIdx).toBeGreaterThan(catchIdx);
});
});
+46
View File
@@ -0,0 +1,46 @@
type ClickLike = Pick<
MouseEvent,
| "defaultPrevented"
| "button"
| "metaKey"
| "ctrlKey"
| "shiftKey"
| "altKey"
| "target"
>;
/**
* Whether a click would leave the open page for another one of this app while
* the browser is offline.
*
* Signed-in pages are never cached (the proxy sends them `no-store`), so that
* navigation can only end on the service worker's offline page and throws
* away a page that was still readable. Clicks the browser handles on its own
* (new tab, download, another origin) and links within the same page are left
* alone.
*/
export function isOfflineNavigationClick(
event: ClickLike,
here: Pick<Location, "origin" | "pathname" | "search">,
online: boolean,
): boolean {
if (online || event.defaultPrevented || event.button !== 0) return false;
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
return false;
}
const anchor = (event.target as Partial<Element> | null)?.closest?.(
"a[href]",
) as HTMLAnchorElement | null | undefined;
// An SVG `<a>` carries an animated string, not a URL.
if (!anchor || typeof anchor.href !== "string") return false;
if (anchor.target && anchor.target !== "_self") return false;
if (anchor.hasAttribute("download")) return false;
let url: URL;
try {
url = new URL(anchor.href, here.origin);
} catch {
return false;
}
if (url.origin !== here.origin) return false;
return url.pathname !== here.pathname || url.search !== here.search;
}
+75 -61
View File
@@ -1,10 +1,10 @@
/**
* Minimal IndexedDB-backed TanStack Query persistence (v1.18.6).
* Minimal IndexedDB-backed TanStack Query persistence.
*
* No external persister dependency: a tiny IDB key/value store plus a manual
* dehydrate-on-cache-change / hydrate-on-boot bridge. The goal is offline
* READ value — an installed PWA opened offline hydrates the last cached
* dashboard/series instantly instead of painting empty skeletons forever.
* dehydrate-on-cache-change / hydrate-after-sign-in bridge. It is a warm
* start for the dashboard reads, not an offline mode: signed-in pages are
* never cached, so the app cannot boot without a connection.
*
* Safety:
* - Only successful (`status: "success"`) query results are persisted.
@@ -12,15 +12,18 @@
* dashboard-offline families off disk. This is the privacy floor: a
* denylist would persist every family it didn't name (cycle, mood, illness,
* labs, coach, insights, medications, …) in plaintext. Only the dashboard
* snapshot, its resolved widget layout, and the measurement daily-series —
* the data the dashboard needs to paint last-known values offline — are
* eligible. Clinical / narrative families are never written to disk.
* snapshot, its resolved widget layout, and the measurement daily-series
* are eligible. Clinical / narrative families are never written to disk.
* - Model-written text never is either: the snapshot carries the daily
* briefing and its recall line, and both are nulled before the write
* (`withoutModelText`).
* - `clearPersistedQueryCache()` is called on every session END (logout AND
* the 401 / session-expiry redirect), so a shared device never leaks one
* account's cached data to the next once the session is gone.
* - The payload is stamped with the current user id; a restore whose stored
* marker doesn't match the live account discards + clears the cache rather
* than hydrating a foreign account's data.
* - The payload is stamped with the current user id. A restore runs only
* once `["auth","me"]` names the live account, and a stored owner that is
* not that account discards + clears the cache rather than hydrating a
* foreign account's data.
* - Respects the centralised queryKey factory: it reads existing query keys,
* it never invents new ones.
*/
@@ -35,10 +38,7 @@ import {
import { trackBackgroundTask } from "@/lib/logging/background-tasks";
import { queryKeys } from "@/lib/query-keys";
import { isReadingSharedRecord } from "@/lib/query-keys/record-scope";
// Session-end cleanup removes every current/legacy HealthLog cache family
// while leaving unrelated CacheStorage namespaces on the same origin
// untouched; the name contract is shared with `public/sw.js`.
import { HEALTHLOG_CACHE_NAME_RE } from "@/lib/pwa/sw-cache-policy";
import { ACCOUNT_CACHE_NAME_RE } from "@/lib/pwa/sw-cache-policy";
const DB_NAME = "healthlog-query-cache";
const STORE = "kv";
@@ -59,8 +59,7 @@ const MAX_PERSIST_BYTES = 2 * 1024 * 1024; // 2 MB
/**
* Strict allowlist of the only query families written to disk — the
* low-sensitivity reads the dashboard needs to paint last-known values when
* opened offline. Everything else (coach, insights, illness, labs, mood,
* low-sensitivity reads the dashboard paints first. Everything else (coach, insights, illness, labs, mood,
* medications, cycle, auth, admin, tokens, …) stays in memory only.
*
* - `["dashboard", …]` — the unified first-paint snapshot
@@ -82,6 +81,29 @@ const MAX_PERSIST_BYTES = 2 * 1024 * 1024; // 2 MB
*/
const PERSIST_ALLOWLIST_HEADS = ["dashboard", "chart-data"] as const;
/** Snapshot fields a model may have written: the daily briefing and its recall line. */
const MODEL_TEXT_FIELDS = ["briefing", "briefingMemory"] as const;
/**
* The dashboard snapshot with its model-written fields nulled. The web
* dashboard reads the briefing from the Today digest, which is never
* persisted, so the restored snapshot loses nothing it paints. Returns new
* objects; the live cache keeps its copy.
*/
export function withoutModelText(
query: DehydratedState["queries"][number],
): DehydratedState["queries"][number] {
const data = query.state.data;
if (query.queryKey[0] !== "dashboard" || !data || typeof data !== "object") {
return query;
}
const stripped: Record<string, unknown> = { ...data };
for (const field of MODEL_TEXT_FIELDS) {
if (field in stripped) stripped[field] = null;
}
return { ...query, state: { ...query.state, data: stripped } };
}
export function isPersistableKey(queryKey: readonly unknown[]): boolean {
const head = queryKey[0];
if (typeof head !== "string") return false;
@@ -166,9 +188,9 @@ function currentUserId(queryClient: QueryClient): string | null {
}
/**
* Restore persisted query data into the client (called once before the first
* paint of the authenticated shell). A build-version or age mismatch discards
* the snapshot rather than hydrating a stale/foreign-schema cache.
* Restore persisted query data into the client once the signed-in account is
* known. A build-version, age or owner mismatch discards the snapshot rather
* than hydrating a stale, foreign-schema or foreign-account cache.
*/
export async function restorePersistedQueryCache(
queryClient: QueryClient,
@@ -182,6 +204,9 @@ export async function restorePersistedQueryCache(
// saying "viewing her record" is the mis-context failure this feature is
// built to prevent, in the one place a full reload cannot clear.
if (isReadingSharedRecord()) return;
// Without a live account there is nothing to compare the owner with.
const liveUserId = currentUserId(queryClient);
if (liveUserId === null) return;
try {
const payload = await idbGet<PersistedPayload>();
if (!payload) return;
@@ -193,32 +218,24 @@ export async function restorePersistedQueryCache(
await clearPersistedQueryCache();
return;
}
// Per-account binding: if the live account is known and differs from the
// snapshot's stored owner, this is a different user on the same browser
// profile — discard + clear rather than hydrate a foreign account's data.
// When the live id is not yet known (auth/me not resolved at restore time)
// we don't gate on it; the session-end wipe is the primary guarantee and
// the build-version + 24 h age gates still apply.
const liveUserId = currentUserId(queryClient);
if (liveUserId !== null && payload.userId !== liveUserId) {
// Per-account binding: a snapshot written by anyone but the live account
// (or before any account was known) is another user's on the same
// browser profile. Discard and clear it.
if (payload.userId !== liveUserId) {
await clearPersistedQueryCache();
return;
}
// Never clobber a query the live client already holds. `hydrate` calls
// `setData` per dehydrated query unconditionally, so a snapshot restored
// in an effect AFTER the first paint would overwrite a query the page
// already fetched/prefetched — replacing the fresh (post-mutation) list
// with the stale persisted (often empty) copy. That was the read-after-
// write break across dashboard/measurements/medications: the restore won
// the race against the in-flight fetch. Drop every dehydrated query whose
// key the cache already carries so restore only ever FILLS gaps, never
// overwrites; a query already present is by definition fresher than disk.
// Only fill gaps, never overwrite data the live client holds: the
// restore lands after the shell has mounted the page, so a query may
// already carry a fresh (post-mutation) answer, and that is fresher than
// disk. A query the page has started but not answered yet has no data
// and is filled; its own fetch replaces the copy when it lands.
const cache = queryClient.getQueryCache();
const filtered: DehydratedState = {
...payload.state,
queries: payload.state.queries.filter(
(q) => cache.get(q.queryHash) === undefined,
(q) => cache.get(q.queryHash)?.state.data === undefined,
),
};
if (filtered.queries.length === 0 || !canHydrate()) return;
@@ -230,9 +247,8 @@ export async function restorePersistedQueryCache(
// after a create/update then serves the stale pre-mutation copy. Marking
// every restored query invalidated makes it stale-but-shown: the persisted
// data still paints instantly, and the first mount triggers a background
// refetch. Online that lands fresh data within ms; offline the refetch
// fails and the hydrated copy stays on screen — the offline value holds.
// Scoped to the keys we just hydrated so we never disturb a live query.
// refetch that lands fresh data within ms. Scoped to the keys just
// hydrated so a live query is never disturbed.
for (const dq of filtered.queries) {
cache.get(dq.queryHash)?.invalidate();
}
@@ -261,10 +277,14 @@ export function startPersistingQueryCache(
// the flush (rather than filtering keys) also means the last good snapshot
// of the caller's own dashboard survives a switch untouched.
if (isReadingSharedRecord()) return;
const state = dehydrate(queryClient, {
const dehydrated = dehydrate(queryClient, {
shouldDehydrateQuery: (query) =>
query.state.status === "success" && isPersistableKey(query.queryKey),
});
const state: DehydratedState = {
...dehydrated,
queries: dehydrated.queries.map(withoutModelText),
};
const payload: PersistedPayload = {
buildVersion,
savedAt: Date.now(),
@@ -339,10 +359,12 @@ export async function clearPersistedQueryCache(): Promise<void> {
}
/**
* Wipe every client-side cache that can hold one account's health data: the
* IndexedDB query snapshot, the SW offline read-data cache, and the SW page
* cache (cached navigation HTML). The single call for a session END (logout or
* 401 / expiry redirect). Best-effort across the board.
* Wipe every client-side cache that can hold one account's data: the
* IndexedDB query snapshot, the worker's page cache and the API caches older
* releases left behind, current and legacy versions alike. The static cache
* (catalogs, icons) holds nothing of an account and stays, so a sign-in does
* not download the locale catalog again. The single call for a session END
* (logout or 401 / expiry redirect) and at sign-in. Best-effort.
*/
export async function clearOfflineCachesForSessionEnd(): Promise<void> {
await clearPersistedQueryCache();
@@ -351,7 +373,7 @@ export async function clearOfflineCachesForSessionEnd(): Promise<void> {
const keys = await caches.keys();
await Promise.all(
keys
.filter((k) => HEALTHLOG_CACHE_NAME_RE.test(k))
.filter((k) => ACCOUNT_CACHE_NAME_RE.test(k))
.map((k) => caches.delete(k)),
);
} catch {
@@ -361,23 +383,15 @@ export async function clearOfflineCachesForSessionEnd(): Promise<void> {
}
/**
* v1.36.0 — the same wipe, before a record switch in either direction.
* The same wipe, before a record switch in either direction.
*
* Deliberately the same bytes as the session-end wipe rather than a narrower
* one, and deliberately named for the act that calls it.
* The full page reload the switch performs clears the in-memory cache; the
* IndexedDB snapshot survives it and holds the dashboard the browser was last
* looking at. Without this call the first paint after the switch could show
* the previous record's numbers under a banner naming the new one.
*
* The full page reload the switch performs clears the in-memory cache; these
* two layers are the ones that survive it. The IndexedDB snapshot holds the
* dashboard the browser was last looking at, and the service worker's
* `healthlog-data-*` cache answers `/api/…` reads from disk on a
* stale-while-revalidate branch — so without this call, the first paint after
* switching into a record can be the previous record's numbers, served by the
* worker, under a banner naming the new one. Nothing about the page's own code
* would be wrong; the answer would just come from somewhere the page does not
* control.
*
* Run it BEFORE the reload and await it. A wipe racing the navigation is a
* wipe that sometimes does not happen, and "sometimes" is the whole failure.
* Run it BEFORE the reload and await it: a wipe racing the navigation
* sometimes does not happen.
*/
export async function clearOfflineCachesForRecordSwitch(): Promise<void> {
await clearOfflineCachesForSessionEnd();
+7 -74
View File
@@ -1,82 +1,15 @@
/**
* Service-worker offline-read cache policy (v1.18.6).
*
* The runtime copy of this logic lives inline in `public/sw.js` (a service
* worker cannot import app modules at runtime). This module is the
* unit-tested source of truth for the safety boundary — the allowlist match,
* the auth/token deny guard, and the body-level secret refusal — so the SW's
* caching decisions are covered by `pnpm test`. Keep the two in lockstep when
* either changes.
*
* Boundary: ONLY idempotent GET reads that render the core views are cached.
* Auth/mutation/token surfaces are never cached, and a body carrying a
* secret-shaped token (`hlk_`/`hlr_`/`sk-`) is refused even if its path was
* allowlisted by mistake — mirroring the idempotency cache's refusal.
*/
/**
* The worker's own cache names: `healthlog-{static,pages,data}-<version>`.
* Everything the app deletes from CacheStorage (session end, the "new
* version" reload) matches against this and nothing else, so another app's
* caches on the same origin are left alone. Keep in lockstep with
* Everything the app deletes from CacheStorage matches one of the two
* patterns below and nothing else, so another app's caches on the same
* origin are left alone. `data` names the API cache older releases kept; it
* stays so those caches are still deleted. Same pattern as
* `HEALTHLOG_CACHE_NAME_RE` in `public/sw.js`.
*/
export const HEALTHLOG_CACHE_NAME_RE = /^healthlog-(?:static|pages|data)-/;
/**
* Path prefixes whose safe GET reads are eligible for the offline data cache.
*
* v1.18.6 — AI/clinical narrative surfaces (`/api/insights`, `/api/analytics`)
* are excluded: `/api/insights` prefix-matched the Coach chat endpoint
* (`/api/insights/chat`) into the disk cache, and neither belongs on 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 cached.
* The caches that can hold something of one account: cached pages and the
* old API answers. The session wipe deletes these and keeps the static cache.
*/
export const API_READ_ALLOWLIST = [
"/api/dashboard/snapshot",
"/api/dashboard/widgets",
// v1.37.20 — the daily digest read: the Today rail is the first thing an
// offline reopen renders, and the digest is an idempotent GET with no
// secret in the body. The deny guard and the body-level refusal still
// apply on top, like every entry here.
"/api/daily/digest",
"/api/measurements",
"/api/medications",
"/api/version",
] as const;
/** Auth/token surfaces refused even when nested under an allowlisted prefix. */
export const API_DENY_RE =
/\/(auth|tokens?|sessions?|login|password|webauthn)(\/|$|\?)/i;
/** Secret-shaped token patterns refused at the response-body level. */
export const SECRET_BODY_RE = /(hlk_|hlr_|sk-)[A-Za-z0-9_-]/;
export function isAllowlistedApiRead(pathname: string): boolean {
if (API_DENY_RE.test(pathname)) return false;
return API_READ_ALLOWLIST.some(
(p) =>
pathname === p ||
pathname.startsWith(p + "/") ||
pathname.startsWith(p + "?"),
);
}
/**
* Decide whether an allowlisted response may be persisted. `ok` + no
* `no-store` + no secret-shaped body. Mirrors `isCacheableApiResponse` in
* `public/sw.js`.
*/
export function isCacheableApiResponse(opts: {
ok: boolean;
cacheControl?: string | null;
bodyText?: string;
}): boolean {
if (!opts.ok) return false;
if (/no-store/i.test(opts.cacheControl || "")) return false;
if (typeof opts.bodyText === "string" && SECRET_BODY_RE.test(opts.bodyText)) {
return false;
}
return true;
}
export const ACCOUNT_CACHE_NAME_RE = /^healthlog-(?:pages|data)-/;