mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
fix(ingest): refuse an external id that cannot be a stable identity
An external id is half of every ingest dedup key — (userId, source, externalId), (userId, externalSource, externalId), (userId, type, source, externalId). Re-posting the same triple is idempotent and returns the existing row, which holds only while the id is stable across client launches. A client that serialised an opaque platform object with its default object description sent a per-allocation memory address instead, so no sweep ever matched its own earlier row and each one minted a fresh record: a live instance grew 23 phantom medications in a day, none of which could collect a dose, because the dose side resolved through the same rotating string. Add one shared classifier for identifiers that provably cannot be an identity — an angle-bracketed object description carrying a hex pointer, a bare 0x address, and a blank value — and wire it at every surface that accepts a client-supplied externalId. Single-entry creates refuse through the schema, so the client gets the standard 422 multi-issue envelope with a message naming the shape it sent and what to send instead. Batch and bulk surfaces classify per entry and report the offending row as skipped with reason unstable_external_id, leaving the rest of the payload to land: one bad row must not stop a sync. Every refusal carries pinned wide-event meta (count, shape, surface) and never the id itself. A structural guard freezes both routes into the floor: a request-side externalId declaration either applies the field check or carries a marker naming the file that checks it per entry, and the guard verifies that file really does. The backup-restore payload is the one exemption, with its reason recorded — it replays ids the server itself wrote.
This commit is contained in:
1 parent
ef9891fec5
commit
2ab66ab2e3
26 files changed
+1232
-64
No files matched your search
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* External-id stability floor.
|
||||
*
|
||||
* The rejected cases are the shapes that provably cannot be an identity.
|
||||
* The accepted cases are every external-id shape this repository actually
|
||||
* receives — grepped out of the ingest routes, the batch contracts, the
|
||||
* OpenAPI examples and the existing fixtures. A false positive here costs
|
||||
* a working client its sync, so the accepted list is the real guard.
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import {
|
||||
assertStableExternalId,
|
||||
classifyExternalId,
|
||||
isStableExternalId,
|
||||
unstableExternalIdMessage,
|
||||
unstableExternalIdMeta,
|
||||
unstableExternalIdShape,
|
||||
UNSTABLE_EXTERNAL_ID_REASON,
|
||||
} from "@/lib/validations/external-id";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
describe("classifyExternalId — refused shapes", () => {
|
||||
it("refuses the object description that caused the live incident", () => {
|
||||
expect(classifyExternalId("<HKHealthConceptIdentifier: 0x12568db80>")).toBe(
|
||||
"object_description",
|
||||
);
|
||||
});
|
||||
|
||||
it("refuses any <Class: 0xHEX> description, not just the one class", () => {
|
||||
for (const value of [
|
||||
"<NSObject: 0x600000c1a2b0>",
|
||||
"<SomeVendorType: 0X7FFEE3B0>",
|
||||
"<Foo: 0x1>",
|
||||
"<HKObject: 0x126b25160; type=bar>",
|
||||
"apple:<HKHealthConceptIdentifier: 0x11f47e3e0>",
|
||||
]) {
|
||||
expect(classifyExternalId(value)).toBe("object_description");
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses a bare pointer value", () => {
|
||||
expect(classifyExternalId("0x12568db80")).toBe("pointer_address");
|
||||
expect(classifyExternalId("0XDEADBEEF")).toBe("pointer_address");
|
||||
});
|
||||
|
||||
it("refuses an empty or whitespace-only id", () => {
|
||||
expect(classifyExternalId("")).toBe("blank");
|
||||
expect(classifyExternalId(" ")).toBe("blank");
|
||||
expect(classifyExternalId("\t\n ")).toBe("blank");
|
||||
});
|
||||
|
||||
it("classifies a padded description after trimming", () => {
|
||||
expect(classifyExternalId(" <HKFoo: 0xabc123> ")).toBe(
|
||||
"object_description",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyExternalId — the id shapes this system actually receives", () => {
|
||||
// Every entry below is a shape that exists in this repository today:
|
||||
// the iOS batch contract, the Apple Health mirror, the Withings /
|
||||
// WHOOP / Oura / Fitbit / Polar sync paths, the CSV importer, and the
|
||||
// web client's own UUID mints.
|
||||
const accepted = [
|
||||
// HealthKit sample UUIDs (upper + lower case, hyphenated)
|
||||
"8AD2A9CB-3F0C-4E4D-9C1E-4B7E2A1D6F30",
|
||||
"3f0c4e4d-9c1e-4b7e-2a1d-6f30ad2a9cb1",
|
||||
// Un-hyphenated / compact ids
|
||||
"8AD2A9CB3F0C4E4D9C1E4B7E2A1D6F30",
|
||||
// The `stats:` aggregate contract (per-day + hourly bucket)
|
||||
"stats:HKQuantityTypeIdentifierStepCount:2026-07-25",
|
||||
"stats:HKQuantityTypeIdentifierActiveEnergyBurned:2026-07-25",
|
||||
"stats:HKQuantityTypeIdentifierHeartRate:2026-07-25T08:10:00Z",
|
||||
// Other structured prefix forms minted in this tree today
|
||||
"assessment:clx1a2b3c4d5e6f7g8h9",
|
||||
"withings:activity:clx1a2b3c4d5e6f7g8h9:2026-07-25:steps",
|
||||
"withings:sleep:clx1a2b3c4d5e6f7g8h9:998877:hr_average",
|
||||
"cycle:123456:strain",
|
||||
"sleep:0f3a8c2e-2b1d-4f5a-9c8e-1d2f3a4b5c6d:hrv_rmssd",
|
||||
"spo2:2026-07-25T03:12:00Z:unknown",
|
||||
"hkcycle:2026-07-25",
|
||||
"stats:steps:2026-07-25",
|
||||
"retired:clx1a2b3c4d5e6f7g8h9:hk-uuid-41",
|
||||
"hk-uuid-41",
|
||||
// Opaque vendor identifiers
|
||||
"1234567890",
|
||||
"clx1a2b3c4d5e6f7g8h9",
|
||||
"a3f5c9e1b7d2486fa0c3e5b7d9f1a2c4e6b8d0f2a4c6e8b0d2f4a6c8e0b2d4f6",
|
||||
// Base64-ish blob
|
||||
"aGVhbHRobG9nOnNhbXBleQ==",
|
||||
// Platform type identifiers
|
||||
"HKQuantityTypeIdentifierStepCount",
|
||||
// Values that merely CONTAIN hex-looking text but are not pointers
|
||||
"0xygen-sample-1",
|
||||
"sample-0x12ab-tail",
|
||||
"not<angle>brackets",
|
||||
"<no-pointer-here>",
|
||||
];
|
||||
|
||||
it.each(accepted)("accepts %s", (value) => {
|
||||
expect(classifyExternalId(value)).toBeNull();
|
||||
expect(isStableExternalId(value)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not reject on length, spaces, or unusual characters alone", () => {
|
||||
expect(isStableExternalId("My Glucose Meter Export Row 41")).toBe(true);
|
||||
expect(isStableExternalId("a")).toBe(true);
|
||||
expect(isStableExternalId("ärztliche-messung-2026-07-25")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("messages", () => {
|
||||
it("names what is wrong and what to send instead", () => {
|
||||
expect(unstableExternalIdMessage("object_description")).toContain(
|
||||
"stable across app restarts",
|
||||
);
|
||||
expect(unstableExternalIdMessage("object_description")).toContain(
|
||||
"object description",
|
||||
);
|
||||
expect(unstableExternalIdMessage("pointer_address")).toContain(
|
||||
"memory address",
|
||||
);
|
||||
expect(unstableExternalIdMessage("blank")).toContain("must not be empty");
|
||||
});
|
||||
});
|
||||
|
||||
describe("assertStableExternalId — object-level Zod check", () => {
|
||||
const schema = z
|
||||
.object({ externalId: z.string().max(128).optional() })
|
||||
.superRefine(assertStableExternalId);
|
||||
|
||||
it("rejects an object description with the actionable message on the field", () => {
|
||||
const parsed = schema.safeParse({
|
||||
externalId: "<HKHealthConceptIdentifier: 0x12568db80>",
|
||||
});
|
||||
expect(parsed.success).toBe(false);
|
||||
if (parsed.success) return;
|
||||
expect(parsed.error.issues).toHaveLength(1);
|
||||
expect(parsed.error.issues[0].path).toEqual(["externalId"]);
|
||||
expect(parsed.error.issues[0].message).toBe(
|
||||
unstableExternalIdMessage("object_description"),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts a stable id and an absent id alike", () => {
|
||||
expect(
|
||||
schema.safeParse({ externalId: "stats:HKFoo:2026-07-25" }).success,
|
||||
).toBe(true);
|
||||
expect(schema.safeParse({}).success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("wide-event helpers", () => {
|
||||
it("reads a top-level externalId off an unparsed body", () => {
|
||||
expect(unstableExternalIdShape({ externalId: "0xdeadbeef" })).toBe(
|
||||
"pointer_address",
|
||||
);
|
||||
expect(unstableExternalIdShape({ externalId: "uuid-1" })).toBeNull();
|
||||
expect(unstableExternalIdShape({ externalId: 42 })).toBeNull();
|
||||
expect(unstableExternalIdShape(null)).toBeNull();
|
||||
expect(unstableExternalIdShape("not-an-object")).toBeNull();
|
||||
});
|
||||
|
||||
it("pins the meta shape and never carries the id itself", () => {
|
||||
expect(
|
||||
unstableExternalIdMeta("measurement.batch", [
|
||||
"object_description",
|
||||
"object_description",
|
||||
"pointer_address",
|
||||
]),
|
||||
).toEqual({
|
||||
external_id_rejected: 3,
|
||||
external_id_shapes: "object_description,pointer_address",
|
||||
external_id_surface: "measurement.batch",
|
||||
});
|
||||
});
|
||||
|
||||
it("exposes one per-entry reason code for every batch surface", () => {
|
||||
expect(UNSTABLE_EXTERNAL_ID_REASON).toBe("unstable_external_id");
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
import { isPlausibleEntryInstant } from "@/lib/validations/entry-instant";
|
||||
import { assertStableExternalId } from "@/lib/validations/external-id";
|
||||
|
||||
/**
|
||||
* v1.17 W1b — `loggedAt` instant on the cycle wire stays a string (the iOS
|
||||
@@ -138,11 +139,28 @@ export const cycleDayLogInputSchema = z.object({
|
||||
note: z.string().max(500).optional(),
|
||||
loggedAt: boundedLoggedAt,
|
||||
source: cycleSourceEnum.optional().default("MANUAL"),
|
||||
// Shared with the bulk ingest, which enforces external-id stability per
|
||||
// entry rather than at the field (a schema-level refusal would fail the
|
||||
// whole batch on one bad row). The single-entry POST parses through
|
||||
// `cycleDayLogCreateSchema` below, which adds the field check.
|
||||
// @external-id-checked-per-entry: src/app/api/cycle/day-logs/bulk/route.ts
|
||||
externalId: z.string().min(1).max(120).optional(),
|
||||
});
|
||||
|
||||
export type CycleDayLogInput = z.infer<typeof cycleDayLogInputSchema>;
|
||||
|
||||
/**
|
||||
* Single-entry POST body. Same shape as the bulk entry plus the
|
||||
* external-id stability floor: a rotating id defeats the
|
||||
* `(userId, source, externalId)` upsert and mints a fresh day log on every
|
||||
* re-post. The bulk path deliberately keeps the permissive entry schema —
|
||||
* it reports the offending entry as `skipped` rather than failing the
|
||||
* whole batch — and applies the same rule per entry in the route.
|
||||
*/
|
||||
export const cycleDayLogCreateSchema = cycleDayLogInputSchema.superRefine(
|
||||
assertStableExternalId,
|
||||
);
|
||||
|
||||
/** PATCH body — every field optional; `date`/`source`/`externalId` are immutable on update. */
|
||||
export const cycleDayLogPatchSchema = z.object({
|
||||
flow: flowLevelEnum.nullable().optional(),
|
||||
@@ -180,12 +198,14 @@ export const cycleBulkSchema = z.object({
|
||||
|
||||
/* ── period-boundary shortcut ────────────────────────────────────── */
|
||||
|
||||
export const cyclePeriodSchema = z.object({
|
||||
action: z.enum(["start", "end"]),
|
||||
date: dateString,
|
||||
externalId: z.string().min(1).max(120).optional(),
|
||||
loggedAt: boundedLoggedAt,
|
||||
});
|
||||
export const cyclePeriodSchema = z
|
||||
.object({
|
||||
action: z.enum(["start", "end"]),
|
||||
date: dateString,
|
||||
externalId: z.string().min(1).max(120).optional(),
|
||||
loggedAt: boundedLoggedAt,
|
||||
})
|
||||
.superRefine(assertStableExternalId);
|
||||
|
||||
/* ── calendar + history queries ──────────────────────────────────── */
|
||||
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* Client-supplied external identifiers — stability floor.
|
||||
*
|
||||
* Every ingest surface that accepts an `externalId` uses it as one half of
|
||||
* a dedup key: `(userId, source, externalId)`, `(userId, externalSource,
|
||||
* externalId)`, `(userId, type, source, externalId)`. Re-posting the same
|
||||
* triple is idempotent and returns the existing row. That idempotency is
|
||||
* only as good as the STABILITY of the identifier — an id that changes
|
||||
* between two runs of the same client never matches its own earlier row,
|
||||
* so every sync sweep mints a fresh record and the user's history fills
|
||||
* with phantom rows that carry no doses, no schedule, no follow-up data.
|
||||
*
|
||||
* That is not hypothetical. A native client serialised an opaque platform
|
||||
* object with the language's default object description and sent the
|
||||
* result as `externalId`. The default description of an object with no
|
||||
* description contract is `<ClassName: 0xADDRESS>` — a per-allocation
|
||||
* MEMORY ADDRESS. A live instance accumulated 23 duplicate medications in
|
||||
* a single day, one per sync sweep, each with a different address in its
|
||||
* id, and the dose events that should have attached to them resolved
|
||||
* through the same rotating string and were never stored at all.
|
||||
*
|
||||
* This module is the one place that recognises an identifier which CANNOT
|
||||
* be a stable identity. It is deliberately narrow: the cost of a false
|
||||
* negative is a duplicate row, the cost of a false positive is a
|
||||
* legitimate client losing the ability to sync at all. Only shapes that
|
||||
* are provably not identities are rejected:
|
||||
*
|
||||
* 1. `blank` — empty or whitespace-only after trimming.
|
||||
* Carries no identity by construction.
|
||||
* 2. `pointer_address` — a bare `0x…` hex value and nothing else.
|
||||
* A raw address, valid only inside the
|
||||
* process that printed it.
|
||||
* 3. `object_description` — an angle-bracketed description containing
|
||||
* an `0x…` hex token, e.g. `<Foo: 0x12568db80>`
|
||||
* or `<Foo: 0x1; bar=2>`. This is the general
|
||||
* form of a default object description, not a
|
||||
* match on one platform class: no identity
|
||||
* format wraps itself in angle brackets around
|
||||
* a hex pointer.
|
||||
*
|
||||
* Everything else passes. In particular the identifier shapes this system
|
||||
* actually receives all survive:
|
||||
*
|
||||
* - UUIDs, upper or lower case, hyphenated or not
|
||||
* (`8AD2A9CB-...`, HealthKit sample UUIDs, SwiftData row ids)
|
||||
* - structured prefix forms
|
||||
* (`stats:HKQuantityTypeIdentifierStepCount:2026-07-25`,
|
||||
* `stats:HKQuantityTypeIdentifierHeartRate:2026-07-25T08:10:00Z`,
|
||||
* `assessment:<id>`, `whoop:<id>`, `oura:<id>`)
|
||||
* - opaque vendor identifiers (numeric ids, base64-ish blobs, hashes —
|
||||
* including a 64-char SHA-256 hex digest, which has no `0x` prefix)
|
||||
* - platform type identifiers (`HKQuantityTypeIdentifierStepCount`)
|
||||
*
|
||||
* There is deliberately NO rule on length, on the presence of spaces, on
|
||||
* character class, or on "looks random enough". Those would reject real
|
||||
* vendor identifiers, and a rule that cannot be justified against a shape
|
||||
* this system actually receives does not belong here.
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
|
||||
/** The closed set of shapes that cannot be a stable identity. */
|
||||
export type UnstableExternalIdShape =
|
||||
"blank" | "pointer_address" | "object_description";
|
||||
|
||||
/**
|
||||
* A bare hex pointer and nothing else — `0x12568db80`. Anchored on both
|
||||
* ends so an opaque vendor id that merely CONTAINS "0x" is untouched.
|
||||
*/
|
||||
const BARE_POINTER = /^0x[0-9a-f]+$/i;
|
||||
|
||||
/**
|
||||
* An angle-bracketed description carrying a hex pointer, searched
|
||||
* anywhere in the value so a client that prefixes its own namespace
|
||||
* (`apple:<Foo: 0x1234>`) is caught too. `[^<>]*` keeps the bracket pair
|
||||
* adjacent — the token has to be one description, not two unrelated
|
||||
* angle brackets spanning half the string.
|
||||
*/
|
||||
const POINTER_DESCRIPTION = /<[^<>]*0x[0-9a-f]+[^<>]*>/i;
|
||||
|
||||
/**
|
||||
* Classify an external identifier. Returns `null` when the value is
|
||||
* usable as an identity, or the shape that disqualifies it.
|
||||
*/
|
||||
export function classifyExternalId(
|
||||
value: string,
|
||||
): UnstableExternalIdShape | null {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return "blank";
|
||||
if (BARE_POINTER.test(trimmed)) return "pointer_address";
|
||||
if (POINTER_DESCRIPTION.test(trimmed)) return "object_description";
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Convenience predicate over {@link classifyExternalId}. */
|
||||
export function isStableExternalId(value: string): boolean {
|
||||
return classifyExternalId(value) === null;
|
||||
}
|
||||
|
||||
const SHAPE_MESSAGES: Record<UnstableExternalIdShape, string> = {
|
||||
blank: "external identifier must not be empty",
|
||||
pointer_address:
|
||||
"external identifier must be stable across app restarts; received a memory address (0x…), which is a new value on every launch and mints a duplicate record on every sync",
|
||||
object_description:
|
||||
"external identifier must be stable across app restarts; received an object description (<Class: 0x…>), which embeds a memory address and is a new value on every launch — serialise the identity itself, not the object's description",
|
||||
};
|
||||
|
||||
/** The 422 message a client developer reads. Names the shape received. */
|
||||
export function unstableExternalIdMessage(
|
||||
shape: UnstableExternalIdShape,
|
||||
): string {
|
||||
return SHAPE_MESSAGES[shape];
|
||||
}
|
||||
|
||||
/**
|
||||
* Object-level Zod check for a single-entry request schema that carries a
|
||||
* top-level `externalId`. Used as `schema.superRefine(assertStableExternalId)`
|
||||
* so the refusal rides the standard 422 multi-issue envelope
|
||||
* (`returnAllZodIssues` / `sanitiseZodIssues`) with `path: ["externalId"]`
|
||||
* instead of a hand-rolled error.
|
||||
*
|
||||
* Batch / bulk surfaces deliberately do NOT use this: a schema-level
|
||||
* refusal fails the whole payload, and one bad row must not stop the other
|
||||
* 499 from landing. Those routes call {@link classifyExternalId} per entry
|
||||
* and report the entry through their own `skipped` contract.
|
||||
*/
|
||||
export function assertStableExternalId(
|
||||
value: { externalId?: string | null },
|
||||
ctx: z.RefinementCtx,
|
||||
): void {
|
||||
const raw = value.externalId;
|
||||
if (typeof raw !== "string") return;
|
||||
const shape = classifyExternalId(raw);
|
||||
if (shape === null) return;
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["externalId"],
|
||||
message: unstableExternalIdMessage(shape),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a top-level `externalId` off an unparsed request body and classify
|
||||
* it. Single-entry routes use this on the 422 path to annotate the wide
|
||||
* event with the SHAPE that was refused — never the id itself, which is
|
||||
* client free-text and can carry anything.
|
||||
*/
|
||||
export function unstableExternalIdShape(
|
||||
body: unknown,
|
||||
): UnstableExternalIdShape | null {
|
||||
if (typeof body !== "object" || body === null) return null;
|
||||
const raw = (body as { externalId?: unknown }).externalId;
|
||||
if (typeof raw !== "string") return null;
|
||||
return classifyExternalId(raw);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pinned wide-event meta for a refusal. Keys are fixed so dashboards stay
|
||||
* stable; the payload carries the count, the classification, and the
|
||||
* surface — never the identifier itself, which is client free-text.
|
||||
*
|
||||
* `external_id_shapes` is the sorted, de-duplicated shape set as a single
|
||||
* comma-joined string — a scalar rather than an array so it groups
|
||||
* cleanly in the event store.
|
||||
*
|
||||
* The surface rides the META rather than only the action name because a
|
||||
* wide event carries exactly one action, and most of these refusals
|
||||
* happen on a path that already names its own (`….validation-failed`,
|
||||
* `measurement.batch.ingest`). Overwriting that action would cost more
|
||||
* than it buys, so `external_id_rejected > 0` is the one query that finds
|
||||
* every occurrence on every surface; routes whose failure path claims no
|
||||
* action of its own additionally set `<surface>.external_id.rejected`.
|
||||
*/
|
||||
export function unstableExternalIdMeta(
|
||||
surface: string,
|
||||
shapes: UnstableExternalIdShape[],
|
||||
): {
|
||||
external_id_rejected: number;
|
||||
external_id_shapes: string;
|
||||
external_id_surface: string;
|
||||
} {
|
||||
return {
|
||||
external_id_rejected: shapes.length,
|
||||
external_id_shapes: [...new Set(shapes)].sort().join(","),
|
||||
external_id_surface: surface,
|
||||
};
|
||||
}
|
||||
|
||||
/** Per-entry `reason` code every batch / bulk surface reports. */
|
||||
export const UNSTABLE_EXTERNAL_ID_REASON = "unstable_external_id";
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
rxNormCodeField,
|
||||
} from "./base";
|
||||
import { scheduleSchema } from "./schedule";
|
||||
import { assertStableExternalId } from "@/lib/validations/external-id";
|
||||
|
||||
/**
|
||||
* v1.5 — medication-level course window + one-shot flag. The fields
|
||||
@@ -187,7 +188,7 @@ export const createMedicationSchema = z
|
||||
.max(128)
|
||||
.optional()
|
||||
.describe(
|
||||
"Stable external identifier of the mirrored medication (the HealthKit `medicationConceptIdentifier`, max 128 chars). Must be supplied together with `externalSource`. Idempotent: re-posting the same pair returns the existing medication with status 200 instead of minting a duplicate.",
|
||||
"Stable external identifier of the mirrored medication (the HealthKit `medicationConceptIdentifier`, max 128 chars). Must be supplied together with `externalSource`. Idempotent: re-posting the same pair returns the existing medication with status 200 instead of minting a duplicate. The value MUST be identical across app restarts: an object description or memory address (`<Class: 0x…>`, `0x12ab34cd`) is a new value on every launch, never matches its own earlier row, and is refused with 422 rather than minting a duplicate mirror.",
|
||||
),
|
||||
...courseWindowFields,
|
||||
/**
|
||||
@@ -206,6 +207,10 @@ export const createMedicationSchema = z
|
||||
path: ["externalId"],
|
||||
},
|
||||
)
|
||||
// The concept id has to be STABLE across client launches or the
|
||||
// idempotent-mirror pre-query above never matches its own earlier row
|
||||
// and every sync sweep mints another phantom medication.
|
||||
.superRefine(assertStableExternalId)
|
||||
.refine((b) => b.oneShot !== true || !!b.startsOn, {
|
||||
message: "startsOn is required when oneShot is true",
|
||||
path: ["startsOn"],
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
INSTRUMENTS,
|
||||
type InstrumentId,
|
||||
} from "@/lib/mental-health/instruments";
|
||||
import { assertStableExternalId } from "@/lib/validations/external-id";
|
||||
|
||||
export const assessmentInstrumentEnum = z.enum(["PHQ9", "GAD7", "WHO5", "SCI"]);
|
||||
|
||||
@@ -69,7 +70,10 @@ export const createAssessmentSchema = z
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
})
|
||||
// The replay anchor only protects against a duplicate administration
|
||||
// while the id is stable across client launches.
|
||||
.superRefine(assertStableExternalId);
|
||||
|
||||
export const listAssessmentsSchema = z.object({
|
||||
instrument: assessmentInstrumentEnum.optional(),
|
||||
|
||||
+40
-33
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
import { validateEntryInstant } from "@/lib/validations/entry-instant";
|
||||
import { assertStableExternalId } from "@/lib/validations/external-id";
|
||||
|
||||
// --- CRUD schemas for mood entries ---
|
||||
|
||||
@@ -68,39 +69,45 @@ const ratedFactor = z.object({
|
||||
});
|
||||
const ratedFactors = z.array(ratedFactor).max(30);
|
||||
|
||||
export const createMoodEntrySchema = z.object({
|
||||
mood: moodLevelEnum,
|
||||
tags: z.array(z.string().max(50)).max(20).optional(),
|
||||
// v1.8.5 — structured-tag keys from the taxonomy. Server resolves each
|
||||
// key to a `MoodTag` row and writes the `MoodEntryTagLink` join;
|
||||
// unknown keys are dropped silently (the catalog is the source of
|
||||
// truth, a stale client can't mint a tag).
|
||||
tagKeys: structuredTagKeys.optional(),
|
||||
// v1.12.0 — rated factors scored 1..5 (or the factor's own scale).
|
||||
// Parallel to the binary `tagKeys`; persisted on
|
||||
// `MoodEntryTagLink.rating`. Out-of-scale or non-RATED keys are
|
||||
// rejected (422) / dropped server-side per the catalog.
|
||||
ratedFactors: ratedFactors.optional(),
|
||||
// v1.4.30 H-5 — first-class free-text note. Replaces the
|
||||
// `tags: ["note:<text>"]` workaround. Capped at 500 chars so the
|
||||
// Coach evidence shelf renders cleanly without truncating chips.
|
||||
note: z.string().max(500).optional(),
|
||||
// v1.17 W1b — plausibility bound (shared `validateEntryInstant`): no
|
||||
// future instants beyond a 5-min clock-skew tolerance, no instant before
|
||||
// 1900. Mirrors the measurement + medication-intake bound.
|
||||
moodLoggedAt: validateEntryInstant(
|
||||
z.iso.datetime({ offset: true }).transform((s) => new Date(s)),
|
||||
),
|
||||
source: moodSourceEnum.optional().default("MANUAL"),
|
||||
// v1.12.1 — optional source-stable id (e.g. an iOS SwiftData row UUID).
|
||||
// When present, the create upserts on `(userId, source, externalId)`
|
||||
// so a re-post with the same id updates the existing row in place
|
||||
// instead of either 409-ing or minting a duplicate — the idempotent
|
||||
// re-import iOS drives over Bearer. NULL keeps the legacy
|
||||
// `(userId, date, moodLoggedAt)` behaviour. Bound matches the bulk
|
||||
// `externalId` so one path can't accept an id the other rejects.
|
||||
externalId: z.string().min(1).max(120).optional(),
|
||||
});
|
||||
export const createMoodEntrySchema = z
|
||||
.object({
|
||||
mood: moodLevelEnum,
|
||||
tags: z.array(z.string().max(50)).max(20).optional(),
|
||||
// v1.8.5 — structured-tag keys from the taxonomy. Server resolves each
|
||||
// key to a `MoodTag` row and writes the `MoodEntryTagLink` join;
|
||||
// unknown keys are dropped silently (the catalog is the source of
|
||||
// truth, a stale client can't mint a tag).
|
||||
tagKeys: structuredTagKeys.optional(),
|
||||
// v1.12.0 — rated factors scored 1..5 (or the factor's own scale).
|
||||
// Parallel to the binary `tagKeys`; persisted on
|
||||
// `MoodEntryTagLink.rating`. Out-of-scale or non-RATED keys are
|
||||
// rejected (422) / dropped server-side per the catalog.
|
||||
ratedFactors: ratedFactors.optional(),
|
||||
// v1.4.30 H-5 — first-class free-text note. Replaces the
|
||||
// `tags: ["note:<text>"]` workaround. Capped at 500 chars so the
|
||||
// Coach evidence shelf renders cleanly without truncating chips.
|
||||
note: z.string().max(500).optional(),
|
||||
// v1.17 W1b — plausibility bound (shared `validateEntryInstant`): no
|
||||
// future instants beyond a 5-min clock-skew tolerance, no instant before
|
||||
// 1900. Mirrors the measurement + medication-intake bound.
|
||||
moodLoggedAt: validateEntryInstant(
|
||||
z.iso.datetime({ offset: true }).transform((s) => new Date(s)),
|
||||
),
|
||||
source: moodSourceEnum.optional().default("MANUAL"),
|
||||
// v1.12.1 — optional source-stable id (e.g. an iOS SwiftData row UUID).
|
||||
// When present, the create upserts on `(userId, source, externalId)`
|
||||
// so a re-post with the same id updates the existing row in place
|
||||
// instead of either 409-ing or minting a duplicate — the idempotent
|
||||
// re-import iOS drives over Bearer. NULL keeps the legacy
|
||||
// `(userId, date, moodLoggedAt)` behaviour. Bound matches the bulk
|
||||
// `externalId` so one path can't accept an id the other rejects.
|
||||
externalId: z.string().min(1).max(120).optional(),
|
||||
})
|
||||
// The upsert key is only idempotent while the id is stable; an id that
|
||||
// rotates per client launch mints a fresh entry on every re-post. The
|
||||
// bulk twin carries the same rule per entry (it cannot fail the whole
|
||||
// batch on one bad row).
|
||||
.superRefine(assertStableExternalId);
|
||||
|
||||
export const updateMoodEntrySchema = z.object({
|
||||
mood: moodLevelEnum.optional(),
|
||||
|
||||
@@ -173,6 +173,10 @@ export const createWorkoutSchema = z
|
||||
// schema, so a client cannot forge a row attributed to an integration it
|
||||
// does not own.
|
||||
source: writableMeasurementSourceEnum.optional().default("MANUAL"),
|
||||
// The only writer of this schema is the batch ingest, which enforces
|
||||
// external-id stability per entry rather than at the field: a
|
||||
// schema-level refusal would fail the whole batch on one bad row.
|
||||
// @external-id-checked-per-entry: src/app/api/workouts/batch/route.ts
|
||||
externalId: z.string().max(128).optional(),
|
||||
externalSourceVersion: z.string().max(64).optional(),
|
||||
metadata: z.record(z.string(), z.unknown()).optional(),
|
||||
|
||||
Reference in new issue
Block a user