chore(release): v1.4.47 — audit-backlog closure + drag-to-reorder + Coach disable + OAuth nonce ledger

Eight changes: W0 idempotency test pin, W1 legacy column drop, W2 Textarea primitive, W3 Coach disable toggle, W4 dnd-kit drag-to-reorder, W5 onboarding 24h gate, W6 Withings OAuth nonce ledger, W7+W8 legacy_form_total drop + Coach onLine pre-check. 6-axis QA reconciled. Migrations 0076/0077/0078 required pre-image. Tests 5093 → ~5170.
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-05-22 09:18:52 +02:00
1 parent ac319c6160
commit 66a7f8b6fa
68 files changed
+3959 -715

No files matched your search

@@ -0,0 +1,260 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
user: {
findUnique: 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("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn().mockResolvedValue({
allowed: true,
remaining: 59,
resetAt: Date.now() + 60_000,
}),
rateLimitHeaders: () => ({}),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET, PATCH } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { auditLog } from "@/lib/auth/audit";
import { checkRateLimit } from "@/lib/rate-limit";
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 mkPatch(body: unknown): Request {
return new Request("http://localhost/api/auth/me/disable-coach", {
method: "PATCH",
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
});
}
beforeEach(() => {
vi.clearAllMocks();
});
describe("GET /api/auth/me/disable-coach", () => {
it("rejects an unauthenticated request with 401", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const res = await (GET as (r: Request) => Promise<Response>)(
new Request("http://localhost/api/auth/me/disable-coach"),
);
expect(res.status).toBe(401);
expect(prisma.user.findUnique).not.toHaveBeenCalled();
});
it("returns false for a fresh user", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
disableCoach: false,
} as never);
const res = await (GET as (r: Request) => Promise<Response>)(
new Request("http://localhost/api/auth/me/disable-coach"),
);
expect(res.status).toBe(200);
const env = (await res.json()) as { data: { disableCoach: boolean } };
expect(env.data.disableCoach).toBe(false);
});
it("returns true for an opted-out user", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
disableCoach: true,
} as never);
const res = await (GET as (r: Request) => Promise<Response>)(
new Request("http://localhost/api/auth/me/disable-coach"),
);
expect(res.status).toBe(200);
const env = (await res.json()) as { data: { disableCoach: boolean } };
expect(env.data.disableCoach).toBe(true);
});
it("returns false when the column is missing (partial-deploy rollback)", async () => {
// Defensive default — the API surface tolerates a `findUnique`
// result that doesn't contain the column. Belt-and-braces with the
// schema-level NOT NULL default; both layers keep the Coach
// visible by default for users who never opted out.
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({} as never);
const res = await (GET as (r: Request) => Promise<Response>)(
new Request("http://localhost/api/auth/me/disable-coach"),
);
expect(res.status).toBe(200);
const env = (await res.json()) as { data: { disableCoach: boolean } };
expect(env.data.disableCoach).toBe(false);
});
});
describe("PATCH /api/auth/me/disable-coach", () => {
it("rejects an unauthenticated request with 401", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const res = await (PATCH as (r: Request) => Promise<Response>)(
mkPatch({ disableCoach: true }),
);
expect(res.status).toBe(401);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("flips the column on and writes the enable audit row", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
disableCoach: false,
} as never);
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
const res = await (PATCH as (r: Request) => Promise<Response>)(
mkPatch({ disableCoach: true }),
);
expect(res.status).toBe(200);
const env = (await res.json()) as { data: { disableCoach: boolean } };
expect(env.data.disableCoach).toBe(true);
expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: "user-1" },
data: { disableCoach: true },
});
expect(auditLog).toHaveBeenCalledWith(
"user.disable-coach.enable",
expect.objectContaining({
userId: "user-1",
details: expect.objectContaining({
previous: false,
next: true,
}),
}),
);
});
it("flips the column off and writes the disable audit row", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
disableCoach: true,
} as never);
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
const res = await (PATCH as (r: Request) => Promise<Response>)(
mkPatch({ disableCoach: false }),
);
expect(res.status).toBe(200);
const env = (await res.json()) as { data: { disableCoach: boolean } };
expect(env.data.disableCoach).toBe(false);
expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: "user-1" },
data: { disableCoach: false },
});
expect(auditLog).toHaveBeenCalledWith(
"user.disable-coach.disable",
expect.objectContaining({
userId: "user-1",
details: expect.objectContaining({
previous: true,
next: false,
}),
}),
);
});
it("rejects a missing disableCoach field with 422", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await (PATCH as (r: Request) => Promise<Response>)(
mkPatch({ otherField: "ignored" }),
);
expect(res.status).toBe(422);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("rejects a non-boolean disableCoach field with 422", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await (PATCH as (r: Request) => Promise<Response>)(
mkPatch({ disableCoach: "true" }),
);
expect(res.status).toBe(422);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("rejects malformed JSON with 422", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const req = new Request("http://localhost/api/auth/me/disable-coach", {
method: "PATCH",
body: "{ not valid json",
headers: { "Content-Type": "application/json" },
});
const res = await (PATCH as (r: Request) => Promise<Response>)(req);
expect(res.status).toBe(422);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("is idempotent when the column already holds the requested value", async () => {
// Toggling a column from true→true (or false→false) still writes
// through so the audit row exists. Matches the research-mode
// route's "always write" posture.
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
disableCoach: true,
} as never);
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
const res = await (PATCH as (r: Request) => Promise<Response>)(
mkPatch({ disableCoach: true }),
);
expect(res.status).toBe(200);
expect(prisma.user.update).toHaveBeenCalledTimes(1);
expect(auditLog).toHaveBeenCalledTimes(1);
});
it("returns 429 when the per-user rate-limit fires", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(checkRateLimit).mockResolvedValueOnce({
allowed: false,
remaining: 0,
resetAt: Date.now() + 30_000,
});
const res = await (PATCH as (r: Request) => Promise<Response>)(
mkPatch({ disableCoach: true }),
);
expect(res.status).toBe(429);
expect(prisma.user.update).not.toHaveBeenCalled();
});
});
+121
View File
@@ -0,0 +1,121 @@
/**
* v1.4.47 W3 — per-user Coach opt-out endpoint.
*
* GET /api/auth/me/disable-coach — current flag.
* PATCH /api/auth/me/disable-coach — body `{ disableCoach: boolean }`.
* Flips the column and emits an
* audit-log row mirroring the
* Research-Mode endpoint pattern.
*
* The toggle is reachable from Settings → Insights as a `<Switch>`
* labelled "Hide Coach" / "Coach ausblenden". Default `false` (Coach
* visible) — see migration `0076_v1447_user_disable_coach` for the
* column-level documentation.
*
* Idempotent. The endpoint always returns the resolved next-state
* shape so the client can hard-set the optimistic update without an
* extra round-trip. Rate-limit is intentionally generous (60/min) —
* the Switch is a one-tap affordance, but iOS clients may eventually
* batch settings round-trips after a passkey re-pair and a tight
* 5/min would surface as a 429 on a normal onboarding flow.
*/
import { apiHandler, requireAuth, HttpError } from "@/lib/api-handler";
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
export const dynamic = "force-dynamic";
const PATCH_RATE_LIMIT = 60;
const PATCH_WINDOW_MS = 60_000;
type DisableCoachResponse = {
disableCoach: boolean;
};
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
annotate({ action: { name: "auth.me.disable-coach.get" } });
const row = await prisma.user.findUnique({
where: { id: user.id },
select: { disableCoach: true },
});
const payload: DisableCoachResponse = {
disableCoach: row?.disableCoach ?? false,
};
return apiSuccess(payload);
});
export const PATCH = apiHandler(async (req: Request) => {
const { user } = await requireAuth();
const rl = await checkRateLimit(
`disable-coach:patch:${user.id}`,
PATCH_RATE_LIMIT,
PATCH_WINDOW_MS,
);
if (!rl.allowed) {
const response = apiError("Too many requests", 429);
for (const [k, v] of Object.entries(rateLimitHeaders(rl))) {
response.headers.set(k, v);
}
return response;
}
let body: unknown;
try {
body = await req.json();
} catch {
throw new HttpError(422, "disable-coach.body.invalid_json");
}
// Hand-rolled validation — single boolean field. Keeps the
// prompt-injection surface visibly empty in code review (no string
// ever reaches an LLM).
if (
!body ||
typeof body !== "object" ||
typeof (body as { disableCoach?: unknown }).disableCoach !== "boolean"
) {
annotate({ action: { name: "auth.me.disable-coach.patch.invalid_shape" } });
throw new HttpError(422, "disable-coach.body.invalid_shape");
}
const next = (body as { disableCoach: boolean }).disableCoach;
const previous = await prisma.user.findUnique({
where: { id: user.id },
select: { disableCoach: true },
});
// Idempotent — write even when the values match so the audit row
// mirrors the API call. The DB write is cheap and the audit log is
// the source of truth for "user toggled this".
await prisma.user.update({
where: { id: user.id },
data: { disableCoach: next },
});
await auditLog(
next ? "user.disable-coach.enable" : "user.disable-coach.disable",
{
userId: user.id,
ipAddress: getClientIp(req),
details: {
previous: previous?.disableCoach ?? false,
next,
},
},
);
annotate({
action: { name: "auth.me.disable-coach.patch" },
meta: { disableCoach: next },
});
const payload: DisableCoachResponse = { disableCoach: next };
return apiSuccess(payload);
});
+6
View File
@@ -32,5 +32,11 @@ export const GET = apiHandler(async () => {
gravatarUrl: user.email ? getGravatarUrl(user.email) : null,
glucoseUnit: user.glucoseUnit ?? null,
lastReportPracticeName: user.lastReportPracticeName ?? null,
// v1.4.47 W3 — per-user Coach opt-out. Default `false` if the
// column is absent (partial-deploy rollback safety, see migration
// 0076 commentary). Every Coach mount point on the client checks
// `user.disableCoach` BELOW the operator-level `flags.coach`
// short-circuit; both gates must agree to paint the affordance.
disableCoach: user.disableCoach ?? false,
});
});