mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-14 06:40:50 +00:00
Eleven touch-disjoint waves landed on develop plus a six-axis QA reconcile round before tagging. See CHANGELOG.md for the user-facing prose; this commit message documents the wave + report inventory for release-management traceability. Waves shipped (each with a phase report under .planning/): - phase-W-POOL-v1440-report.md — p-limit(4) wrapper around the analytics 15-way fan-out + pg.Pool max raised 10 -> 20. Closes the v1.4.39 empirical-trace finding #1 (Prisma pool starvation). - phase-W-DELETED-v1440-report.md — 11 reader-tier helpers + 3 integration contracts close audit Critical Finding #3 (soft-delete invisibility) across dashboard, analytics, summaries, rollup tiers, and the Coach snapshot path. - phase-W-INSIGHTS-v1440-report.md — mood-rollup swap on the three /api/insights/{features,targets,cards} routes plus the compliance-rollup hook gap closure for bulk-projection mints; the post-QA reconcile patch closes the six remaining measurement.findMany sites in the cluster that still leaked tombstoned rows. - phase-W-INFRA-v1440-report.md — rollup helper umbrella consolidation under src/lib/rollups/* with zero orphan re-exports; lint, typecheck, knip, and 93/93 rollup tests green post-restructure. - phase-W-RSC-v1440-report.md — per-tile Suspense boundaries plus the queryKey factory-bypass walker test (extended to comparison/ in the reconcile pass). - phase-W-PRIVACY-v1440-report.md — bilingual /privacy page with 17 paired-section tests pinning the 9 SB-3 disclosure requirements. - phase-W-AASA-v1440-report.md — /.well-known/apple-app-site-association endpoint pinned to S8WDX4W5KX.dev.healthlog.app with app-ID parity assertions guarding against split rotation. - phase-W-APNS-NOTIFY-v1440-report.md — MEDICATION_REMINDER time-sensitive APNs payload (priority 10 + interruption-level) scoped via a parameterised test that pins all 6 other event-types do not bypass Focus. AP-2 .p8 install gates real delivery. - phase-W-CONSENT-v1440-report.md — AI consent receipts CRUD with append-only invariant pinned in test; revoke-then-regrant leaves both rows; idempotent DELETE returns 200 + receipt: null. - phase-W-WMY-WIRE-v1440-report.md — three previously-dead WMY readers (week/month/year) wired through summaries-slice and health-score-fast-path with a linear-composability parity test pinning the cross-consumer routing contract. - phase-W-GHOSTS-v1440-report.md — ~1 177 lines of dead code removed across 9 atomic commits; startOfUtcDay + wallClockInTz consolidation eliminates a sibling-drift risk; knip whitelist trimmed to three files pending follow-up. QA reconcile patches applied per the v1.4.40 QA round (six reports under .planning/round-v1440-QA-*-findings.md): - senior C1 — dashboard-suspense-boundaries regex aligned with the post-W-INFRA Thread 2 userTimezone-local lift. - senior H1 — soft-delete filter added to the six remaining insights measurement.findMany sites. - specialist H1 — Promise.allSettled around bulk-projection compliance recompute on both /api/medications/intake and /api/dashboard/summary. - ux H1 — compare-toggle migrated to queryKeys.dashboardWidgets factory; walker test extended to src/components/comparison/. - security M1 — consent artefact 64 KB cap enforced via Buffer.byteLength (UTF-8 bytes, not UTF-16 code units). Quality gates green at tag: pnpm typecheck, pnpm lint, pnpm knip --include files,dependencies,binaries,unlisted, pnpm test --run (4726 passing / 1 skipped). Tests 4525 -> 4726 unit + 1 skipped over the v1.4.39 -> v1.4.40 span. User-facing prose: see CHANGELOG.md.
171 lines
4.7 KiB
TypeScript
171 lines
4.7 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
import { NextRequest } from "next/server";
|
|
|
|
vi.mock("@/lib/db", () => ({
|
|
prisma: {
|
|
consentReceipt: {
|
|
create: vi.fn(),
|
|
findFirst: vi.fn(),
|
|
findMany: vi.fn(),
|
|
update: vi.fn(),
|
|
},
|
|
},
|
|
}));
|
|
|
|
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 { POST } from "../route";
|
|
import { prisma } from "@/lib/db";
|
|
import { getSession } from "@/lib/auth/session";
|
|
import { auditLog } from "@/lib/auth/audit";
|
|
|
|
const SESSION_OK = {
|
|
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
|
user: { id: "user-1", username: "marc", role: "USER" as const },
|
|
};
|
|
|
|
function req(body: unknown): NextRequest {
|
|
return new NextRequest("http://localhost/api/consent/ai", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify(body),
|
|
});
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.resetAllMocks();
|
|
// `resetAllMocks` clears every mock's implementation, including the
|
|
// top-level `vi.mock(...).mockResolvedValue(undefined)` for audit.
|
|
// Re-arm it here so the fire-and-forget `.catch()` in the route
|
|
// doesn't crash on an undefined return.
|
|
vi.mocked(auditLog).mockResolvedValue(undefined);
|
|
});
|
|
|
|
describe("POST /api/consent/ai", () => {
|
|
it("returns 401 when unauthenticated", async () => {
|
|
vi.mocked(getSession).mockResolvedValue(null);
|
|
const res = await POST(
|
|
req({
|
|
kind: "ai_full",
|
|
artefact: "PDF",
|
|
signedAt: "2026-05-18T10:00:00.000Z",
|
|
}),
|
|
);
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it("returns 400 for an invalid kind", async () => {
|
|
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
|
const res = await POST(
|
|
req({
|
|
kind: "ai_total_world_domination",
|
|
artefact: "PDF",
|
|
signedAt: "2026-05-18T10:00:00.000Z",
|
|
}),
|
|
);
|
|
expect(res.status).toBe(400);
|
|
expect(prisma.consentReceipt.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("returns 400 for a non-ISO signedAt", async () => {
|
|
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
|
const res = await POST(
|
|
req({
|
|
kind: "ai_full",
|
|
artefact: "PDF",
|
|
signedAt: "yesterday",
|
|
}),
|
|
);
|
|
expect(res.status).toBe(400);
|
|
});
|
|
|
|
it("returns 400 when artefact exceeds the 64 KB cap", async () => {
|
|
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
|
const oversize = "A".repeat(64 * 1024 + 1);
|
|
const res = await POST(
|
|
req({
|
|
kind: "ai_full",
|
|
artefact: oversize,
|
|
signedAt: "2026-05-18T10:00:00.000Z",
|
|
}),
|
|
);
|
|
expect(res.status).toBe(400);
|
|
expect(prisma.consentReceipt.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("inserts a row and returns the receipt id + serialised row", async () => {
|
|
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
|
const signedAt = new Date("2026-05-18T10:00:00.000Z");
|
|
const createdAt = new Date("2026-05-18T10:00:01.000Z");
|
|
vi.mocked(prisma.consentReceipt.create).mockResolvedValue({
|
|
id: "rcpt-1",
|
|
userId: "user-1",
|
|
kind: "ai_full",
|
|
artefact: "PDF",
|
|
signedAt,
|
|
revokedAt: null,
|
|
createdAt,
|
|
} as never);
|
|
|
|
const res = await POST(
|
|
req({
|
|
kind: "ai_full",
|
|
artefact: "PDF",
|
|
signedAt: signedAt.toISOString(),
|
|
}),
|
|
);
|
|
expect(res.status).toBe(200);
|
|
|
|
const body = (await res.json()) as {
|
|
data: {
|
|
id: string;
|
|
receipt: {
|
|
id: string;
|
|
userId: string;
|
|
kind: string;
|
|
signedAt: string;
|
|
revokedAt: string | null;
|
|
createdAt: string;
|
|
};
|
|
};
|
|
};
|
|
expect(body.data.id).toBe("rcpt-1");
|
|
expect(body.data.receipt.kind).toBe("ai_full");
|
|
expect(body.data.receipt.userId).toBe("user-1");
|
|
expect(body.data.receipt.signedAt).toBe(signedAt.toISOString());
|
|
expect(body.data.receipt.revokedAt).toBeNull();
|
|
// `artefact` is intentionally stripped from the response — verify
|
|
// it is not echoed back over the wire.
|
|
expect(body.data.receipt).not.toHaveProperty("artefact");
|
|
|
|
expect(prisma.consentReceipt.create).toHaveBeenCalledWith({
|
|
data: {
|
|
userId: "user-1",
|
|
kind: "ai_full",
|
|
artefact: "PDF",
|
|
signedAt,
|
|
},
|
|
});
|
|
});
|
|
});
|