Files
HealthLog/src/lib/__tests__/api-response-zod.test.ts
T
Marc-André Bombeck f92e644154 chore(release): v1.4.49 — audit-backlog closure + server reminder suppression + diagnostic endpoint + analytics cold-path fix
Bundles the deferred v1.4.47 Mediums + Lows with the v1.4.48-deferred items
into a single release. Headline: server-side suppression of MEDICATION_REMINDER
APNs for iOS clients that own their local reminders (closes GH #206), a
push_attempts table backing /api/admin/notifications/diagnostic, and a sweep
of v1.4.48 QA forward-findings.

Performance (the user-visible win):
- /api/analytics cold-fallback path splits the heavy single-statement
  aggregate into two parallel queries. The linearly composable columns
  (count / min / max / mean) keep the full-partition scan; the windowed
  7 / 30 / 90-day avg / slope / r² columns take a 90-day outer cap so
  the planner does an index range scan on (user_id, type, measured_at)
  instead of a full-partition sequential scan. Output is bit-identical;
  cold slim slice drops from multi-second to sub-second on tenants with
  large measurement partitions.

Server-side notifications:
- GET + PATCH /api/auth/me/notification-prefs with deep-merge semantics.
  Initial category medication.clientManaged: boolean (default false). Cron
  medicationReminderJob skips dose-due APNs when the flag is true,
  emitting a medication_reminder.suppressed_client_managed wide-event
  annotation per skip.
- push_attempts table backs the diagnostic endpoint. Every APNS /
  Web-Push / Telegram / NTFY sender writes a fire-and-forget row.
  Daily 03:35 Europe/Berlin cleanup prunes rows older than 90 days.
- /api/admin/notifications/diagnostic — admin-only endpoint surfacing
  device APNs token presence (masked), channel config presence, and
  recent push attempts. Registered in OpenAPI.
- Per-channel APNs "Send test" button now fires with
  eventType: "MEDICATION_REMINDER" so the dispatcher's time-sensitive +
  priority-10 branch runs. A successful self-test now exercises the
  exact path production reminders take; an unsuccessful one points the
  user at iOS Settings → Time Sensitive Notifications rather than
  appearing to be a server-side bug.

Withings reliability:
- OAuth callback consumes the nonce atomically (delete-first with
  P2025 catch for the replay branch). The previous read-then-delete
  pattern allowed a race between two concurrent callbacks.
- ?reason=state redirect differentiated into csrf1 / replay / expired /
  cross_user so operators can tell mismatch types apart without DB
  shell access.
- connect endpoint rate-limited to 10/60s/user; row-create failures
  redirect to a consistent error surface.

Observability hardening:
- redactSensitiveFields(body) denylist helper covers password / token /
  secret / apiKey / authorization / csrfState / nonce, recursive,
  case-insensitive. Caught: /api/devices invalid_format issues were
  echoing apnsToken values verbatim into the audit log.
- sanitiseZodIssues(issues, { stripValuesFromMessage: true }) overload
  applied to 14 audit-log sites.

Migrations: 0079 (notification_prefs), 0080 (push_attempts).

Tests: 4815 → 5272 unit + integration. Workout-batch integration suite
that had been red on main since v1.4.45 (three release commits shipped
through it) now green again — updated to match v1.4.42 cross-source
dedup semantics.

Resolves PR #207.
2026-05-23 12:51:41 +02:00

168 lines
6.2 KiB
TypeScript

import { describe, it, expect } from "vitest";
import { z } from "zod/v4";
import {
returnAllZodIssues,
sanitiseZodIssues,
} from "../api-response";
// v1.4.42 W2 — every Zod-validated route historically returned
// `parsed.error.issues[0].message`, dropping every issue past the first.
// `returnAllZodIssues` is the additive replacement: clients that only
// read `error` keep working, new callers branch on `details.issues`.
const schema = z.object({
version: z.literal(1),
widgets: z.array(z.object({ id: z.string() })).min(1),
comparisonBaseline: z.enum(["none", "lastMonth", "lastYear"]).optional(),
});
describe("returnAllZodIssues", () => {
it("returns 422 by default with a sanitised issue list", async () => {
const parsed = schema.safeParse({});
expect(parsed.success).toBe(false);
if (parsed.success) return;
const response = returnAllZodIssues(parsed.error);
expect(response.status).toBe(422);
const body = (await response.json()) as {
data: null;
error: string;
details: { issues: Array<{ path: string; code: string; message: string }> };
};
expect(body.data).toBeNull();
expect(body.error).toBe("Validation failed");
expect(body.details.issues.length).toBeGreaterThanOrEqual(2);
expect(body.details.issues[0]).toMatchObject({
code: expect.any(String),
message: expect.any(String),
path: expect.any(String),
});
});
it("surfaces TWO simultaneous validation errors", async () => {
const parsed = schema.safeParse({ version: 2, widgets: [] });
expect(parsed.success).toBe(false);
if (parsed.success) return;
const response = returnAllZodIssues(parsed.error);
const body = (await response.json()) as {
details: { issues: Array<{ path: string; code: string }> };
};
expect(body.details.issues.length).toBe(2);
const paths = body.details.issues.map((i) => i.path).sort();
expect(paths).toEqual(["version", "widgets"]);
});
it("surfaces THREE simultaneous validation errors", async () => {
const parsed = schema.safeParse({
version: 2,
widgets: [],
comparisonBaseline: "yesterday",
});
expect(parsed.success).toBe(false);
if (parsed.success) return;
const response = returnAllZodIssues(parsed.error);
const body = (await response.json()) as {
details: { issues: Array<{ path: string; code: string }> };
};
expect(body.details.issues.length).toBe(3);
const paths = body.details.issues.map((i) => i.path).sort();
expect(paths).toEqual(["comparisonBaseline", "version", "widgets"]);
});
it("flattens nested paths with dots", async () => {
const nested = z.object({ outer: z.object({ inner: z.string() }) });
const parsed = nested.safeParse({ outer: { inner: 5 } });
if (parsed.success) throw new Error("expected failure");
const sanitised = sanitiseZodIssues(parsed.error.issues);
expect(sanitised[0].path).toBe("outer.inner");
});
it("does NOT echo issue.params (privacy: may contain user input)", async () => {
const parsed = schema.safeParse({
version: 99,
widgets: [{ id: "x" }],
});
if (parsed.success) throw new Error("expected failure");
const response = returnAllZodIssues(parsed.error);
const body = (await response.json()) as {
details: { issues: Array<Record<string, unknown>> };
};
for (const issue of body.details.issues) {
expect(issue).not.toHaveProperty("params");
// Only path / code / message survive the sanitiser.
expect(Object.keys(issue).sort()).toEqual(["code", "message", "path"]);
}
});
it("respects a custom status code", async () => {
const parsed = schema.safeParse({});
if (parsed.success) throw new Error("expected failure");
const response = returnAllZodIssues(parsed.error, 400);
expect(response.status).toBe(400);
});
it("forwards meta.errorCode and headers like apiError", async () => {
const parsed = schema.safeParse({});
if (parsed.success) throw new Error("expected failure");
const response = returnAllZodIssues(parsed.error, 422, {
errorCode: "dashboard.widgets.invalid",
headers: { "X-Test": "yes" },
});
expect(response.headers.get("X-Test")).toBe("yes");
const body = (await response.json()) as {
meta?: { errorCode?: string; headers?: unknown };
};
expect(body.meta?.errorCode).toBe("dashboard.widgets.invalid");
// Headers are consumed by the NextResponse constructor and stripped
// from the JSON envelope, matching apiError's contract.
expect(body.meta?.headers).toBeUndefined();
});
// v1.4.49 — opt-in `stripValuesFromMessage` mode for audit-ledger
// writes. The default Zod message for `invalid_enum_value` and a
// handful of other codes embeds the offending value verbatim; an
// audit-row write on a free-text route would persist user content.
// The opt-in keeps the additive multi-issue envelope shape but
// drops `message` entirely so only `path` + `code` survive.
describe("sanitiseZodIssues with stripValuesFromMessage", () => {
it("returns { path, code } only when the option is set", () => {
const enumSchema = z.object({
kind: z.enum(["weight", "pulse"]),
});
const parsed = enumSchema.safeParse({ kind: "garbage-value-xxx" });
if (parsed.success) throw new Error("expected failure");
const stripped = sanitiseZodIssues(parsed.error.issues, {
stripValuesFromMessage: true,
});
expect(stripped.length).toBe(1);
for (const issue of stripped) {
expect(Object.keys(issue).sort()).toEqual(["code", "path"]);
// The offending value must not survive on any returned key.
expect(JSON.stringify(issue)).not.toContain("garbage-value-xxx");
}
});
it("default behaviour (no option) keeps message intact", () => {
const enumSchema = z.object({
kind: z.enum(["weight", "pulse"]),
});
const parsed = enumSchema.safeParse({ kind: "garbage" });
if (parsed.success) throw new Error("expected failure");
const kept = sanitiseZodIssues(parsed.error.issues);
expect(kept[0]).toMatchObject({
path: "kind",
code: expect.any(String),
message: expect.any(String),
});
});
});
});