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

+185
View File
@@ -0,0 +1,185 @@
# Apple Health (Salud)
KuentaGYM does not read Apple Health. Your iPhone posts it.
An iOS automation in [Health Auto Export](https://www.healthexportapp.com/) (HAE) reads Apple
Health and POSTs its JSON export to your KuentaGYM profile. The **Salud** tab draws whatever
arrived, as read-only cards; `api/vitals.js` does the arithmetic; `frontend/src/lib/vitals-view.js`
decides which number each card shows.
Nothing here is an input. There is no way to type a step count into this screen, and the workouts
the watch records are shown as a list rather than merged into your workout history — they carry no
sets and no weights, so folding them in would put entries into your progression, your PRs and the
recovery model that nothing in them can support.
---
## 1. Connect it
Signed in as the profile that should own the data (a guest has no profile to post to — Salud says
so), open **Salud → ⚙**, and:
1. **Create an ingest key.** It is created on first use and shown once — copy it.
2. Note the endpoint: `https://your-instance/api/vitals/ingest`.
3. In Health Auto Export on the iPhone: **Automations → New Automation → REST API**.
- **URL**: the endpoint above.
- **Add Headers** → `Authorization` = `Bearer <your ingest key>`
(`X-Ingest-Key: <key>` works too, if you would rather keep the header plain.)
- **Export Format**: `JSON`
- **Export Version**: `2`
- **Data Type**: `Health Metrics` (add `Workouts` as a second automation, or include both)
- **Summarize Data**: `On`
- **Time Grouping**: `Days`
- **Date Range**: `Previous 7 Days` (or `Default`)
- **Sync Cadence**: whatever you like — 5 minutes, hourly, once a day.
4. **Manual Sync → Export** once, to prove it works. It runs in the foreground, so it works even
while iOS is being cautious about background time.
One automation per profile: the key *is* the profile. Two people, two phones, two keys, two files —
neither can see the other's, and the URL is the only thing they share.
### Why those settings
| Setting | Value | Why |
| --- | --- | --- |
| Summarize Data | On | Sends day aggregates instead of every sample. Smaller payloads, and the numbers on the cards are the ones Apple already summarised. |
| Time Grouping | Days | Makes each sync carry the **whole day's total**, which the receiver can then replace rather than add up (see §2). Raw samples work too, at more bytes and the same result. |
| Date Range | Previous 7 Days / Default | Always re-sends the last few days, so a sync missed while the phone was locked or in Low Power Mode is filled in by the next one. |
| Export Version | 2 | The current payload shape (`{"data":{"metrics":[…]}}`). Version 1 is also accepted. |
Apple's own limits apply and cannot be worked around: HAE cannot read Health data while the phone
is locked, and iOS decides when background runs happen. Opening the app (or tapping the Automations
widget) is what makes a sync happen on demand. That is a limitation of iOS, not of this endpoint.
---
## 2. Why a 5-minute automation does not double-count
This is the part worth understanding, because it is the part that goes wrong.
A five-minute automation re-sends overlapping windows: with **Date Range = Today** each run carries
the entire day so far, and appending would count it again every five minutes. With **Date Range =
Since Last Sync** the windows are disjoint, and *replacing* would throw away everything but the last
five minutes. The same endpoint has to survive both without knowing which one the phone is
configured for, so the rule is chosen per payload, from the payload's own shape:
| The payload looks like | What the receiver does | Safe with |
| --- | --- | --- |
| Every datapoint sits exactly on midnight (`00:00:00`) — HAE's **Days** grouping, i.e. a **total** per day | The day it names is **replaced** by it, in full. A day total only ever supersedes another day total, so re-sending the same day all afternoon converges on the day's total instead of accumulating. | Overlapping windows, disjoint windows, manual re-exports, first sync of a year of history. |
| Anything else (real sample timestamps, or Hour/Minute grouping) | Each sample is identified by its **instant plus its numbers** and stored once. A repeat is skipped and reported back as `duplicates`; a genuinely new sample is added. | Overlapping windows (repeats detected) and disjoint ones (new samples add). |
Day keys come from the date **the phone wrote**, never from the server's clock. HAE stamps each
sample with its own local offset, so grouping by a server-local date would slide every evening's
steps into the next day for anyone not on UTC.
The one configuration neither rule rescues is **Minute** grouping with an overlapping window: the
minute still in progress is re-sent with a larger value each time, so it is a new sample by the
union rule and gets added twice. The error is bounded by one partial minute of the cheapest metric —
a handful of steps, a few hundredths of a kcal — and grouping by `Days` removes it entirely. Being
explicit about that is better than a cleverer rule that silently miscounts a whole day.
What every sync answers with is the receipt: how many points arrived, how many were recognised as
already stored, and what the profile holds now.
```json
{ "ok": true, "ts": 1756900000000,
"received": { "metrics": 12, "points": 40, "duplicates": 288, "workouts": 1 },
"stored": { "metrics": 24, "days": 190, "workouts": 37 } }
```
---
## 3. What is stored, and where
One file per profile: `data/vitals-<uid>.json`, mode 0600, written atomically. It is deliberately
**not** part of `state-<uid>.json`:
- the phone writes it while the browser writes the state document, and one file would have the two
fighting over the same revision counter;
- the state document is pushed back to the server by every client, so a year of heart rate would
round-trip through `localStorage` on every device;
- a reader that only wants the health data needs no merge logic to find it.
Inside, numbers are kept **per day and per field, generically**:
```json
{ "v": 1, "updatedAt": 1756900000000,
"last": { "ts": 1756900000000, "metrics": 12, "points": 40, "duplicates": 288, "workouts": 1 },
"metrics": {
"heart_rate": { "units": "bpm", "sources": ["Apple Watch"],
"days": { "2026-09-03": { "n": 288, "lastTs": 1756900000000,
"f": { "Avg": { "n": 288, "sum": 20000, "min": 55, "max": 96, "last": 72, "avg": 69.4 } } } },
"seen": { "2026-09-03 09:05:00 +0200|Avg:70": 1756900000000 } } },
"workouts": [ { "name": "Walking", "start": 1756900000000, "durMin": 60, "avgHr": 128, "fields": {} } ] }
```
The server does not decide what "steps today" means. A counter's day is its `sum`, a rate's is its
`avg`, a gauge's is its `last` — and all four are stored, because which one a *card* shows is a
presentation rule, and it lives in `vitals-view.js` with the labels. That is also why a metric HAE
ships next year shows up without a server change: an unrecognised name still lands in `f` under
whatever HAE called it, gets a humanised label and a card of its own under **Other**.
Bounds, all enforced on write:
| Kept | Limit | Why |
| --- | --- | --- |
| Days per metric | 400 | A little over a year, so "this time last year" still exists. |
| Dedupe ledger per metric | 72 h | A repeat can only be recent — the next automation run is minutes away, not days. |
| Workouts | newest 300 | A wrist that records every walk produces thousands a year; nobody scrolls past the last few hundred. |
| Request body | 32 MB | A full-history export with Summarize off is tens of megabytes. Over it: `413` with a readable message. The bundled web container allows this **one route** the bigger body (`web/nginx.conf.template`); every other `/api` path stays at 5 MB. Behind your own reverse proxy, raise `client_max_body_size` there too, or it is your proxy's 413 the phone sees. |
**Salud → ⚙ → Delete the health data** removes this file. Your workouts, routines, account, passes
and ingest key are untouched, so the phone needs no re-configuring to sync again.
---
## 4. Security
- **The ingest key is write-only.** It can add to one profile's health file and cannot read a single
number out of it: `GET /api/vitals` requires a session. A key that leaks out of a phone is a
nuisance, not a disclosure.
- **It is its own credential**, not the session token, so rotating it (Salud → ⚙ → Replace the key)
invalidates the phone without signing you out anywhere. Lost phone, one tap.
- **Per profile.** The key resolves to exactly one account; a payload can never land in somebody
else's file. A disabled account's key stops working with the account.
- **Compared in constant time** as SHA-256 digests, and refused on length before any hashing.
- **CSRF-exempt** by design: the request carries its own credential in a header and has no session
to borrow (the same reasoning as `POST /api/pair/redeem`). A browser cannot attach a bearer header
on its own, so there is no ambient authority for a hostile page to reach for.
- **Audited**: the first sync from a phone, key creation and rotation, a deleted history — plus
failed syncs with a reason. Successful syncs are *not* logged: a five-minute cadence would write
288 identical lines a day and bury everything else. Refused requests (bad key) go to the container
log instead, so the activity log cannot be filled from the open internet.
Health data is not encrypted at rest beyond the file mode — it sits in `./data` next to your
workouts, which is the same trust model as the rest of a self-hosted KuentaGYM. **Back up `./data`**
and you have backed up your health file too.
---
## 5. Troubleshooting
| What you see | What it is |
| --- | --- |
| `401 invalid ingest key` | Wrong key, a revoked one, or the header is missing `Bearer `. The key is shown in Salud → ⚙; re-copy it rather than retyping. A disabled account also answers 401. |
| `400 not a Health Auto Export JSON export` | Export Format is set to **CSV**, or the URL points at something else. Set JSON. |
| `413 body too large` | A first sync with everything selected and Summarize off. Turn Summarize Data on, group by Days, or split the metrics across two automations. Behind your own reverse proxy (Caddy, Cloudflare, a second nginx), raise its body limit for this path as well — the bundled stack already does. |
| `200` with `received.points: 0` every time | Working, with nothing to add: bring your phone to Health Auto Export → Manual Sync → Export, and check Date Range covers a day that has data. |
| Nothing on the screen | Salud fetches 30 days by default — widen the range. A metric HAE has no samples for is skipped rather than shown as a zero. |
| Steps look half a day behind | HAE cannot read Health while the phone is locked. Open the app (or tap the Automations widget) and the day fills in. |
| A metric shows under **Other** | Marketing-free behaviour: the catalogue in `vitals-view.js` covers ~50 metrics by name. Anything else is still stored and still charted — humanised, with every field HAE sent listed in its detail sheet. Add a line to `METRICS` to give it a better label, unit and aggregate. |
| Workouts do not appear in History | By design. They are read-only in Salud; see the top of this file. |
## 6. For developers
- `api/vitals.js` — parsing, the merge rules of §2, retention. Pure; tests in `api/test/vitals.test.js`
cover the merge under overlapping, disjoint, day-grouped, raw, heart-rate, sleep and
blood-pressure payloads, plus pruning and timezone handling.
- `api/server.js` — the five routes and the ingest key. Route tests in `api/test/server-vitals.test.js`
run the real server and check isolation between profiles, that the key cannot read, and that ten
re-sends of the same window change nothing.
- `frontend/src/lib/vitals-view.js` — the metric catalogue, the card model, the units and the
workout rows. Tests beside it.
- `frontend/src/views/Health.jsx` — the screen and its two sheets.
- Endpoints are documented in `api/openapi.yaml` (tag `health`); rebuild `website/api.html` after
changing them.