feat(insights): view ECG recordings

ECG recordings synced from a compatible watch were stored encrypted but
shown nowhere. They now have a surface in Insights: a list of recordings,
each opening the full single-lead waveform on a familiar ECG grid, with the
date, duration, average heart rate, and the result the device recorded.

The read routes narrow ownership in the query and decrypt the waveform
through the existing fail-closed codec; the overview is min/max-decimated so
the R-wave peaks survive the reduction, with a raw path for a calibrated
view. The result shown is the recording device's own classification,
attributed to the device — HealthLog does not read or interpret the trace
and produces no verdict of its own. A permanent note states this, and a
non-normal result carries a line to discuss the recording with a clinician.
This commit is contained in:
Marc-André Bombeck committed 2026-07-16 09:55:35 +02:00
1 parent 7a0a271c70
commit 49ed0f41df
28 files changed
+2124 -4

No files matched your search

@@ -67,6 +67,12 @@ const NON_COACH_GATED_ROUTES: ReadonlyArray<string> = [
// the same `insightStatus` sub-flag as the assessment routes (no Coach
// prose).
"src/app/api/insights/rhythm-events/route.ts",
// v1.28.50 — ECG recording surface (list + per-recording waveform). Pure
// DB read of the device's own recordings + verdicts; gates on the same
// `insightStatus` sub-flag as the assessment routes (no Coach prose — the
// waveform is never interpreted).
"src/app/api/insights/ecg/route.ts",
"src/app/api/insights/ecg/[id]/route.ts",
"src/app/api/insights/weight-status/route.ts",
];
@@ -0,0 +1,161 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { NextRequest } from "next/server";
/**
* v1.28.50 — `GET /api/insights/ecg/[id]` (waveform detail).
*
* Load-bearing behaviour under test:
* - ownership is narrowed IN THE where ({ id, userId }) so a foreign id
* is null and 404s (cross-user leak structurally impossible);
* - the waveform is decrypted through the real fail-closed codec
* (encrypt → Bytes → route → decrypt round-trip);
* - the ~9000-sample strip is min/max-decimated to ~2500 by default and
* `?full=1` returns the raw array;
* - the response is `no-store`.
*/
vi.mock("@/lib/db", () => ({
prisma: {
appSettings: { findUnique: vi.fn().mockResolvedValue(null) },
ecgRecording: { findFirst: vi.fn() },
},
}));
vi.mock("@/lib/modules/gate", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/modules/gate")>()),
requireModuleEnabled: vi.fn().mockResolvedValue({ enabled: true }),
resolveModuleMap: vi.fn().mockResolvedValue({}),
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET } from "../route";
import { getSession } from "@/lib/auth/session";
import { prisma } from "@/lib/db";
import { _resetCryptoCacheForTests } from "@/lib/crypto";
import { encryptWaveformToBytes } from "@/lib/withings/ecg-waveform-codec";
const KEY = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: {
id: "user-1",
username: "testuser",
role: "USER" as const,
locale: "en",
},
};
type Ctx = { params: Promise<{ id: string }> };
const callGet = GET as unknown as (
req: NextRequest,
ctx: Ctx,
) => Promise<Response>;
function makeReq(query = ""): NextRequest {
return new NextRequest(
new URL(`http://localhost/api/insights/ecg/ecg_1${query}`),
);
}
function ctx(id = "ecg_1"): Ctx {
return { params: Promise.resolve({ id }) };
}
function rowWith(samples: number[]) {
return {
recordedAt: new Date("2026-06-01T09:15:00.000Z"),
durationSeconds: 30,
samplingFrequency: 300,
averageHeartRate: 72,
lead: null,
rhythmClassification: "IRREGULAR",
source: "WITHINGS",
waveformEncrypted: encryptWaveformToBytes(samples),
};
}
beforeEach(() => {
vi.clearAllMocks();
vi.unstubAllEnvs();
vi.stubEnv("ENCRYPTION_KEYS", "");
vi.stubEnv("ENCRYPTION_ACTIVE_KEY_ID", "");
vi.stubEnv("ENCRYPTION_KEY", KEY);
_resetCryptoCacheForTests();
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue(null as never);
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
});
afterEach(() => {
vi.unstubAllEnvs();
_resetCryptoCacheForTests();
});
describe("GET /api/insights/ecg/[id]", () => {
it("narrows ownership in the where and 404s an unknown / foreign id", async () => {
vi.mocked(prisma.ecgRecording.findFirst).mockResolvedValue(null as never);
const res = await callGet(makeReq(), ctx("ecg_x"));
expect(res.status).toBe(404);
const where = vi.mocked(prisma.ecgRecording.findFirst).mock.calls[0][0]
?.where as { id: string; userId: string };
expect(where).toEqual({ id: "ecg_x", userId: "user-1" });
});
it("decrypts the waveform and min/max-decimates the ~9000-sample strip", async () => {
const raw = Array.from({ length: 9000 }, (_, i) =>
Math.round(Math.sin(i / 8) * 500),
);
raw[4500] = 9999; // an R-wave peak that must survive
vi.mocked(prisma.ecgRecording.findFirst).mockResolvedValue(
rowWith(raw) as never,
);
const res = await callGet(makeReq(), ctx());
expect(res.status).toBe(200);
expect(res.headers.get("Cache-Control")).toBe("no-store");
const body = (await res.json()) as {
data: {
samples: number[];
decimated: boolean;
classification: string;
};
};
expect(body.data.decimated).toBe(true);
expect(body.data.samples.length).toBeLessThanOrEqual(2500);
expect(body.data.samples.length).toBeLessThan(9000);
// The device verdict is surfaced verbatim.
expect(body.data.classification).toBe("IRREGULAR");
// The peak survives the decimation (min/max, never a naive stride).
expect(Math.max(...body.data.samples)).toBe(9999);
});
it("returns the raw array unchanged when ?full=1", async () => {
const raw = Array.from({ length: 9000 }, (_, i) => i % 17);
vi.mocked(prisma.ecgRecording.findFirst).mockResolvedValue(
rowWith(raw) as never,
);
const res = await callGet(makeReq("?full=1"), ctx());
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { samples: number[]; decimated: boolean };
};
expect(body.data.decimated).toBe(false);
expect(body.data.samples).toEqual(raw);
});
});
+101
View File
@@ -0,0 +1,101 @@
/**
* v1.28.50 — single ECG recording WITH waveform.
*
* `GET /api/insights/ecg/[id]` returns one recording's decrypted waveform
* plus its metadata and the DEVICE's own rhythm classification. Ownership
* is narrowed IN THE `where` (`{ id, userId }`) so a cross-user read is
* structurally impossible — a foreign or unknown id resolves to null and
* 404s, sealing existence exactly like the documents cache-leak fix.
*
* The waveform is AES-256-GCM at rest; it is decrypted through the
* existing fail-closed `decryptWaveformFromBytes` (a bad key id or a
* non-array payload throws rather than leaking plaintext). By default the
* ~9000-sample strip is min/max-decimated to ~2500 display points so the
* R-wave peaks survive the reduction (see `decimateMinMax`); `?full=1`
* returns the raw array for the true-calibration zoom view.
*
* Regulatory framing (load-bearing): the response carries the waveform,
* the metadata, and the device's verbatim `classification` ONLY. HealthLog
* does not interpret the trace, measure intervals, annotate beats, or emit
* a verdict of its own.
*
* Mirrors the `rhythm-events` gating: `apiHandler`, cookie OR Bearer auth,
* `userId` from the session, the `insights` module gate, and the
* `insightStatus` assistant-surface gate. No AI provider call.
*/
import { NextRequest } from "next/server";
import { apiError, apiSuccess } from "@/lib/api-response";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { prisma } from "@/lib/db";
import { decryptWaveformFromBytes } from "@/lib/withings/ecg-waveform-codec";
import {
ECG_DISPLAY_TARGET_POINTS,
decimateMinMax,
} from "@/lib/insights/ecg-decimate";
export const dynamic = "force-dynamic";
type RouteParams = { params: Promise<{ id: string }> };
export const GET = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireAuth();
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
await requireAssistantSurface("insightStatus");
const { id } = await params;
const full = request.nextUrl.searchParams.get("full") === "1";
// Ownership narrowed in the where — a foreign / unknown id is null.
const row = await prisma.ecgRecording.findFirst({
where: { id, userId: user.id },
select: {
recordedAt: true,
durationSeconds: true,
samplingFrequency: true,
averageHeartRate: true,
lead: true,
rhythmClassification: true,
source: true,
waveformEncrypted: true,
},
});
if (!row) {
return apiError("ECG recording not found", 404);
}
// Fail-closed decrypt (throws on a bad key id / non-array payload).
const raw = decryptWaveformFromBytes(row.waveformEncrypted);
const decimated = !full && raw.length > ECG_DISPLAY_TARGET_POINTS;
const samples = decimated
? decimateMinMax(raw, ECG_DISPLAY_TARGET_POINTS)
: raw;
annotate({
action: { name: "insights.ecg.detail" },
meta: { sampleCount: raw.length, decimated },
});
const res = apiSuccess({
recordedAt: row.recordedAt.toISOString(),
durationSeconds: row.durationSeconds,
samplingFrequency: row.samplingFrequency,
averageHeartRate: row.averageHeartRate,
lead: row.lead,
classification: row.rhythmClassification,
source: row.source,
samples,
decimated,
});
// Never cache a decrypted health-data waveform at any hop.
res.headers.set("Cache-Control", "no-store");
return res;
},
);
@@ -0,0 +1,144 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
/**
* v1.28.50 — `GET /api/insights/ecg` (metadata-only recording list).
*
* Load-bearing behaviour under test: it narrows the query to the session
* user, NEVER selects the encrypted waveform, returns the device's own
* classification per row, and reports `hasRecordings: false` (the
* data-availability gate the UI keys off) when the user has none.
*/
vi.mock("@/lib/db", () => ({
prisma: {
appSettings: { findUnique: vi.fn().mockResolvedValue(null) },
ecgRecording: { findMany: vi.fn() },
},
}));
// Module gate mocked default-enabled; the off → 403 coverage lives in the
// module-route-gate inventory test (the route calls requireModuleEnabled).
vi.mock("@/lib/modules/gate", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/modules/gate")>()),
requireModuleEnabled: vi.fn().mockResolvedValue({ enabled: true }),
resolveModuleMap: vi.fn().mockResolvedValue({}),
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET } from "../route";
import { getSession } from "@/lib/auth/session";
import { prisma } from "@/lib/db";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: {
id: "user-1",
username: "testuser",
role: "USER" as const,
locale: "en",
},
};
const callGet = GET as unknown as (req: NextRequest) => Promise<Response>;
function makeReq(): NextRequest {
return new NextRequest(new URL("http://localhost/api/insights/ecg"));
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue(null as never);
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
});
describe("GET /api/insights/ecg", () => {
it("returns hasRecordings:false with an empty list when the user has none", async () => {
vi.mocked(prisma.ecgRecording.findMany).mockResolvedValue([] as never);
const res = await callGet(makeReq());
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { recordings: unknown[]; hasRecordings: boolean };
};
expect(body.data.hasRecordings).toBe(false);
expect(body.data.recordings).toEqual([]);
});
it("narrows the query to the session user and never selects the waveform", async () => {
vi.mocked(prisma.ecgRecording.findMany).mockResolvedValue([] as never);
await callGet(makeReq());
const arg = vi.mocked(prisma.ecgRecording.findMany).mock.calls[0][0] as {
where: { userId: string };
select: Record<string, boolean>;
};
expect(arg.where.userId).toBe("user-1");
// The encrypted blob must never be pulled into the list read.
expect(arg.select.waveformEncrypted).toBeUndefined();
expect(arg.select.id).toBe(true);
expect(arg.select.rhythmClassification).toBe(true);
});
it("maps each row to metadata + the device verdict, flagging hasWaveform", async () => {
vi.mocked(prisma.ecgRecording.findMany).mockResolvedValue([
{
id: "ecg_1",
recordedAt: new Date("2026-06-01T09:15:00.000Z"),
durationSeconds: 30,
samplingFrequency: 300,
sampleCount: 9000,
averageHeartRate: 72,
lead: null,
rhythmClassification: "IRREGULAR",
source: "WITHINGS",
},
{
id: "ecg_2",
recordedAt: new Date("2026-05-01T09:15:00.000Z"),
durationSeconds: null,
samplingFrequency: 0,
sampleCount: 0,
averageHeartRate: null,
lead: null,
rhythmClassification: "NOT_DETECTED",
source: "WITHINGS",
},
] as never);
const res = await callGet(makeReq());
const body = (await res.json()) as {
data: {
hasRecordings: boolean;
recordings: Array<{
id: string;
classification: string | null;
hasWaveform: boolean;
recordedAt: string;
}>;
};
};
expect(body.data.hasRecordings).toBe(true);
expect(body.data.recordings[0]).toMatchObject({
id: "ecg_1",
classification: "IRREGULAR",
hasWaveform: true,
recordedAt: "2026-06-01T09:15:00.000Z",
});
// A verdict-only fallback (sampleCount 0) reports hasWaveform:false.
expect(body.data.recordings[1].hasWaveform).toBe(false);
expect(body.data.recordings[1].classification).toBe("NOT_DETECTED");
});
});
+87
View File
@@ -0,0 +1,87 @@
/**
* v1.28.50 — ECG recording list route (metadata only, no waveform).
*
* `GET /api/insights/ecg` returns the authenticated user's ECG recordings
* as a cheap, index-covered metadata list — recorded time, duration,
* sampling rate, sample count, average heart rate, lead, and the DEVICE's
* own rhythm classification. It NEVER decrypts or returns the waveform;
* the per-recording strip is fetched on demand via
* `GET /api/insights/ecg/[id]`.
*
* Regulatory framing (load-bearing): this surface reflects ONLY the
* classification RESULT the recording device's certified on-device
* algorithm produced. HealthLog never re-classifies an ECG, never reads
* the waveform to form a verdict, and never produces a diagnosis. The
* `classification` field the client renders is the device's, verbatim.
*
* Data-availability-gated by construction: an account with no recordings
* gets `{ recordings: [], hasRecordings: false }`, and the client un-mounts
* the whole surface rather than painting an empty card.
*
* Mirrors the `rhythm-events` route gating exactly: `apiHandler` wrapper,
* cookie OR Bearer auth, `userId` narrowed from the session (never a query
* field), the `insights` module gate, and the `insightStatus`
* assistant-surface gate. No AI provider call — this is a pure DB read.
*/
import { apiSuccess } from "@/lib/api-response";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { prisma } from "@/lib/db";
export const dynamic = "force-dynamic";
// Defensive cap. A ScanWatch user records a handful to a few dozen strips
// over time; this is a bound, not an expected ceiling.
const MAX_RECORDINGS = 200;
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
await requireAssistantSurface("insightStatus");
const rows = await prisma.ecgRecording.findMany({
where: { userId: user.id },
// Everything EXCEPT `waveformEncrypted` — the list never touches the
// encrypted blob, so no decrypt happens on this path.
select: {
id: true,
recordedAt: true,
durationSeconds: true,
samplingFrequency: true,
sampleCount: true,
averageHeartRate: true,
lead: true,
rhythmClassification: true,
source: true,
},
orderBy: { recordedAt: "desc" },
take: MAX_RECORDINGS,
});
const recordings = rows.map((r) => ({
id: r.id,
recordedAt: r.recordedAt.toISOString(),
durationSeconds: r.durationSeconds,
samplingFrequency: r.samplingFrequency,
sampleCount: r.sampleCount,
averageHeartRate: r.averageHeartRate,
lead: r.lead,
classification: r.rhythmClassification,
source: r.source,
// A `ts-` fallback event carries a verdict but no signal to fetch.
hasWaveform: r.sampleCount > 0,
}));
annotate({
action: { name: "insights.ecg.list" },
meta: { count: recordings.length },
});
return apiSuccess({
recordings,
hasRecordings: recordings.length > 0,
});
});