chore(release): v1.4.40 — comprehensive Critical+High architecture closure plus iOS PB30 enablement

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.
This commit is contained in:
Marc-André Bombeck committed 2026-05-21 12:48:02 +02:00
1 parent f9996552ed
commit 1114cf7e63
146 files changed
+8207 -2279

No files matched your search

@@ -0,0 +1,170 @@
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,
},
});
});
});
@@ -0,0 +1,393 @@
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 { GET, DELETE } from "../route";
import { POST as POST_GRANT } 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 },
};
beforeEach(() => {
vi.resetAllMocks();
// `resetAllMocks` clears the top-level `mockResolvedValue(undefined)`
// on `auditLog`. Re-arm so the route's fire-and-forget `.catch()`
// chain doesn't NPE on an undefined return.
vi.mocked(auditLog).mockResolvedValue(undefined);
});
describe("GET /api/consent/ai/latest", () => {
it("returns 401 when unauthenticated", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const res = await GET(
new NextRequest("http://localhost/api/consent/ai/latest?kind=ai_full"),
);
expect(res.status).toBe(401);
});
it("returns 400 for an unknown kind", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await GET(
new NextRequest("http://localhost/api/consent/ai/latest?kind=invalid"),
);
expect(res.status).toBe(400);
});
it("returns null receipt when nothing has been granted", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.consentReceipt.findFirst).mockResolvedValue(null);
const res = await GET(
new NextRequest("http://localhost/api/consent/ai/latest?kind=ai_full"),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { kind: string; receipt: unknown | null };
};
expect(body.data.kind).toBe("ai_full");
expect(body.data.receipt).toBeNull();
});
it("returns the latest non-revoked receipt by kind", 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.findFirst).mockResolvedValue({
id: "rcpt-1",
userId: "user-1",
kind: "ai_full",
artefact: "PDF",
signedAt,
revokedAt: null,
createdAt,
} as never);
const res = await GET(
new NextRequest("http://localhost/api/consent/ai/latest?kind=ai_full"),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { kind: string; receipt: { id: string; kind: string } | null };
};
expect(body.data.receipt?.id).toBe("rcpt-1");
expect(body.data.receipt?.kind).toBe("ai_full");
expect(prisma.consentReceipt.findFirst).toHaveBeenCalledWith({
where: { userId: "user-1", kind: "ai_full", revokedAt: null },
orderBy: { createdAt: "desc" },
});
});
it("returns the full keyspace when called without ?kind", 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.findMany).mockResolvedValue([
{
id: "rcpt-full",
userId: "user-1",
kind: "ai_full",
artefact: "PDF",
signedAt,
revokedAt: null,
createdAt,
},
] as never);
const res = await GET(
new NextRequest("http://localhost/api/consent/ai/latest"),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: Record<string, { id: string } | null>;
};
expect(body.data.ai_full?.id).toBe("rcpt-full");
expect(body.data.ai_coach).toBeNull();
expect(body.data.ai_insights_only).toBeNull();
});
});
describe("DELETE /api/consent/ai/latest", () => {
it("returns 401 when unauthenticated", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const res = await DELETE(
new NextRequest("http://localhost/api/consent/ai/latest?kind=ai_full", {
method: "DELETE",
}),
);
expect(res.status).toBe(401);
});
it("marks the latest receipt as revoked and returns it", 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");
const revokedAt = new Date("2026-05-18T11:00:00.000Z");
vi.mocked(prisma.consentReceipt.findFirst).mockResolvedValue({
id: "rcpt-1",
userId: "user-1",
kind: "ai_full",
artefact: "PDF",
signedAt,
revokedAt: null,
createdAt,
} as never);
vi.mocked(prisma.consentReceipt.update).mockResolvedValue({
id: "rcpt-1",
userId: "user-1",
kind: "ai_full",
artefact: "PDF",
signedAt,
revokedAt,
createdAt,
} as never);
const res = await DELETE(
new NextRequest("http://localhost/api/consent/ai/latest?kind=ai_full", {
method: "DELETE",
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { kind: string; receipt: { id: string; revokedAt: string } | null };
};
expect(body.data.receipt?.id).toBe("rcpt-1");
expect(body.data.receipt?.revokedAt).toBe(revokedAt.toISOString());
expect(prisma.consentReceipt.update).toHaveBeenCalledWith({
where: { id: "rcpt-1" },
data: { revokedAt: expect.any(Date) },
});
});
it("is idempotent — returns null receipt without writing when nothing to revoke", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.consentReceipt.findFirst).mockResolvedValue(null);
const res = await DELETE(
new NextRequest("http://localhost/api/consent/ai/latest?kind=ai_full", {
method: "DELETE",
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { kind: string; receipt: unknown | null };
};
expect(body.data.receipt).toBeNull();
expect(prisma.consentReceipt.update).not.toHaveBeenCalled();
});
it("master toggle revokes the latest active row per kind", 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");
const revokedAt = new Date("2026-05-18T11:00:00.000Z");
// First call (ai_full) finds a row, second (ai_insights_only)
// finds none, third (ai_coach) finds a row.
vi.mocked(prisma.consentReceipt.findFirst)
.mockResolvedValueOnce({
id: "rcpt-full",
userId: "user-1",
kind: "ai_full",
artefact: "PDF",
signedAt,
revokedAt: null,
createdAt,
} as never)
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({
id: "rcpt-coach",
userId: "user-1",
kind: "ai_coach",
artefact: "PDF",
signedAt,
revokedAt: null,
createdAt,
} as never);
vi.mocked(prisma.consentReceipt.update).mockImplementation(
((args: { where: { id: string }; data: { revokedAt: Date } }) =>
Promise.resolve({
id: args.where.id,
userId: "user-1",
kind: args.where.id === "rcpt-full" ? "ai_full" : "ai_coach",
artefact: "PDF",
signedAt,
revokedAt,
createdAt,
})) as never,
);
const res = await DELETE(
new NextRequest("http://localhost/api/consent/ai/latest", {
method: "DELETE",
}),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { revoked: Array<{ kind: string; receipt: { id: string } }> };
};
expect(body.data.revoked).toHaveLength(2);
expect(body.data.revoked.map((r) => r.kind).sort()).toEqual([
"ai_coach",
"ai_full",
]);
});
});
describe("append-only invariant", () => {
/**
* v1.4.40 SB-10 — the receipts table is the legal audit trail.
* Revoking + re-granting must leave the original row in place
* (just with `revokedAt` set) and mint a fresh row for the new
* grant. The latest active receipt after the cycle is the newest
* one, not the original.
*/
it("revoke + re-grant leaves both rows; latestActive points at the re-grant", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const signedAt1 = new Date("2026-05-18T10:00:00.000Z");
const createdAt1 = new Date("2026-05-18T10:00:01.000Z");
const revokedAt = new Date("2026-05-18T11:00:00.000Z");
const signedAt2 = new Date("2026-05-18T12:00:00.000Z");
const createdAt2 = new Date("2026-05-18T12:00:01.000Z");
// Step 1: initial grant.
vi.mocked(prisma.consentReceipt.create).mockResolvedValueOnce({
id: "rcpt-1",
userId: "user-1",
kind: "ai_full",
artefact: "PDF-v1",
signedAt: signedAt1,
revokedAt: null,
createdAt: createdAt1,
} as never);
const grant1 = await POST_GRANT(
new NextRequest("http://localhost/api/consent/ai", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
kind: "ai_full",
artefact: "PDF-v1",
signedAt: signedAt1.toISOString(),
}),
}),
);
expect(grant1.status).toBe(200);
// Step 2: revoke. The DELETE handler reads + updates.
vi.mocked(prisma.consentReceipt.findFirst).mockResolvedValueOnce({
id: "rcpt-1",
userId: "user-1",
kind: "ai_full",
artefact: "PDF-v1",
signedAt: signedAt1,
revokedAt: null,
createdAt: createdAt1,
} as never);
vi.mocked(prisma.consentReceipt.update).mockResolvedValueOnce({
id: "rcpt-1",
userId: "user-1",
kind: "ai_full",
artefact: "PDF-v1",
signedAt: signedAt1,
revokedAt,
createdAt: createdAt1,
} as never);
const revokeRes = await DELETE(
new NextRequest("http://localhost/api/consent/ai/latest?kind=ai_full", {
method: "DELETE",
}),
);
expect(revokeRes.status).toBe(200);
expect(prisma.consentReceipt.update).toHaveBeenCalledTimes(1);
// Critical invariant — `delete` was NEVER called on the receipt.
// Only an update setting `revokedAt`. The old row stays in place.
const updateCall = vi.mocked(prisma.consentReceipt.update).mock.calls[0][0];
expect(updateCall).toMatchObject({
where: { id: "rcpt-1" },
data: { revokedAt: expect.any(Date) },
});
// Step 3: re-grant mints a fresh row.
vi.mocked(prisma.consentReceipt.create).mockResolvedValueOnce({
id: "rcpt-2",
userId: "user-1",
kind: "ai_full",
artefact: "PDF-v2",
signedAt: signedAt2,
revokedAt: null,
createdAt: createdAt2,
} as never);
const grant2 = await POST_GRANT(
new NextRequest("http://localhost/api/consent/ai", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
kind: "ai_full",
artefact: "PDF-v2",
signedAt: signedAt2.toISOString(),
}),
}),
);
expect(grant2.status).toBe(200);
expect(prisma.consentReceipt.create).toHaveBeenCalledTimes(2);
// Step 4: GET latest now points at the re-grant.
vi.mocked(prisma.consentReceipt.findFirst).mockResolvedValueOnce({
id: "rcpt-2",
userId: "user-1",
kind: "ai_full",
artefact: "PDF-v2",
signedAt: signedAt2,
revokedAt: null,
createdAt: createdAt2,
} as never);
const latest = await GET(
new NextRequest("http://localhost/api/consent/ai/latest?kind=ai_full"),
);
const body = (await latest.json()) as {
data: { receipt: { id: string } | null };
};
expect(body.data.receipt?.id).toBe("rcpt-2");
});
});
+143
View File
@@ -0,0 +1,143 @@
/**
* v1.4.40 SB-10 — AI consent latest-receipt reader + revoke endpoint.
*
* GET /api/consent/ai/latest?kind=ai_full
* Returns the latest non-revoked receipt for that kind, or null.
*
* GET /api/consent/ai/latest
* Returns the latest non-revoked receipt per kind, keyed by kind.
*
* DELETE /api/consent/ai/latest?kind=ai_full
* Marks the latest active receipt for that kind as revoked.
*
* DELETE /api/consent/ai/latest
* Master toggle — revokes the latest active receipt across every
* consent kind. Returns the list of revoked rows.
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiError, apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import {
consentKindEnum,
consentLatestQuery,
type ConsentKind,
} from "@/lib/validations/consent";
import {
latestActiveReceipt,
latestActiveReceiptsByKind,
revokeLatest,
} from "@/lib/consent/receipts";
import { serialiseReceipt } from "../route";
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const parsed = consentLatestQuery.safeParse(
Object.fromEntries(request.nextUrl.searchParams),
);
if (!parsed.success) {
return apiError(parsed.error.issues[0].message, 400);
}
const { kind } = parsed.data;
if (kind) {
const receipt = await latestActiveReceipt(user.id, kind);
annotate({
action: { name: "consent.ai.latest" },
meta: { kind, found: receipt != null },
});
return apiSuccess({
kind,
receipt: receipt ? serialiseReceipt(receipt) : null,
});
}
const byKind = await latestActiveReceiptsByKind(user.id);
// Map each enum value to either the serialised row or `null` so the
// client always sees the full keyspace and never has to guess
// whether a missing key means "not granted" or "schema gap".
const result: Record<ConsentKind, ReturnType<typeof serialiseReceipt> | null> = {
ai_full: byKind.ai_full ? serialiseReceipt(byKind.ai_full) : null,
ai_insights_only: byKind.ai_insights_only
? serialiseReceipt(byKind.ai_insights_only)
: null,
ai_coach: byKind.ai_coach ? serialiseReceipt(byKind.ai_coach) : null,
};
annotate({
action: { name: "consent.ai.latest" },
meta: {
kinds_active: Object.entries(result)
.filter(([, v]) => v != null)
.map(([k]) => k),
},
});
return apiSuccess(result);
});
export const DELETE = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const parsed = consentLatestQuery.safeParse(
Object.fromEntries(request.nextUrl.searchParams),
);
if (!parsed.success) {
return apiError(parsed.error.issues[0].message, 400);
}
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 });
}
auditLog("consent.ai.revoke", {
userId: user.id,
details: { kind, receiptId: revoked.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(() => {});
}
}
annotate({
action: { name: "consent.ai.revoke" },
meta: {
kinds_revoked: revokedRows.map((r) => r.kind),
count: revokedRows.length,
},
});
return apiSuccess({ revoked: revokedRows });
});
+84
View File
@@ -0,0 +1,84 @@
/**
* v1.4.40 SB-10 — AI consent receipts.
*
* POST /api/consent/ai
* Body: { kind, artefact, signedAt }
* Persists a fresh consent receipt. Returns the inserted row.
*
* Reader + revoke handlers live in `./latest/route.ts`.
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiError, apiSuccess, safeJson } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { consentPostBody } from "@/lib/validations/consent";
import { createReceipt } from "@/lib/consent/receipts";
export const POST = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const { data: body, error } = await safeJson(request);
if (error) return error;
const parsed = consentPostBody.safeParse(body);
if (!parsed.success) {
return apiError(parsed.error.issues[0].message, 400);
}
const { kind, artefact, signedAt } = parsed.data;
const receipt = await createReceipt(user.id, kind, artefact, signedAt);
// Audit trail — separate from the row itself so the legal team can
// reconstruct "who minted this and when" even if the receipts table
// is rebuilt from a backup. Fire-and-forget; audit failures must
// never bubble into a user-facing 500.
auditLog("consent.ai.grant", {
userId: user.id,
details: { kind, receiptId: receipt.id },
}).catch(() => {});
annotate({
action: { name: "consent.ai.grant" },
meta: { kind, receiptId: receipt.id },
});
return apiSuccess({
id: receipt.id,
receipt: serialiseReceipt(receipt),
});
});
interface SerialisedReceipt {
id: string;
userId: string;
kind: string;
signedAt: string;
revokedAt: string | null;
createdAt: string;
}
/**
* Public projection of a `ConsentReceipt`. We deliberately strip
* `artefact` from the API response — the artefact is large, opaque,
* and only useful at audit time (read directly from the DB by an
* operator). Echoing it on every grant would balloon the payload and
* leak the signed token over network paths it doesn't need to cross.
*/
export function serialiseReceipt(receipt: {
id: string;
userId: string;
kind: string;
signedAt: Date;
revokedAt: Date | null;
createdAt: Date;
}): SerialisedReceipt {
return {
id: receipt.id,
userId: receipt.userId,
kind: receipt.kind,
signedAt: receipt.signedAt.toISOString(),
revokedAt: receipt.revokedAt?.toISOString() ?? null,
createdAt: receipt.createdAt.toISOString(),
};
}