Since v1.30.17 there has been no self-service path to a token that can write a measurement. That release made the Bearer scope default fail-closed, which closed a real privilege-escalation hole, and removed the generic mint at POST /api/tokens along with it. The generic mint had been the only way to get a token that could reach /api/measurements, so a local sensor pushed through Home Assistant or Node-RED lost its door while the OAuth integrations kept theirs. Add a narrow scope accepted by exactly two routes, both writes, both on the holder's own record. The scope constant is a leaf module beside the surface that consumes it, matching FHIR_READ_SCOPE and the MCP scopes. requireRecordAuth grows an options object rather than a sibling function, because the sharing surface guard keys every leg on that one identifier and a second name would mean two copies of the delegable declaration. AuthContext carries the admitting scope as a single nullable string rather than the token's permission array, so nothing downstream can re-derive an authorisation decision from it. A scoped credential is refused a record selector before any grant is read. Placing the refusal above the sharing check rather than beside it means no future widening of what a grant permits can reach one of these tokens. Rows are attributed MANUAL. An entry that explicitly names APPLE_HEALTH is refused 422 rather than relabelled: that source is half the (userId, type, source, externalId) dedup key the iOS client writes into, it participates in the cross-source merge, and it gates the HealthKit sync fields. For the same reason a scoped write no longer advances User.lastSyncedAt, which the phone reads to size its undelivered window. Also closes a narrower gap found while building this. The idempotency wrapper resolved a replayed delegated response against a live grant without considering which credential was presenting it, so a cached response about a shared record could be returned to a token the handler itself would refuse. No write was reachable that way; the response body was. Guards: T3 gains the mint site, T4's vocabulary gains the scope and learns to read the requireRecordAuth form (without which this change would open a way to widen a route that the closed vocabulary could not see), and a new T5 freezes the set of delegable routes naming a scope. The sharing surface guard's AST matcher reads only the first two arguments, so it needed prose but no code.
4.8 KiB
HealthLog API Spec
openapi.yaml is the OpenAPI 3.1 description for the HealthLog
Next.js API and the source of truth for the native iOS client's DTO
codegen. The file is generated: pnpm openapi:generate emits it
from the Zod registry under src/lib/openapi/ (registry.ts plus the
route modules in src/lib/openapi/routes/). Do not edit the YAML by
hand; the next generation overwrites it, and CI (openapi:check)
fails the build when the committed YAML drifts from the registry.
The MCP server is documented separately — it is a distinct contract over JSON-RPC, not part of the REST OpenAPI spec:
mcp-capabilities.md— the tool, resource, and prompt catalogue, the grounding contract, and the write model.mcp-skills.md— building a connector or skill on top of it.../self-hosting/mcp.md— enabling and connecting the surface (operator guide).
Preview locally
Open an interactive Redoc preview in your browser:
npx @redocly/cli preview docs/api/openapi.yaml
Generate static HTML for sharing:
npx @redocly/cli build-docs docs/api/openapi.yaml --output docs/api/index.html
Validate
npx @redocly/cli lint docs/api/openapi.yaml
The spec is expected to be lint-clean (errors = 0). Warnings such as
no-server-example.com for the localhost dev server are tolerated;
re-run the lint to see what it produces against the current file
before treating a warning as a regression.
Layout
info— title, description, andversionmirrored automatically frompackage.jsonat generation time. Never bump it by hand.servers—https://healthlog.example.comas the self-hosted placeholder plushttp://localhost:3000for local development.tags— domain groupings; the current set lives at the top of the generated file (Auth,Measurements,Medications,Mood,Analytics,Insights,Consent,Dashboard,Notifications,Devices,Export,Sync,Cycle,MeasurementReminders,Labs,Illness,Documents,Records,Admin,Meta,Retired).securitySchemes:-
bearerAuth—hlk_*API tokens. A scope grants what it names and nothing adjacent, so where a token comes from decides what it reaches:- a completed password / passkey / refresh exchange mints the
cookie-equivalent
["*"]token the native client carries; - a medication's own API-endpoint toggle mints
medication:ingestplusmedication:<id>:ingest, the pair/api/ingest/medicationgates on; POST /api/mcp/tokensmintshealth:read(optionally plushealth:write), audience-bound to/mcpand refused on REST writes;POST /api/tokens/measurementsmintsmeasurements:write, accepted byPOST /api/measurementsandPOST /api/measurements/batchonly, on the holder's own record only.
POST /api/tokensis not among them — that generic mint was removed in v1.30.17. The path still lists (GET) and revokes (DELETE /api/tokens/{id}) every token above, whichever surface issued it. - a completed password / passkey / refresh exchange mints the
cookie-equivalent
-
sessionCookie— HttpOnlyhealthlog_sessioncookie set by the password and passkey login flows. Used by the web app and any iOS client running inside a web view.
-
components.schemas— DTOs for the documented routes plus the underlying Prisma models (e.g.Measurement,Medication,MedicationIntakeEvent,MoodEntry,User,DashboardLayout,ApiEnvelope,ApiError).paths— the client-facing REST surface. Not everysrc/app/api/**/route.tsis in the contract: most/api/admin/*routes, the OAuth connect/callback legs, and the webhook surfaces are not documented here. TheRetiredtag lists removed paths that answer410 Gone.
Conventions
- Successful responses use the envelope
{ data, error: null }. - Error responses use the envelope
{ data: null, error: '<message>' }. - Pagination uses
limit+offsetquery parameters and ameta: { total, limit, offset }block on the response. - All timestamps are ISO 8601 / RFC 3339 (
format: date-time) in UTC. - IDs are CUIDs (opaque strings).
Updating the spec
When adding or changing routes:
- Update the relevant route handler under
src/app/api/**/route.ts. - Change the Zod schemas and their
.meta()registrations undersrc/lib/openapi/(registry entry plus the matching module insrc/lib/openapi/routes/). KeepoperationIdcamelCase and stable; the iOS codegen keys off it. - Run
pnpm openapi:generateand commit the regeneratedopenapi.yamlalongside the schema change. CI'sopenapi:checkfails on drift. - Never edit the YAML directly and never bump
info.versionby hand; the version followspackage.jsonat generation time.