mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 07:42:23 +00:00
chore(release): v1.4.25
Largest feature delta in the v1.4.x line. Insights expands into seven dedicated metric sub-pages; GLP-1 medication tracking lands end-to-end (drug-level chart with Research Mode acknowledgment, EMA titration ladder, cadence + compliance, side-effect taxonomy, pen/vial inventory); cross-source priority becomes a two-axis resolver; per-user timezone threads through ten analytics surfaces; Withings activity + sleep v2 sync; onboarding rebuilt as a nested-route wizard; Personal Records ship end-to-end; Health Score provenance accordion; Coach runs native first-party prompts across six locales with a 1800-assertion refusal-probe matrix; OpenAPI drift gate hard-fails; multi-arch GHCR image. Migrations 0043 through 0060 are additive and forward-only. PROMPT_VERSION 4.24.0 → 4.25.0 with GROUND RULE 9 (refuses dose recommendations) and GROUND RULE 15 (refuses drug-level estimates with MDR + MDCG 2021-24 cites). See CHANGELOG.md for the full per-section delta.
This commit is contained in:
1 parent
de0689e419
commit
17b8d8d2c2
528 files changed
+104033
-6524
No files matched your search
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* v1.4.25 W21 Fix-M — concurrency regression for
|
||||
* `POST /api/onboarding/step`.
|
||||
*
|
||||
* The step write was fetch-then-update: two parallel tabs both
|
||||
* reading `onboardingStep = 2` and both POSTing `step: 3` would both
|
||||
* succeed because the second write didn't re-check the precondition.
|
||||
* The route now claims the row via `updateMany` with the precondition
|
||||
* embedded in the WHERE clause, so exactly one update lands and the
|
||||
* loser sees `count = 0` and returns 409.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
findUniqueOrThrow: vi.fn(),
|
||||
update: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({
|
||||
getSession: vi.fn(),
|
||||
setOnboardingPendingCookie: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
checkRateLimit: vi.fn().mockResolvedValue({
|
||||
allowed: true,
|
||||
remaining: 29,
|
||||
resetAt: Date.now() + 60_000,
|
||||
}),
|
||||
rateLimitHeaders: vi.fn(() => ({})),
|
||||
}));
|
||||
|
||||
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 "../step/route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
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 req(body: unknown): NextRequest {
|
||||
return new NextRequest("http://localhost/api/onboarding/step", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(checkRateLimit).mockResolvedValue({
|
||||
allowed: true,
|
||||
remaining: 29,
|
||||
resetAt: Date.now() + 60_000,
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/onboarding/step — happy path", () => {
|
||||
it("advances 0 → 1 on the first wizard submission", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
onboardingStep: 0,
|
||||
onboardingCompletedAt: null,
|
||||
} as never);
|
||||
vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 1 } as never);
|
||||
vi.mocked(prisma.user.findUniqueOrThrow).mockResolvedValue({
|
||||
onboardingStep: 1,
|
||||
onboardingCompletedAt: null,
|
||||
} as never);
|
||||
|
||||
const res = await POST(req({ step: 1 }));
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { data: { step: number } };
|
||||
expect(body.data.step).toBe(1);
|
||||
});
|
||||
|
||||
it("marks completion on step 4 (sets onboardingCompletedAt)", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
onboardingStep: 3,
|
||||
onboardingCompletedAt: null,
|
||||
} as never);
|
||||
vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 1 } as never);
|
||||
vi.mocked(prisma.user.findUniqueOrThrow).mockResolvedValue({
|
||||
onboardingStep: 4,
|
||||
onboardingCompletedAt: new Date("2026-05-14T12:00:00Z"),
|
||||
} as never);
|
||||
|
||||
const res = await POST(req({ step: 4 }));
|
||||
expect(res.status).toBe(200);
|
||||
const updateCall = vi.mocked(prisma.user.updateMany).mock.calls[0][0];
|
||||
expect(updateCall.data).toMatchObject({
|
||||
onboardingStep: 4,
|
||||
});
|
||||
expect(updateCall.data).toHaveProperty("onboardingCompletedAt");
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/onboarding/step — guard rails", () => {
|
||||
it("returns 401 when unauthenticated", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(null);
|
||||
const res = await POST(req({ step: 1 }));
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns 422 for an out-of-range step value", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
const res = await POST(req({ step: 99 }));
|
||||
expect(res.status).toBe(422);
|
||||
});
|
||||
|
||||
it("returns 409 when the user has already completed onboarding", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
onboardingStep: 4,
|
||||
onboardingCompletedAt: new Date("2026-05-01T12:00:00Z"),
|
||||
} as never);
|
||||
|
||||
const res = await POST(req({ step: 1 }));
|
||||
expect(res.status).toBe(409);
|
||||
expect(prisma.user.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 409 when the requested step is out of order", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
onboardingStep: 1,
|
||||
onboardingCompletedAt: null,
|
||||
} as never);
|
||||
|
||||
// The route sees current = 1; submitting step 3 (skipping 2) must
|
||||
// be rejected before the write.
|
||||
const res = await POST(req({ step: 3 }));
|
||||
expect(res.status).toBe(409);
|
||||
expect(prisma.user.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/onboarding/step — concurrent write race", () => {
|
||||
it("returns 409 when the conditional update affects zero rows", async () => {
|
||||
// Regression for Fix-M / code-M7: two parallel tabs both read
|
||||
// `onboardingStep = 2`, both POST `step: 3`. The first lands;
|
||||
// when the second runs the conditional updateMany, the WHERE
|
||||
// clause no longer matches (the column moved to 3) and Prisma
|
||||
// returns `count = 0`. The route must surface 409 so the client
|
||||
// can refresh and retry instead of double-advancing the wizard.
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
onboardingStep: 2,
|
||||
onboardingCompletedAt: null,
|
||||
} as never);
|
||||
vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 0 } as never);
|
||||
|
||||
const res = await POST(req({ step: 3 }));
|
||||
expect(res.status).toBe(409);
|
||||
// findUniqueOrThrow must NOT be called when the claim fails —
|
||||
// the route returns before re-reading the row.
|
||||
expect(prisma.user.findUniqueOrThrow).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("includes the precondition in the updateMany WHERE clause", async () => {
|
||||
// The whole point of the conditional update is that the WHERE
|
||||
// clause re-asserts the precondition we read. Pin the contract
|
||||
// so a future refactor can't quietly drop the guard.
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
onboardingStep: 2,
|
||||
onboardingCompletedAt: null,
|
||||
} as never);
|
||||
vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 1 } as never);
|
||||
vi.mocked(prisma.user.findUniqueOrThrow).mockResolvedValue({
|
||||
onboardingStep: 3,
|
||||
onboardingCompletedAt: null,
|
||||
} as never);
|
||||
|
||||
await POST(req({ step: 3 }));
|
||||
const whereArg = vi.mocked(prisma.user.updateMany).mock.calls[0][0]
|
||||
.where as Record<string, unknown>;
|
||||
expect(whereArg).toMatchObject({
|
||||
id: "user-1",
|
||||
onboardingCompletedAt: null,
|
||||
});
|
||||
// Strict-equality precondition — Migration 0060 dropped the
|
||||
// legacy nullable path so every advance uses `{ in: [current] }`.
|
||||
expect(whereArg.onboardingStep).toEqual({ in: [2] });
|
||||
});
|
||||
|
||||
it("advances a step-0 row to step 1 using the strict-equality precondition", async () => {
|
||||
// Migration 0060 (v1.4.25 W21 Fix-O) backfilled NULL → 0 and
|
||||
// flipped `onboarding_step` to NOT NULL, so the conditional
|
||||
// update always uses the strict-equality form — there is no
|
||||
// legacy null branch left for the route to widen.
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
onboardingStep: 0,
|
||||
onboardingCompletedAt: null,
|
||||
} as never);
|
||||
vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 1 } as never);
|
||||
vi.mocked(prisma.user.findUniqueOrThrow).mockResolvedValue({
|
||||
onboardingStep: 1,
|
||||
onboardingCompletedAt: null,
|
||||
} as never);
|
||||
|
||||
const res = await POST(req({ step: 1 }));
|
||||
expect(res.status).toBe(200);
|
||||
const whereArg = vi.mocked(prisma.user.updateMany).mock.calls[0][0]
|
||||
.where as Record<string, unknown>;
|
||||
expect(whereArg.onboardingStep).toEqual({ in: [0] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/onboarding/step — rate limit", () => {
|
||||
it("returns 429 when the per-user rate limit is exceeded", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(checkRateLimit).mockResolvedValueOnce({
|
||||
allowed: false,
|
||||
remaining: 0,
|
||||
resetAt: Date.now() + 60_000,
|
||||
});
|
||||
const res = await POST(req({ step: 1 }));
|
||||
expect(res.status).toBe(429);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import {
|
||||
apiError,
|
||||
apiSuccess,
|
||||
getClientIp,
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { setOnboardingPendingCookie } from "@/lib/auth/session";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
/**
|
||||
* v1.4.25 W14b — POST /api/onboarding/step.
|
||||
*
|
||||
* Persists the user's progress through the rebuilt
|
||||
* `/onboarding/[step]` wizard. Body: `{ step: number }` where `step`
|
||||
* is 1..4. The endpoint enforces a strict step-by-step contract:
|
||||
*
|
||||
* - Submitted step must equal `current + 1` (no skipping ahead).
|
||||
* - Submitting step 4 marks completion — `onboardingCompletedAt`
|
||||
* flips from null to NOW() in the same write and the
|
||||
* `hl_onboarding` proxy cookie is cleared.
|
||||
* - Already-completed users (`onboardingCompletedAt != null`)
|
||||
* receive a 409. Replays must call this endpoint only while the
|
||||
* wizard is in-progress.
|
||||
*
|
||||
* Companion to:
|
||||
* - `GET ` not implemented (the User row is already loaded into
|
||||
* every server-rendered step page).
|
||||
* - `POST /api/onboarding/complete` remains the legacy v1.4.20
|
||||
* completion path used by the old single-file wizard; the new
|
||||
* flow uses this endpoint with `step: 4` instead.
|
||||
*
|
||||
* Rate limit: 30 writes / 10 min / user — generous for a 4-step flow
|
||||
* but tight enough to defang a stuck retry loop.
|
||||
*/
|
||||
|
||||
const stepBodySchema = z.object({
|
||||
step: z.number().int().min(1).max(4),
|
||||
});
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "onboarding.step" } });
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`onboarding-step:${user.id}`,
|
||||
30,
|
||||
10 * 60 * 1000,
|
||||
);
|
||||
if (!rl.allowed) {
|
||||
annotate({
|
||||
action: { name: "onboarding.step" },
|
||||
meta: { outcome: "rate_limited" },
|
||||
});
|
||||
return apiError("Too many onboarding writes, try again later", 429);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson<unknown>(request);
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
const parsed = stepBodySchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
annotate({
|
||||
action: { name: "onboarding.step" },
|
||||
meta: { outcome: "validation_failed" },
|
||||
});
|
||||
return apiError("Invalid step payload", 422);
|
||||
}
|
||||
const { step } = parsed.data;
|
||||
|
||||
// Re-fetch the fresh User row so concurrent step submissions in
|
||||
// separate tabs can't race past each other — the session.user
|
||||
// snapshot might be a request-old.
|
||||
const fresh = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
onboardingStep: true,
|
||||
onboardingCompletedAt: true,
|
||||
},
|
||||
});
|
||||
if (!fresh) {
|
||||
return apiError("User not found", 404);
|
||||
}
|
||||
|
||||
if (fresh.onboardingCompletedAt) {
|
||||
annotate({
|
||||
action: { name: "onboarding.step" },
|
||||
meta: { outcome: "already_completed" },
|
||||
});
|
||||
return apiError("Onboarding already completed", 409);
|
||||
}
|
||||
|
||||
const current = fresh.onboardingStep;
|
||||
if (step !== current + 1) {
|
||||
annotate({
|
||||
action: { name: "onboarding.step" },
|
||||
meta: { outcome: "out_of_order", current, requested: step },
|
||||
});
|
||||
return apiError(
|
||||
`Step out of order — current step is ${current}`,
|
||||
409,
|
||||
);
|
||||
}
|
||||
|
||||
const completing = step === 4;
|
||||
|
||||
// Conditional update — the WHERE clause re-asserts the
|
||||
// precondition we read above so the write can only land on a row
|
||||
// whose state still matches what we validated. Two parallel tabs
|
||||
// both reading `onboardingStep = 2` and both POSTing `step: 3`
|
||||
// would otherwise both succeed (the read-then-write race); with
|
||||
// this guard exactly one update sees `count = 1`, the second sees
|
||||
// `count = 0` and returns 409. `onboardingCompletedAt: null` also
|
||||
// catches a race with `POST /api/onboarding/complete`. Migration
|
||||
// 0060 (v1.4.25 W21) backfilled NULL → 0 and flipped the column
|
||||
// to NOT NULL, so the legacy null branch this code carried before
|
||||
// is dropped — every row now matches the strict-equality form.
|
||||
const claimed = await prisma.user.updateMany({
|
||||
where: {
|
||||
id: user.id,
|
||||
onboardingCompletedAt: null,
|
||||
onboardingStep: { in: [current] },
|
||||
},
|
||||
data: {
|
||||
onboardingStep: step,
|
||||
...(completing ? { onboardingCompletedAt: new Date() } : {}),
|
||||
},
|
||||
});
|
||||
if (claimed.count !== 1) {
|
||||
annotate({
|
||||
action: { name: "onboarding.step" },
|
||||
meta: { outcome: "concurrent_write", current, requested: step },
|
||||
});
|
||||
return apiError(
|
||||
"Onboarding step changed concurrently, refresh and retry",
|
||||
409,
|
||||
);
|
||||
}
|
||||
const updated = await prisma.user.findUniqueOrThrow({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
onboardingStep: true,
|
||||
onboardingCompletedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (completing) {
|
||||
// Mirror /api/onboarding/complete — clear the proxy-readable
|
||||
// pending cookie so the next navigation drops the /onboarding
|
||||
// redirect immediately.
|
||||
await setOnboardingPendingCookie(false);
|
||||
}
|
||||
|
||||
await auditLog("onboarding.step", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: {
|
||||
step,
|
||||
completed: completing,
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: { name: "onboarding.step" },
|
||||
meta: { outcome: completing ? "completed" : "advanced", step },
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
step: updated.onboardingStep,
|
||||
onboardingCompletedAt: updated.onboardingCompletedAt,
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user