feat(api): DELETE /api/measurements/by-external-ids for iOS deletion-sync

HealthKit's API does not surface a stream of deleted UUIDs, so the iOS
HealthLog client performs a periodic 30-day reconciliation: it diffs
HealthKit's current UUID set against the server's externalIds and
posts the surplus here. This endpoint deletes the user's matching
rows and never touches another user's data (Prisma's deleteMany with
the userId predicate is the cross-user 404 guard).

Contract:
  - Body: { externalIds: string[] } with min 0, max 500 entries.
  - Auth: requireAuth() — session cookie or bearer.
  - Empty array: returns { deletedCount: 0 } with 200 (no-op, not a
    failure — matches the ingest path's symmetric tolerance).
  - Over-cap: 422 with errorCode "measurement.delete.too_large" so
    the iOS client can surface a specific diagnostic.

Integration coverage: happy path, cross-user 404 guard, empty array,
and batch-cap rejection. The cap (500) mirrors POST /measurements/batch
so the two surfaces share one operational ceiling.

OpenAPI: registered as DELETE on /api/measurements/by-external-ids
with the Measurements tag; req/res schemas reuse the same z.array cap
the runtime validator enforces. openapi.yaml regenerated.
This commit is contained in:
Marc-André Bombeck committed 2026-05-14 13:07:05 +02:00
1 parent 57bd4453ba
commit 959adec899
4 files changed
+411

No files matched your search

@@ -0,0 +1,107 @@
/**
* `DELETE /api/measurements/by-external-ids` — iOS deletion reconciliation.
*
* HealthKit's API does not surface a stream of deleted UUIDs, so the
* iOS client performs a periodic 30-day window reconciliation: it pulls
* the current set of HealthKit sample UUIDs in the window and posts the
* externalIds the server holds that are no longer present. This endpoint
* accepts that batch-delete list and removes every matching row owned by
* the calling user.
*
* Idempotency contract:
* - Cross-user safety: rows owned by another user are silently skipped
* (Prisma's `deleteMany` with `userId` in the where-clause guarantees
* this), so a duplicate / replayed delete is a no-op rather than a
* 401.
* - Empty arrays return `{ deletedCount: 0 }` with 200 — the iOS
* client should not consider that a failure.
* - The batch cap mirrors the ingest path (`/api/measurements/batch`)
* so the two surfaces share the same operational ceiling.
*/
import { NextRequest } from "next/server";
import { z } from "zod/v4";
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import {
apiError,
apiSuccess,
getClientIp,
safeJson,
} from "@/lib/api-response";
const MAX_BATCH_ENTRIES = 500;
const payloadSchema = z.object({
externalIds: z
.array(z.string().min(1).max(120))
.min(0)
.max(MAX_BATCH_ENTRIES),
});
export const DELETE = apiHandler(deleteByExternalIds);
async function deleteByExternalIds(request: NextRequest): Promise<Response> {
const { user } = await requireAuth();
const { data: rawBody, error: jsonError } = await safeJson<unknown>(request);
if (jsonError) return jsonError;
// Distinguish "too many entries" from "validation failed" so the iOS
// client surfaces a useful diagnostic — same shape the ingest endpoint
// uses for its symmetric cap.
if (
typeof rawBody === "object" &&
rawBody !== null &&
"externalIds" in rawBody &&
Array.isArray((rawBody as { externalIds: unknown }).externalIds) &&
(rawBody as { externalIds: unknown[] }).externalIds.length >
MAX_BATCH_ENTRIES
) {
return apiError(`Batch exceeds the ${MAX_BATCH_ENTRIES}-entry limit`, 422, {
errorCode: "measurement.delete.too_large",
});
}
const parsed = payloadSchema.safeParse(rawBody);
if (!parsed.success) {
return apiError(parsed.error.issues[0]?.message ?? "Invalid batch", 422);
}
const { externalIds } = parsed.data;
if (externalIds.length === 0) {
annotate({
action: { name: "measurement.delete.by_external_ids" },
meta: { processed: 0, deleted: 0 },
});
return apiSuccess({ deletedCount: 0 });
}
// Prisma `deleteMany` with the userId predicate is the cross-user
// 404 guard: rows belonging to other users are simply not matched.
// No need for a pre-flight findMany — the unique index on
// `(userId, type, source, externalId)` keeps the matching set small
// even when the user has overlapping HealthKit history.
const result = await prisma.measurement.deleteMany({
where: {
userId: user.id,
externalId: { in: externalIds },
},
});
await auditLog("measurement.delete.by_external_ids", {
userId: user.id,
ipAddress: getClientIp(request),
details: { processed: externalIds.length, deleted: result.count },
});
annotate({
action: { name: "measurement.delete.by_external_ids" },
meta: { processed: externalIds.length, deleted: result.count },
});
return apiSuccess({ deletedCount: result.count });
}
+44
View File
@@ -267,6 +267,22 @@ const batchResponse = z
})
.meta({ id: "AppleHealthBatchResponse" });
const deleteByExternalIdsRequest = z
.object({
externalIds: z.array(z.string().min(1).max(120)).min(0).max(500),
})
.meta({
id: "MeasurementsDeleteByExternalIdsRequest",
description:
"iOS deletion-sync. Up to 500 externalIds per call; matching rows owned by other users are silently skipped (cross-user 404 guard).",
});
const deleteByExternalIdsResponse = z
.object({
deletedCount: z.number().int().nonnegative(),
})
.meta({ id: "MeasurementsDeleteByExternalIdsResult" });
const measurementResource = z
.object({
id: z.string(),
@@ -467,6 +483,34 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
"/api/measurements/by-external-ids": {
delete: {
tags: ["Measurements"],
summary: "Delete measurements by external ID (iOS deletion-sync)",
description:
"Removes the user's measurement rows whose externalId is in the request list. Rows owned by another user are silently skipped (cross-user 404 guard). Up to 500 externalIds per call.",
requestBody: {
required: true,
content: {
"application/json": { schema: deleteByExternalIdsRequest },
},
},
responses: {
"200": {
description: "Delete batch processed.",
content: {
"application/json": {
schema: dataEnvelope(
deleteByExternalIdsResponse,
"MeasurementsDeleteByExternalIdsResponse",
),
},
},
},
...stdResponses,
},
},
},
"/api/devices": {
post: {
tags: ["Devices"],