feat(apple-health): ingest the activity rings, mindfulness, State of Mind and AFib burden

Six Apple Health signals leave the deferred list and ride
POST /api/measurements/batch and the export.zip import end to end:
EXERCISE_MINUTES, STAND_MINUTES and STAND_HOURS (the exercise and stand
rings), MINDFUL_MINUTES, STATE_OF_MIND_VALENCE (iOS 18 State of Mind,
-1..1) and AFIB_BURDEN (AFib History, percent of the week). The ring
types and mindful minutes are cumulative, so the daily rollup is their
sum; AFib burden is scaled strictly from Apple's fraction and a value
above 1 is refused rather than guessed at. The archive import takes
mindful minutes from the session's dates and skips idle stand hours.
Every registry carries them: units, ranges, labels in all locales,
categories, chart tokens, report catalogue (mindful minutes and the
valence fenced as sensitive), signal registry with FHIR codings, and
MCP exposure for the three ring types only.

Workout GPS tracks are now an opt-in, off by default
(PATCH /api/auth/me/workout-routes, a switch on Data & Privacy). While
it is off, the workout batch route and the export import keep every
workout and drop its track with the same per-entry status. With it on,
the import reads the referenced GPX files from the archive one bounded
member at a time, thins each to the point cap and stores it sealed.
The climb a track carries is written to Workout.elevationM at write
time, so the workout insight no longer opens the track, and the AI
egress guard now freezes the set of files that read route geometry.
This commit is contained in:
Marc-André Bombeck committed 2026-10-21 20:14:20 +02:00
1 parent d44af06467
commit b045703493
58 files changed
+2233 -163

No files matched your search

