Files
kuentagym/docs/HEALTH.md
T
dsantillan 5c69540f62
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: reset one measurement, without losing the rest
"Podemos reiniciar los números de esas mediciones para yo enviar el de hoy." The whole-file reset
already existed two taps away in the setup sheet, but it is the wrong size for the question: the
four metrics he suspects are not the profile. Throwing away a month of heart rate to start steps
over is not a reset, it is a tax.

So a metric can now be forgotten on its own: the detail sheet has **Reset this measurement**, which
deletes that metric's days (and hours) and nothing else — the other metrics, the workouts and the
ingest key stay. With any Date Range wider than a day the phone re-sends that metric on its next
sync, which is what makes this a reset rather than a loss: Apple Health still has the data, and a
day total replaces the day it names, so the stored past is rewritten rather than duplicated.

The two destructive rows are worded apart on purpose and the confirm names the metric ("¿Reiniciar
Pasos?"), because the neighbouring action in the setup sheet takes every metric there is.

`dropMetric()` is pure and returns how many days it took, and the route answers `metric: null` for
a metric the profile does not have (or a profile with no health file at all) instead of an error —
a screen that says "nothing stored" is more useful than a 404 answering a button press. Tested
from both ends: the helper's purity and arithmetic, the route against a real server (one metric
gone, the others and the workouts intact, the key still working, and a re-sync rebuilding it), and
the sheet's flow through the real confirm. Mutation-checked: pointing the row at the whole-file
delete fails it.
2026-09-23 16:18:28 -04:00

15 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.

To start over on one measurement instead — "these steps look wrong" — open the metric's card and use Reset this measurement: that metric's days and hours go, everything else stays, and with a Date Range of a week or more the next sync rebuilds it from Apple Health. Because a day total replaces the day it names, a re-sync corrects the stored past as well: there is no separate "recalculate" step to run.


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.
Numbers that look doubled (steps, above all) The export can carry the same walking twice — once from the Apple Watch and once from the iPhone. Apple Health de-duplicates that; an export of individual samples does not. A day total from HAE's own aggregation is the number the Health app shows, so Time Grouping: Days is the setting that keeps a card honest; grouping by Hours or Minutes reads the samples instead.
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.