mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 23:12:04 +00:00
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.
This commit is contained in:
1 parent
aab2e0ae7d
commit
bfa6873d96
23 files changed
+1828
-7
No files matched your search
@@ -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;
|
||||
@@ -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<typeof POST>[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,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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.
|
||||
|
||||
@@ -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" },
|
||||
});
|
||||
|
||||
@@ -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 },
|
||||
});
|
||||
|
||||
@@ -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<TokenMirrorOutcome> {
|
||||
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 };
|
||||
}
|
||||
@@ -450,6 +450,7 @@ export const ERROR_CODE_CATALOGUE: Readonly<Record<string, readonly string[]>> =
|
||||
tokens: [
|
||||
"tokens.documents.ceiling_reached",
|
||||
"tokens.measurements.ceiling_reached",
|
||||
"tokens.mirror.not_measurement_token",
|
||||
"tokens.workouts.ceiling_reached",
|
||||
],
|
||||
vaccination: [
|
||||
|
||||
@@ -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<
|
||||
|
||||
@@ -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<string, string>,
|
||||
) {
|
||||
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<string, string | number> = {}) {
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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) {
|
||||
|
||||
@@ -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": "<id:1>",
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"status": 200,
|
||||
"body": {
|
||||
"data": {
|
||||
"id": "<id:1>",
|
||||
"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": "<mirrorChangedAt>"
|
||||
}
|
||||
],
|
||||
"audit": [
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"readings": [
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": null,
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": "<id:1>",
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"status": 200,
|
||||
"body": {
|
||||
"data": {
|
||||
"id": "<id:1>",
|
||||
"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": "<mirrorChangedAt>"
|
||||
}
|
||||
],
|
||||
"audit": [
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"readings": [
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": null,
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": "<id:1>",
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
{
|
||||
"status": 200,
|
||||
"body": {
|
||||
"data": [
|
||||
{
|
||||
"id": "<id:1>",
|
||||
"name": "Scale",
|
||||
"permissions": [
|
||||
"measurements:write"
|
||||
],
|
||||
"lastUsedAt": null,
|
||||
"expiresAt": "2027-01-13T12:00:00.000Z",
|
||||
"createdAt": "<createdAt>",
|
||||
"revoked": false,
|
||||
"mirrorToAppleHealth": true
|
||||
},
|
||||
{
|
||||
"id": "<id:2>",
|
||||
"name": "Phone",
|
||||
"permissions": [
|
||||
"*"
|
||||
],
|
||||
"lastUsedAt": null,
|
||||
"expiresAt": "2027-01-13T12:00:00.000Z",
|
||||
"createdAt": "<createdAt>",
|
||||
"revoked": false,
|
||||
"mirrorToAppleHealth": false
|
||||
},
|
||||
{
|
||||
"id": "<id:3>",
|
||||
"name": "Connector",
|
||||
"permissions": [
|
||||
"health:read"
|
||||
],
|
||||
"lastUsedAt": null,
|
||||
"expiresAt": "2027-01-13T12:00:00.000Z",
|
||||
"createdAt": "<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": "<mirrorChangedAt>"
|
||||
}
|
||||
],
|
||||
"audit": [
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"readings": [
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": null,
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": "<id:1>",
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"status": 200,
|
||||
"body": {
|
||||
"data": {
|
||||
"id": "<id:1>",
|
||||
"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": "<mirrorChangedAt>"
|
||||
}
|
||||
],
|
||||
"audit": [
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"readings": [
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": null,
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": "<id:1>",
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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": "<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": "<mirrorChangedAt>"
|
||||
}
|
||||
],
|
||||
"audit": [
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"readings": [
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": null,
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": "<id:1>",
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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": "<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": "<mirrorChangedAt>"
|
||||
}
|
||||
],
|
||||
"audit": [
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"readings": [
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": null,
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": "<id:1>",
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"status": 404,
|
||||
"body": {
|
||||
"data": null,
|
||||
"error": "Token not found",
|
||||
"meta": {
|
||||
"errorCode": "http.not_found",
|
||||
"requestId": "<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": "<mirrorChangedAt>"
|
||||
}
|
||||
],
|
||||
"audit": [
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"readings": [
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": null,
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": "<id:1>",
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"status": 404,
|
||||
"body": {
|
||||
"data": null,
|
||||
"error": "Token not found",
|
||||
"meta": {
|
||||
"errorCode": "http.not_found",
|
||||
"requestId": "<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": "<mirrorChangedAt>"
|
||||
}
|
||||
],
|
||||
"audit": [
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"readings": [
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": null,
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": "<id:1>",
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
+100
@@ -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": "<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": "<mirrorChangedAt>"
|
||||
}
|
||||
],
|
||||
"audit": [
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"readings": [
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": null,
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": "<id:1>",
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
{
|
||||
"status": 401,
|
||||
"body": {
|
||||
"data": null,
|
||||
"error": "Not authenticated",
|
||||
"meta": {
|
||||
"errorCode": "auth.missing",
|
||||
"requestId": "<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": "<mirrorChangedAt>"
|
||||
}
|
||||
],
|
||||
"audit": [
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"readings": [
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": null,
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": "<id:1>",
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
{
|
||||
"status": 401,
|
||||
"body": {
|
||||
"data": null,
|
||||
"error": "Not authenticated",
|
||||
"meta": {
|
||||
"errorCode": "auth.missing",
|
||||
"requestId": "<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": "<mirrorChangedAt>"
|
||||
}
|
||||
],
|
||||
"audit": [
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"action": "tokens.measurements.mirror.update",
|
||||
"details": {
|
||||
"tokenId": "<id:1>",
|
||||
"mirrorToAppleHealth": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"readings": [
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": null,
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"source": "EXTERNAL",
|
||||
"ingestTokenId": "<id:1>",
|
||||
"stamp": "2026-10-10T08:00:00.000Z",
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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<typeof import("@/lib/logging/transports")>();
|
||||
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<void> {
|
||||
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 });
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user