Apple Health (Salud): a per-profile ingest endpoint, and a tab that draws it
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s

An iOS automation in Health Auto Export POSTs Apple Health to /api/vitals/ingest,
and the new Salud tab (next to Plan) draws whatever arrived: steps, heart rate,
sleep, weight, oxygen, workouts and every other metric HAE can export, grouped into
cards with a trend, a sparkline and a 7/30/90/365-day range. Nothing on that screen
is an input, and the watch's workouts stay out of the history on purpose — they
carry no sets and no weights, so folding them into progression, PRs and the recovery
model would be inventing data.

The interesting part is duplicates. A five-minute automation re-sends overlapping
windows: with Date Range "Today", appending would count a day of steps again on
every run, and with "Since Last Sync", replacing would throw away everything but the
last five minutes. So the endpoint decides per payload instead. Datapoints that sit
on midnight are HAE's own day grouping, i.e. a *total*, and a day total replaces the
day it names — re-sending the same day all afternoon converges on that day's total.
Anything else is a real sample, identified by its instant plus its numbers and
stored once, which is right for overlapping and disjoint windows alike. Every sync
answers with a receipt (received / duplicates / stored), so a misconfigured
automation is visible rather than silent, and day keys come from the date the phone
wrote — never the server's clock, or every evening's steps would land on tomorrow.

Per profile and private by construction. Each profile mints its own ingest key
(Salud → ⚙), which is write-only: it can add to that one profile's health file and
cannot read a single number back, so a key leaking out of a phone is a nuisance
rather than a disclosure. It is its own credential, so rotating it disconnects a
phone without signing anybody out anywhere. The data lives in
data/vitals-<uid>.json, outside the synced state document, so a year of heart rate
never round-trips through localStorage on every device, and it is bounded on write:
400 days per metric, a 72 h dedupe ledger, the newest 300 workouts.

Two traps that only exist in production, both fixed here and both of which would
have shipped broken. api/Dockerfile copies the modules server.js imports by name,
and vitals.js was not on that list — a container that boots straight into
ERR_MODULE_NOT_FOUND. And the web container's nginx capped every /api body at 5 MB,
which a health export with Summarize Data off exceeds; that one route now gets the
API's own 32 MB while every other path keeps 5 MB, with the shared proxy settings
hoisted to server level so the two locations cannot drift apart.

Coverage: vitals.js (13 tests — overlapping, disjoint, day-grouped, raw, heart rate,
sleep, blood pressure, pruning, timezones), the routes against a real server (4 —
isolation between profiles, a key that cannot read, ten re-sends changing nothing),
the card model (18) and the screen (4). docs/HEALTH.md has the Health Auto Export
settings and the merge table; the five endpoints are in api/openapi.yaml under the
health tag, and website/api.html is rebuilt from it.
This commit is contained in:
dsantillan committed 2026-09-23 10:11:00 -04:00
1 parent 0819d03efb
commit 691e664d3f
22 files changed
+2897 -42

No files matched your search

