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,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)-/;