From bfa6873d9605ecc805d14e1e3428220d5b802868 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 23 Oct 2026 19:28:05 +0200 Subject: [PATCH] feat(tokens): add a per-token Apple Health setting PATCH /api/tokens/{id} sets mirrorToAppleHealth on a measurement token: cookie session only, the caller's own tokens only, revoked ones included, any other token refused with tokens.mirror.not_measurement_token. It stamps mirrorChangedAt and audits only when the value changes. The mint accepts the setting (off by default), the token list returns it, and GET /api/tokens/measurements counts the EXTERNAL readings no token reaches. --- src/app/api/tokens/[id]/route.ts | 65 +++- .../measurements/__tests__/route.test.ts | 42 ++- src/app/api/tokens/measurements/route.ts | 34 +- src/app/api/tokens/route.ts | 3 + src/lib/auth/issue-token.ts | 5 + src/lib/measurements/token-mirror.ts | 62 ++++ src/lib/openapi/error-codes.ts | 1 + src/lib/validations/tokens.ts | 15 + tests/integration/apple-health-mirror.test.ts | 351 ++++++++++++++++++ tests/integration/routes/kit-contract.test.ts | 1 + .../tokens-mirror.01-summary.json.snap | 68 ++++ .../tokens-mirror.02-on.json.snap | 78 ++++ .../tokens-mirror.03-on-again.json.snap | 78 ++++ .../tokens-mirror.04-list.json.snap | 109 ++++++ .../tokens-mirror.05-off-revoked.json.snap | 85 +++++ .../tokens-mirror.06-wildcard.json.snap | 83 +++++ .../tokens-mirror.07-connector.json.snap | 83 +++++ ...tokens-mirror.08-another-account.json.snap | 83 +++++ .../tokens-mirror.09-unknown.json.snap | 83 +++++ .../tokens-mirror.10-invalid-body.json.snap | 100 +++++ .../tokens-mirror.11-bearer.json.snap | 84 +++++ .../tokens-mirror.12-summary-bearer.json.snap | 84 +++++ .../parity/tokens-mirror.parity.test.ts | 238 ++++++++++++ 23 files changed, 1828 insertions(+), 7 deletions(-) create mode 100644 src/lib/measurements/token-mirror.ts create mode 100644 tests/integration/apple-health-mirror.test.ts create mode 100644 tests/integration/routes/parity/__snapshots__/tokens-mirror.01-summary.json.snap create mode 100644 tests/integration/routes/parity/__snapshots__/tokens-mirror.02-on.json.snap create mode 100644 tests/integration/routes/parity/__snapshots__/tokens-mirror.03-on-again.json.snap create mode 100644 tests/integration/routes/parity/__snapshots__/tokens-mirror.04-list.json.snap create mode 100644 tests/integration/routes/parity/__snapshots__/tokens-mirror.05-off-revoked.json.snap create mode 100644 tests/integration/routes/parity/__snapshots__/tokens-mirror.06-wildcard.json.snap create mode 100644 tests/integration/routes/parity/__snapshots__/tokens-mirror.07-connector.json.snap create mode 100644 tests/integration/routes/parity/__snapshots__/tokens-mirror.08-another-account.json.snap create mode 100644 tests/integration/routes/parity/__snapshots__/tokens-mirror.09-unknown.json.snap create mode 100644 tests/integration/routes/parity/__snapshots__/tokens-mirror.10-invalid-body.json.snap create mode 100644 tests/integration/routes/parity/__snapshots__/tokens-mirror.11-bearer.json.snap create mode 100644 tests/integration/routes/parity/__snapshots__/tokens-mirror.12-summary-bearer.json.snap create mode 100644 tests/integration/routes/parity/tokens-mirror.parity.test.ts diff --git a/src/app/api/tokens/[id]/route.ts b/src/app/api/tokens/[id]/route.ts index c6659d20d..9777d5aed 100644 --- a/src/app/api/tokens/[id]/route.ts +++ b/src/app/api/tokens/[id]/route.ts @@ -1,8 +1,12 @@ import { prisma } from "@/lib/db"; -import { apiHandler, requireAuth } from "@/lib/api-handler"; +import { apiHandler, requireAuth, requireCookieAuth } from "@/lib/api-handler"; import { annotate } from "@/lib/logging/context"; -import { apiSuccess, apiError } from "@/lib/api-response"; +import { apiSuccess, apiError, getClientIp } from "@/lib/api-response"; import { isApiGloballyEnabled } from "@/lib/app-settings"; +import { parseJsonBody } from "@/lib/api/body"; +import { checkRateLimit } from "@/lib/rate-limit"; +import { updateMeasurementTokenSchema } from "@/lib/validations/tokens"; +import { setMeasurementTokenMirror } from "@/lib/measurements/token-mirror"; type RouteParams = { params: Promise<{ id: string }> }; @@ -38,3 +42,60 @@ export const DELETE = apiHandler( return apiSuccess({ revoked: true }); }, ); + +/** + * Change a measurement token's one setting: whether the HealthLog app writes + * its readings into Apple Health (#1272). + * + * - Cookie only. A Bearer, the token's own included, cannot change what its + * readings are allowed to become; the person decides, from the browser + * they are sitting at. + * - The caller's own tokens only: another account's answers 404. + * - Measurement tokens only. A wildcard, an MCP or any other narrow token has + * no such setting and is refused with 422 `tokens.mirror.not_measurement_token`. + * - A revoked token is accepted: its readings stay in the record. + * + * Not gated on the instance-wide API switch: no credential is created or + * extended, and the readings already in the record are what it governs. + */ +export const PATCH = apiHandler( + async (request: Request, { params }: RouteParams) => { + const { user } = await requireCookieAuth(); + annotate({ action: { name: "tokens.measurements.mirror.update" } }); + + const rl = await checkRateLimit( + `tokens:mirror:${user.id}`, + MIRROR_RATE_LIMIT_MAX, + MIRROR_RATE_LIMIT_WINDOW_MS, + ); + if (!rl.allowed) { + return apiError("Too many changes, try again later", 429); + } + + const parsed = await parseJsonBody(request, updateMeasurementTokenSchema, { + maxBytes: 4 * 1024, + }); + if (!parsed.ok) return parsed.error; + + const { id } = await params; + const outcome = await setMeasurementTokenMirror({ + userId: user.id, + tokenId: id, + mirrorToAppleHealth: parsed.data.mirrorToAppleHealth, + ipAddress: getClientIp(request), + }); + if (outcome.kind === "not_found") { + return apiError("Token not found", 404); + } + if (outcome.kind === "not_measurement_token") { + return apiError("Only a measurement token has this setting", 422, { + errorCode: "tokens.mirror.not_measurement_token", + }); + } + return apiSuccess({ id, mirrorToAppleHealth: outcome.mirrorToAppleHealth }); + }, +); + +/** Changes per account per window: a settings switch, not an API. */ +const MIRROR_RATE_LIMIT_MAX = 30; +const MIRROR_RATE_LIMIT_WINDOW_MS = 60 * 1000; diff --git a/src/app/api/tokens/measurements/__tests__/route.test.ts b/src/app/api/tokens/measurements/__tests__/route.test.ts index 3a584dd17..29beb8428 100644 --- a/src/app/api/tokens/measurements/__tests__/route.test.ts +++ b/src/app/api/tokens/measurements/__tests__/route.test.ts @@ -39,10 +39,10 @@ vi.mock("@/lib/logging/context", () => ({ })); vi.mock("@/lib/db", () => ({ - prisma: { apiToken: { count: vi.fn() } }, + prisma: { apiToken: { count: vi.fn() }, measurement: { count: vi.fn() } }, })); -import { POST } from "../route"; +import { GET, POST } from "../route"; import { assertRecentCookieProof, requireCookieAuth } from "@/lib/api-handler"; import { issueApiToken } from "@/lib/auth/issue-token"; import { isApiGloballyEnabled } from "@/lib/app-settings"; @@ -147,6 +147,27 @@ describe("what it mints", () => { ); }); + it("leaves the write-back off unless asked, and refuses a non-boolean", async () => { + const mint = (body: unknown) => + POST(req(body) as Parameters[0]); + await mint({ name: "Scale" }); + expect(vi.mocked(issueApiToken).mock.calls[0][0].mirrorToAppleHealth).toBe( + false, + ); + await mint({ name: "Scale", mirrorToAppleHealth: true }); + await mint({ name: "Scale", mirrorToAppleHealth: "yes" }); + expect(issueApiToken).toHaveBeenCalledTimes(2); + expect(vi.mocked(issueApiToken).mock.calls[1][0].mirrorToAppleHealth).toBe( + true, + ); + expect(auditLog).toHaveBeenLastCalledWith( + "tokens.measurements.create", + expect.objectContaining({ + details: expect.objectContaining({ mirrorToAppleHealth: true }), + }), + ); + }); + it("counts only live tokens carrying this scope", async () => { // The whole shape of the query, asserted rather than assumed. Counting // every row would let the `["*"]` tokens a login mints consume the budget @@ -239,3 +260,20 @@ describe("when it refuses", () => { ]); }); }); + +describe("the readings no token reaches", () => { + it("counts the caller's live EXTERNAL readings without a token", async () => { + vi.mocked(prisma.measurement.count).mockResolvedValue(4); + const res = await GET(); + expect(res.status).toBe(200); + expect((await res.json()).data).toEqual({ unattributedReadings: 4 }); + expect(prisma.measurement.count).toHaveBeenCalledWith({ + where: { + userId: USER.id, + source: "EXTERNAL", + ingestTokenId: null, + deletedAt: null, + }, + }); + }); +}); diff --git a/src/app/api/tokens/measurements/route.ts b/src/app/api/tokens/measurements/route.ts index 600b968db..2036ec183 100644 --- a/src/app/api/tokens/measurements/route.ts +++ b/src/app/api/tokens/measurements/route.ts @@ -21,8 +21,8 @@ * operate should not include making more credentials. * * No listing leg. `/api/tokens` already returns every token with its - * `permissions`, so the settings card filters that one query rather than - * duplicating it — the MCP module needs its own list only because it must hide + * `permissions` (and a measurement token's Apple Health setting), so the + * settings card filters that one query rather than duplicating it — the MCP module needs its own list only because it must hide * transient OAuth access rows, and there is no such row here. No revoke-all * either: `DELETE /api/tokens/[id]` is per-row and the card shows the rows. The * per-medication toggle's bulk revoke exists because that surface is a boolean @@ -44,6 +44,7 @@ import { issueApiToken } from "@/lib/auth/issue-token"; import { isApiGloballyEnabled } from "@/lib/app-settings"; import { checkRateLimit } from "@/lib/rate-limit"; import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes"; +import { EXTERNAL_SOURCE } from "@/lib/measurements/external-source"; import { createMeasurementTokenSchema } from "@/lib/validations/tokens"; /** @@ -58,6 +59,28 @@ import { createMeasurementTokenSchema } from "@/lib/validations/tokens"; */ const DEFAULT_EXPIRY_DAYS = 365; +/** + * What the token list cannot say: how many of the account's EXTERNAL readings + * belong to no token (#1272). They were sent before readings were linked to + * the token that carried them, by an account holding more than one token, so + * no token's Apple Health setting reaches them and they stay out of Apple + * Health. The settings card shows a notice when the count is not zero. + */ +export const GET = apiHandler(async () => { + const { user } = await requireCookieAuth(); + annotate({ action: { name: "tokens.measurements.summary" } }); + const unattributedReadings = await prisma.measurement.count({ + where: { + userId: user.id, + source: EXTERNAL_SOURCE, + ingestTokenId: null, + deletedAt: null, + }, + }); + annotate({ meta: { unattributed_readings: unattributedReadings } }); + return apiSuccess({ unattributedReadings }); +}); + /** Mints per user per minute. A credential mint is worth its own bucket. */ const MINT_RATE_LIMIT_MAX = 10; const MINT_RATE_LIMIT_WINDOW_MS = 60 * 1000; @@ -177,12 +200,17 @@ export const POST = apiHandler(async (request: NextRequest) => { // which is why the unit suite asserts this array and not merely the 201. permissions: [MEASUREMENTS_WRITE_SCOPE], expiresInDays: parsed.data.expiresInDays ?? DEFAULT_EXPIRY_DAYS, + mirrorToAppleHealth: parsed.data.mirrorToAppleHealth === true, }); await auditLog("tokens.measurements.create", { userId: user.id, ipAddress: getClientIp(request), - details: { tokenId: issued.tokenId, scope: MEASUREMENTS_WRITE_SCOPE }, + details: { + tokenId: issued.tokenId, + scope: MEASUREMENTS_WRITE_SCOPE, + mirrorToAppleHealth: parsed.data.mirrorToAppleHealth === true, + }, }); // The raw token, once. It is stored as an HMAC and no path re-reveals it. diff --git a/src/app/api/tokens/route.ts b/src/app/api/tokens/route.ts index 0a653efb0..71d44c559 100644 --- a/src/app/api/tokens/route.ts +++ b/src/app/api/tokens/route.ts @@ -46,6 +46,9 @@ export const GET = apiHandler(async () => { expiresAt: true, createdAt: true, revoked: true, + // A measurement token's Apple Health write-back (#1272); false for + // every other token. + mirrorToAppleHealth: true, }, orderBy: { createdAt: "desc" }, }); diff --git a/src/lib/auth/issue-token.ts b/src/lib/auth/issue-token.ts index 0939aaec2..90e878e4e 100644 --- a/src/lib/auth/issue-token.ts +++ b/src/lib/auth/issue-token.ts @@ -36,6 +36,8 @@ export interface IssueTokenOptions { * issued and the connector token list can exclude the transient access rows. */ mcpConnectionId?: string; + /** A measurement token's Apple Health write-back (#1272). Off by default. */ + mirrorToAppleHealth?: boolean; } /** @@ -64,6 +66,9 @@ export async function issueApiToken( ...(opts.mcpConnectionId ? { mcpConnectionId: opts.mcpConnectionId } : {}), + ...(opts.mirrorToAppleHealth === true + ? { mirrorToAppleHealth: true } + : {}), }, select: { id: true }, }); diff --git a/src/lib/measurements/token-mirror.ts b/src/lib/measurements/token-mirror.ts new file mode 100644 index 000000000..e590adf59 --- /dev/null +++ b/src/lib/measurements/token-mirror.ts @@ -0,0 +1,62 @@ +/** + * Switching a measurement token's Apple Health write-back (#1272), for + * `PATCH /api/tokens/{id}`. + * + * One statement on the token row. The readings the token carried are not + * touched: their `updatedAt` and `syncVersion` stay as they are, so nothing + * keyed on them (the rollup freshness probe, personal-record detection, the + * status re-warm) sees a change that is not one. The rows reach a paired + * client again through the `measurementMirror` domain of `/api/sync/changes`, + * keyed on the `mirrorChangedAt` this stamps. + */ +import { prisma } from "@/lib/db"; +import { annotate } from "@/lib/logging/context"; +import { auditLog } from "@/lib/auth/audit"; +import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes"; + +/** A token minted by `POST /api/tokens/measurements`, and nothing else. */ +export function isMeasurementToken(permissions: readonly string[]): boolean { + return ( + permissions.length === 1 && permissions[0] === MEASUREMENTS_WRITE_SCOPE + ); +} + +export type TokenMirrorOutcome = + | { kind: "not_found" } + | { kind: "not_measurement_token" } + | { kind: "set"; mirrorToAppleHealth: boolean }; + +export async function setMeasurementTokenMirror(input: { + userId: string; + tokenId: string; + mirrorToAppleHealth: boolean; + ipAddress: string | null; +}): Promise { + const { userId, tokenId, mirrorToAppleHealth } = input; + const token = await prisma.apiToken.findUnique({ + where: { id: tokenId }, + select: { userId: true, permissions: true, mirrorToAppleHealth: true }, + }); + // Another account's token is answered as missing, like the revoke. + if (!token || token.userId !== userId) return { kind: "not_found" }; + // A revoked token is accepted: its readings stay in the record, and + // whether they are mirrored is still the person's choice. + if (!isMeasurementToken(token.permissions)) { + return { kind: "not_measurement_token" }; + } + + const changed = token.mirrorToAppleHealth !== mirrorToAppleHealth; + if (changed) { + await prisma.apiToken.update({ + where: { id: tokenId }, + data: { mirrorToAppleHealth, mirrorChangedAt: new Date() }, + }); + await auditLog("tokens.measurements.mirror.update", { + userId, + ipAddress: input.ipAddress, + details: { tokenId, mirrorToAppleHealth }, + }); + } + annotate({ meta: { mirror_to_apple_health: mirrorToAppleHealth, changed } }); + return { kind: "set", mirrorToAppleHealth }; +} diff --git a/src/lib/openapi/error-codes.ts b/src/lib/openapi/error-codes.ts index b91330fb2..fba66f494 100644 --- a/src/lib/openapi/error-codes.ts +++ b/src/lib/openapi/error-codes.ts @@ -450,6 +450,7 @@ export const ERROR_CODE_CATALOGUE: Readonly> = tokens: [ "tokens.documents.ceiling_reached", "tokens.measurements.ceiling_reached", + "tokens.mirror.not_measurement_token", "tokens.workouts.ceiling_reached", ], vaccination: [ diff --git a/src/lib/validations/tokens.ts b/src/lib/validations/tokens.ts index d0fcca994..99926eb1d 100644 --- a/src/lib/validations/tokens.ts +++ b/src/lib/validations/tokens.ts @@ -19,6 +19,21 @@ import { z } from "zod/v4"; export const createMeasurementTokenSchema = z.object({ name: z.string().min(1, "Name required").max(100), expiresInDays: z.number().int().min(1).max(365).optional(), + /** + * Whether the HealthLog app writes this token's readings into Apple Health + * (#1272). Off unless the person turns it on; changeable later with + * `PATCH /api/tokens/{id}`. + */ + mirrorToAppleHealth: z.boolean().optional(), +}); + +/** + * Body of `PATCH /api/tokens/{id}`: the one setting a measurement token has. + * Strict, so a key this route does not understand (a `permissions`, a + * `name`) is refused rather than ignored. + */ +export const updateMeasurementTokenSchema = z.strictObject({ + mirrorToAppleHealth: z.boolean(), }); export type CreateMeasurementTokenInput = z.infer< diff --git a/tests/integration/apple-health-mirror.test.ts b/tests/integration/apple-health-mirror.test.ts new file mode 100644 index 000000000..fb62b59d3 --- /dev/null +++ b/tests/integration/apple-health-mirror.test.ts @@ -0,0 +1,351 @@ +/** + * Per-token Apple Health write-back (#1272), end to end against Postgres. + * + * A reading a `measurements:write` token carries keeps its `EXTERNAL` source + * and is linked to the token. Every measurement row answers a resolved + * `appleHealthMirror`: WITHINGS, IMPORT and MANUAL true, EXTERNAL whatever the + * person chose for the token, everything else false. Switching the setting is + * one statement on the token row: the readings themselves are not touched + * (no `updatedAt` or `syncVersion` bump, so nothing keyed on them recomputes), + * and the `measurementMirror` domain of `/api/sync/changes` re-delivers the + * token's rows with the new value. + */ +import { beforeEach, describe, expect, it } from "vitest"; + +import { + GET as listMeasurements, + POST as createMeasurement, +} from "@/app/api/measurements/route"; +import { POST as batchMeasurements } from "@/app/api/measurements/batch/route"; +import { GET as readMeasurement } from "@/app/api/measurements/[id]/route"; +import { GET as syncChanges } from "@/app/api/sync/changes/route"; +import { + PATCH as patchToken, + DELETE as revokeToken, +} from "@/app/api/tokens/[id]/route"; +import { GET as listTokens } from "@/app/api/tokens/route"; +import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes"; +import { MEASUREMENT_SOURCES } from "@/lib/measurements/sources"; + +import { callRoute, type RouteAuth } from "../kit/call-route"; +import { + makeMeasurement, + makeSession, + makeToken, + makeUser, + type BearerFixture, +} from "../kit/factories"; +import { getPrismaClient, truncateAllTables } from "./setup"; + +const prisma = getPrismaClient(); + +let userId: string; +let owner: RouteAuth; +let scale: BearerFixture; + +beforeEach(async () => { + await truncateAllTables(prisma); + const user = await makeUser({ timezone: "UTC" }); + userId = user.id; + owner = await makeSession(user); + scale = await makeToken(user, { + permissions: [MEASUREMENTS_WRITE_SCOPE], + name: "Scale", + }); +}); + +async function postReading( + value: number, + at: string, + headers?: Record, +) { + return callRoute<{ id: string }>(createMeasurement, { + method: "POST", + route: "/api/measurements", + body: { type: "WEIGHT", value, unit: "kg", measuredAt: at }, + auth: scale, + headers, + }); +} + +async function list(query: Record = {}) { + const res = await callRoute<{ + measurements: Array<{ + id: string; + source: string; + appleHealthMirror: boolean; + }>; + }>(listMeasurements, { + method: "GET", + route: "/api/measurements", + query: { limit: 50, ...query }, + auth: owner, + }); + expect(res.status).toBe(200); + return res.data.measurements; +} + +async function setMirror(id: string, on: boolean, auth: RouteAuth = owner) { + return callRoute<{ id: string; mirrorToAppleHealth: boolean }>(patchToken, { + method: "PATCH", + route: "/api/tokens/{id}", + params: { id }, + body: { mirrorToAppleHealth: on }, + auth, + }); +} + +describe("a token's readings and the resolved write-back", () => { + it("links the reading to its token and resolves each source", async () => { + const res = await postReading(81.2, "2026-10-14T06:30:00.000Z"); + expect(res.status).toBe(201); + const stored = await prisma.measurement.findFirstOrThrow({ + where: { userId, source: "EXTERNAL" }, + select: { ingestTokenId: true }, + }); + expect(stored.ingestTokenId).toBe(scale.tokenId); + + await makeMeasurement( + { id: userId }, + { + source: "MANUAL", + measuredAt: new Date("2026-10-13T06:30:00.000Z"), + }, + ); + await makeMeasurement( + { id: userId }, + { + source: "APPLE_HEALTH", + measuredAt: new Date("2026-10-12T06:30:00.000Z"), + externalId: "hk-1", + }, + ); + + const rows = await list({ type: "WEIGHT" }); + const bySource = Object.fromEntries( + rows.map((r) => [r.source, r.appleHealthMirror]), + ); + expect(bySource).toEqual({ + EXTERNAL: false, + MANUAL: true, + APPLE_HEALTH: false, + }); + // The token never reaches the wire. + for (const row of rows) { + expect(row).not.toHaveProperty("ingestTokenId"); + expect(row).not.toHaveProperty("ingestToken"); + } + }); + + it("links every row of a token batch", async () => { + const res = await callRoute(batchMeasurements, { + method: "POST", + route: "/api/measurements/batch", + body: { + entries: [ + { + hkIdentifier: "HKQuantityTypeIdentifierBodyMass", + value: 80.1, + unit: "kg", + startDate: "2026-10-14T06:30:00.000Z", + endDate: "2026-10-14T06:30:00.000Z", + externalId: "scale-1", + }, + ], + }, + auth: scale, + }); + expect(res.status).toBe(200); + const rows = await prisma.measurement.findMany({ + where: { userId }, + select: { source: true, ingestTokenId: true }, + }); + expect(rows).toEqual([ + { source: "EXTERNAL", ingestTokenId: scale.tokenId }, + ]); + }); +}); + +describe("the list filter", () => { + it("returns exactly the rows that resolve true, for every source", async () => { + const on = await makeToken( + { id: userId }, + { permissions: [MEASUREMENTS_WRITE_SCOPE], name: "On" }, + ); + await prisma.apiToken.update({ + where: { id: on.tokenId }, + data: { mirrorToAppleHealth: true }, + }); + let minute = 0; + for (const source of MEASUREMENT_SOURCES) { + for (const ingestTokenId of [null, scale.tokenId, on.tokenId]) { + minute += 1; + await makeMeasurement( + { id: userId }, + { + source, + ingestTokenId, + measuredAt: new Date(Date.UTC(2026, 9, 1, 6, minute)), + externalId: `row-${minute}`, + }, + ); + } + } + const all = await list({ limit: 500 }); + expect(all).toHaveLength(MEASUREMENT_SOURCES.length * 3); + const expected = all + .filter((r) => r.appleHealthMirror) + .map((r) => r.id) + .sort(); + expect(expected.length).toBeGreaterThan(0); + const filtered = await list({ limit: 500, appleHealthMirror: "true" }); + expect(filtered.map((r) => r.id).sort()).toEqual(expected); + }); + + it.each([ + { groupBy: "day" }, + { dayKey: "2026-10-14" }, + { aggregate: "daily" }, + { type: "SLEEP_DURATION" }, + ])("is refused beside %j", async (mode) => { + const res = await callRoute(listMeasurements, { + method: "GET", + route: "/api/measurements", + query: { type: "WEIGHT", ...mode, appleHealthMirror: "true" }, + auth: owner, + }); + expect(res.status).toBe(422); + }); +}); + +describe("switching the setting", () => { + it("turns the token's rows true everywhere, and leaves the rows themselves alone", async () => { + const created = await postReading(81.2, "2026-10-14T06:30:00.000Z"); + const id = created.data.id; + const before = await prisma.measurement.findUniqueOrThrow({ + where: { id }, + select: { updatedAt: true, syncVersion: true }, + }); + const first = await callRoute<{ cursor: string }>(syncChanges, { + method: "GET", + route: "/api/sync/changes", + auth: owner, + }); + + const res = await setMirror(scale.tokenId, true); + expect(res.status).toBe(200); + expect(res.data).toEqual({ id: scale.tokenId, mirrorToAppleHealth: true }); + + const after = await prisma.measurement.findUniqueOrThrow({ + where: { id }, + select: { updatedAt: true, syncVersion: true }, + }); + expect(after).toEqual(before); + + expect((await list())[0].appleHealthMirror).toBe(true); + expect( + (await list({ appleHealthMirror: "true" })).map((r) => r.id), + ).toEqual([id]); + const detail = await callRoute<{ appleHealthMirror: boolean }>( + readMeasurement, + { + method: "GET", + route: "/api/measurements/{id}", + params: { id }, + auth: owner, + }, + ); + expect(detail.data.appleHealthMirror).toBe(true); + + const next = await callRoute<{ + changes: { + measurements: { upserts: unknown[] }; + measurementMirror: { + upserts: Array<{ id: string; appleHealthMirror: boolean }>; + }; + }; + }>(syncChanges, { + method: "GET", + route: "/api/sync/changes", + query: { cursor: first.data.cursor }, + auth: owner, + }); + expect(next.data.changes.measurements.upserts).toEqual([]); + expect(next.data.changes.measurementMirror.upserts).toEqual([ + { id, appleHealthMirror: true }, + ]); + + const audit = await prisma.auditLog.findMany({ + where: { userId, action: "tokens.measurements.mirror.update" }, + select: { details: true }, + }); + expect(audit).toHaveLength(1); + expect(JSON.parse(audit[0].details ?? "{}")).toMatchObject({ + tokenId: scale.tokenId, + mirrorToAppleHealth: true, + }); + }); + + it("keeps a revoked token's choice, and shows it on the token list", async () => { + await postReading(81.2, "2026-10-14T06:30:00.000Z"); + await setMirror(scale.tokenId, true); + const revoked = await callRoute(revokeToken, { + method: "DELETE", + route: "/api/tokens/{id}", + params: { id: scale.tokenId }, + auth: owner, + }); + expect(revoked.status).toBe(200); + expect((await list())[0].appleHealthMirror).toBe(true); + + // A revoked token can still be switched. + expect((await setMirror(scale.tokenId, false)).status).toBe(200); + expect((await list())[0].appleHealthMirror).toBe(false); + + const tokens = await callRoute< + Array<{ id: string; mirrorToAppleHealth: boolean }> + >(listTokens, { method: "GET", route: "/api/tokens", auth: owner }); + expect(tokens.data.find((t) => t.id === scale.tokenId)).toMatchObject({ + mirrorToAppleHealth: false, + }); + }); + + it("answers a retried create from its idempotency record, unchanged", async () => { + const headers = { "idempotency-key": "scale-reading-1" }; + const first = await postReading(81.2, "2026-10-14T06:30:00.000Z", headers); + await setMirror(scale.tokenId, true); + const replay = await postReading(81.2, "2026-10-14T06:30:00.000Z", headers); + expect(replay.status).toBe(first.status); + expect(replay.body).toEqual(first.body); + expect( + await prisma.measurement.count({ where: { userId, source: "EXTERNAL" } }), + ).toBe(1); + }); +}); + +describe("what the switch refuses", () => { + it("refuses a token that is not a measurement token", async () => { + const wildcard = await makeToken({ id: userId }, { permissions: ["*"] }); + const res = await setMirror(wildcard.tokenId, true); + expect(res.status).toBe(422); + expect(res.meta?.errorCode).toBe("tokens.mirror.not_measurement_token"); + }); + + it("answers another account's token as missing", async () => { + const stranger = await makeUser({ timezone: "UTC" }); + const theirs = await makeToken(stranger, { + permissions: [MEASUREMENTS_WRITE_SCOPE], + }); + expect((await setMirror(theirs.tokenId, true)).status).toBe(404); + }); + + it("refuses a Bearer caller, the token's own included", async () => { + const res = await setMirror(scale.tokenId, true, scale); + expect([401, 403]).toContain(res.status); + const stored = await prisma.apiToken.findUniqueOrThrow({ + where: { id: scale.tokenId }, + select: { mirrorToAppleHealth: true }, + }); + expect(stored.mirrorToAppleHealth).toBe(false); + }); +}); diff --git a/tests/integration/routes/kit-contract.test.ts b/tests/integration/routes/kit-contract.test.ts index d2e28b609..c0866f4c6 100644 --- a/tests/integration/routes/kit-contract.test.ts +++ b/tests/integration/routes/kit-contract.test.ts @@ -27,6 +27,7 @@ const token = { expiresAt: null, createdAt: "2026-01-01T00:00:00.000Z", revoked: false, + mirrorToAppleHealth: false, }; function answering(status: number, body: unknown) { diff --git a/tests/integration/routes/parity/__snapshots__/tokens-mirror.01-summary.json.snap b/tests/integration/routes/parity/__snapshots__/tokens-mirror.01-summary.json.snap new file mode 100644 index 000000000..64122a4e9 --- /dev/null +++ b/tests/integration/routes/parity/__snapshots__/tokens-mirror.01-summary.json.snap @@ -0,0 +1,68 @@ +{ + "status": 200, + "body": { + "data": { + "unattributedReadings": 1 + }, + "error": null + }, + "events": [ + { + "status": 200, + "action": { + "name": "tokens.measurements.summary" + }, + "meta": { + "unattributed_readings": 1 + }, + "warnings": null, + "error": null + } + ], + "stored": { + "tokens": [ + { + "name": "Connector", + "permissions": [ + "health:read" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Phone", + "permissions": [ + "*" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + } + ], + "audit": [], + "readings": [ + { + "source": "EXTERNAL", + "ingestTokenId": null, + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + }, + { + "source": "EXTERNAL", + "ingestTokenId": "", + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + } + ] + } +} diff --git a/tests/integration/routes/parity/__snapshots__/tokens-mirror.02-on.json.snap b/tests/integration/routes/parity/__snapshots__/tokens-mirror.02-on.json.snap new file mode 100644 index 000000000..c4acf2966 --- /dev/null +++ b/tests/integration/routes/parity/__snapshots__/tokens-mirror.02-on.json.snap @@ -0,0 +1,78 @@ +{ + "status": 200, + "body": { + "data": { + "id": "", + "mirrorToAppleHealth": true + }, + "error": null + }, + "events": [ + { + "status": 200, + "action": { + "name": "tokens.measurements.mirror.update" + }, + "meta": { + "mirror_to_apple_health": true, + "changed": true + }, + "warnings": null, + "error": null + } + ], + "stored": { + "tokens": [ + { + "name": "Connector", + "permissions": [ + "health:read" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Phone", + "permissions": [ + "*" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "revoked": false, + "mirrorToAppleHealth": true, + "mirrorChangedAt": "" + } + ], + "audit": [ + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": true + } + } + ], + "readings": [ + { + "source": "EXTERNAL", + "ingestTokenId": null, + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + }, + { + "source": "EXTERNAL", + "ingestTokenId": "", + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + } + ] + } +} diff --git a/tests/integration/routes/parity/__snapshots__/tokens-mirror.03-on-again.json.snap b/tests/integration/routes/parity/__snapshots__/tokens-mirror.03-on-again.json.snap new file mode 100644 index 000000000..9786092b0 --- /dev/null +++ b/tests/integration/routes/parity/__snapshots__/tokens-mirror.03-on-again.json.snap @@ -0,0 +1,78 @@ +{ + "status": 200, + "body": { + "data": { + "id": "", + "mirrorToAppleHealth": true + }, + "error": null + }, + "events": [ + { + "status": 200, + "action": { + "name": "tokens.measurements.mirror.update" + }, + "meta": { + "mirror_to_apple_health": true, + "changed": false + }, + "warnings": null, + "error": null + } + ], + "stored": { + "tokens": [ + { + "name": "Connector", + "permissions": [ + "health:read" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Phone", + "permissions": [ + "*" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "revoked": false, + "mirrorToAppleHealth": true, + "mirrorChangedAt": "" + } + ], + "audit": [ + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": true + } + } + ], + "readings": [ + { + "source": "EXTERNAL", + "ingestTokenId": null, + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + }, + { + "source": "EXTERNAL", + "ingestTokenId": "", + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + } + ] + } +} diff --git a/tests/integration/routes/parity/__snapshots__/tokens-mirror.04-list.json.snap b/tests/integration/routes/parity/__snapshots__/tokens-mirror.04-list.json.snap new file mode 100644 index 000000000..7b1e922ca --- /dev/null +++ b/tests/integration/routes/parity/__snapshots__/tokens-mirror.04-list.json.snap @@ -0,0 +1,109 @@ +{ + "status": 200, + "body": { + "data": [ + { + "id": "", + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "lastUsedAt": null, + "expiresAt": "2027-01-13T12:00:00.000Z", + "createdAt": "", + "revoked": false, + "mirrorToAppleHealth": true + }, + { + "id": "", + "name": "Phone", + "permissions": [ + "*" + ], + "lastUsedAt": null, + "expiresAt": "2027-01-13T12:00:00.000Z", + "createdAt": "", + "revoked": false, + "mirrorToAppleHealth": false + }, + { + "id": "", + "name": "Connector", + "permissions": [ + "health:read" + ], + "lastUsedAt": null, + "expiresAt": "2027-01-13T12:00:00.000Z", + "createdAt": "", + "revoked": false, + "mirrorToAppleHealth": false + } + ], + "error": null + }, + "events": [ + { + "status": 200, + "action": { + "name": "tokens.list" + }, + "meta": null, + "warnings": null, + "error": null + } + ], + "stored": { + "tokens": [ + { + "name": "Connector", + "permissions": [ + "health:read" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Phone", + "permissions": [ + "*" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "revoked": false, + "mirrorToAppleHealth": true, + "mirrorChangedAt": "" + } + ], + "audit": [ + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": true + } + } + ], + "readings": [ + { + "source": "EXTERNAL", + "ingestTokenId": null, + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + }, + { + "source": "EXTERNAL", + "ingestTokenId": "", + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + } + ] + } +} diff --git a/tests/integration/routes/parity/__snapshots__/tokens-mirror.05-off-revoked.json.snap b/tests/integration/routes/parity/__snapshots__/tokens-mirror.05-off-revoked.json.snap new file mode 100644 index 000000000..78d0c3a5c --- /dev/null +++ b/tests/integration/routes/parity/__snapshots__/tokens-mirror.05-off-revoked.json.snap @@ -0,0 +1,85 @@ +{ + "status": 200, + "body": { + "data": { + "id": "", + "mirrorToAppleHealth": false + }, + "error": null + }, + "events": [ + { + "status": 200, + "action": { + "name": "tokens.measurements.mirror.update" + }, + "meta": { + "mirror_to_apple_health": false, + "changed": true + }, + "warnings": null, + "error": null + } + ], + "stored": { + "tokens": [ + { + "name": "Connector", + "permissions": [ + "health:read" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Phone", + "permissions": [ + "*" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "revoked": true, + "mirrorToAppleHealth": false, + "mirrorChangedAt": "" + } + ], + "audit": [ + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": true + } + }, + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": false + } + } + ], + "readings": [ + { + "source": "EXTERNAL", + "ingestTokenId": null, + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + }, + { + "source": "EXTERNAL", + "ingestTokenId": "", + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + } + ] + } +} diff --git a/tests/integration/routes/parity/__snapshots__/tokens-mirror.06-wildcard.json.snap b/tests/integration/routes/parity/__snapshots__/tokens-mirror.06-wildcard.json.snap new file mode 100644 index 000000000..2998d1a45 --- /dev/null +++ b/tests/integration/routes/parity/__snapshots__/tokens-mirror.06-wildcard.json.snap @@ -0,0 +1,83 @@ +{ + "status": 422, + "body": { + "data": null, + "error": "Only a measurement token has this setting", + "meta": { + "errorCode": "tokens.mirror.not_measurement_token", + "requestId": "" + } + }, + "events": [ + { + "status": 422, + "action": { + "name": "tokens.measurements.mirror.update" + }, + "meta": null, + "warnings": null, + "error": null + } + ], + "stored": { + "tokens": [ + { + "name": "Connector", + "permissions": [ + "health:read" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Phone", + "permissions": [ + "*" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "revoked": true, + "mirrorToAppleHealth": false, + "mirrorChangedAt": "" + } + ], + "audit": [ + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": true + } + }, + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": false + } + } + ], + "readings": [ + { + "source": "EXTERNAL", + "ingestTokenId": null, + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + }, + { + "source": "EXTERNAL", + "ingestTokenId": "", + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + } + ] + } +} diff --git a/tests/integration/routes/parity/__snapshots__/tokens-mirror.07-connector.json.snap b/tests/integration/routes/parity/__snapshots__/tokens-mirror.07-connector.json.snap new file mode 100644 index 000000000..2998d1a45 --- /dev/null +++ b/tests/integration/routes/parity/__snapshots__/tokens-mirror.07-connector.json.snap @@ -0,0 +1,83 @@ +{ + "status": 422, + "body": { + "data": null, + "error": "Only a measurement token has this setting", + "meta": { + "errorCode": "tokens.mirror.not_measurement_token", + "requestId": "" + } + }, + "events": [ + { + "status": 422, + "action": { + "name": "tokens.measurements.mirror.update" + }, + "meta": null, + "warnings": null, + "error": null + } + ], + "stored": { + "tokens": [ + { + "name": "Connector", + "permissions": [ + "health:read" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Phone", + "permissions": [ + "*" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "revoked": true, + "mirrorToAppleHealth": false, + "mirrorChangedAt": "" + } + ], + "audit": [ + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": true + } + }, + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": false + } + } + ], + "readings": [ + { + "source": "EXTERNAL", + "ingestTokenId": null, + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + }, + { + "source": "EXTERNAL", + "ingestTokenId": "", + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + } + ] + } +} diff --git a/tests/integration/routes/parity/__snapshots__/tokens-mirror.08-another-account.json.snap b/tests/integration/routes/parity/__snapshots__/tokens-mirror.08-another-account.json.snap new file mode 100644 index 000000000..127519719 --- /dev/null +++ b/tests/integration/routes/parity/__snapshots__/tokens-mirror.08-another-account.json.snap @@ -0,0 +1,83 @@ +{ + "status": 404, + "body": { + "data": null, + "error": "Token not found", + "meta": { + "errorCode": "http.not_found", + "requestId": "" + } + }, + "events": [ + { + "status": 404, + "action": { + "name": "tokens.measurements.mirror.update" + }, + "meta": null, + "warnings": null, + "error": null + } + ], + "stored": { + "tokens": [ + { + "name": "Connector", + "permissions": [ + "health:read" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Phone", + "permissions": [ + "*" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "revoked": true, + "mirrorToAppleHealth": false, + "mirrorChangedAt": "" + } + ], + "audit": [ + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": true + } + }, + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": false + } + } + ], + "readings": [ + { + "source": "EXTERNAL", + "ingestTokenId": null, + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + }, + { + "source": "EXTERNAL", + "ingestTokenId": "", + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + } + ] + } +} diff --git a/tests/integration/routes/parity/__snapshots__/tokens-mirror.09-unknown.json.snap b/tests/integration/routes/parity/__snapshots__/tokens-mirror.09-unknown.json.snap new file mode 100644 index 000000000..127519719 --- /dev/null +++ b/tests/integration/routes/parity/__snapshots__/tokens-mirror.09-unknown.json.snap @@ -0,0 +1,83 @@ +{ + "status": 404, + "body": { + "data": null, + "error": "Token not found", + "meta": { + "errorCode": "http.not_found", + "requestId": "" + } + }, + "events": [ + { + "status": 404, + "action": { + "name": "tokens.measurements.mirror.update" + }, + "meta": null, + "warnings": null, + "error": null + } + ], + "stored": { + "tokens": [ + { + "name": "Connector", + "permissions": [ + "health:read" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Phone", + "permissions": [ + "*" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "revoked": true, + "mirrorToAppleHealth": false, + "mirrorChangedAt": "" + } + ], + "audit": [ + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": true + } + }, + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": false + } + } + ], + "readings": [ + { + "source": "EXTERNAL", + "ingestTokenId": null, + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + }, + { + "source": "EXTERNAL", + "ingestTokenId": "", + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + } + ] + } +} diff --git a/tests/integration/routes/parity/__snapshots__/tokens-mirror.10-invalid-body.json.snap b/tests/integration/routes/parity/__snapshots__/tokens-mirror.10-invalid-body.json.snap new file mode 100644 index 000000000..7fb7648f3 --- /dev/null +++ b/tests/integration/routes/parity/__snapshots__/tokens-mirror.10-invalid-body.json.snap @@ -0,0 +1,100 @@ +{ + "status": 422, + "body": { + "data": null, + "error": "Validation failed", + "details": { + "issues": [ + { + "path": "mirrorToAppleHealth", + "code": "invalid_type", + "message": "Invalid input: expected boolean, received string" + }, + { + "path": "", + "code": "unrecognized_keys", + "message": "Unrecognized key: \"name\"", + "keys": [ + "name" + ] + } + ] + }, + "meta": { + "errorCode": "http.invalid", + "requestId": "" + } + }, + "events": [ + { + "status": 422, + "action": { + "name": "tokens.measurements.mirror.update" + }, + "meta": null, + "warnings": null, + "error": null + } + ], + "stored": { + "tokens": [ + { + "name": "Connector", + "permissions": [ + "health:read" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Phone", + "permissions": [ + "*" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "revoked": true, + "mirrorToAppleHealth": false, + "mirrorChangedAt": "" + } + ], + "audit": [ + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": true + } + }, + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": false + } + } + ], + "readings": [ + { + "source": "EXTERNAL", + "ingestTokenId": null, + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + }, + { + "source": "EXTERNAL", + "ingestTokenId": "", + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + } + ] + } +} diff --git a/tests/integration/routes/parity/__snapshots__/tokens-mirror.11-bearer.json.snap b/tests/integration/routes/parity/__snapshots__/tokens-mirror.11-bearer.json.snap new file mode 100644 index 000000000..29e858126 --- /dev/null +++ b/tests/integration/routes/parity/__snapshots__/tokens-mirror.11-bearer.json.snap @@ -0,0 +1,84 @@ +{ + "status": 401, + "body": { + "data": null, + "error": "Not authenticated", + "meta": { + "errorCode": "auth.missing", + "requestId": "" + } + }, + "events": [ + { + "status": 401, + "action": null, + "meta": null, + "warnings": null, + "error": { + "type": "HttpError", + "message": "Not authenticated" + } + } + ], + "stored": { + "tokens": [ + { + "name": "Connector", + "permissions": [ + "health:read" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Phone", + "permissions": [ + "*" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "revoked": true, + "mirrorToAppleHealth": false, + "mirrorChangedAt": "" + } + ], + "audit": [ + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": true + } + }, + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": false + } + } + ], + "readings": [ + { + "source": "EXTERNAL", + "ingestTokenId": null, + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + }, + { + "source": "EXTERNAL", + "ingestTokenId": "", + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + } + ] + } +} diff --git a/tests/integration/routes/parity/__snapshots__/tokens-mirror.12-summary-bearer.json.snap b/tests/integration/routes/parity/__snapshots__/tokens-mirror.12-summary-bearer.json.snap new file mode 100644 index 000000000..29e858126 --- /dev/null +++ b/tests/integration/routes/parity/__snapshots__/tokens-mirror.12-summary-bearer.json.snap @@ -0,0 +1,84 @@ +{ + "status": 401, + "body": { + "data": null, + "error": "Not authenticated", + "meta": { + "errorCode": "auth.missing", + "requestId": "" + } + }, + "events": [ + { + "status": 401, + "action": null, + "meta": null, + "warnings": null, + "error": { + "type": "HttpError", + "message": "Not authenticated" + } + } + ], + "stored": { + "tokens": [ + { + "name": "Connector", + "permissions": [ + "health:read" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Phone", + "permissions": [ + "*" + ], + "revoked": false, + "mirrorToAppleHealth": false, + "mirrorChangedAt": null + }, + { + "name": "Scale", + "permissions": [ + "measurements:write" + ], + "revoked": true, + "mirrorToAppleHealth": false, + "mirrorChangedAt": "" + } + ], + "audit": [ + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": true + } + }, + { + "action": "tokens.measurements.mirror.update", + "details": { + "tokenId": "", + "mirrorToAppleHealth": false + } + } + ], + "readings": [ + { + "source": "EXTERNAL", + "ingestTokenId": null, + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + }, + { + "source": "EXTERNAL", + "ingestTokenId": "", + "stamp": "2026-10-10T08:00:00.000Z", + "version": 1 + } + ] + } +} diff --git a/tests/integration/routes/parity/tokens-mirror.parity.test.ts b/tests/integration/routes/parity/tokens-mirror.parity.test.ts new file mode 100644 index 000000000..141c811ec --- /dev/null +++ b/tests/integration/routes/parity/tokens-mirror.parity.test.ts @@ -0,0 +1,238 @@ +/** + * Parity for the Apple Health write-back of measurement tokens (#1272): + * `PATCH /api/tokens/{id}`, the summary `GET /api/tokens/measurements` and + * the token list that carries the setting. + * + * One account walks through the cases the routes tell apart, in order: the + * summary with readings no token reaches, the switch turned on, the same + * value again (nothing written, nothing audited), turned off on a revoked + * token, a wildcard and an MCP token refused, another account's token, an + * unknown id, bodies the schema refuses, and a Bearer caller. After each + * request the snapshot holds the response, the wide event, the token rows, + * the audit rows and the readings' stamps, which must never move. + */ +import { beforeAll, describe, expect, it, vi } from "vitest"; + +import { PATCH, DELETE as revoke } from "@/app/api/tokens/[id]/route"; +import { GET as listTokens } from "@/app/api/tokens/route"; +import { GET as summary } from "@/app/api/tokens/measurements/route"; +import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes"; + +import { callRoute, type RouteAuth } from "../../../kit/call-route"; +import { + makeMeasurement, + makeSession, + makeToken, + makeUser, + type BearerFixture, +} from "../../../kit/factories"; +import { + eventFacts, + expectParity, + stable, + wideEventRecorder, +} from "../../../kit/parity"; +import { getPrismaClient, truncateAllTables } from "../../setup"; + +vi.mock("@/lib/logging/transports", async (importOriginal) => { + const actual = + await importOriginal(); + const { wideEventRecorder: recorder } = await import("../../../kit/parity"); + return { + ...actual, + emitIfSampled: (event: (typeof recorder.events)[number]) => { + recorder.events.push(event); + }, + }; +}); + +const prisma = getPrismaClient(); +const NOW = new Date("2026-10-15T12:00:00.000Z"); + +let userId: string; +let owner: RouteAuth; +let scale: BearerFixture; +let wildcard: BearerFixture; +let connector: BearerFixture; +let theirs: BearerFixture; + +async function stored() { + const [tokens, audit, readings] = await Promise.all([ + prisma.apiToken.findMany({ + where: { userId }, + orderBy: { name: "asc" }, + select: { + name: true, + permissions: true, + revoked: true, + mirrorToAppleHealth: true, + mirrorChangedAt: true, + }, + }), + prisma.auditLog.findMany({ + where: { userId, action: { startsWith: "tokens." } }, + orderBy: { createdAt: "asc" }, + select: { action: true, details: true }, + }), + prisma.measurement.findMany({ + where: { userId }, + orderBy: { measuredAt: "asc" }, + select: { + source: true, + ingestTokenId: true, + updatedAt: true, + syncVersion: true, + }, + }), + ]); + // Renamed so the snapshot keeps the values (`updatedAt` and `syncVersion` + // are blanked as volatile): a switch must never move them. + return { + tokens, + // Parsed, so the token id inside reads as its placeholder. + audit: audit.map((a) => ({ + action: a.action, + details: a.details ? JSON.parse(a.details) : null, + })), + readings: readings.map((r) => ({ + source: r.source, + ingestTokenId: r.ingestTokenId, + stamp: r.updatedAt.toISOString(), + version: r.syncVersion, + })), + }; +} + +async function step( + name: string, + call: + | { kind: "patch"; id: string; body: unknown; auth?: RouteAuth } + | { kind: "summary" | "list"; auth?: RouteAuth }, +): Promise { + wideEventRecorder.take(); + const res = + call.kind === "patch" + ? await callRoute(PATCH, { + method: "PATCH", + route: "/api/tokens/{id}", + params: { id: call.id }, + body: call.body, + auth: call.auth ?? owner, + }) + : await callRoute(call.kind === "summary" ? summary : listTokens, { + method: "GET", + route: + call.kind === "summary" + ? "/api/tokens/measurements" + : "/api/tokens", + auth: call.auth ?? owner, + }); + const events = wideEventRecorder.take(); + expect(events.length).toBeGreaterThan(0); + await expectParity( + `tokens-mirror.${name}`, + stable( + { + status: res.status, + body: res.body, + events: events.map(eventFacts), + stored: await stored(), + }, + { since: NOW, volatileKeys: ["mirrorChangedAt"] }, + ), + ); +} + +beforeAll(async () => { + vi.useFakeTimers({ toFake: ["Date"], now: NOW }); + await truncateAllTables(prisma); + const user = await makeUser({ timezone: "UTC" }); + userId = user.id; + owner = await makeSession(user); + scale = await makeToken(user, { + permissions: [MEASUREMENTS_WRITE_SCOPE], + name: "Scale", + }); + wildcard = await makeToken(user, { permissions: ["*"], name: "Phone" }); + connector = await makeToken(user, { + permissions: ["health:read"], + name: "Connector", + }); + theirs = await makeToken(await makeUser({ timezone: "UTC" }), { + permissions: [MEASUREMENTS_WRITE_SCOPE], + name: "Theirs", + }); + const stamp = new Date("2026-10-10T08:00:00.000Z"); + await makeMeasurement(user, { + source: "EXTERNAL", + ingestTokenId: scale.tokenId, + measuredAt: new Date("2026-10-10T07:00:00.000Z"), + updatedAt: stamp, + }); + await makeMeasurement(user, { + source: "EXTERNAL", + measuredAt: new Date("2026-10-09T07:00:00.000Z"), + updatedAt: stamp, + }); +}); + +describe("the Apple Health write-back of a measurement token", () => { + it("walks the cases in order", async () => { + await step("01-summary", { kind: "summary" }); + await step("02-on", { + kind: "patch", + id: scale.tokenId, + body: { mirrorToAppleHealth: true }, + }); + await step("03-on-again", { + kind: "patch", + id: scale.tokenId, + body: { mirrorToAppleHealth: true }, + }); + await step("04-list", { kind: "list" }); + const revoked = await callRoute(revoke, { + method: "DELETE", + route: "/api/tokens/{id}", + params: { id: scale.tokenId }, + auth: owner, + }); + expect(revoked.status).toBe(200); + await step("05-off-revoked", { + kind: "patch", + id: scale.tokenId, + body: { mirrorToAppleHealth: false }, + }); + await step("06-wildcard", { + kind: "patch", + id: wildcard.tokenId, + body: { mirrorToAppleHealth: true }, + }); + await step("07-connector", { + kind: "patch", + id: connector.tokenId, + body: { mirrorToAppleHealth: true }, + }); + await step("08-another-account", { + kind: "patch", + id: theirs.tokenId, + body: { mirrorToAppleHealth: true }, + }); + await step("09-unknown", { + kind: "patch", + id: "missing-token", + body: { mirrorToAppleHealth: true }, + }); + await step("10-invalid-body", { + kind: "patch", + id: scale.tokenId, + body: { mirrorToAppleHealth: "yes", name: "Renamed" }, + }); + await step("11-bearer", { + kind: "patch", + id: scale.tokenId, + body: { mirrorToAppleHealth: true }, + auth: wildcard, + }); + await step("12-summary-bearer", { kind: "summary", auth: wildcard }); + }); +});