feat(concurrency): guard layout and about-me writes against a concurrent overwrite

Extract the dashboard-layout optimistic-concurrency mechanism (issue #581)
into a shared server helper (takeBaseToken plus guardedUserUpdate /
guardedRowUpdate) and a client helper (readUpdatedAtToken, withBaseToken,
isConflict). Retrofit the dashboard-widgets route onto the helper and apply the
same guard to the insights layout, medications layout, and coach about-me write
endpoints.

A request that omits the base token keeps the byte-identical unconditional
write, so older clients are unaffected. Document the contract in the OpenAPI
registry, including the dashboard-widgets path that was previously absent.
This commit is contained in:
Marc-André Bombeck committed 2026-07-24 16:26:58 +02:00
1 parent df4425babf
commit ab03bc96f1
27 files changed
+1669 -352

No files matched your search

+52 -12
View File
@@ -33,7 +33,13 @@ import {
coachReminderPatchSchema,
coachSuggestedActionSchema,
} from "@/lib/validations/coach-reminder";
import { dataEnvelope, errorEnvelope, stdResponses } from "./shared";
import {
dataEnvelope,
errorEnvelope,
stdResponses,
baseUpdatedAtField,
conflictResponse409,
} from "./shared";
// ── Coach cadence suggestions (v1.18.1) ──────────────────────────────
// The action endpoint behind the one-tap reminder-suggestion card. The
@@ -191,6 +197,31 @@ const insightsLayoutSchema = z
"Per-user Insights layout (v2). `tiles` is the per-metric pill list (ordered, with a visibility flag); `sections` is the additive v2 list of the overview's big semantic blocks (wellness-scores, daily-briefing, vitals, trends, period-review, cycle-summary, signals, rhythm-events), each with order + visibility. `version` is the layout schema version: BOTH 1 and 2 are accepted on input (a pre-v2 iOS client still PUTs `version: 1`); the server always normalises to the canonical v2 blob before persisting, and GET responses always carry `version: 2`. Both arrays are optional on input — a client sending only `tiles` (the pre-v2 contract) still validates, and the server fills missing defaults; a v1 blob with no `sections` resolves forward with all sections default-visible. Tile ids are a closed enum: the canonical ids are English (matching the routed `/insights/<slug>` sub-pages). The legacy German tile ids (blutdruck, puls, sauerstoff, koerpertemperatur, gewicht, aktive-energie, schlaf, ruhepuls, stimmung, medikamente) remain accepted on input for backward compatibility and are normalised to their English equivalents before persisting; GET responses always carry the canonical English ids. Section ids are English-only. The legacy tile ids are deprecated and will be removed in a future major version.",
});
// v1.32.21 (R5a) — the PUT body additionally carries the optional
// optimistic-concurrency base token (stripped pre-Zod at runtime by
// `takeBaseToken`); GET / PUT responses echo the fresh `updatedAt` token.
const insightsLayoutPutBody = insightsLayoutSchema
.extend({ baseUpdatedAt: baseUpdatedAtField })
.meta({
id: "InsightsLayoutPutBody",
description:
"PUT body for the Insights layout — the layout fields plus the optional optimistic-concurrency base token (`baseUpdatedAt`). Omit the token for the legacy unconditional write.",
});
const insightsLayoutResult = insightsLayoutSchema
.extend({
updatedAt: z.iso
.datetime({ offset: true })
.optional()
.describe(
"Optimistic-concurrency token: the stored row's `updatedAt` at read/write time. Echo it back as `baseUpdatedAt` on the next write. Opaque.",
),
})
.meta({
id: "InsightsLayoutResult",
description:
"Resolved Insights layout plus the optimistic-concurrency `updatedAt` token.",
});
// v1.7.0 — health-record export selection. Strict shape: unknown keys
// (including any attempt to smuggle a userId) 422 via returnAllZodIssues.
// v1.11.0 — clinician share-link create payload. Strict; no `userId` field
@@ -920,13 +951,13 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
tags: ["Insights"],
summary: "Read the calling user's Insights tile layout",
description:
"Returns the per-user Insights tile layout (visibility + order). Falls back to the default layout when the user has not customised it. Mirrors the dashboard-widgets contract.",
"Returns the per-user Insights tile layout (visibility + order) plus the optimistic-concurrency `updatedAt` token. Falls back to the default layout when the user has not customised it. Mirrors the dashboard-widgets contract.",
responses: {
"200": {
description: "The resolved layout (custom or default).",
description: "The resolved layout (custom or default) plus its token.",
content: {
"application/json": {
schema: dataEnvelope(insightsLayoutSchema, "InsightsLayout"),
schema: dataEnvelope(insightsLayoutResult, "InsightsLayout"),
},
},
},
@@ -937,22 +968,24 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
tags: ["Insights"],
summary: "Replace the calling user's Insights tile layout",
description:
"Persists the full tile layout. The normalised layout is returned. Invalid bodies return the multi-issue 422 envelope, matching the dashboard-widgets route.",
"Persists the full tile layout. The normalised layout plus the advanced `updatedAt` token is returned. Optimistic concurrency (v1.32.21): send `baseUpdatedAt` (the token from a prior read) and the write 409s if the stored row changed since; omit it for the legacy unconditional write. Invalid bodies return the multi-issue 422 envelope, matching the dashboard-widgets route.",
requestBody: {
required: true,
content: {
"application/json": { schema: insightsLayoutSchema },
"application/json": { schema: insightsLayoutPutBody },
},
},
responses: {
"200": {
description: "Layout saved; the normalised layout is echoed back.",
description:
"Layout saved; the normalised layout plus the advanced token is echoed back.",
content: {
"application/json": {
schema: dataEnvelope(insightsLayoutSchema, "InsightsLayoutSaved"),
schema: dataEnvelope(insightsLayoutResult, "InsightsLayoutSaved"),
},
},
},
...conflictResponse409("Insights layout", "insights_layout_conflict"),
// 422 (multi-issue validation envelope) comes from stdResponses.
...stdResponses,
},
@@ -967,7 +1000,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
description: "Layout reset; the default layout is returned.",
content: {
"application/json": {
schema: dataEnvelope(insightsLayoutSchema, "InsightsLayoutReset"),
schema: dataEnvelope(insightsLayoutResult, "InsightsLayoutReset"),
},
},
},
@@ -1138,15 +1171,21 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
tags: ["Insights"],
summary: "Write (or clear) the caller's self-context",
description:
"v1.16.0 — persists the free text (4 000-char cap) and the three structured fields (500-char cap each) encrypted at rest; caps are enforced before encryption. Structured fields are optional: omitted leaves the stored value untouched, an empty string clears it. After a non-empty save the server derives up to 3 clarifying questions (AI when a provider and the daily Coach token budget allow, deterministic completion hints otherwise) and returns them as `pendingQuestions`. Rate-limited per user.",
"v1.16.0 — persists the free text (4 000-char cap) and the three structured fields (500-char cap each) encrypted at rest; caps are enforced before encryption. Structured fields are optional: omitted leaves the stored value untouched, an empty string clears it. After a non-empty save the server derives up to 3 clarifying questions (AI when a provider and the daily Coach token budget allow, deterministic completion hints otherwise) and returns them as `pendingQuestions`. Rate-limited per user. Optimistic concurrency (v1.32.21): send `baseUpdatedAt` (the `updatedAt` from a prior read) and the write 409s if the stored self-context changed since; omit it for the legacy unconditional write. The token is per-surface (`UserHealthProfile.updatedAt`), so it is not perturbed by unrelated account writes.",
requestBody: {
required: true,
content: { "application/json": { schema: aboutMePutSchema } },
content: {
"application/json": {
schema: aboutMePutSchema.extend({
baseUpdatedAt: baseUpdatedAtField,
}),
},
},
},
responses: {
"200": {
description:
"The effective (trimmed) state echoed back plus the freshly derived pending questions.",
"The effective (trimmed) state echoed back plus the freshly derived pending questions and the advanced `updatedAt` token.",
content: {
"application/json": {
schema: dataEnvelope(
@@ -1165,6 +1204,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
...conflictResponse409("Self-context", "about_me_conflict"),
...stdResponses,
},
},
+162
View File
@@ -0,0 +1,162 @@
/**
* OpenAPI route table — dashboard widget layout (`/api/dashboard/widgets`).
*
* v1.32.21 (R5a) — this endpoint was ENTIRELY absent from the registry
* even though it is the reference implementation for the optimistic-
* concurrency token contract the native client is being asked to adopt
* (issue #581, shipped v1.32.16). Documenting it here closes that gap: the
* contract iOS validates against now carries the `baseUpdatedAt` request
* field, the `updatedAt` response token, and the 409 conflict envelope.
*
* The schema mirrors the inline Zod shape in
* `src/app/api/dashboard/widgets/route.ts`; the id sets are imported from
* the single-source `@/lib/dashboard-layout` module so the contract cannot
* drift. Part of the OpenAPI route table; aggregated in `./index.ts`.
*/
import { z } from "zod/v4";
import type { ZodOpenApiObject } from "zod-openapi";
import {
DASHBOARD_WIDGET_CATALOGUE_IDS,
COMPARISON_BASELINES,
CHART_OVERLAY_KEYS,
SCORE_RING_IDS,
HERO_RING_IDS,
} from "@/lib/dashboard-layout";
import {
dataEnvelope,
stdResponses,
baseUpdatedAtField,
conflictResponse409,
} from "./shared";
const dashboardWidgetConfig = z.object({
id: z.enum(DASHBOARD_WIDGET_CATALOGUE_IDS),
visible: z.boolean(),
tileVisible: z.boolean().optional(),
order: z.number().int().min(0).max(99),
});
const dashboardChartOverlayPrefs = z.object({
showTrendIndicator: z.boolean(),
showTrendArrow: z.boolean(),
showTargetRange: z.boolean(),
comparisonBaseline: z.enum(COMPARISON_BASELINES).optional(),
rangePoints: z
.union([z.literal(0), z.literal(7), z.literal(30), z.literal(90)])
.optional(),
});
// The layout shape shared by GET/PUT/DELETE. `widgets` (and the other
// preserve-when-absent fields) are optional on the wire: the Settings
// instant score-ring PUT omits `widgets` entirely so the server carries
// forward whatever is currently stored (issue #581).
const dashboardLayoutSchema = z
.object({
version: z.literal(1),
widgets: z.array(dashboardWidgetConfig).min(1).max(50).optional(),
comparisonBaseline: z.enum(COMPARISON_BASELINES).optional(),
chartOverlayPrefs: z
.partialRecord(z.enum(CHART_OVERLAY_KEYS), dashboardChartOverlayPrefs)
.optional(),
selectedScoreRings: z.array(z.enum(SCORE_RING_IDS)).max(3).optional(),
heroRingOrder: z.array(z.enum(HERO_RING_IDS)).max(4).optional(),
})
.meta({
id: "DashboardLayoutBody",
description:
"Per-user dashboard widget layout. `widgets` is the ordered tile/chart list (each with a visibility flag plus the independent `tileVisible` strip-tile flag); `comparisonBaseline`, `chartOverlayPrefs`, `selectedScoreRings`, and `heroRingOrder` are the additive dashboard-preference fields. Every field except `version` is optional on input and preserve-when-absent: an omitted field is carried forward from the stored layout rather than reset, so a single-surface PUT (e.g. the instant hero-ring toggle, which omits `widgets`) can never clobber a choice made on another surface. Widget ids are the closed 27-id catalogue (16 web + 11 iOS-only); unknown ids are dropped before validation.",
});
const dashboardLayoutPutBody = dashboardLayoutSchema
.extend({ baseUpdatedAt: baseUpdatedAtField })
.meta({
id: "DashboardLayoutPutBody",
description:
"PUT body for the dashboard layout — the layout fields plus the optional optimistic-concurrency base token (`baseUpdatedAt`). Omit the token for the legacy unconditional write.",
});
const dashboardLayoutResult = dashboardLayoutSchema
.extend({
updatedAt: z.iso
.datetime({ offset: true })
.optional()
.describe(
"Optimistic-concurrency token: the stored row's `updatedAt` at read/write time. Echo it back as `baseUpdatedAt` on the next write. Opaque.",
),
})
.meta({
id: "DashboardLayoutResult",
description:
"Resolved dashboard layout plus the optimistic-concurrency `updatedAt` token.",
});
export const dashboardWidgetPaths: NonNullable<ZodOpenApiObject["paths"]> = {
"/api/dashboard/widgets": {
get: {
tags: ["Dashboard"],
summary: "Read the calling user's dashboard widget layout",
description:
"Returns the resolved effective layout (defaults merged in if the user has not customised it) plus the optimistic-concurrency `updatedAt` token.",
responses: {
"200": {
description: "The resolved layout (custom or default) plus its token.",
content: {
"application/json": {
schema: dataEnvelope(dashboardLayoutResult, "DashboardLayout"),
},
},
},
...stdResponses,
},
},
put: {
tags: ["Dashboard"],
summary: "Replace the calling user's dashboard widget layout",
description:
"Persists the layout with preserve-when-absent semantics and returns the normalised layout plus the advanced `updatedAt` token. Optimistic concurrency (v1.32.16): send `baseUpdatedAt` (the token from a prior read) and the write 409s if the stored row changed since — so a committed Save can never be silently reverted by a later request that started from an older snapshot; omit it for the legacy unconditional write. Invalid bodies return the multi-issue 422 envelope.",
requestBody: {
required: true,
content: {
"application/json": { schema: dashboardLayoutPutBody },
},
},
responses: {
"200": {
description:
"Layout saved; the normalised layout plus the advanced token is echoed back.",
content: {
"application/json": {
schema: dataEnvelope(
dashboardLayoutResult,
"DashboardLayoutSaved",
),
},
},
},
...conflictResponse409("Dashboard layout", "dashboard_layout_conflict"),
...stdResponses,
},
},
delete: {
tags: ["Dashboard"],
summary: "Reset the calling user's dashboard widget layout",
description:
"Clears the persisted layout and returns the default layout. Idempotent.",
responses: {
"200": {
description: "Layout reset; the default layout is returned.",
content: {
"application/json": {
schema: dataEnvelope(
dashboardLayoutResult,
"DashboardLayoutReset",
),
},
},
},
...stdResponses,
},
},
},
};
+5
View File
@@ -35,6 +35,7 @@ import { consentPaths } from "./consent";
import { customMetricPaths } from "./custom-metrics";
import { dailyPaths } from "./daily";
import { cyclePaths } from "./cycle";
import { dashboardWidgetPaths } from "./dashboard";
import { biomarkerPaths } from "./biomarkers";
import { inboundDocumentPaths } from "./documents";
import { devicePaths } from "./devices";
@@ -105,6 +106,10 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
// v1.28 — the unified daily digest (P3 spine; appended, spread order is
// load-bearing).
...dailyPaths,
// v1.32.21 (R5a) — dashboard widget layout: previously absent from the
// registry entirely, now documented as the reference optimistic-concurrency
// contract (appended, spread order is load-bearing).
...dashboardWidgetPaths,
};
export const openApiComponents: NonNullable<ZodOpenApiObject["components"]> = {
+20 -10
View File
@@ -22,7 +22,12 @@ import {
efficacyTargetOverrideSchema,
medicationEfficacyResponseSchema,
} from "@/lib/validations/medication-efficacy";
import { dataEnvelope, errorEnvelope, stdResponses } from "../shared";
import {
dataEnvelope,
errorEnvelope,
stdResponses,
conflictResponse409,
} from "../shared";
efficacyTargetOverrideSchema.meta({
id: "SetMedicationEfficacyTargetRequest",
@@ -47,7 +52,8 @@ import {
scheduleRevisionResource,
scheduleRevisionListResponse,
medicationExtractRequest,
medicationListLayoutSchema,
medicationListLayoutPutBody,
medicationListLayoutResult,
doseHistoryQuery,
doseHistoryResponse,
} from "./schemas";
@@ -224,14 +230,14 @@ export const medicationPaths: NonNullable<ZodOpenApiObject["paths"]> = {
tags: ["Medications"],
summary: "Read the calling user's medications list presentation",
description:
"Returns the per-user /medications presentation (card/table view + manual order). Falls back to the defaults (cards, empty order) when the user has not customised it. Mirrors the insights-layout contract.",
"Returns the per-user /medications presentation (card/table view + manual order) plus the optimistic-concurrency `updatedAt` token. Falls back to the defaults (cards, empty order) when the user has not customised it. Mirrors the insights-layout contract.",
responses: {
"200": {
description: "The resolved presentation (custom or default).",
description: "The resolved presentation (custom or default) plus its token.",
content: {
"application/json": {
schema: dataEnvelope(
medicationListLayoutSchema,
medicationListLayoutResult,
"MedicationListLayoutResponse",
),
},
@@ -244,26 +250,30 @@ export const medicationPaths: NonNullable<ZodOpenApiObject["paths"]> = {
tags: ["Medications"],
summary: "Update the calling user's medications list presentation",
description:
"Field-scoped update: `view` and `order` are each optional, and whichever the body omits is preserved from the stored blob — a view toggle can never wipe the manual order and vice versa. The normalised presentation is returned. Invalid bodies return the multi-issue 422 envelope.",
"Field-scoped update: `view` and `order` are each optional, and whichever the body omits is preserved from the stored blob — a view toggle can never wipe the manual order and vice versa. The normalised presentation plus the advanced `updatedAt` token is returned. Optimistic concurrency (v1.32.21): send `baseUpdatedAt` (the token from a prior read) and the write 409s if the stored blob changed since; omit it for the legacy unconditional write. Invalid bodies return the multi-issue 422 envelope.",
requestBody: {
required: true,
content: {
"application/json": { schema: medicationListLayoutSchema },
"application/json": { schema: medicationListLayoutPutBody },
},
},
responses: {
"200": {
description:
"Presentation saved; the normalised blob is echoed back.",
"Presentation saved; the normalised blob plus the advanced token is echoed back.",
content: {
"application/json": {
schema: dataEnvelope(
medicationListLayoutSchema,
medicationListLayoutResult,
"MedicationListLayoutSaved",
),
},
},
},
...conflictResponse409(
"Medications layout",
"medication_layout_conflict",
),
...stdResponses,
},
},
@@ -278,7 +288,7 @@ export const medicationPaths: NonNullable<ZodOpenApiObject["paths"]> = {
content: {
"application/json": {
schema: dataEnvelope(
medicationListLayoutSchema,
medicationListLayoutResult,
"MedicationListLayoutReset",
),
},
@@ -6,6 +6,7 @@
* runtime request parsing, so the wire contract stays single-source.
*/
import { z } from "zod/v4";
import { baseUpdatedAtField } from "../shared";
import {
MEDICATION_CATEGORY_VALUES,
MEDICATION_CONTAINER_TYPE_VALUES,
@@ -894,3 +895,29 @@ export const medicationListLayoutSchema = z
description:
"Per-user /medications presentation: the card/table view choice plus the manual medication order shared by both views. Mirrors the dashboard-widgets / insights-layout contract.",
});
// v1.32.21 (R5a) — the PUT body additionally carries the optional
// optimistic-concurrency base token (stripped pre-Zod at runtime by
// `takeBaseToken`); GET / PUT responses echo the fresh `updatedAt` token.
export const medicationListLayoutPutBody = medicationListLayoutSchema
.extend({ baseUpdatedAt: baseUpdatedAtField })
.meta({
id: "MedicationListLayoutPutBody",
description:
"PUT body for the medications list presentation — the presentation fields plus the optional optimistic-concurrency base token (`baseUpdatedAt`). Omit the token for the legacy unconditional write.",
});
export const medicationListLayoutResult = medicationListLayoutSchema
.extend({
updatedAt: z.iso
.datetime({ offset: true })
.optional()
.describe(
"Optimistic-concurrency token: the stored row's `updatedAt` at read/write time. Echo it back as `baseUpdatedAt` on the next write. Opaque.",
),
})
.meta({
id: "MedicationListLayoutResult",
description:
"Resolved medications list presentation plus the optimistic-concurrency `updatedAt` token.",
});
+35
View File
@@ -91,6 +91,41 @@ createBatchWorkoutSchema.meta({
"Typed workout batch ingest. Each entry is an HKWorkout-aligned record with an optional nested GeoJSON LineString route AND an optional route-independent per-workout heart-rate series (`samples`: `[{ t, hr?, speedMs?, power?, cadence? }]`, up to 30 000 points). The `samples` series is the strain-engine input for indoor workouts that have no GPS route. Up to 100 workouts per call; nested route geometry capped at 20 000 points. Withings server-to-server callers pass source: WITHINGS and ship no route (Withings reports aggregates only).",
});
// ── Optimistic concurrency (v1.32.21 / R5a) ──────────────────────────
// The write endpoints that read-modify-write a per-user blob accept an
// optional `baseUpdatedAt` base token (the `updatedAt` the client last
// read) and guard the write on the stored row still carrying it. A stale
// token fails the write with 409 and changes nothing; an omitted token
// takes the prior unconditional write (backward-compatible). The token is
// OPAQUE — clients only ever echo a server-returned value.
/**
* Optional request field carrying the optimistic-concurrency base token.
* Extend a request schema with `{ baseUpdatedAt: baseUpdatedAtField }` at the
* OpenAPI layer: the runtime strips it pre-Zod (`takeBaseToken`), so the
* runtime schema alone would under-document the wire.
*/
export const baseUpdatedAtField = z.iso
.datetime({ offset: true })
.optional()
.describe(
"Optimistic-concurrency base token: the `updatedAt` the client last read for this resource. Omit it for the legacy unconditional write (older clients are unaffected). When present, the write is guarded on the stored row still carrying this exact value — a stale token fails with 409 and changes nothing. Treat as opaque: only ever echo a server-returned value, never parse or synthesise it.",
);
/**
* The 409 the guarded write returns when the base token is stale. `errorCode`
* is per-endpoint; the caller passes the resource noun + the concrete
* errorCode so the prose enumerates it.
*/
export function conflictResponse409(resource: string, errorCode: string) {
return {
"409": {
description: `${resource} changed since it was loaded (optimistic-concurrency conflict). No write happened. Re-read the resource, re-apply the user's change against the fresh state, and resend with the new token. \`meta.errorCode\` = \`${errorCode}\`.`,
content: { "application/json": { schema: errorEnvelope } },
},
};
}
// ── Standard 401 / 422 / 429 responses ───────────────────────────────
export const stdResponses = {