+272
View File
@@ -84,6 +84,10 @@ tags:
description: Web Push (VAPID) subscriptions, rest-timer and test pushes
- name: activity
description: Live-workout presence heartbeat
- name: health
description: >-
Apple Health metrics ingested from an iPhone (Health Auto Export automations) —
per profile, write-only for the phone's ingest key
- name: admin
description: Admin dashboard — requires an admin session (`ADMIN_UIDS` or `admin:true`)
@@ -591,6 +595,224 @@ paths:
rev: { type: integer }
'401': { $ref: '#/components/responses/Unauthorized' }
/api/vitals:
get:
tags: [health]
operationId: vitalsGet
summary: The caller's Apple Health metrics, as per-day aggregates
description: |
What the Salud view renders: one entry per metric, one bucket per day, and every bucket
carrying every numeric field HAE sent under the name it used (`qty`, `Min`/`Avg`/`Max`,
`systolic`/`diastolic`, `asleep`/`inBed`/`core`/`deep`/`rem`…), already summed and
averaged for that day.
The server deliberately does not decide what "steps today" means — which field a card shows
is a presentation rule (frontend `lib/vitals-view.js`), so a metric HAE adds later needs no
change here.
A session is always required: the ingest key is write-only, so a key that leaks out of a
phone can add to a profile's health file and still cannot read it back.
parameters:
- name: days
in: query
schema: { type: integer, minimum: 1, maximum: 400, default: 90 }
description: Calendar days to return, including today.
responses:
'200':
description: The stored metrics for the window, oldest day first.
content:
application/json:
schema:
type: object
properties:
ok: { type: boolean }
days: { type: integer }
key:
type: string
nullable: true
description: The caller's ingest key, or null before one has been created.
updatedAt: { type: integer, description: Epoch ms of the last ingest. }
last:
type: object
nullable: true
description: What the most recent ingest contained.
properties:
ts: { type: integer }
metrics: { type: integer }
points: { type: integer }
duplicates: { type: integer }
workouts: { type: integer }
metrics:
type: object
additionalProperties: { $ref: '#/components/schemas/VitalsMetric' }
workouts:
type: array
description: Read-only; never folded into the workout history.
items: { type: object }
example:
ok: true
days: 30
key: "kghealth_5Z0d…"
updatedAt: 1756900000000
metrics:
step_count:
units: count
sources: [Apple Watch]
days: [{ day: "2026-09-03", n: 1, lastTs: 1756900000000, f: { qty: { n: 1, sum: 12481, min: 12481, max: 12481, last: 12481, avg: 12481 } } }]
heart_rate:
units: bpm
sources: [Apple Watch]
days: [{ day: "2026-09-03", n: 288, lastTs: 1756900000000, f: { Avg: { n: 288, sum: 20000, min: 55, max: 96, last: 72, avg: 69.4 } } }]
workouts: []
'401': { $ref: '#/components/responses/Unauthorized' }
delete:
tags: [health]
operationId: vitalsClear
summary: Delete the caller's health data
description: >-
Removes the profile's health file and nothing else: the workout history, the account and the
ingest key are untouched, so a phone needs no re-configuring to sync again.
responses:
'200':
description: Deleted (also when there was nothing stored).
content:
application/json:
schema:
type: object
properties: { ok: { type: boolean } }
'401': { $ref: '#/components/responses/Unauthorized' }
/api/vitals/ingest:
post:
tags: [health]
operationId: vitalsIngest
summary: Receive a Health Auto Export JSON export
description: |
The endpoint an iOS automation posts to. In Health Auto Export: Automation Type **REST
API**, URL = this endpoint, header `Authorization: Bearer <ingest key>` (from
`POST /api/vitals/key`), Export Format **JSON**, Export Version **2**, Summarize Data
**On**, Time Grouping **Days**.
The merge is idempotent, which is what makes a five-minute cadence safe:
* A payload whose datapoints all sit on midnight is HAE's own day grouping, and a day total
*replaces* the day it names — so the same day re-sent all afternoon converges on the
day's total instead of adding up.
* Anything else is a real sample (or an hour/minute grouping): a sample is identified by its
instant plus its numbers and is counted once, so overlapping and disjoint windows both
come out right. Repeats come back as `duplicates`.
CSRF-exempt: the request carries its own credential in a header and has no session to
borrow.
security:
- ingestKeyAuth: []
- bearerAuth: []
requestBody:
required: true
description: >-
The HAE export verbatim (`{"data":{"metrics":[…],"workouts":[…]}}`). Both arrays are
optional; a metric with `"data": null` is a selected metric with no samples and is skipped.
content:
application/json:
schema: { type: object }
example:
data:
metrics:
- name: step_count
units: count
data: [{ qty: 12481, date: "2026-09-03 00:00:00 +0200" }]
responses:
'200':
description: >-
Accepted — including an export with nothing in it, because a scheduled automation that
fires when there is nothing to report is not a failure.
content:
application/json:
schema:
type: object
properties:
ok: { type: boolean }
ts: { type: integer }
received:
type: object
properties:
metrics: { type: integer }
points: { type: integer }
duplicates: { type: integer, description: Samples already stored; nothing was added for them. }
workouts: { type: integer }
stored:
type: object
description: What the profile holds now.
properties:
metrics: { type: integer }
days: { type: integer }
workouts: { type: integer }
example:
ok: true
ts: 1756900000000
received: { metrics: 2, points: 3, duplicates: 1, workouts: 1 }
stored: { metrics: 12, days: 40, workouts: 7 }
'400':
description: Not a Health Auto Export JSON export (or not JSON at all).
content:
application/json:
schema: { $ref: '#/components/schemas/Error' }
example: { error: "not a Health Auto Export JSON export" }
'401':
description: No ingest key, an unknown or rotated key, or a disabled account.
content:
application/json:
schema: { $ref: '#/components/schemas/Error' }
example: { error: "invalid ingest key" }
'413':
description: Body over 32 MB. Group by days in HAE, or select fewer metrics.
content:
application/json:
schema: { $ref: '#/components/schemas/Error' }
example: { error: "body too large" }
/api/vitals/key:
post:
tags: [health]
operationId: vitalsKeyCreate
summary: Get the profile's ingest key, creating it on first use
description: >-
Idempotent: a second call returns the key that exists rather than invalidating the
configuration already pasted into the phone.
responses:
'200':
description: The ingest key.
content:
application/json:
schema:
type: object
properties:
ok: { type: boolean }
key: { type: string }
example: { ok: true, key: "kghealth_5Z0d…" }
'401': { $ref: '#/components/responses/Unauthorized' }
/api/vitals/key/rotate:
post:
tags: [health]
operationId: vitalsKeyRotate
summary: Replace the profile's ingest key
description: >-
The old key stops working everywhere at once. Stored health data is untouched; the phone
stops syncing until the new key is pasted in. Separate from the session token on purpose —
losing a phone should not sign you out of the app.
responses:
'200':
description: A new key.
content:
application/json:
schema:
type: object
properties:
ok: { type: boolean }
key: { type: string }
'401': { $ref: '#/components/responses/Unauthorized' }
/api/push/public-key:
get:
tags: [push]
@@ -1134,6 +1356,16 @@ components:
The same signed session token, carried as `Authorization: Bearer <token>` by
the paired mobile app (obtained from `POST /api/pair/redeem`). Bearer requests
skip the CSRF origin check — a browser never attaches this header on its own.
ingestKeyAuth:
type: http
scheme: bearer
description: >-
A per-profile Apple Health ingest key (`kghealth_…`, from `POST /api/vitals/key`),
carried by the iPhone's Health Auto Export automation as
`Authorization: Bearer <key>` or `X-Ingest-Key: <key>`. It can write the profile's
health file and nothing else: no reads, no workouts, no admin, and it can be
rotated on its own without touching anybody's session. Compared as digests in
constant time, and refused for a disabled account.
responses:
Unauthorized:
@@ -1494,6 +1726,46 @@ components:
description: Resolved display name (only in GET /api/admin/invites).
additionalProperties: true
VitalsField:
type: object
description: >-
One numeric field of one metric for one day, aggregated over the samples that carried it.
A counter's day is its `sum`; a rate's is its `avg`; a gauge's is its `last`. Both are
stored so the rule that picks one is a display decision rather than a storage one.
properties:
n: { type: integer, description: Samples that contributed. }
sum: { type: number }
min: { type: number }
max: { type: number }
last: { type: number }
avg: { type: number }
VitalsDay:
type: object
description: >-
One day for one metric, keyed by the date the *phone* wrote (HAE stamps every sample with
its own local offset, so the server never re-derives the day from its own clock).
properties:
day: { type: string, example: "2026-09-03" }
n: { type: integer, description: Samples stored for this day. }
lastTs: { type: integer, description: Epoch ms of the day's newest sample. }
f:
type: object
description: Field name as HAE wrote it — `qty`, `Avg`, `asleep`, `systolic`…
additionalProperties: { $ref: '#/components/schemas/VitalsField' }
VitalsMetric:
type: object
properties:
units: { type: string, example: bpm }
sources:
type: array
description: The apps/devices that reported this metric, newest first.
items: { type: string }
days:
type: array
items: { $ref: '#/components/schemas/VitalsDay' }
AuditEvent:
type: object
description: One line of the audit log.