feat(nutrients): accept measurements:write tokens on the nutrient batch

A bridge such as a food tracker can now post daily nutrient totals with
the measurement token. The credential picks the source row: a scoped
token writes EXTERNAL, the native client keeps writing APPLE_HEALTH, and
the body has no say. Bridge tokens count in their own rate-limit bucket,
and the source is recorded in the audit row.

The write phase moves into writeNutrientDayTotals so the route keeps
only parsing, validation and bookkeeping. The scope guard now freezes
four doors for measurements:write. Refs #1402.
This commit is contained in:
Marc-André Bombeck committed 2026-11-17 18:47:11 +01:00
1 parent 8f96c2f0a2
commit 7c40ba8202
12 files changed
+485 -186

No files matched your search

+4 -2
View File
@@ -65,8 +65,10 @@ before treating a warning as a regression.
- `POST /api/mcp/tokens` mints `health:read` (optionally plus
`health:write`), audience-bound to `/mcp` and refused on REST writes;
- `POST /api/tokens/measurements` mints `measurements:write`, accepted by
`POST /api/measurements` and `POST /api/measurements/batch` only, on the
holder's own record only. The readings it writes carry `source: EXTERNAL`
`POST /api/measurements`, `POST /api/measurements/batch`,
`POST /api/custom-metrics/{id}/entries` and `POST /api/nutrients/batch`
only, on the holder's own record only. The readings and nutrient day
totals it writes carry `source: EXTERNAL`
and are linked to the token; whether the HealthLog app writes them into
Apple Health is the token's `mirrorToAppleHealth` setting (off by
default, changed with `PATCH /api/tokens/{id}`), resolved onto every
@@ -1,7 +1,7 @@
{
"$comment": "Production files over 800 lines and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
"count": 84,
"total": 93816,
"total": 93804,
"entries": {
"app/medications/page-client.tsx": 842,
"components/charts/mood-chart.tsx": 1166,
@@ -40,7 +40,7 @@
"lib/daily/load-digest.ts": 1000,
"lib/daily/today-overview.ts": 838,
"lib/dashboard-layout.ts": 977,
"lib/dashboard/snapshot.ts": 1550,
"lib/dashboard/snapshot.ts": 1548,
"lib/day/records.ts": 1172,
"lib/export/backup-plan.ts": 838,
"lib/export/coach-backup.ts": 1070,
@@ -56,7 +56,7 @@
"lib/import/health-connect/import.ts": 1689,
"lib/import/unzip-export-xml.ts": 825,
"lib/insights/comprehensive-aggregator.ts": 868,
"lib/insights/comprehensive-generate.ts": 1670,
"lib/insights/comprehensive-generate.ts": 1660,
"lib/insights/correlation-channel-series.ts": 1330,
"lib/insights/correlation-discovery.ts": 1240,
"lib/insights/correlations.ts": 1026,
@@ -1,7 +1,7 @@
{
"$comment": "Production functions over 200 lines, keyed \"file :: name\", and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
"count": 335,
"total": 109025,
"total": 108911,
"entries": {
"app/achievements/page.tsx :: AchievementsPage": 206,
"app/api/admin/backups/upload/route.ts :: apiHandler(arg)": 275,
@@ -33,7 +33,7 @@
"app/api/mental-health/assessments/route.ts :: postAssessment": 249,
"app/api/mood-entries/[id]/route.ts :: apiHandler(arg) #2": 296,
"app/api/mood-entries/route.ts :: postMoodEntry": 324,
"app/api/nutrients/batch/route.ts :: postBatch": 304,
"app/api/nutrients/batch/route.ts :: postBatch": 209,
"app/api/onboarding/complete/route.ts :: completeNeedsFlow": 218,
"app/api/record-settings/[family]/route.ts :: apiHandler(arg) #2": 262,
"app/api/user/ai-provider/route.ts :: apiHandler(arg) #2": 224,
@@ -159,7 +159,7 @@
"components/medications/scheduling/schedule-history-timeline.tsx :: EraDialog": 219,
"components/medications/scheduling/schedule-history-timeline.tsx :: ScheduleHistoryTimeline": 254,
"components/medications/sections/api-tokens-row.tsx :: ApiTokensRow": 294,
"components/medications/sections/composition-section.tsx :: CompositionEditor": 362,
"components/medications/sections/composition-section.tsx :: CompositionEditor": 360,
"components/medications/sections/inventory-dialogs.tsx :: AddInventoryDialog": 238,
"components/medications/sections/inventory-section.tsx :: InventorySection": 368,
"components/medications/side-effects-section.tsx :: SideEffectsSection": 518,
@@ -279,8 +279,8 @@
"lib/import/labs-csv.ts :: importLabsCsv": 305,
"lib/import/labs-csv.ts :: importLabsCsv > flush": 227,
"lib/insights/comprehensive-aggregator.ts :: buildFromRollups": 217,
"lib/insights/comprehensive-generate.ts :: generateComprehensiveInsight": 872,
"lib/insights/features.ts :: extractFeatures": 772,
"lib/insights/comprehensive-generate.ts :: generateComprehensiveInsight": 868,
"lib/insights/features.ts :: extractFeatures": 771,
"lib/insights/mood-aggregates.ts :: fetchMoodAggregates": 227,
"lib/insights/status-provider.ts :: runStatusCompletion": 215,
"lib/integrations/connection-health-load.ts :: loadConnectionFacts": 229,
@@ -294,8 +294,8 @@
"lib/jobs/google-health-backfill.ts :: runGoogleHealthBackfillForUser": 276,
"lib/jobs/insight-pregenerate.ts :: forceWarmUser": 282,
"lib/jobs/insight-pregenerate.ts :: forceWarmUser > withFeatureCacheScope(arg)": 252,
"lib/jobs/insight-pregenerate.ts :: runInsightPregenerate": 383,
"lib/jobs/insight-pregenerate.ts :: runInsightPregenerate > pregenerateCandidate": 233,
"lib/jobs/insight-pregenerate.ts :: runInsightPregenerate": 379,
"lib/jobs/insight-pregenerate.ts :: runInsightPregenerate > pregenerateCandidate": 225,
"lib/jobs/measurement-reminder.ts :: runMeasurementReminderTick": 286,
"lib/jobs/medication-intake-import.ts :: processNextChunk": 220,
"lib/jobs/medication-intake-import.ts :: processNextChunk > client.$transaction(arg)": 212,
@@ -1,7 +1,7 @@
{
"$comment": "Comment lines that open with a release version, per file under src/. Maintained by src/__tests__/version-stamp-ratchet.test.ts.",
"count": 2863,
"total": 9112,
"count": 2862,
"total": 9107,
"entries": {
"__tests__/account-payload-consumer-guard.test.ts": 2,
"__tests__/acting-account-boundary-guard.test.ts": 7,
@@ -477,7 +477,7 @@
"app/api/notifications/status/route.ts": 1,
"app/api/nutrients/__tests__/route.test.ts": 2,
"app/api/nutrients/batch/__tests__/route.test.ts": 3,
"app/api/nutrients/batch/route.ts": 4,
"app/api/nutrients/batch/route.ts": 3,
"app/api/nutrients/daily/__tests__/route.test.ts": 1,
"app/api/nutrients/route.ts": 1,
"app/api/nutrients/water/__tests__/route.test.ts": 2,
@@ -1018,10 +1018,9 @@
"components/insights/mood/mood-time-of-day-chart.tsx": 2,
"components/insights/mood/mood-weekday-chart.tsx": 4,
"components/insights/mood/mood-what-stands-out.tsx": 1,
"components/insights/nutrients/caffeine-card.tsx": 1,
"components/insights/nutrients/hydration-card.tsx": 1,
"components/insights/nutrients/micronutrients-card.tsx": 3,
"components/insights/nutrients/types.ts": 4,
"components/insights/nutrients/types.ts": 3,
"components/insights/period-narrative-card.tsx": 1,
"components/insights/prose-blocks.tsx": 1,
"components/insights/recovery/recovery-metric-block.tsx": 2,
@@ -2826,7 +2825,7 @@
"lib/validations/modules.ts": 1,
"lib/validations/mood.ts": 18,
"lib/validations/notification-prefs.ts": 36,
"lib/validations/nutrients.ts": 3,
"lib/validations/nutrients.ts": 1,
"lib/validations/onboarding-needs.ts": 1,
"lib/validations/onboarding.ts": 1,
"lib/validations/pulse-day-mean.ts": 1,
@@ -430,13 +430,14 @@ describe("T4 — declared scopes are exported constants, never string literals",
});
});
describe("T4a — `measurements:write` opens exactly three doors", () => {
it("the two measurement writes and the custom-metric value write, POST only", () => {
describe("T4a — `measurements:write` opens exactly four doors", () => {
it("the two measurement writes, the custom-metric value write and the nutrient batch, POST only", () => {
// The set of files naming the scope IS its reach. The single and batch
// measurement writes, and logging a value against a custom metric the
// person already made. Not the measurement reads, not the custom-metric
// list or detail, and not creating, editing or deleting a metric: a
// fourth file here is a widening and belongs in review.
// measurement writes, logging a value against a custom metric the person
// already made, and posting nutrient day totals. Not the measurement or
// nutrient reads, not the custom-metric list or detail, and not creating,
// editing or deleting a metric: a fifth file here is a widening and
// belongs in review.
const declaring = sourceFiles().filter((rel) => {
const src = read(rel);
return (
@@ -448,8 +449,26 @@ describe("T4a — `measurements:write` opens exactly three doors", () => {
"app/api/custom-metrics/[id]/entries/route.ts",
"app/api/measurements/batch/route.ts",
"app/api/measurements/route.ts",
"app/api/nutrients/batch/route.ts",
]);
// The nutrient batch names it once and exports nothing but its POST: the
// nutrient reads live in other files and keep refusing the token.
const nutrients = readSource(
"src/app/api/nutrients/batch/route.ts",
"MEASUREMENTS_WRITE_SCOPE",
);
expect(
requireAuthScopes(nutrients).filter(
(x) => x === "MEASUREMENTS_WRITE_SCOPE",
),
).toHaveLength(1);
expect(
[
...nutrients.matchAll(/export const (GET|POST|PUT|PATCH|DELETE)\b/g),
].map((m) => m[1]),
).toEqual(["POST"]);
// Within the custom-metric file, once, and on the POST: the GET beside it
// lists the metric's values and must keep refusing the token.
const entries = readSource(
+1 -1
View File
@@ -81,7 +81,7 @@ const OWN_BUCKET: Record<string, string> = {
"app/api/cycle/day-logs/bulk/route.ts":
"The cycle HealthKit sweep sends 500-day slices in sequence; the route's own bulk bucket meters it.",
"app/api/nutrients/batch/route.ts":
"The nutrient sync sends 500-row batches in sequence; the route's own batch bucket meters it.",
"The nutrient sync sends 500-row batches in sequence; the route's own batch bucket meters it, with a separate bucket for bridge tokens.",
"app/api/insights/chat/route.ts":
"A Coach turn is metered by the Coach's own buckets: 20 turns a minute (`coach-chat`) and one turn slot at a time.",
"app/api/insights/chat/fenced/route.ts":
@@ -0,0 +1,208 @@
/**
* `POST /api/nutrients/batch` under a narrow `measurements:write` token.
*
* The credential picks the source row: a bridge token writes EXTERNAL in the
* probe, the insert and the update, counts in its own rate-limit bucket, and
* says so in the audit row; the native client keeps writing APPLE_HEALTH.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
nutrientIntakeDay: {
findMany: vi.fn(),
createMany: vi.fn(),
update: vi.fn(),
},
$transaction: vi.fn(),
},
}));
vi.mock("@/lib/api-handler", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/api-handler")>();
return { ...actual, requireAuth: vi.fn() };
});
vi.mock("@/lib/modules/gate", () => ({ requireModuleEnabled: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn(),
rateLimitHeaders: () => ({}),
}));
vi.mock("@/lib/idempotency", () => ({
withIdempotency:
<Args extends unknown[]>(fn: (...args: Args) => Promise<Response>) =>
(...args: Args) =>
fn(...args),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/cache/invalidate", () => ({
invalidateUserHealthContext: vi.fn(),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { POST } from "../route";
import { prisma } from "@/lib/db";
import { requireAuth } from "@/lib/api-handler";
import { auditLog } from "@/lib/auth/audit";
import { checkRateLimit } from "@/lib/rate-limit";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes";
const USER = { id: "user-1", username: "tester", role: "USER" as const };
function asBridge() {
vi.mocked(requireAuth).mockResolvedValue({
session: { id: "t" },
user: USER,
bearerScope: MEASUREMENTS_WRITE_SCOPE,
} as never);
}
function asPhone() {
vi.mocked(requireAuth).mockResolvedValue({
session: { id: "s" },
user: USER,
} as never);
}
function post(entries: unknown[]): Promise<Response> {
return POST(
new NextRequest("http://localhost/api/nutrients/batch", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ entries }),
}),
);
}
const ENERGY = {
day: "2026-11-01",
nutrient: "energy",
unit: "kcal",
amount: 2100,
};
const PROTEIN = {
day: "2026-11-02",
nutrient: "protein",
unit: "g",
amount: 95,
};
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: true } as never);
vi.mocked(requireModuleEnabled).mockResolvedValue({ enabled: true });
vi.mocked(auditLog).mockResolvedValue(undefined as never);
// ENERGY's day already exists, PROTEIN's is new.
vi.mocked(prisma.nutrientIntakeDay.findMany).mockResolvedValue([
{ day: ENERGY.day, nutrient: "energy" },
] as never);
vi.mocked(prisma.nutrientIntakeDay.createMany).mockImplementation(
(async (args: { data: unknown[] }) => ({
count: args.data.length,
})) as never,
);
vi.mocked(prisma.nutrientIntakeDay.update).mockResolvedValue({} as never);
vi.mocked(prisma.$transaction).mockImplementation((async (ops: unknown[]) =>
Promise.all(ops)) as never);
});
describe("POST /api/nutrients/batch with a measurements:write token", () => {
it("asks requireAuth for the measurements:write scope", async () => {
asBridge();
await post([ENERGY]);
expect(requireAuth).toHaveBeenCalledWith(MEASUREMENTS_WRITE_SCOPE, {
writeBucket: "own",
});
});
it("writes the EXTERNAL row in the probe, the insert and the update", async () => {
asBridge();
const res = await post([ENERGY, PROTEIN]);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { inserted: number; updated: number };
};
expect(body.data).toMatchObject({ inserted: 1, updated: 1 });
const probe = vi.mocked(prisma.nutrientIntakeDay.findMany).mock.calls[0][0];
expect(probe?.where).toMatchObject({
userId: "user-1",
source: "EXTERNAL",
});
const created = vi.mocked(prisma.nutrientIntakeDay.createMany).mock
.calls[0][0] as { data: Array<{ source: string; nutrient: string }> };
expect(created.data).toEqual([
expect.objectContaining({ nutrient: "protein", source: "EXTERNAL" }),
]);
const update = vi.mocked(prisma.nutrientIntakeDay.update).mock.calls[0][0];
expect(update.where).toEqual({
userId_day_nutrient_source: {
userId: "user-1",
day: ENERGY.day,
nutrient: "energy",
source: "EXTERNAL",
},
});
});
it("counts in the bridge bucket and names the source in the audit row", async () => {
asBridge();
await post([ENERGY]);
expect(vi.mocked(checkRateLimit).mock.calls[0][0]).toBe(
"nutrients:batch:bridge:user-1",
);
expect(auditLog).toHaveBeenCalledWith(
"nutrient.batch.ingest",
expect.objectContaining({
details: expect.objectContaining({ source: "EXTERNAL" }),
}),
);
});
it("accepts alcohol, which no HealthKit type carries", async () => {
asBridge();
const res = await post([
{ day: "2026-11-01", nutrient: "alcohol", unit: "g", amount: 24 },
]);
const body = (await res.json()) as { data: { skipped: unknown[] } };
expect(body.data.skipped).toEqual([]);
});
it("skips energy posted in kJ rather than converting it", async () => {
asBridge();
const res = await post([{ ...ENERGY, unit: "kJ", amount: 8800 }]);
const body = (await res.json()) as {
data: { skipped: Array<{ reason: string }> };
};
expect(body.data.skipped).toEqual([{ index: 0, reason: "unit_mismatch" }]);
});
});
describe("POST /api/nutrients/batch from the native client", () => {
it("keeps writing the APPLE_HEALTH row in its own bucket", async () => {
asPhone();
await post([ENERGY, PROTEIN]);
expect(vi.mocked(checkRateLimit).mock.calls[0][0]).toBe(
"nutrients:batch:user-1",
);
const probe = vi.mocked(prisma.nutrientIntakeDay.findMany).mock.calls[0][0];
expect(probe?.where).toMatchObject({ source: "APPLE_HEALTH" });
const created = vi.mocked(prisma.nutrientIntakeDay.createMany).mock
.calls[0][0] as { data: Array<{ source: string }> };
expect(created.data.every((r) => r.source === "APPLE_HEALTH")).toBe(true);
expect(auditLog).toHaveBeenCalledWith(
"nutrient.batch.ingest",
expect.objectContaining({
details: expect.objectContaining({ source: "APPLE_HEALTH" }),
}),
);
});
});
+70 -157
View File
@@ -1,36 +1,37 @@
/**
* `POST /api/nutrients/batch` — micronutrient day-total ingest (v1.28).
* `POST /api/nutrients/batch` — nutrient day-total ingest (v1.28).
*
* iOS posts daily totals for the closed 26-code catalog (vitamins,
* minerals, water, caffeine) computed via `HKStatisticsCollectionQuery`
* day-anchored cumulative sums; `day` arrives as YYYY-MM-DD in the
* user's IANA timezone (the `stats:` day-key contract — the server
* trusts the string after regex + calendar sanity, no re-derivation).
* Two callers. The native client posts daily totals for the HealthKit codes
* (vitamins, minerals, water, caffeine, energy, the macros) computed via
* `HKStatisticsCollectionQuery` day-anchored cumulative sums, with a cookie
* session or the wildcard token its login mints; those rows are stored as
* APPLE_HEALTH. A bridge (a food tracker, a script) posts with a narrow
* `measurements:write` token; its rows are stored as EXTERNAL, and it may post
* `alcohol` too. The credential picks the source, never the body, so the two
* never overwrite each other and the reads count the larger day total
* (`foldNutrientDay`). `day` arrives as YYYY-MM-DD in the user's IANA timezone
* (the `stats:` day-key contract — the server trusts the string after regex +
* calendar sanity, no re-derivation); any past day is accepted, so a bridge
* can backfill its history.
*
* Upsert key = the composite PK (userId, day, nutrient, source), and this
* route always owns the APPLE_HEALTH row. Re-post
* replaces amount / unit / externalSourceVersion — last-writer-wins,
* the day-total contract; per-entry status is `updated` then, never
* `duplicate`. Validation failures (`unit_mismatch` | `value_out_of_range`
* | `day_invalid`) are always isolated per entry. The DB write itself runs
* as two batched groups — a single indexed existence read splits valid
* entries into a bulk `createMany` (new pairs) and a `$transaction` of
* per-row updates (existing pairs), the measurements-batch shape. A write
* failure marks its WHOLE group `skipped upsert_failed` rather than
* isolating the one entry that would have caused it (unavoidable once the
* write is batched) — the request itself never fails. That reason is
* transient, unlike the validation skips: the client sends those entries
* again, and the response is marked `no-store` so an idempotent retry is not
* answered from the cache.
* Upsert key = the composite PK (userId, day, nutrient, source). Re-post
* replaces amount / unit / externalSourceVersion — last-writer-wins, the
* day-total contract; a bridge corrects a day by posting 0. Per-entry status
* is `updated` then, never `duplicate`. Validation failures (`unit_mismatch` |
* `value_out_of_range` | `day_invalid`) are always isolated per entry. The
* write (`writeNutrientDayTotals`) runs as two batched groups; a write failure
* marks its WHOLE group `skipped upsert_failed` — the request itself never
* fails. That reason is transient, unlike the validation skips: the client
* sends those entries again, and the response is marked `no-store` so an
* idempotent retry is not answered from the cache.
*
* Module gate FIRST: the opt-in `nutrients` module (default off)
* refuses ingest with the 403 `module.disabled` envelope, so a phone
* whose user never opted in cannot land rows server-side
* refuses ingest with the 403 `module.disabled` envelope, so a phone or a
* bridge whose user never opted in cannot land rows server-side
* (refuse-ingest posture, mirroring mental health — not surface-only).
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
@@ -45,8 +46,15 @@ import { withIdempotency } from "@/lib/idempotency";
import { checkRateLimit } from "@/lib/rate-limit";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { invalidateUserHealthContext } from "@/lib/cache/invalidate";
import { isScopedCredential } from "@/lib/auth/guards/context";
import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes";
import { NUTRIENT_CATALOG } from "@/lib/nutrients/catalog";
import { maxAcceptableNutrientDay } from "@/lib/nutrients/day-bounds";
import {
writeNutrientDayTotals,
type ValidNutrientEntry,
} from "@/lib/nutrients/day-total-write";
import { NUTRIENT_SOURCE, type NutrientSource } from "@/lib/nutrients/sources";
import {
MAX_NUTRIENT_ENTRIES_PER_BATCH,
nutrientBatchSchema,
@@ -79,10 +87,27 @@ interface EntryResult {
export const POST = apiHandler(withIdempotency<[NextRequest]>(postBatch));
async function postBatch(request: NextRequest): Promise<Response> {
// Declares the third-party ingest scope, so a narrow `measurements:write`
// token reaches this route alongside cookie sessions and the wildcard tokens
// a native login mints. `requireAuth` refuses any acting-account carrier for
// every credential shape, so the scoped token is confined to its owner's own
// record here without this route adding an arm of its own.
// Metered by this route's own bulk bucket below, not the shared per-account
// write bucket: the native client syncs through here in bursts (see
// `meterAccountWrite`).
const { user } = await requireAuth(undefined, { writeBucket: "own" });
const auth = await requireAuth(MEASUREMENTS_WRITE_SCOPE, {
writeBucket: "own",
});
const { user } = auth;
// A scoped credential is a bridge — a food tracker, a script — and not the
// native client. Its rows are stored as EXTERNAL, the phone's as
// APPLE_HEALTH; the body has no say. Two sources, so a bridge and the phone
// never overwrite each other's day total, and the reads count the larger.
const scoped = isScopedCredential(auth);
const source: NutrientSource = scoped
? NUTRIENT_SOURCE.EXTERNAL
: NUTRIENT_SOURCE.APPLE_HEALTH;
// Module gate first: a disabled module must refuse before any body
// work, so iOS can branch on the 403 `module.disabled` errorCode and
@@ -90,8 +115,12 @@ async function postBatch(request: NextRequest): Promise<Response> {
const gate = await requireModuleEnabled(user.id, "nutrients");
if (!gate.enabled) return gate.response;
// A bridge counts in a bucket of its own, so a bridge stuck in a retry loop
// cannot use up the allowance the phone needs to sync the same account. All
// bridge tokens of one account share that bucket, so minting more tokens
// does not multiply the allowance.
const rl = await checkRateLimit(
`nutrients:batch:${user.id}`,
scoped ? `nutrients:batch:bridge:${user.id}` : `nutrients:batch:${user.id}`,
BATCH_RATE_LIMIT_MAX,
BATCH_RATE_LIMIT_WINDOW_MS,
);
@@ -138,15 +167,7 @@ async function postBatch(request: NextRequest): Promise<Response> {
let inserted = 0;
let updated = 0;
interface ValidEntry {
index: number;
day: string;
nutrient: (typeof entries)[number]["nutrient"];
amount: number;
unit: string;
externalSourceVersion: string | null;
}
const validEntries: ValidEntry[] = [];
const validEntries: ValidNutrientEntry[] = [];
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
@@ -187,128 +208,18 @@ async function postBatch(request: NextRequest): Promise<Response> {
});
}
// v1.29 — `source` joined the composite PK (migration 0249) so a manual
// water entry (source=MANUAL, written by `POST /api/nutrients/water`)
// coexists with the Apple-synced day total instead of one clobbering the
// other on the next sync. The batch route always owns the APPLE_HEALTH
// row.
//
// Perf (measurements/batch shape): ONE indexed existence read replaces the
// per-entry probe-then-upsert (up to 1000 sequential round trips pre-fix).
// Genuinely new (day, nutrient) pairs land via a single chunked
// `createMany`; pairs that already exist update via a batched
// `$transaction` of per-row `update` calls (values differ per row, so a
// single bulk statement isn't available without raw SQL — this still
// collapses the per-entry PROBE, and pipelines the writes through one
// transaction instead of N standalone round trips).
if (validEntries.length > 0) {
const existing = await prisma.nutrientIntakeDay.findMany({
where: {
userId: user.id,
source: "APPLE_HEALTH",
OR: validEntries.map((e) => ({ day: e.day, nutrient: e.nutrient })),
},
select: { day: true, nutrient: true },
});
const existingKeys = new Set(
existing.map((r) => `${r.day}::${r.nutrient}`),
);
const toInsert: ValidEntry[] = [];
const toUpdate: ValidEntry[] = [];
for (const e of validEntries) {
(existingKeys.has(`${e.day}::${e.nutrient}`) ? toUpdate : toInsert).push(
e,
);
}
if (toInsert.length > 0) {
try {
const result = await prisma.nutrientIntakeDay.createMany({
data: toInsert.map((e) => ({
userId: user.id,
day: e.day,
nutrient: e.nutrient,
amount: e.amount,
unit: e.unit,
source: "APPLE_HEALTH" as const,
externalSourceVersion: e.externalSourceVersion,
})),
skipDuplicates: true,
});
inserted += result.count;
for (const e of toInsert) {
results[e.index] = { index: e.index, status: "inserted" };
}
// Rare race: a concurrent request claimed one of these keys between
// our existence probe and this createMany, so skipDuplicates
// silently dropped that row's write here — measurements/batch
// accepts the same count-only trade-off for its own createMany race.
// The DB itself stays consistent (the racing writer's row is
// stored); only this response's per-row label may be stale for
// that one entry.
if (result.count < toInsert.length) {
annotate({
action: { name: "nutrient.batch.insert_race" },
meta: { attempted: toInsert.length, stored: result.count },
});
}
} catch (err: unknown) {
console.error("[nutrient-batch] bulk insert failed", err);
for (const e of toInsert) {
skipped.push({ index: e.index, reason: "upsert_failed" });
results[e.index] = {
index: e.index,
status: "skipped",
reason: "upsert_failed",
};
}
}
}
if (toUpdate.length > 0) {
try {
await prisma.$transaction(
toUpdate.map((e) =>
prisma.nutrientIntakeDay.update({
where: {
userId_day_nutrient_source: {
userId: user.id,
day: e.day,
nutrient: e.nutrient,
source: "APPLE_HEALTH",
},
},
data: {
// Last-writer-wins on the day total: iOS re-posts the
// current and previous local day on every sync as the
// totals grow.
amount: e.amount,
unit: e.unit,
externalSourceVersion: e.externalSourceVersion,
},
}),
),
);
updated += toUpdate.length;
for (const e of toUpdate) {
results[e.index] = { index: e.index, status: "updated" };
}
} catch (err: unknown) {
// The client-facing `reason` is a closed set (see the file header) —
// never echo raw exception text into it. Log the real error
// server-side only (SWC keeps `console.error` in prod) and return
// the fixed `upsert_failed` member.
console.error("[nutrient-batch] bulk update failed", err);
for (const e of toUpdate) {
skipped.push({ index: e.index, reason: "upsert_failed" });
results[e.index] = {
index: e.index,
status: "skipped",
reason: "upsert_failed",
};
}
}
// `source` is part of the composite PK (migration 0249), so this write
// touches only the caller's own source row: a manual water entry, the
// supplement total and the other day-total source are never clobbered.
const written = await writeNutrientDayTotals(user.id, source, validEntries);
inserted += written.inserted;
updated += written.updated;
for (const { index, status } of written.statuses) {
if (status === "failed") {
skipped.push({ index, reason: "upsert_failed" });
results[index] = { index, status: "skipped", reason: "upsert_failed" };
} else {
results[index] = { index, status };
}
}
@@ -337,6 +248,7 @@ async function postBatch(request: NextRequest): Promise<Response> {
userId: user.id,
ipAddress: getClientIp(request),
details: {
source,
processed: entries.length,
inserted,
updated,
@@ -358,6 +270,7 @@ async function postBatch(request: NextRequest): Promise<Response> {
annotate({
action: { name: "nutrient.batch.ingest" },
meta: {
source,
processed: entries.length,
inserted,
updated,
+4 -2
View File
@@ -12,8 +12,10 @@
* behind a home-automation bridge.
*
* What this mints is narrow by construction. `permissions` is a literal, so no
* request shape reaches it; the scope it names is accepted by exactly two
* routes, both writes, both on the holder's own record. It cannot read a
* request shape reaches it; the scope it names is accepted by exactly four
* routes (the single and batch measurement writes, a custom metric's value
* write, and the nutrient day-total batch), all writes, all on the holder's
* own record. It cannot read a
* reading back, cannot edit or delete one, cannot reach the export, and cannot
* mint another token — no Bearer credential reaches this endpoint at all, at
* any scope. That last property is why the mint is worth its own file: the
+12 -1
View File
@@ -6,10 +6,21 @@
* beside the surface that consumes it, and a central scope registry would
* invite a route to pick one off a menu — the opposite of the closed vocabulary
* `bearer-scope-enforcement-guard.test.ts` freezes. Zero imports because the
* mint route, both write routes, the settings card (a client component) and the
* mint route, the write routes, the settings card (a client component) and the
* guards all read it, and none of them should inherit an import graph for a
* string.
*
* It opens four doors, all writes on the holder's own record: the single and
* batch measurement writes, a custom metric's value write, and the nutrient
* day-total batch (`POST /api/nutrients/batch`, #1402). The last one is a
* deliberate reuse rather than a scope of its own, unlike `workouts:write`
* (`@/lib/workouts/scopes`). That precedent guards against a token pasted into
* a scale quietly accepting a different kind of record; a food tracker's day
* totals are the same kind of thing a scale sends, numbers about the day,
* written as source EXTERNAL and never read back, and a bridge that already
* posts weight should not need a second credential for calories. The nutrient
* route still refuses while the nutrients module is off.
*
* Deliberately alone. There is no read counterpart and must not be one: the
* measurement read legs stay cookie-equivalent, so a credential minted for a
* scale or a home-automation rule cannot read a health history back out. An
+145
View File
@@ -0,0 +1,145 @@
/**
* The write phase of `POST /api/nutrients/batch`: land validated day totals
* as one source's rows.
*
* Upsert key = the composite PK (userId, day, nutrient, source). The caller
* picks the source from the credential (APPLE_HEALTH for the native client,
* EXTERNAL for a bridge token) and this module writes only that source's rows,
* so a manual water entry, a supplement total and the other day-total source
* are never touched.
*
* Perf (measurements/batch shape): ONE indexed existence read splits the
* entries into genuinely new (day, nutrient) pairs, landed by a single
* `createMany`, and existing ones, updated through a batched `$transaction` of
* per-row `update` calls (values differ per row, so a single bulk statement is
* not available without raw SQL). A write failure marks its WHOLE group
* `skipped upsert_failed` rather than isolating the one entry that would have
* caused it (unavoidable once the write is batched); the request itself never
* fails.
*/
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import type { NutrientCode } from "@/lib/nutrients/catalog";
import type { NutrientSource } from "@/lib/nutrients/sources";
export interface ValidNutrientEntry {
/** Position in the request, echoed in the per-entry result. */
index: number;
day: string;
nutrient: NutrientCode;
amount: number;
unit: string;
externalSourceVersion: string | null;
}
export interface NutrientWriteOutcome {
inserted: number;
updated: number;
/** Per entry: `inserted`, `updated`, or a failed write. */
statuses: Array<{ index: number; status: "inserted" | "updated" | "failed" }>;
}
export async function writeNutrientDayTotals(
userId: string,
source: NutrientSource,
entries: ReadonlyArray<ValidNutrientEntry>,
): Promise<NutrientWriteOutcome> {
const outcome: NutrientWriteOutcome = {
inserted: 0,
updated: 0,
statuses: [],
};
if (entries.length === 0) return outcome;
const existing = await prisma.nutrientIntakeDay.findMany({
where: {
userId,
source,
OR: entries.map((e) => ({ day: e.day, nutrient: e.nutrient })),
},
select: { day: true, nutrient: true },
});
const existingKeys = new Set(existing.map((r) => `${r.day}::${r.nutrient}`));
const toInsert: ValidNutrientEntry[] = [];
const toUpdate: ValidNutrientEntry[] = [];
for (const e of entries) {
(existingKeys.has(`${e.day}::${e.nutrient}`) ? toUpdate : toInsert).push(e);
}
if (toInsert.length > 0) {
try {
const result = await prisma.nutrientIntakeDay.createMany({
data: toInsert.map((e) => ({
userId,
day: e.day,
nutrient: e.nutrient,
amount: e.amount,
unit: e.unit,
source,
externalSourceVersion: e.externalSourceVersion,
})),
skipDuplicates: true,
});
outcome.inserted += result.count;
for (const e of toInsert) {
outcome.statuses.push({ index: e.index, status: "inserted" });
}
// Rare race: a concurrent request claimed one of these keys between the
// existence probe and this createMany, so skipDuplicates dropped that
// row's write here — measurements/batch accepts the same count-only
// trade-off. The database stays consistent (the racing writer's row is
// stored); only this response's per-row label may be stale.
if (result.count < toInsert.length) {
annotate({
action: { name: "nutrient.batch.insert_race" },
meta: { attempted: toInsert.length, stored: result.count },
});
}
} catch (err: unknown) {
console.error("[nutrient-batch] bulk insert failed", err);
for (const e of toInsert) {
outcome.statuses.push({ index: e.index, status: "failed" });
}
}
}
if (toUpdate.length > 0) {
try {
await prisma.$transaction(
toUpdate.map((e) =>
prisma.nutrientIntakeDay.update({
where: {
userId_day_nutrient_source: {
userId,
day: e.day,
nutrient: e.nutrient,
source,
},
},
data: {
// Last-writer-wins on the day total: a client re-posts the
// current and previous local day on every sync as the totals
// grow, and a bridge posts 0 to correct a day.
amount: e.amount,
unit: e.unit,
externalSourceVersion: e.externalSourceVersion,
},
}),
),
);
outcome.updated += toUpdate.length;
for (const e of toUpdate) {
outcome.statuses.push({ index: e.index, status: "updated" });
}
} catch (err: unknown) {
// Logged server-side only; the client sees the closed `upsert_failed`
// reason, never raw exception text.
console.error("[nutrient-batch] bulk update failed", err);
for (const e of toUpdate) {
outcome.statuses.push({ index: e.index, status: "failed" });
}
}
}
return outcome;
}
+1 -1
View File
@@ -2011,7 +2011,7 @@ export const authPaths: NonNullable<ZodOpenApiObject["paths"]> = {
summary: "Mint a measurement-ingest token",
description:
"Mints a Bearer scoped to exactly `measurements:write` and audits the mint. THE RESPONSE CARRIES THE RAW TOKEN — the only place it ever exists; it is stored as an HMAC and no path re-reveals it.\n\n" +
"**What it can do.** `POST /api/measurements` and `POST /api/measurements/batch`, on its owner's own record, and `POST /api/custom-metrics/{id}/entries` for a custom metric its owner already created (it cannot list, create, edit or delete metrics, so the id comes from the metric's page in the app). Measurement rows it writes carry `source: EXTERNAL`, resolved from the credential rather than taken from the body, so a reading pushed by a bridge stays distinguishable from one typed in by hand and can be picked out with the source filter. A body naming ANY source is refused 422 rather than relabelled — honouring it would defeat the label, overriding it silently would hand the caller rows it did not ask for. `APPLE_HEALTH` is the one that would do real damage: it is half a dedup key the phone also writes into, it participates in the cross-source merge, and it is what decides the Apple Health card may claim a sync happened. For the same reason a write through this credential does not move the native client's sync checkpoint. The rows stay editable by their owner, unlike a connected provider's — the hardware behind the token is the user's own.\n\n" +
"**What it can do.** `POST /api/measurements` and `POST /api/measurements/batch`, on its owner's own record, `POST /api/custom-metrics/{id}/entries` for a custom metric its owner already created (it cannot list, create, edit or delete metrics, so the id comes from the metric's page in the app), and `POST /api/nutrients/batch` for daily nutrient totals (energy, macronutrients, alcohol, vitamins, minerals, water, caffeine) while the owner has the nutrients module on; the day totals it posts are stored as source `EXTERNAL`, apart from the phone's Apple Health totals, and a re-post replaces the day. Measurement rows it writes carry `source: EXTERNAL`, resolved from the credential rather than taken from the body, so a reading pushed by a bridge stays distinguishable from one typed in by hand and can be picked out with the source filter. A body naming ANY source is refused 422 rather than relabelled — honouring it would defeat the label, overriding it silently would hand the caller rows it did not ask for. `APPLE_HEALTH` is the one that would do real damage: it is half a dedup key the phone also writes into, it participates in the cross-source merge, and it is what decides the Apple Health card may claim a sync happened. For the same reason a write through this credential does not move the native client's sync checkpoint. The rows stay editable by their owner, unlike a connected provider's — the hardware behind the token is the user's own.\n\n" +
"**What it cannot do.** Everything else, including the measurement reads on the same paths, the custom-metric list and value reads, the edit and delete legs, and the export — a scope grants what it names and nothing adjacent. It cannot be pointed at a shared record: a request carrying the account selector is refused 403 before any grant is read, whatever grants its holder actually has. And it cannot mint another token, this endpoint included.\n\n" +
"Minting requires a COOKIE SESSION with a fresh proof: a sign-in or `POST /api/auth/reproof` within the last five minutes (with a second factor, on an account that has one), otherwise 401 `auth.reproof.required` with `meta.methods`. No Bearer credential reaches this endpoint at any scope, wildcard included — not because a wildcard lacks the reach, but because of the lifetimes involved: a native access token lives a day and what it could mint here lives a year, so admitting one would let a short-lived compromise leave behind a credential that outlives revoking it. Gated by the operator's instance-wide API switch. Body capped at 16 KiB; 10 mints per user per minute, and at most 10 live tokens held at once. Tokens appear in `GET /api/tokens` and are revoked at `DELETE /api/tokens/{id}` like any other — revoking frees a slot against the ceiling.",
requestBody: {