@@ -0,0 +1,121 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
/**
* The workout-route opt-in: off by default, a hard-set PATCH, audit-logged,
* and a malformed body refused before anything is written.
*/
vi.mock("@/lib/db", () => ({
prisma: { user: { findUnique: vi.fn(), update: vi.fn() } },
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn().mockResolvedValue({
allowed: true,
remaining: 59,
resetAt: Date.now() + 60_000,
}),
rateLimitHeaders: () => ({}),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET, PATCH } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { auditLog } from "@/lib/auth/audit";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function mkPatch(body: unknown): Request {
return new Request("http://localhost/api/auth/me/workout-routes", {
method: "PATCH",
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
});
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
});
describe("/api/auth/me/workout-routes", () => {
it("reads off when the row carries no value", async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue(null);
const res = await GET(
new Request("http://localhost/api/auth/me/workout-routes") as never,
{ params: Promise.resolve({}) } as never,
);
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({
data: { storeWorkoutRoutes: false },
});
});
it("sets the flag field by field and audits the change", async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue({
storeWorkoutRoutes: false,
} as never);
const res = await PATCH(
mkPatch({ storeWorkoutRoutes: true }) as never,
{
params: Promise.resolve({}),
} as never,
);
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({
data: { storeWorkoutRoutes: true },
});
expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: "user-1" },
data: { storeWorkoutRoutes: true },
});
expect(auditLog).toHaveBeenCalledWith(
"user.storeWorkoutRoutes.update",
expect.objectContaining({
details: { previous: false, next: true },
}),
);
});
it("refuses a malformed body with 422 and writes nothing", async () => {
const res = await PATCH(
mkPatch({ storeWorkoutRoutes: "yes" }) as never,
{
params: Promise.resolve({}),
} as never,
);
expect(res.status).toBe(422);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("refuses an unauthenticated caller", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const res = await PATCH(
mkPatch({ storeWorkoutRoutes: true }) as never,
{
params: Promise.resolve({}),
} as never,
);
expect(res.status).toBe(401);
expect(prisma.user.update).not.toHaveBeenCalled();
});
});
+109
View File
@@ -0,0 +1,109 @@
/**
* Per-account opt-in for keeping workout GPS tracks.
*
* GET /api/auth/me/workout-routes — current flag.
* PATCH /api/auth/me/workout-routes — body `{ storeWorkoutRoutes: boolean }`.
*
* Off by default. While it is off, `POST /api/workouts/batch` and the
* Apple Health export import keep every workout but drop its track, so a
* route (where a person lives, works and trains) is stored only after the
* person asked for it. Turning it off later stops new tracks; tracks already
* stored stay until the workout or the account is deleted.
*
* Same per-user-scalar pattern as `labs-local-ocr`: 60/min rate limit, a
* bounded body, Zod safeParse → 422, field-by-field write, audit row, and
* the resolved next state in the response.
*/
import { apiHandler, requireAuth } from "@/lib/api-handler";
import {
apiError,
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import { workoutRoutesPatchSchema } from "@/lib/validations/user-prefs";
export const dynamic = "force-dynamic";
const PATCH_RATE_LIMIT = 60;
const PATCH_WINDOW_MS = 60_000;
type WorkoutRoutesResponse = {
storeWorkoutRoutes: boolean;
};
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
annotate({ action: { name: "auth.me.workoutRoutes.get" } });
const row = await prisma.user.findUnique({
where: { id: user.id },
select: { storeWorkoutRoutes: true },
});
const payload: WorkoutRoutesResponse = {
storeWorkoutRoutes: row?.storeWorkoutRoutes ?? false,
};
return apiSuccess(payload);
});
export const PATCH = apiHandler(async (req: Request) => {
const { user } = await requireAuth();
const rl = await checkRateLimit(
`workout-routes:patch:${user.id}`,
PATCH_RATE_LIMIT,
PATCH_WINDOW_MS,
);
if (!rl.allowed) {
const response = apiError("Too many requests", 429);
for (const [k, v] of Object.entries(rateLimitHeaders(rl))) {
response.headers.set(k, v);
}
return response;
}
const { data: body, error: jsonError } = await safeJson(req, {
maxBytes: 1024,
});
if (jsonError) return jsonError;
const parsed = workoutRoutesPatchSchema.safeParse(body);
if (!parsed.success) {
annotate({ action: { name: "auth.me.workoutRoutes.patch.invalid_shape" } });
return returnAllZodIssues(parsed.error, 422);
}
const next = parsed.data.storeWorkoutRoutes;
const previous = await prisma.user.findUnique({
where: { id: user.id },
select: { storeWorkoutRoutes: true },
});
await prisma.user.update({
where: { id: user.id },
data: { storeWorkoutRoutes: next },
});
await auditLog("user.storeWorkoutRoutes.update", {
userId: user.id,
ipAddress: getClientIp(req),
details: {
previous: previous?.storeWorkoutRoutes ?? false,
next,
},
});
annotate({
action: { name: "auth.me.workoutRoutes.patch" },
meta: { storeWorkoutRoutes: next },
});
const payload: WorkoutRoutesResponse = { storeWorkoutRoutes: next };
return apiSuccess(payload);
});
@@ -203,8 +203,11 @@ beforeEach(() => {
// v1.4.43 — default to no per-user source-priority override so
// the write-time picker walks the canonical default ladder. Tests
// that exercise a custom ladder override this in-line.
// The route opt-in is on here so the route cases below exercise the
// write; the off case sets it explicitly.
vi.mocked(prisma.user.findUnique).mockResolvedValue({
sourcePriorityJson: null,
storeWorkoutRoutes: true,
} as never);
});
@@ -507,6 +510,55 @@ describe("POST /api/workouts/batch — per-entry status envelope", () => {
});
});
describe("POST /api/workouts/batch — workout-route opt-in", () => {
const withRoute = () =>
validWorkout("uuid-with-route", {
route: {
geometry: {
type: "LineString",
coordinates: [
[11.077, 49.452],
[11.078, 49.453],
],
},
},
});
it("keeps the workout and drops the track while the opt-in is off", async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue({
sourcePriorityJson: null,
storeWorkoutRoutes: false,
} as never);
vi.mocked(prisma.workout.createMany).mockResolvedValue({ count: 1 });
mockInsertReturning([
{ id: "wkt-off", source: "APPLE_HEALTH", externalId: "uuid-with-route" },
]);
const res = await POST(makeRequest({ workouts: [withRoute()] }));
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { entries: Array<{ status: string }> };
};
// Same per-entry status as a stored track: the client needs no branch.
expect(body.data.entries[0]?.status).toBe("inserted");
expect(prisma.workoutRoute.createMany).not.toHaveBeenCalled();
});
it("drops the track when the account row carries no opt-in at all", async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue({
sourcePriorityJson: null,
} as never);
vi.mocked(prisma.workout.createMany).mockResolvedValue({ count: 1 });
mockInsertReturning([
{ id: "wkt-none", source: "APPLE_HEALTH", externalId: "uuid-with-route" },
]);
const res = await POST(makeRequest({ workouts: [withRoute()] }));
expect(res.status).toBe(200);
expect(prisma.workoutRoute.createMany).not.toHaveBeenCalled();
});
});
describe("POST /api/workouts/batch — nested route attachment", () => {
it("creates a WorkoutRoute row for a workout that ships a route", async () => {
vi.mocked(prisma.workout.createMany).mockResolvedValue({ count: 1 });
@@ -700,7 +752,7 @@ describe("POST /api/workouts/batch — user source-priority (v1.4.43 W9)", () =>
expect(sourcePriorityReads).toHaveLength(1);
expect(prisma.user.findUnique).toHaveBeenCalledWith({
where: { id: "user-1" },
select: { sourcePriorityJson: true },
select: { sourcePriorityJson: true, storeWorkoutRoutes: true },
});
});
+21 -8
View File
@@ -66,6 +66,7 @@ import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, isScopedCredential, requireAuth } from "@/lib/api-handler";
import { routeClimbM } from "@/lib/workouts/route-climb";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import {
@@ -259,10 +260,15 @@ async function postBatch(request: NextRequest): Promise<Response> {
// time before the read-time picker ever ran. One indexed
// findUnique per batch — well under the cost of letting the
// duplicate persist and carrying it forward on every read.
// The same read carries the route opt-in: a GPS track is kept only when
// the person turned `storeWorkoutRoutes` on. While it is off the workout
// is stored and the track dropped, with the same per-entry status, so a
// client cannot tell the two apart and needs no new branch.
const userPriority = await prisma.user.findUnique({
where: { id: user.id },
select: { sourcePriorityJson: true },
select: { sourcePriorityJson: true, storeWorkoutRoutes: true },
});
const keepRoutes = userPriority?.storeWorkoutRoutes === true;
// Content-Length pre-flight. The body cap exists to bound the
// request-pipeline cost BEFORE Node has to read the full payload —
@@ -440,12 +446,13 @@ async function postBatch(request: NextRequest): Promise<Response> {
0,
Math.round((w.endedAt.getTime() - w.startedAt.getTime()) / 1000),
);
const route = w.route
? {
geometry: w.route.geometry as unknown,
sampleTimestamps: (w.route.sampleTimestamps ?? null) as unknown,
}
: null;
const route =
w.route && keepRoutes
? {
geometry: w.route.geometry as unknown,
sampleTimestamps: (w.route.sampleTimestamps ?? null) as unknown,
}
: null;
const samples = w.samples
? {
samples: w.samples as unknown,
@@ -464,7 +471,9 @@ async function postBatch(request: NextRequest): Promise<Response> {
maxHeartRate: w.maxHeartRate ?? null,
minHeartRate: w.minHeartRate ?? null,
stepCount: w.stepCount ?? null,
elevationM: w.elevationM ?? null,
// A kept track fills the climb when the source sent none, so the figure
// lives on the workout row and no reader has to open the track for it.
elevationM: w.elevationM ?? (route ? routeClimbM(route.geometry) : null),
pauseDurationSec: w.pauseDurationSec ?? null,
// `EXTERNAL` under a scoped credential, and nothing else: the guard
// above refused any body that named a source, so nothing asserted is
@@ -908,6 +917,10 @@ async function postBatch(request: NextRequest): Promise<Response> {
enriched: enrichedCount,
updated: updatedCount,
skipped: skipped.length,
// Tracks the body carried but the opt-in told us not to keep.
routes_dropped: keepRoutes
? 0
: workouts.filter((w) => w.route != null).length,
},
});