feat(consent): add the extraction consent kind and purge on withdrawal

A new receipt kind, ai_extraction, covers reading documents, lab report
scans and typed medication text with an external model. Switching the
document auto-read on now mints ai_extraction instead of ai_full, so it
no longer grants the Coach or the analysis as a side effect. Existing
ai_full receipts keep covering everything.

DELETE /api/consent/ai/latest now runs through withdrawConsent: the
revoke and, when it leaves no receipt covering the analysis, the
deletion of the text a model wrote under it commit in one transaction.
That is the status notes, the cached briefing, model-written period
narratives, reaction lines and workout paragraphs. Coach conversations,
facts and plans and document summaries stay. The purge is audit-logged
as consent.ai.purge with counts only.

Refs #975
This commit is contained in:
Marc-André Bombeck committed 2026-09-24 09:05:09 +02:00
1 parent 2710dfc041
commit 8325f3964d
14 files changed
+607 -185

No files matched your search

@@ -22,7 +22,7 @@ vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/consent/web-grant", () => ({
ensureWebAiConsentReceipt: vi.fn().mockResolvedValue(undefined),
ensureExtractionConsentReceipt: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/jobs/document-summary-catchup", () => ({
enqueueSummaryCatchUp: vi.fn().mockResolvedValue({ enqueued: true }),
@@ -47,7 +47,7 @@ vi.mock("next/headers", () => ({
import { PATCH } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { ensureWebAiConsentReceipt } from "@/lib/consent/web-grant";
import { ensureExtractionConsentReceipt } from "@/lib/consent/web-grant";
import { enqueueSummaryCatchUp } from "@/lib/jobs/document-summary-catchup";
const SESSION_OK = {
@@ -103,23 +103,20 @@ describe("PATCH /api/auth/me/documents-auto-ai-read — catch-up scheduling", ()
await PATCH(mkPatch(false));
expect(enqueueSummaryCatchUp).not.toHaveBeenCalled();
expect(ensureWebAiConsentReceipt).not.toHaveBeenCalled();
expect(ensureExtractionConsentReceipt).not.toHaveBeenCalled();
});
it("still mints the consent receipt on the flip that schedules the pass", async () => {
// The catch-up rides the same act of consent, never around it. The mint
// is marked `affirmative` because switching the toggle on IS the consent
// act: unlike the settings-mount heal, it may lift an earlier
// withdrawal, which is the user deciding again rather than the page
// deciding for them.
// is the extraction kind (documents, lab scans, medication text) and
// nothing wider: switching document reading on does not consent to the
// Coach or to the analysis. It is the person's own affirmative act, so
// it may lift an earlier withdrawal of the same kind.
withPrevious(false);
await PATCH(mkPatch(true));
expect(ensureWebAiConsentReceipt).toHaveBeenCalledWith(
"user-1",
"affirmative",
);
expect(ensureExtractionConsentReceipt).toHaveBeenCalledWith("user-1");
});
it("persists the flag field-by-field", async () => {
@@ -30,7 +30,7 @@ import {
} from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { ensureWebAiConsentReceipt } from "@/lib/consent/web-grant";
import { ensureExtractionConsentReceipt } from "@/lib/consent/web-grant";
import { prisma } from "@/lib/db";
import { enqueueSummaryCatchUp } from "@/lib/jobs/document-summary-catchup";
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
@@ -102,11 +102,12 @@ export const PATCH = apiHandler(async (req: Request) => {
data: { documentsAutoAiRead: next },
});
// Turning the toggle ON is the standing consent act — mint an append-only
// `ai_full` receipt (idempotent) so the durable audit trail records it, in
// addition to the runtime short-circuit the document consent gate reads.
// Turning the toggle ON is the consent act for reading documents — mint an
// append-only `ai_extraction` receipt (idempotent). The document consent
// gate reads that receipt, not the toggle, so a later revocation wins over
// a toggle left on. It does not grant the Coach or the analysis.
if (next) {
await ensureWebAiConsentReceipt(user.id, "affirmative");
await ensureExtractionConsentReceipt(user.id);
}
// A genuine OFF→ON flip schedules a catch-up over the documents already in
@@ -1,24 +1,30 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
// v1.16.16 — `createReceipt` + `revokeLatest` run inside a transaction; the
// mock runs the callback against the same proxy.
// v1.16.16 — `createReceipt` and the withdrawal run inside a transaction;
// the mock runs the callback against the same proxy. The withdrawal also
// purges the regenerable AI text, so the proxy carries those delegates too.
type TxFn = (tx: unknown) => unknown;
vi.mock("@/lib/db", () => {
const consentReceipt = {
create: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(),
update: vi.fn(),
updateMany: vi.fn(),
};
return {
prisma: {
consentReceipt,
$transaction: vi.fn((fn: TxFn) => fn({ consentReceipt })),
const prisma = {
consentReceipt: {
create: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(),
update: vi.fn(),
updateMany: vi.fn(),
count: vi.fn(),
},
insightStatusCache: { deleteMany: vi.fn() },
user: { updateMany: vi.fn() },
insightNarrative: { deleteMany: vi.fn() },
arrivalReaction: { updateMany: vi.fn() },
workoutInsight: { deleteMany: vi.fn() },
$transaction: vi.fn(),
};
prisma.$transaction.mockImplementation((fn: TxFn) => fn(prisma));
return { prisma };
});
vi.mock("@/lib/rate-limit", () => ({
@@ -78,9 +84,21 @@ beforeEach(() => {
vi.mocked(auditLog).mockResolvedValue(undefined);
// Re-arm rate-limit + transaction pass-throughs cleared by reset.
vi.mocked(checkConsentRateLimit).mockResolvedValue(RL_OK);
$transaction.mockImplementation((fn: TxFn) =>
fn({ consentReceipt: prisma.consentReceipt }),
);
$transaction.mockImplementation((fn: TxFn) => fn(prisma));
// Default: another receipt still covers the analysis, so no purge runs.
// The purge cases below set this to 0.
vi.mocked(prisma.consentReceipt.count).mockResolvedValue(1 as never);
for (const deleteMany of [
prisma.insightStatusCache.deleteMany,
prisma.insightNarrative.deleteMany,
prisma.workoutInsight.deleteMany,
]) {
vi.mocked(deleteMany).mockResolvedValue({ count: 0 } as never);
}
vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 0 } as never);
vi.mocked(prisma.arrivalReaction.updateMany).mockResolvedValue({
count: 0,
} as never);
});
describe("GET /api/consent/ai/latest", () => {
@@ -278,14 +296,15 @@ describe("DELETE /api/consent/ai/latest", () => {
const createdAt = new Date("2026-05-18T10:00:01.000Z");
const revokedAt = new Date("2026-05-18T11:00:00.000Z");
// v1.16.16 — `revokeLatest` runs per kind in `consentKindEnum.options`
// order: ai_full → ai_insights_only → ai_coach. The `updateMany` count
// gates the follow-up re-read. ai_full + ai_coach revoke a row;
// ai_insights_only has none (count 0, no re-read).
// The withdrawal runs per kind in `consentKindEnum.options` order:
// ai_full → ai_insights_only → ai_coach → ai_extraction. The
// `updateMany` count gates the follow-up re-read. ai_full + ai_coach
// revoke a row; the others have none (count 0, no re-read).
vi.mocked(prisma.consentReceipt.updateMany)
.mockResolvedValueOnce({ count: 1 } as never) // ai_full
.mockResolvedValueOnce({ count: 0 } as never) // ai_insights_only
.mockResolvedValueOnce({ count: 1 } as never); // ai_coach
.mockResolvedValueOnce({ count: 1 } as never) // ai_coach
.mockResolvedValueOnce({ count: 0 } as never); // ai_extraction
vi.mocked(prisma.consentReceipt.findFirst)
.mockResolvedValueOnce({
id: "rcpt-full",
@@ -323,6 +342,80 @@ describe("DELETE /api/consent/ai/latest", () => {
});
});
describe("DELETE /api/consent/ai/latest — purge of regenerable AI text", () => {
const revokedRow = {
id: "rcpt-1",
userId: "user-1",
kind: "ai_insights_only",
artefact: "PDF",
signedAt: new Date("2026-05-18T10:00:00.000Z"),
revokedAt: new Date("2026-05-18T11:00:00.000Z"),
createdAt: new Date("2026-05-18T10:00:01.000Z"),
};
it("deletes the regenerable text and writes a counts-only purge audit row when nothing covers the analysis any more", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.consentReceipt.updateMany).mockResolvedValue({
count: 1,
} as never);
vi.mocked(prisma.consentReceipt.findFirst).mockResolvedValue(
revokedRow as never,
);
vi.mocked(prisma.consentReceipt.count).mockResolvedValue(0 as never);
vi.mocked(prisma.insightStatusCache.deleteMany).mockResolvedValue({
count: 4,
} as never);
const res = await DELETE(
new NextRequest(
"http://localhost/api/consent/ai/latest?kind=ai_insights_only",
{ method: "DELETE" },
),
);
expect(res.status).toBe(200);
expect(prisma.insightStatusCache.deleteMany).toHaveBeenCalledWith({
where: { userId: "user-1" },
});
expect(prisma.workoutInsight.deleteMany).toHaveBeenCalledWith({
where: { userId: "user-1" },
});
expect(auditLog).toHaveBeenCalledWith("consent.ai.purge", {
userId: "user-1",
details: {
statusNotes: 4,
briefing: 0,
narratives: 0,
reactionLines: 0,
workoutParagraphs: 0,
},
});
});
it("keeps the text while another receipt still covers the analysis", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.consentReceipt.updateMany).mockResolvedValue({
count: 1,
} as never);
vi.mocked(prisma.consentReceipt.findFirst).mockResolvedValue(
revokedRow as never,
);
vi.mocked(prisma.consentReceipt.count).mockResolvedValue(1 as never);
const res = await DELETE(
new NextRequest(
"http://localhost/api/consent/ai/latest?kind=ai_insights_only",
{ method: "DELETE" },
),
);
expect(res.status).toBe(200);
expect(prisma.insightStatusCache.deleteMany).not.toHaveBeenCalled();
expect(auditLog).not.toHaveBeenCalledWith(
"consent.ai.purge",
expect.anything(),
);
});
});
describe("append-only invariant", () => {
/**
* v1.4.40 SB-10 — the receipts table is the legal audit trail.
+43 -38
View File
@@ -13,6 +13,11 @@
* DELETE /api/consent/ai/latest
* Master toggle — revokes the latest active receipt across every
* consent kind. Returns the list of revoked rows.
*
* Either DELETE also deletes the regenerable model-written text (status
* notes, the cached briefing, model-written narratives, reaction lines,
* workout paragraphs) when it leaves no receipt covering the analysis, in the
* same transaction as the revoke. Coach memory and document summaries stay.
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
@@ -28,8 +33,8 @@ import {
import {
latestActiveReceipt,
latestActiveReceiptsByKind,
revokeLatest,
} from "@/lib/consent/receipts";
import { withdrawConsent } from "@/lib/consent/withdrawal";
import { serialiseReceipt } from "../route";
export const GET = apiHandler(async (request: NextRequest) => {
@@ -81,6 +86,9 @@ export const GET = apiHandler(async (request: NextRequest) => {
? serialiseReceipt(byKind.ai_insights_only)
: null,
ai_coach: byKind.ai_coach ? serialiseReceipt(byKind.ai_coach) : null,
ai_extraction: byKind.ai_extraction
? serialiseReceipt(byKind.ai_extraction)
: null,
};
annotate({
@@ -119,53 +127,50 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
const { kind } = parsed.data;
if (kind) {
const revoked = await revokeLatest(user.id, kind);
if (!revoked) {
// Idempotent: "no active receipt to revoke" is success-shaped.
// The iOS toggle hammers this on every flip; returning 404
// would surface as a spurious error in the client.
annotate({
action: { name: "consent.ai.revoke" },
meta: { kind, revoked: false },
});
return apiSuccess({ kind, receipt: null });
}
// One kind, or every kind for the master "turn AI off" toggle. The revoke
// and the purge of the regenerable text the consent covered commit
// together (`withdrawConsent`).
const kinds = kind ? [kind] : consentKindEnum.options;
const { revoked, purged } = await withdrawConsent(user.id, kinds);
for (const { kind: k, receipt } of revoked) {
auditLog("consent.ai.revoke", {
userId: user.id,
details: { kind, receiptId: revoked.id },
details: { kind: k, receiptId: receipt.id },
}).catch(() => {});
annotate({
action: { name: "consent.ai.revoke" },
meta: { kind, receiptId: revoked.id },
});
return apiSuccess({ kind, receipt: serialiseReceipt(revoked) });
}
// No kind specified — master "AI deaktivieren" toggle. Revoke the
// latest active row for every kind that currently has one.
const revokedRows: Array<{
kind: ConsentKind;
receipt: ReturnType<typeof serialiseReceipt>;
}> = [];
for (const k of consentKindEnum.options) {
const r = await revokeLatest(user.id, k);
if (r) {
revokedRows.push({ kind: k, receipt: serialiseReceipt(r) });
auditLog("consent.ai.revoke", {
userId: user.id,
details: { kind: k, receiptId: r.id },
}).catch(() => {});
}
if (purged) {
// Counts only, never content.
auditLog("consent.ai.purge", {
userId: user.id,
details: { ...purged },
}).catch(() => {});
}
annotate({
action: { name: "consent.ai.revoke" },
meta: {
kinds_revoked: revokedRows.map((r) => r.kind),
count: revokedRows.length,
kinds_revoked: revoked.map((r) => r.kind),
count: revoked.length,
purged: purged !== null,
},
});
return apiSuccess({ revoked: revokedRows });
if (kind) {
// Idempotent: "no active receipt to revoke" is success-shaped. The iOS
// toggle hammers this on every flip; returning 404 would surface as a
// spurious error in the client.
const receipt = revoked[0]?.receipt ?? null;
return apiSuccess({
kind,
receipt: receipt ? serialiseReceipt(receipt) : null,
});
}
return apiSuccess({
revoked: revoked.map((r) => ({
kind: r.kind,
receipt: serialiseReceipt(r.receipt),
})),
});
});