Files
kuentagym/docs/HEALTH.md
T
dsantillan aa6ec8ef22
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
Salud: a card opens onto the day, hour by hour, and onto the days before it
Reported as "le doy a cualquier actividad y solo me presenta los pasos de hoy… debiera
presentarme una medida por hora, y no me da el histórico". Two separate things, and only one
of them was the app's fault.

**The history was the automation's setting.** With Date Range on its default (`Today`) every
sync carries today and nothing else, so there is exactly one day in the file to draw. That is
why a card looked frozen: not a rendering bug, a range that was never sent. The setup steps
now say `Previous 7 Days` and say why.

**The hours were thrown away by us.** Even when the phone sends 288 readings a day, the
receiver folded every one of them into a single day aggregate, so "8,123 steps today" was all
there could ever be — a number you cannot look into. Worse, the recommended setting was Time
Grouping `Days`, which sends one point per metric per day: the intraday detail never arrived
in the first place. The recommendation is now `Hours`, and the storage keeps the hours.

The merge rule for them is the same shape as the day rule, for the same reason: a payload
whose datapoints all sit on the hour is HAE's own hour grouping, and the hour *in progress*
grows on every run of a five-minute automation, so it is replaced and never unioned — 500 +
900 + 1,340 steps in one hour is a number no watch recorded. The day is then recomputed as
the sum of its hours, which is what keeps the card and the detail from ever disagreeing, and
which also makes switching an automation from Days to Hours mid-day converge instead of
double-count. Raw samples (real timestamps) still union by instant plus numbers, and they now
land in their own hour, which is where intraday detail comes from when nothing is grouped.

Three things that would have been silent bugs, caught while writing it:

- The hour rule is decided from the **whole payload**, never from one timestamp. A five-minute
  automation produces samples that sit exactly on the hour, and reading one of those as an hour
  total wipes the hour it belongs to. There is a test with a 09:00:00 and a 09:05:00 sample in
  one payload, and it fails against the per-point version of the rule.
- A day that arrived as a day total keeps its hours beside it, and a day stored before this
  existed keeps its aggregate when the first hour shows up — recomputing it from hours it does
  not have would delete 2,000 steps. Both are mutation-checked (removing either guard fails a
  test).
- A payload grouped by hour writes the ledger row anyway, because a later payload with real
  minutes can describe the same instant and the union path can only see the ledger. Without it
  the raw-sample route test double-counts a single sample.

The hours are the bulky part of this data, so they are kept for a week (the day aggregates
still live the full 400 days), pruned when the night's file is written, and fetched one metric
and one day at a time — `GET /api/vitals/hours`. A screen listing forty cards downloads none
of them; the day view carries only a count per day, which is what tells the sheet whether it
is worth asking. The sheet draws the hours, the days before it (tapping one moves the hour
list to that day), and every field the watch sent; when the automation groups by Days it says
so instead of leaving a gap where a chart should be.

Coverage: 6 new tests in `api/test/vitals.test.js` (19 total) and a route test in
`api/test/server-vitals.test.js` (5), the hour/history model in `vitals-view.test.js` (31),
three render tests through the real sheet, the route documented in `api/openapi.yaml` and
`website/api.html`, and `docs/HEALTH.md` with the settings, the new merge row and the two
symptoms now in Troubleshooting.
2026-09-23 13:28:58 -04:00

14 KiB
Raw Blame History

Apple Health (Salud)

KuentaGYM does not read Apple Health. Your iPhone posts it.

An iOS automation in Health Auto Export (HAE) reads Apple Health and POSTs its JSON export to your KuentaGYM profile. The Salud screen — the heart button in Home's header, next to the gear: the tab bar keeps its five tabs so its raised Start button stays centred — 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: Hours (or Days if you only ever want one number a day)
    • Date Range: Previous 7 Days (not Today — see below)
    • 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 aggregates instead of every sample. Smaller payloads, and the numbers on the cards are the ones Apple already summarised.
Time Grouping Hours Each sync carries the hours of the day, so the day is the sum of its hours and the detail sheet can draw the day hour by hour. Every hour is replaced by the next report of it, so a five-minute cadence is still safe (see §2). Days is the smaller option: one total per day, exact, and with nothing behind it to look into.
Date Range Previous 7 Days How much history exists at all. With Today (the default) every sync carries today only, and yesterday is never in the file — the cards then have a single day to draw. Previous 7 Days re-sends the last week every time, which also fills in a sync missed while the phone was locked or in Low Power Mode.
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.
Every datapoint sits exactly on the hour (HH:00:00) — HAE's Hours grouping, i.e. a total per hour That hour is replaced, for the same reason: the hour in progress grows on every run. The day is then recomputed as the sum of its hours, so the day total and the hourly detail can never disagree. The hours are what the detail sheet draws (kept for 7 days; the day aggregates live on). Overlapping windows, disjoint windows, and switching an automation from Days to Hours mid-day.
Anything else — real sample timestamps, or Minute grouping Each sample is identified by its instant plus its numbers and stored once, in its own hour. 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).

The hour rule is decided from the whole payload, never from a single timestamp: a five-minute automation also produces samples that land exactly on the hour, and reading one of those as an hour total would wipe the hour it belongs to.

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 (or Hours) 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.

{ "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:

{ "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": 24, "lastTs": 1756900000000,
                "f": { "Avg": { "n": 24, "sum": 1665.6, "min": 55, "max": 96, "last": 72, "avg": 69.4 } },
                "h": { "08": { "n": 1, "lastTs": 1756900400000,
                               "f": { "Avg": { "n": 1, "sum": 62, "min": 62, "max": 62, "last": 62 } } } } } },
      "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.
Hours per day 7 days Detail is what makes the file grow (24 buckets × every metric × every day of a year); it is also only interesting for the last few days, which is what the detail sheet opens. The day aggregates underneath keep the full 400.
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 Hours, 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.
A card shows one day, and its sheet has nothing before it The automation's Date Range is Today, so yesterday was never sent. Set it to Previous 7 Days; the past cannot be invented server-side.
The detail sheet says "arrived as one total a day", with no hour list Time Grouping is Days: the payload has one number per day and no hours to draw. Set it to Hours — the day stays the sum of its hours, so nothing is double-counted, and the hour list appears from the next sync on.
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, hour-grouped, raw, heart-rate, sleep and blood-pressure payloads, plus pruning (days and hours), the day-from-hours projection and timezone handling.
  • api/server.js — the six 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, the hour rows and the day history the detail sheet lists. 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.