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

+28
View File
@@ -1,5 +1,33 @@
# Changelog
## Sin publicar — Apple Health (Salud)
A new **Salud** tab, next to Plan, and an endpoint behind it. An iOS automation in *Health Auto
Export* POSTs Apple Health to your profile and the data shows up as read-only cards: steps, heart
rate, sleep, weight, oxygen, workouts, and every other metric HAE can export — including ones this
fork has never heard of, which land under **Other** with a humanised name and a detail sheet listing
every field the watch sent.
Per profile, and private by construction. Each profile mints its own **ingest key** (write-only: it
can add to that one profile's health file and cannot read a single number back), and rotating it
disconnects a phone without signing anybody out. The health data lives in its own
`data/vitals-<uid>.json`, outside the synced state document, so a year of heart rate never
round-trips through `localStorage` on every device.
The interesting problem was duplicates. A five-minute automation re-sends overlapping windows, and
"append" would count a day of steps again on every run while "replace" would throw away everything
but the last five minutes under a different HAE setting. The receiver decides per payload instead:
day-grouped totals replace the day they name (converging on the day's total no matter how often it
is re-sent), while real samples are identified by instant plus numbers and stored once — so a sync
every five minutes, hourly, or once a day all land the same way. `docs/HEALTH.md` has the settings,
the merge table and the one configuration that is merely approximate rather than wrong.
Also here: the watch's workouts are shown **read-only** in Salud and deliberately kept out of the
history — they carry no sets or weights, so folding them into progression, PRs and the recovery
model would be inventing data. Coverage: `api/vitals.js` (13 tests), the routes against a real
server (4), the card model (18), plus the endpoint documented in `api/openapi.yaml` and the new
`docs/HEALTH.md` setup guide.
<!-- Everything below this note is the **upstream** changelog, kept verbatim: the entries name the
project as it was called then (openGym) and reference upstream issue and merge-request
numbers. They are a record of what actually shipped, so they are deliberately not rewritten
+16 -6
View File
@@ -27,7 +27,7 @@ mcp/ optional MCP server — read-only stdio bridge exposing a user's work
media/ exercise img/gif, gitignored, fetched at runtime by the `media` compose service.
website/ static marketing site (plain HTML/CSS/JS) — not deployed for this fork; built by hand
when someone wants it (node scripts/build-api-docs.mjs fills in api.html).
docs/ SELF_HOSTING.md, MOBILE.md.
docs/ SELF_HOSTING.md, MOBILE.md, AI_COACH.md, HEALTH.md (Apple Health ingest).
```
## Commands
@@ -84,12 +84,14 @@ would catch is a change nothing checks here.
- `recovery.js` / `recovery-view.js` — fatigue/muscle-recovery model.
- `workout-model.js`, `supersetFlow.js` — in-session workout state machine, incl. supersets.
- `exercises.js` / `exercises-data.js` — the exercise library (1,324 built-ins + user-defined).
- `vitals-view.js` — the Apple Health metric catalogue and card model (labels, units, which
aggregate a card shows, workout rows). The server stores numbers; this decides how they read.
- `api.js` — the only place that talks to the backend (`fetch` wrapper, session cookie flows).
- CONTRIBUTING.md is explicit: **anything that decides what you lift next, or reads a logged
session back, is a pure helper here with a unit test beside it** — not verifiable by
clicking, and the progression engine has already had two bugs that only a test caught.
- **`views/`** — one file per screen (Home, Workout, Plan, Library, Stats, History, Settings,
Admin, Login, RoutineEdit), routed by `react-router-dom` from `App.jsx`.
- **`views/`** — one file per screen (Home, Workout, Plan, Library, Stats, History, Health,
Settings, Admin, Login, RoutineEdit), routed by `react-router-dom` from `App.jsx`.
- **`components/`** — shared UI (charts, modals, timers); `instr/` holds per-language exercise
instruction text; `locales/` is the i18n string catalogue (`lib/i18n.js` / `i18n-core.js`).
- Mobile: `@capacitor/*` wraps the same web build into native shells under `frontend/android` and
@@ -100,16 +102,24 @@ would catch is a change nothing checks here.
Single file, no framework, plain `node:http`. Requests are dispatched through a `routes` object
keyed by `'METHOD /path'` (e.g. `routes['GET /api/health']`) matched against `req.method + ' ' +
url.pathname` — add a new endpoint by adding a key here. State is two flat JSON files under
url.pathname` — add a new endpoint by adding a key here. State is three flat JSON files under
`DATA_DIR` (`db.json`: users/credentials/subscriptions/invites; `state-<uid>.json`: per-user
workout data), written with a write-temp-then-rename atomic pattern (`atomicWrite`). Auth is
workout data; `vitals-<uid>.json`: per-user Apple Health, written only by `POST /api/vitals/ingest`
— see `docs/HEALTH.md`), written with a write-temp-then-rename atomic pattern (`atomicWrite`). Auth is
WebAuthn passkeys (`@simplewebauthn/server`) plus a signed session cookie (HMAC'd with a
`DATA_DIR/secret` generated on first boot) — no JWT/session-store dependency. Optional pieces
`DATA_DIR/secret` generated on first boot) — no JWT/session-store dependency. A second, write-only
credential exists for the health ingest (`user.healthKey`, minted by `POST /api/vitals/key`, given
to an iOS automation), deliberately not the session token. Optional pieces
gated by env vars: `ADMIN_UIDS` (admin dashboard), `INVITE_ONLY` (signup needs a code),
`ALLOW_GUEST` (client-only guest mode never hits the server at all), plus a rotating
`data/audit.log` (JSONL) for sign-in/admin events. Web Push (`web-push`, VAPID keys
auto-generated into `data/vapid.json`) drives rest-timer-over and day-reminder notifications.
`vitals.js` sits beside `server.js` as the only non-`server.js` module with real logic on the API
side: HAE parsing, the idempotent merge (the reason a 5-minute automation does not double a day of
steps) and retention. `server.js` owns the bytes; that file owns the arithmetic, which is why it is
testable without a phone.
### MCP server (`mcp/src`)
Read-only stdio MCP bridge (`@modelcontextprotocol/sdk`) that lets an LLM client read a single
+1
View File
@@ -94,6 +94,7 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
- 🎨 **Designed, not assembled** — light/dark themes and 8 accent colors saved to your profile, over a hand-drawn icon set instead of emoji, so it looks the same on every phone
- 🌍 **14 languages** — full UI translation (EN, DE, ES, FR, IT, PT (Portugal), PT (Brazil), PL, TR, RU, ZH, KO, HI, TH, HU); exercise instructions localized in 12 of them and built-in exercise names shown bilingually in PT-BR and HU, all loaded on demand so the app stays fast
- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy** (CSV or directly with a [Hevy Pro API key](https://hevy.com/settings?developer)), or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped
- ❤️ **Salud: your Apple Health, live** — a **Salud** tab draws whatever your iPhone reports: steps, heart rate, sleep, weight, oxygen, workouts and every other metric Health Auto Export can send, as cards with trends over 7/30/90/365 days. Per profile and private by construction — each profile mints its own **write-only** ingest key, the phone's data lands in its own file, and re-sends are de-duplicated, so an automation firing every five minutes never counts a day twice. See [docs/HEALTH.md](docs/HEALTH.md)
- 📦 **Yours to keep** — one-tap JSON export/import, guest mode, **no telemetry**; switching kg ↔ lb offers to convert every stored number
- 🤖 **Ask an AI about your training** (optional) — an [MCP server](mcp/README.md) lets a client like Claude Desktop or Cursor read your history in your own words: *"what did I bench last week?"*. Read-only, spawned locally by the client, nothing leaves your box. Not in the Docker build — if you don't use an AI assistant, it isn't there
- 🧠 **An AI coach that writes your plan** (optional, off by default) — answer a handful of questions and it designs a week of routines; later it reads what you actually logged and proposes changes, each one with the evidence behind it. You approve every change and can undo it. It runs on **your** server under **your** provider account — Anthropic, OpenAI, Gemini or any OpenAI-compatible endpoint (Ollama on your LAN counts) with a pasted API key on the default image, or the Claude Agent SDK / Codex CLI on a separate build. The phone app can use your instance or its own key. See [docs/AI_COACH.md](docs/AI_COACH.md)
+6 -1
View File
@@ -51,7 +51,12 @@ COPY package.json package-lock.json* ./
# build host happened to be.
RUN npm ci --omit=dev --omit=optional && npm cache clean --force
COPY server.js push-messages.js verify-error.js ./
# Every local module server.js imports, listed rather than `COPY . .` so a stray file in api/
# (a test, a script, a stray JSON) cannot reach the published image. vitals.js joined the list
# with the Apple Health ingest — an import of a file that is not copied here is a container that
# boots straight into ERR_MODULE_NOT_FOUND, which is exactly what the first health build would
# have done.
COPY server.js push-messages.js verify-error.js vitals.js ./
COPY coach ./coach
ENV NODE_ENV=production
ENV PORT=3000
+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.
+162 -4
View File
@@ -19,6 +19,7 @@ import { startCadence } from './coach/cadence.js';
import { startWarmup } from './coach/warmup.js';
import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
import { verifyError } from './verify-error.js';
import { parsePayload, mergeVitals, vitalsSeries, emptyVitals, RETENTION_DAYS } from './vitals.js';
const PORT = +(process.env.PORT || 3000);
const DATA = process.env.DATA_DIR || '/data';
@@ -40,6 +41,11 @@ const ALLOW_GUEST = !/^(0|false|no|off)$/i.test(process.env.ALLOW_GUEST || '');
// baked into each cookie when it's issued, so lowering this never cuts an existing session short.
const SESSION_DAYS = Math.max(1, +(process.env.SESSION_DAYS || 90) || 90);
const MAX_BODY = 5 * 1024 * 1024;
/* Apple Health arrives in bulk: the phone's first export of a year of raw samples is tens of
megabytes, and Health Auto Export itself warns that "several hundred MB" is possible. 32 MB
covers a full-history export of the metrics somebody actually tracks; past it the route answers
a readable 413 rather than reading until the container runs out of memory. */
const VITALS_MAX_BODY = 32 * 1024 * 1024;
// Secure cookies require HTTPS; over plain http://localhost the flag would drop the cookie
const SECURE = /^https:/i.test(ORIGIN) ? ' Secure;' : '';
@@ -92,6 +98,69 @@ function readState(uid) {
const record = x => !!x && typeof x === 'object' && !Array.isArray(x);
const records = v => (Array.isArray(v) ? v.filter(record) : []);
/* ---------- health data (Apple Health, via Health Auto Export) ----------
*
* Stored beside the profile's own state but in a file of its own, and never inside state-<uid>.json,
* for three reasons: the phone writes it while the browser writes the state document, and sharing
* one file would have the two clobbering each other's revisions; 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; and a reader that only wants the health data (the view, the tests) then needs no
* merge logic to find it.
*
* All arithmetic lives in vitals.js — this file only owns the bytes. */
const vitalsFile = uid => path.join(DATA, 'vitals-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json');
function readVitals(uid) {
try { return JSON.parse(fs.readFileSync(vitalsFile(uid), 'utf8')); } catch { return null; }
}
// 0600 like db.json: a year of somebody's heart rate is not for every process on the box.
function writeVitals(uid, doc) { atomicWrite(vitalsFile(uid), JSON.stringify(doc), 0o600); }
/** What a sync is answered with: how much is in the profile now, not just what just arrived. */
const storedCounts = doc => ({
metrics: doc ? Object.keys(doc.metrics || {}).length : 0,
days: doc ? Object.values(doc.metrics || {}).reduce((n, m) => n + Object.keys(m.days || {}).length, 0) : 0,
workouts: doc && Array.isArray(doc.workouts) ? doc.workouts.length : 0
});
// The credential the phone carries. A passkey ceremony cannot run inside an iOS automation, and
// handing HAE the session token instead would give a third-party app that can never be signed out
// individually the run of the whole account — this key can do exactly one thing, write this one
// person's health file, and can be rotated on its own from Settings.
const INGEST_KEY_PREFIX = 'kghealth_';
const newIngestKey = () => INGEST_KEY_PREFIX + crypto.randomBytes(24).toString('base64url');
const sha256 = s => crypto.createHash('sha256').update(s).digest();
/**
* Resolve the account an ingest key belongs to, or null.
*
* Compared as digests through timingSafeEqual so a wrong key cannot be narrowed down a byte at a
* time, and refused outright on length before any hashing: a short string is a mistake, not a
* guess. A disabled account resolves to null — it is locked out everywhere, and a health file is
* no exception.
*/
function userByIngestKey(key) {
if (typeof key !== 'string' || key.length < 20 || key.length > 200) return null;
const want = sha256(key);
for (const u of db.users) {
if (typeof u.healthKey !== 'string' || !u.healthKey) continue;
if (!crypto.timingSafeEqual(sha256(u.healthKey), want)) continue;
return u.disabled ? null : u;
}
return null;
}
/**
* The account a health ingest is for. Health Auto Export can only authenticate with a custom
* header, so `Authorization: Bearer <ingest key>` is the documented setting; `X-Ingest-Key` is
* accepted too because it is friendlier for the manual test curl and for a Shortcut. A browser
* session also passes, so somebody can replay a saved export by hand from a signed-in tab.
*/
function vitalsUser(req) {
const auth = String(req.headers.authorization || '');
const key = (auth.startsWith('Bearer ') ? auth.slice(7).trim() : '') || String(req.headers['x-ingest-key'] || '').trim();
if (!key) return null;
const session = readSession(req); // a session token is HMAC-verified; an ingest key never is
if (session) return session;
return userByIngestKey(key);
}
/* ---------- push notifications (Web Push / VAPID) ---------- */
const vapidFile = path.join(DATA, 'vapid.json');
let vapid;
@@ -463,7 +532,11 @@ const clearCookie = COOKIE === LEGACY_COOKIE
const CSRF_EXEMPT = new Set([
'POST /api/register/options', 'POST /api/register/verify',
'POST /api/login/options', 'POST /api/login/verify',
'POST /api/pair/redeem'
'POST /api/pair/redeem',
// The phone's health automation: it carries an ingest key in a header and has no session to
// borrow, and a key is not ambient authority a hostile page could reach for — the same
// reasoning as the pairing code above.
'POST /api/vitals/ingest'
]);
const originsMatch = (a, b) => a.replace(/\/+$/, '') === b.replace(/\/+$/, '');
function csrfOk(req, key) {
@@ -531,7 +604,7 @@ function json(res, code, obj, extraHeaders) {
class HttpError extends Error {
constructor(status, message) { super(message); this.status = status; }
}
function readBody(req) {
function readBody(req, max = MAX_BODY) {
return new Promise((resolve, reject) => {
let size = 0, over = false; const chunks = [];
req.on('data', d => {
@@ -543,10 +616,10 @@ function readBody(req) {
// reset before it has parsed the answer reports a dropped connection instead of the
// 413. A client that keeps streaming past twice the cap is not a mistaken one, and is
// cut off.
if (size > 2 * MAX_BODY) req.destroy();
if (size > 2 * max) req.destroy();
return;
}
if (size > MAX_BODY) {
if (size > max) {
over = true; chunks.length = 0;
reject(new HttpError(413, 'body too large'));
return;
@@ -942,6 +1015,91 @@ const routes = {
json(res, 200, { ok: true, ts: body.state._ts || null, rev: body.state._rev });
},
/* ---------- health (Apple Health / Health Auto Export) ----------
*
* The phone posts its export to the ingest route; the app reads it back from GET /api/vitals.
* What the client gets back is the stored per-day aggregates, not a server-side opinion about
* "steps today": which field a card shows is a presentation decision and lives in the frontend
* (lib/vitals-view.js), so a metric HAE adds next year needs no change here.
*/
// Health Auto Export → Automation Type "REST API" → URL = this endpoint, header
// `Authorization: Bearer <ingest key>`. docs/HEALTH.md has the settings that make the merge
// exact and the ones that make it approximate.
'POST /api/vitals/ingest': async (req, res) => {
const user = vitalsUser(req);
if (!user) {
// Reachable without a session, so this is a container-log line rather than an audit entry:
// an audit log anyone can fill from the open internet is a liability, not a record.
console.warn('vitals ingest refused: bad ingest key');
return json(res, 401, { error: 'invalid ingest key' });
}
const body = await readBody(req, VITALS_MAX_BODY);
let payload;
try { payload = parsePayload(body); }
catch (e) {
const doc = readVitals(user.id);
// An automation that runs on a schedule will fire when there is nothing to report — first
// run after installing, a night away from the watch. That is not a failure, and answering
// 4xx would have the app show an error the user cannot act on.
if (e.code === 'empty') return json(res, 200, { ok: true, received: { metrics: 0, points: 0, workouts: 0, duplicates: 0 }, stored: storedCounts(doc) });
audit(req, 'auth.health.ingest', { ok: false, user, msg: 'bad-payload' });
return json(res, 400, { error: 'not a Health Auto Export JSON export' });
}
const before = readVitals(user.id);
const { doc, stats } = mergeVitals(before, payload);
writeVitals(user.id, doc);
// Audited once per profile instead of once per sync: a five-minute automation would write
// 288 identical lines a day and bury every other event in the log.
if (!before) audit(req, 'auth.health.ingest.first', { user, msg: `${Object.keys(doc.metrics).length} metrics` });
json(res, 200, { ok: true, ts: doc.updatedAt, received: stats, stored: storedCounts(doc) });
},
// Everything the Salud view renders for the signed-in profile. Always a session: the ingest key
// is write-only on purpose, so a key that leaks out of somebody's phone can add to their health
// file and still cannot read a single number out of it.
'GET /api/vitals': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const want = +(new URL(req.url, 'http://x').searchParams.get('days') || 90);
const days = Math.min(RETENTION_DAYS, Math.max(1, Number.isFinite(want) ? Math.round(want) : 90));
const doc = readVitals(user.id);
// The key rides along because the empty state of that view IS the setup instructions — the
// URL and the header to paste into Health Auto Export. Same session, same response, one fetch.
json(res, 200, { ok: true, days, key: user.healthKey || null, ...vitalsSeries(doc || emptyVitals(), { days }) });
},
// Mint the ingest key on first use; a second call returns the one that exists rather than
// silently invalidating the phone's configuration on a page reload.
'POST /api/vitals/key': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
if (!user.healthKey) { user.healthKey = newIngestKey(); saveDb(); audit(req, 'auth.health.key.create', { user }); }
json(res, 200, { ok: true, key: user.healthKey });
},
// A new key, and the old one stops working everywhere at once — the reason this is its own
// credential rather than the session token: losing a phone should not sign you out of the app.
'POST /api/vitals/key/rotate': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
user.healthKey = newIngestKey();
saveDb();
audit(req, 'auth.health.key.rotate', { user });
json(res, 200, { ok: true, key: user.healthKey });
},
// Wipe the health file and nothing else. The state document, the workouts and the account are
// untouched, and the key survives — a user who wants the history gone should not have to
// re-configure their phone to get it back.
'DELETE /api/vitals': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
try { fs.unlinkSync(vitalsFile(user.id)); } catch { /* nothing stored */ }
audit(req, 'auth.health.clear', { user });
json(res, 200, { ok: true });
},
'GET /api/push/public-key': async (req, res) => json(res, 200, { key: vapid.publicKey }),
'POST /api/push/subscribe': async (req, res) => {
+239
View File
@@ -0,0 +1,239 @@
/* The health ingest endpoint, end to end against the real server: a five-minute automation must
not double a day of steps, one profile's key must never reach another profile's file, and the
ingest key must be good for exactly one thing (writing). */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import net from 'node:net';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
// Same construction as server.js makeSession(): payload `uid:exp:sv`, HMAC-SHA256 over SECRET.
function mintSession(uid, sv = 0) {
const payload = `${uid}:${Date.now() + 86400000}:${sv}`;
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
}
const cookie = uid => ({ Cookie: `gymsid=${mintSession(uid)}` });
const freePort = () => new Promise(r => {
const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
});
const USERS = [
{ id: 'u_h1', name: 'One', created: '2026-01-01T00:00:00.000Z' },
{ id: 'u_h2', name: 'Two', created: '2026-01-01T00:00:00.000Z' },
// A disabled account keeps whatever key it had; the route has to refuse it anyway.
{ id: 'u_h3', name: 'Three', created: '2026-01-01T00:00:00.000Z', disabled: true, healthKey: 'kghealth_' + 'x'.repeat(32) }
];
async function startServer(t) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-vitals-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: USERS, creds: [], subs: [], invites: [] }));
const port = await freePort();
const child = spawn(process.execPath, ['server.js'], {
cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost', AUDIT_LOG: '1' }
});
const h = { api: `http://127.0.0.1:${port}`, dataDir, log: '' };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
let up = false;
for (let i = 0; i < 100 && !up; i++) {
try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
if (!up) await new Promise(r => setTimeout(r, 100));
}
assert.ok(up, `server never came up:\n${h.log}`);
return h;
}
const today = new Date().toISOString().slice(0, 10);
const yday = new Date(Date.now() - 86400000).toISOString().slice(0, 10);
/** One sync's worth of payload: a day-grouped step total, raw heart rate, and a workout. */
const payload = () => ({
data: {
metrics: [
{ name: 'step_count', units: 'count', data: [{ qty: 8000, date: `${today} 00:00:00 +0000` }] },
{ name: 'heart_rate', units: 'bpm', data: [{ date: `${today} 09:00:00 +0000`, Min: 55, Avg: 70, Max: 95 }] },
{ name: 'weight_body_mass', units: 'kg', data: [{ qty: 80.5, date: `${today} 07:30:00 +0000` }] }
],
workouts: [{
name: 'Walking',
start: `${today} 17:00:00 +0000`,
end: `${today} 18:00:00 +0000`,
activeEnergy: { qty: 210, units: 'kcal' }
}]
}
});
const ingest = (h, key, body) => fetch(`${h.api}/api/vitals/ingest`, {
method: 'POST',
headers: key ? { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` } : { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
test('the ingest key: created once, writes the profile\'s own file, and cannot read', async t => {
const h = await startServer(t);
const keyOf = async uid => (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie(uid) })).json()).key;
// Signed out, there is no key to mint.
assert.equal((await fetch(`${h.api}/api/vitals/key`, { method: 'POST' })).status, 401);
const key1 = await keyOf('u_h1');
assert.match(key1, /^kghealth_[A-Za-z0-9_-]{32}$/);
assert.equal(await keyOf('u_h1'), key1, 'asking again returns the same key, not a new one');
const key2 = await keyOf('u_h2');
assert.notEqual(key1, key2);
// A payload with no key at all, and one with a made-up key.
assert.equal((await ingest(h, '', payload())).status, 401);
assert.equal((await ingest(h, 'kghealth_' + 'nope'.repeat(8), payload())).status, 401);
// One profile's key cannot write another profile's file, and a disabled account's key is dead.
assert.equal((await ingest(h, USERS[2].healthKey, payload())).status, 401);
const first = await ingest(h, key1, payload());
assert.equal(first.status, 200);
const body1 = await first.json();
assert.equal(body1.ok, true);
assert.equal(body1.received.points, 3);
assert.equal(body1.received.workouts, 1);
assert.deepEqual(body1.stored, { metrics: 3, days: 3, workouts: 1 }, '3 metrics, one day each, one workout');
// The whole point: the same window again, ten times over, changes nothing.
for (let i = 0; i < 10; i++) {
const again = await (await ingest(h, key1, payload())).json();
assert.equal(again.received.points, 0, 'a re-sent window adds no points');
assert.equal(again.stored.days, 3);
}
// The ingest key is write-only: it can add to the file and never read it back.
assert.equal((await fetch(`${h.api}/api/vitals`, { headers: { Authorization: `Bearer ${key1}` } })).status, 401, 'an ingest key must not read health data');
// Reading needs a session, and each profile sees only its own file.
const read = async uid => (await (await fetch(`${h.api}/api/vitals`, { headers: cookie(uid) })).json());
const mine = await read('u_h1');
assert.equal(mine.ok, true);
assert.equal(mine.key, key1);
assert.deepEqual(Object.keys(mine.metrics).sort(), ['heart_rate', 'step_count', 'weight_body_mass']);
assert.deepEqual(mine.metrics.step_count.days.map(d => d.f.qty.sum), [8000], 'the day total is 8000, not 88000');
assert.equal(mine.metrics.heart_rate.days[0].f.Avg.avg, 70);
assert.equal(mine.metrics.weight_body_mass.days[0].f.qty.last, 80.5);
assert.equal(mine.workouts.length, 1);
assert.equal(mine.workouts[0].durMin, 60);
const other = await read('u_h2');
assert.deepEqual(other.metrics, {}, 'the other profile has no health data at all');
assert.deepEqual(other.workouts, []);
assert.equal(other.key, key2);
// Rotating invalidates the old key everywhere, and the key that replaces it works.
const rotated = await (await fetch(`${h.api}/api/vitals/key/rotate`, { method: 'POST', headers: cookie('u_h1') })).json();
assert.match(rotated.key, /^kghealth_/);
assert.notEqual(rotated.key, key1);
assert.equal((await ingest(h, key1, payload())).status, 401, 'the old key is dead');
assert.equal((await ingest(h, rotated.key, payload())).status, 200);
// ...and rotating did not touch the other profile's key.
assert.equal((await ingest(h, key2, payload())).status, 200);
});
test('a payload that is not an export is refused; an export with nothing in it is not an error', async t => {
const h = await startServer(t);
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key;
const bad = await ingest(h, key, { hello: 'world' });
assert.equal(bad.status, 400);
assert.match((await bad.json()).error, /Health Auto Export/);
// Nothing stored by the refusals.
const after = await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json();
assert.deepEqual(after.metrics, {});
// "Nothing to report" — the automation fired, the range was empty. 200, with zeroes.
const empty = await ingest(h, key, { data: { metrics: [], workouts: [] } });
assert.equal(empty.status, 200);
const e = await empty.json();
assert.equal(e.ok, true);
assert.deepEqual(e.received, { metrics: 0, points: 0, workouts: 0, duplicates: 0 });
assert.deepEqual(e.stored, { metrics: 0, days: 0, workouts: 0 });
// A metric that is selected but has no samples is equally a no-op, and it must not wipe what
// is already stored: that is the shape the phone sends all night.
await ingest(h, key, payload());
const quiet = await ingest(h, key, { data: { metrics: [{ name: 'step_count', units: 'count', data: null }] } });
assert.equal(quiet.status, 200);
assert.deepEqual((await quiet.json()).stored, { metrics: 3, days: 3, workouts: 1 });
});
test('a raw-sample automation accumulates a day without double counting, and a fresh day still lands', async t => {
const h = await startServer(t);
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key;
const sample = (day, time, qty) => ({ name: 'step_count', units: 'count', data: [{ qty, date: `${day} ${time} +0000` }] });
// Date Range "Since Last Sync": five minutes at a time.
for (const [time, qty] of [['09:00:00', 300], ['09:05:00', 700], ['09:10:00', 200]]) {
assert.equal((await ingest(h, key, { data: { metrics: [sample(today, time, qty)] } })).status, 200);
}
const read = async () => (await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json());
let doc = await read();
const sum = d => d.metrics.step_count.days.reduce((n, day) => n + day.f.qty.sum, 0);
assert.equal(sum(doc), 1200);
// Date Range "Today": the same three samples again, plus a new one.
const todayWindow = { data: { metrics: [{ name: 'step_count', units: 'count', data: [
{ qty: 300, date: `${today} 09:00:00 +0000` },
{ qty: 700, date: `${today} 09:05:00 +0000` },
{ qty: 200, date: `${today} 09:10:00 +0000` },
{ qty: 1000, date: `${today} 09:15:00 +0000` }
] }] } };
const overlap = await (await ingest(h, key, todayWindow)).json();
assert.equal(overlap.received.points, 1, 'only the new sample counts');
assert.equal(overlap.received.duplicates, 3);
doc = await read();
assert.equal(sum(doc), 2200);
// The default range also carries yesterday, which must land as its own day.
await ingest(h, key, { data: { metrics: [sample(yday, '09:00:00', 5000)] } });
doc = await read();
assert.equal(doc.metrics.step_count.days.length, 2);
assert.equal(doc.metrics.step_count.days[0].day, yday);
// ...and a window narrowing to one day is still one day.
const narrow = await (await fetch(`${h.api}/api/vitals?days=1`, { headers: cookie('u_h1') })).json();
assert.deepEqual(narrow.metrics.step_count.days.map(d => d.day), [today]);
});
test('DELETE /api/vitals wipes the health file and leaves the account, the key and the workouts alone', async t => {
const h = await startServer(t);
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key;
await ingest(h, key, payload());
// A workout logged in the app lives in the state document, not in the health file.
const state = { unit: 'kg', lang: 'es', workouts: [{ id: 'w1', d: today, name: 'Full body', entries: [] }], routines: [] };
const put = await fetch(`${h.api}/api/data`, { method: 'PUT', headers: { ...cookie('u_h1'), 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin' }, body: JSON.stringify({ state }) });
assert.equal(put.status, 200);
assert.equal((await fetch(`${h.api}/api/vitals`, { method: 'DELETE' })).status, 401, 'a session is required');
assert.equal((await fetch(`${h.api}/api/vitals`, { method: 'DELETE', headers: cookie('u_h2') })).status, 200, 'wiping an empty profile is fine');
assert.equal((await fetch(`${h.api}/api/vitals`, { method: 'DELETE', headers: cookie('u_h1') })).status, 200);
const after = await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json();
assert.deepEqual(after.metrics, {});
assert.deepEqual(after.workouts, []);
assert.equal(after.key, key, 'the key survives, so the phone does not need re-configuring');
const data = await (await fetch(`${h.api}/api/data`, { headers: cookie('u_h1') })).json();
assert.equal(data.state.workouts.length, 1, 'the workout history is untouched');
// The phone can simply sync again.
assert.equal((await ingest(h, key, payload())).status, 200);
assert.equal((await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json()).metrics.step_count.days.length, 1);
});
+288
View File
@@ -0,0 +1,288 @@
/* The merge rule is the whole point of vitals.js: an automation that runs every five minutes
must not turn a day of steps into three days of steps. These tests are all about that, plus
the shapes HAE actually sends (day-grouped totals, raw samples, Min/Avg/Max heart rate,
aggregated and segmented sleep, blood pressure, a metric that is selected but empty).
Every merge is given an explicit `now`, because the dedupe ledger is pruned against the wall
clock: a test that let the real clock in would delete its own fixtures the moment they were a
few days old, and start passing for the wrong reason. */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
parsePayload, mergeVitals, vitalsSeries, emptyVitals, parseHaeDate, normalizeDoc,
RETENTION_DAYS, LEDGER_MS
} from '../vitals.js';
const NOW = Date.parse('2026-05-01T23:30:00Z');
const merge = (doc, payload, now = NOW) => mergeVitals(doc, payload, now);
const at = (day, time = '00:00:00', off = '+0000') => `${day} ${time} ${off}`;
/** One metric, one payload. */
const metric = (name, units, data) => ({ data: { metrics: [{ name, units, data }] } });
/* ---------- parsing ---------- */
test('parses both HAE date spellings, including the 12-hour one with a narrow no-break space', () => {
const a = parseHaeDate('2026-05-01 13:04:05 +0200');
assert.equal(a.day, '2026-05-01');
assert.equal(a.time, '13:04:05');
assert.equal(a.ms, Date.parse('2026-05-01T13:04:05+02:00'));
// U+202F between the time and the meridiem — what HAE writes on a 12-hour phone.
const b = parseHaeDate('2026-05-01 1:04:05\u202fPM -0700');
assert.equal(b.time, '13:04:05');
assert.equal(b.ms, Date.parse('2026-05-01T13:04:05-07:00'));
// The two hours a naive modulo gets wrong.
assert.equal(parseHaeDate('2026-05-01 12:00:00\u202fAM +0000').time, '00:00:00');
assert.equal(parseHaeDate('2026-05-01 12:30:00\u202fPM +0000').time, '12:30:00');
// No offset at all means UTC, not "whatever the server is".
assert.equal(parseHaeDate('2026-05-01 08:00:00').ms, Date.parse('2026-05-01T08:00:00Z'));
assert.equal(parseHaeDate('not a date'), null);
assert.equal(parseHaeDate('2026-13-45 08:00:00 +0000'), null);
assert.equal(parseHaeDate(undefined), null);
});
test('parsePayload accepts v2 (wrapped in data), the older flat shape, and drops empty metrics', () => {
const v2 = parsePayload({
data: {
metrics: [
{ name: 'step_count', units: 'count', data: [{ qty: 100, date: at('2026-05-01', '09:00:00') }] },
{ name: 'basal_body_temperature', units: 'degC', data: null }
],
workouts: []
}
});
assert.equal(v2.metrics.length, 2);
assert.equal(v2.metrics[1].points.length, 0, 'a selected-but-empty metric parses to no points');
const flat = parsePayload({ metrics: [{ name: 'weight_body_mass', units: 'kg', data: [{ qty: 80, date: at('2026-05-01', '07:00:00') }] }] });
assert.equal(flat.metrics[0].points[0].fields.qty, 80);
assert.throws(() => parsePayload({ hello: 'world' }), e => e.code === 'shape');
assert.throws(() => parsePayload(null), e => e.code === 'shape');
assert.throws(() => parsePayload({ data: { metrics: [], workouts: [] } }), e => e.code === 'empty');
// A datapoint with no readable date, or with no numbers at all, is not a datapoint.
const junk = parsePayload(metric('foo', 'x', [{ qty: 1, date: 'nonsense' }, { date: at('2026-05-01') }]));
assert.equal(junk.metrics[0].points.length, 0);
});
/* ---------- the merge rule ---------- */
test('raw samples: disjoint windows accumulate, overlapping ones do not double count', () => {
const p = (t, qty) => ({ qty, date: at('2026-05-01', t) });
// "Since Last Sync": each run carries only what happened since the last one.
let doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [p('09:00:00', 300), p('09:05:00', 700)]))).doc;
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1000);
const inc = merge(doc, parsePayload(metric('step_count', 'count', [p('09:10:00', 200), p('09:15:00', 800)])));
doc = inc.doc;
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 2000, 'new samples add on');
assert.equal(inc.stats.points, 2);
// "Today": every run re-sends the whole day, with the two samples since the last run added.
const today = metric('step_count', 'count', [
p('09:00:00', 300), p('09:05:00', 700), p('09:10:00', 200), p('09:15:00', 800),
p('09:20:00', 1000), p('09:25:00', 500)
]);
const first = merge(doc, parsePayload(today));
assert.equal(first.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 3500, 'only the two new samples count');
assert.equal(first.stats.points, 2);
assert.equal(first.stats.duplicates, 4);
const again = merge(first.doc, parsePayload(today));
assert.equal(again.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 3500, 're-sending changes nothing');
assert.equal(again.stats.points, 0);
assert.equal(again.stats.duplicates, 6);
});
test('day-grouped payloads replace the day: a growing total never adds up', () => {
const grouped = sum => metric('step_count', 'count', [{ qty: sum, date: at('2026-05-01') }]);
let doc = merge(emptyVitals(), parsePayload(grouped(1200))).doc;
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1200);
// Ten more syncs through the day, each carrying the day's total so far — "Time Grouping: Days".
for (const total of [1400, 2600, 4100, 9800]) doc = merge(doc, parsePayload(grouped(total))).doc;
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800, 'replaced, not accumulated');
const same = merge(doc, parsePayload(grouped(9800)));
assert.equal(same.stats.duplicates, 1);
assert.equal(same.stats.points, 0, 'the same total again is a no-op');
assert.equal(same.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800);
// A day-grouped payload covering several days corrects each of them independently.
const multi = merge(same.doc, parsePayload(metric('step_count', 'count', [
{ qty: 9800, date: at('2026-05-01') }, { qty: 3000, date: at('2026-04-30') }
])));
assert.equal(multi.doc.metrics.step_count.days['2026-04-30'].f.qty.sum, 3000);
assert.equal(multi.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800);
});
test('a day total and raw samples for the same day are kept apart by their own payload shape', () => {
// Two metrics in one payload, one grouped by day and one raw: each takes its own branch.
const body = {
data: {
metrics: [
{ name: 'step_count', units: 'count', data: [{ qty: 5000, date: at('2026-05-01') }] },
{ name: 'resting_heart_rate', units: 'bpm', data: [{ qty: 52, date: at('2026-05-01', '06:30:00') }] }
]
}
};
const { doc } = merge(emptyVitals(), parsePayload(body));
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 5000);
assert.equal(doc.metrics.resting_heart_rate.days['2026-05-01'].f.qty.sum, 52);
});
test('the day key is the phone\'s own date, not the server\'s', () => {
// 23:30 in Manila is the previous day in UTC. The sample belongs to the phone's day.
const { doc } = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
{ qty: 500, date: at('2026-05-01', '23:30:00', '+0800') }
])));
assert.deepEqual(Object.keys(doc.metrics.step_count.days), ['2026-05-01']);
});
/* ---------- the shapes HAE actually sends ---------- */
test('heart rate keeps Min/Avg/Max per day instead of pretending they are one number', () => {
const body = metric('heart_rate', 'bpm', [
{ date: at('2026-05-01', '09:00:00'), Min: 58, Avg: 72, Max: 96, source: 'Apple Watch' },
{ date: at('2026-05-01', '10:00:00'), Min: 55, Avg: 68, Max: 88, source: 'Apple Watch' }
]);
const { doc } = merge(emptyVitals(), parsePayload(body));
const day = doc.metrics.heart_rate.days['2026-05-01'];
assert.equal(day.f.Avg.n, 2);
assert.equal(Math.round(day.f.Avg.sum), 140);
assert.equal(day.f.Min.min, 55);
assert.equal(day.f.Max.max, 96);
assert.deepEqual(doc.metrics.heart_rate.sources, ['Apple Watch']);
});
test('sleep: both the aggregated night and the segmented one land as hours per day', () => {
const aggregated = metric('sleep_analysis', 'hr', [{
date: at('2026-05-01', '07:00:00'),
sleepStart: at('2026-04-30', '23:10:00'), sleepEnd: at('2026-05-01', '06:55:00'),
inBed: 8.2, asleep: 7.4, core: 4.1, deep: 1.2, rem: 2.1, awake: 0.8, source: 'Apple Watch'
}]);
const { doc } = merge(emptyVitals(), parsePayload(aggregated));
// Keyed by the day the metric's own `date` names — the morning you woke up.
assert.equal(doc.metrics.sleep_analysis.days['2026-05-01'].f.asleep.last, 7.4);
assert.equal(doc.metrics.sleep_analysis.days['2026-05-01'].f.deep.last, 1.2);
const segments = [
{ startDate: at('2026-05-01', '22:10:00'), endDate: at('2026-05-01', '22:50:00'), qty: 0.67, value: 'asleepCore' },
{ startDate: at('2026-05-01', '23:10:00'), endDate: at('2026-05-01', '23:25:00'), qty: 1.33, value: 'asleepDeep' }
];
const seg = merge(emptyVitals(), parsePayload(metric('sleep_analysis', 'hr', segments))).doc;
// Segments carry no `date`, only startDate/endDate, so the day comes from the segment start.
assert.equal(seg.metrics.sleep_analysis.days['2026-05-01'].f.qty.sum, 2);
assert.equal(seg.metrics.sleep_analysis.days['2026-05-01'].f.qty.n, 2);
const repeat = merge(seg, parsePayload(metric('sleep_analysis', 'hr', segments)));
assert.equal(repeat.stats.duplicates, 2, 'the same segments again are the same segments');
assert.equal(repeat.doc.metrics.sleep_analysis.days['2026-05-01'].f.qty.sum, 2, 'and do not add up twice');
});
test('blood pressure keeps both numbers, and an unknown metric is stored rather than dropped', () => {
const body = {
data: {
metrics: [
{ name: 'blood_pressure_systolic', units: 'mmHg', data: [{ date: at('2026-05-01', '08:00:00'), systolic: 128, diastolic: 82 }] },
{ name: 'walking_steadiness', units: '%', data: [{ date: at('2026-05-01', '08:00:00'), qty: 91 }] }
]
}
};
const { doc } = merge(emptyVitals(), parsePayload(body));
assert.equal(doc.metrics.blood_pressure_systolic.days['2026-05-01'].f.systolic.last, 128);
assert.equal(doc.metrics.blood_pressure_systolic.days['2026-05-01'].f.diastolic.last, 82);
assert.equal(doc.metrics.walking_steadiness.days['2026-05-01'].f.qty.last, 91);
});
/* ---------- workouts ---------- */
test('workouts dedupe on name+start+end, newest first, and a re-send adds nothing', () => {
const w = (name, start, end, energy) => ({
name, start, end,
activeEnergy: { qty: energy, units: 'kcal' },
distance: { qty: 3.2, units: 'km' },
heartRateData: [{ date: at('2026-05-01', '18:00:00'), Avg: 128 }, { date: at('2026-05-01', '18:05:00'), Avg: 136, Max: 172 }]
});
const body = {
data: {
workouts: [
w('Walking', at('2026-05-01', '17:00:00'), at('2026-05-01', '18:00:00'), 210),
w('Functional Strength Training', at('2026-05-01', '07:00:00'), at('2026-05-01', '07:45:00'), 320)
]
}
};
const first = merge(emptyVitals(), parsePayload(body));
assert.equal(first.stats.workouts, 2);
assert.equal(first.doc.workouts[0].name, 'Walking', 'newest first (17:00 after 07:00)');
assert.equal(first.doc.workouts[0].durMin, 60);
assert.equal(first.doc.workouts[0].fields.activeEnergy.qty, 210);
assert.equal(first.doc.workouts[0].avgHr, 132, 'average of the heart-rate samples');
assert.equal(first.doc.workouts[0].maxHr, 172);
assert.equal(first.doc.workouts[1].name, 'Functional Strength Training');
assert.equal(first.doc.workouts[1].fields.activeEnergy.qty, 320);
const again = merge(first.doc, parsePayload(body));
assert.equal(again.stats.workouts, 0);
assert.equal(again.stats.duplicates, 2);
assert.equal(again.doc.workouts.length, 2);
});
/* ---------- housekeeping ---------- */
test('the dedupe ledger and the day buckets are both pruned, so the file stays bounded', () => {
const first = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:00:00') }])), NOW);
const seen = first.doc.metrics.step_count.seen;
assert.equal(Object.keys(seen).length, 1);
assert.equal(seen[Object.keys(seen)[0]], Date.parse('2026-05-01T09:00:00Z'));
// A sync a week later: last week's sample can no longer be a repeat, so its ledger row goes
// while the day it belongs to stays.
const later = merge(first.doc, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-08', '09:00:00') }])), Date.parse('2026-05-08T12:00:00Z')).doc;
assert.equal(Object.keys(later.metrics.step_count.seen).length, 1, 'the stale ledger row is gone');
assert.deepEqual(Object.keys(later.metrics.step_count.days), ['2026-05-01', '2026-05-08']);
// Days past retention are dropped.
const old = new Date(NOW - (RETENTION_DAYS + 30) * 86400000).toISOString().slice(0, 10);
const withOld = normalizeDoc({ metrics: { step_count: { days: { [old]: { n: 1, f: { qty: { n: 1, sum: 1, min: 1, max: 1, last: 1 } } } } } } });
const pruned = merge(withOld, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:00:00') }]))).doc;
assert.equal(pruned.metrics.step_count.days[old], undefined);
assert.ok(LEDGER_MS === 72 * 3600 * 1000 && RETENTION_DAYS > 365);
});
test('normalizeDoc survives a hand-edited or half-written file', () => {
const d = normalizeDoc({ metrics: { step_count: null, heart_rate: { days: 'nope', units: 7, sources: 'x' } }, workouts: 'nope' });
assert.deepEqual(d.workouts, []);
assert.deepEqual(Object.keys(d.metrics), ['heart_rate']);
assert.deepEqual(d.metrics.heart_rate.days, {});
assert.deepEqual(d.metrics.heart_rate.sources, []);
assert.equal(d.metrics.heart_rate.units, '');
assert.deepEqual(normalizeDoc(null).metrics, {});
});
/* ---------- reading it back ---------- */
test('vitalsSeries gives per-field totals, averages and a window, oldest day first', () => {
const body = {
data: {
metrics: [
{ name: 'step_count', units: 'count', data: [{ qty: 4000, date: at('2026-04-30') }, { qty: 6000, date: at('2026-05-01') }] },
{ name: 'heart_rate', units: 'bpm', data: [{ date: at('2026-05-01', '09:00:00'), Min: 55, Avg: 70, Max: 90 }] }
],
workouts: [{ name: 'Walking', start: at('2026-05-01', '09:00:00'), end: at('2026-05-01', '09:30:00'), activeEnergy: { qty: 100, units: 'kcal' } }]
}
};
const { doc } = merge(emptyVitals(), parsePayload(body));
const s = vitalsSeries(doc, { days: 90, now: NOW });
assert.deepEqual(s.metrics.step_count.days.map(d => d.day), ['2026-04-30', '2026-05-01']);
assert.deepEqual(s.metrics.step_count.days.map(d => d.f.qty.sum), [4000, 6000]);
assert.equal(s.metrics.heart_rate.days[0].f.Avg.avg, 70);
assert.equal(s.metrics.step_count.units, 'count');
assert.equal(s.workouts.length, 1);
// A one-day window keeps only the day inside it.
const narrow = vitalsSeries(doc, { days: 1, now: NOW });
assert.deepEqual(narrow.metrics.step_count.days.map(d => d.day), ['2026-05-01']);
});
+405
View File
@@ -0,0 +1,405 @@
/* vitals.js — Apple Health ingestion (Health Auto Export → KuentaGYM).
*
* The phone runs a "REST API" automation in Health Auto Export (HAE) that POSTs its JSON export
* to /api/vitals/ingest. This module is the whole of what happens to that payload: parse, fold
* into per-day buckets, merge with what is already stored, prune. Nothing here touches the
* filesystem or the network — server.js owns the file, this owns the arithmetic, which is what
* makes it testable without a phone (see test/vitals.test.js).
*
* ── Why this is not just "append the samples" ───────────────────────────────────────────────
*
* A five-minute automation re-sends overlapping windows: with Date Range = "Today" or the
* default ("previous day + today so far") every sync carries the whole day again, so appending
* would double every step count. With Date Range = "Since Last Sync" the windows are disjoint
* and *replacing* would throw away everything but the last five minutes. The same receiver 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:
*
* dayAggregated() every datapoint sits exactly on midnight
* → HAE already grouped by day ("Time Grouping: Days"), and a grouped day is a *total*:
* a day total only ever replaces another one. Wait, "replaces" is wrong for the current
* day, which legitimately grows all day long — and that is precisely why replacement is
* right here: the newer, larger total is the better answer, and re-sending the same
* number is a no-op. Idempotent by construction, no ledger needed.
*
* otherwise real timestamps (raw samples, or grouped by hour/minute/second)
* → union: a sample is identified by its instant plus its numbers and seen once. A repeat
* is skipped, a genuinely new sample is added. Overlapping and disjoint windows both
* come out right, because "have I seen this exact sample" is the question that does not
* depend on the window at all.
*
* The one configuration neither rule can fully rescue is grouping by *minutes* 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 its value is 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 the
* setup steps in docs/HEALTH.md say to group by Days. Being explicit about that beats a "smart"
* rule that silently miscounts a whole day.
*
* ── What a stored document looks like ────────────────────────────────────────────────────────
*
* Buckets are **per day, keyed by the day the phone wrote**, never by the server's own timezone:
* HAE stamps each sample with the phone's 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 day key is therefore
* taken straight from the payload's own date text.
*
* {
* v: 1, updatedAt: 1699999999999,
* last: { ts, metrics, points, duplicates, workouts, source },
* metrics: {
* step_count: {
* units: 'count', sources: ['iPhone'],
* days: { '2026-05-01': { n: 288, lastTs: 1699999999999,
* f: { qty: { sum, min, max, last, n } } } },
* seen: { '2026-05-01 13:05:00 +0200|qty:12': 1699999999999 }
* }
* },
* workouts: [ { name, start, end, durMin, fields: { activeEnergy: { qty, units } } } ]
* }
*
* Numeric fields are kept generically (`f`) rather than decoded per metric, because a health
* catalogue is wide and keeps growing: heart_rate carries Min/Avg/Max, blood_pressure carries
* systolic/diastolic, sleep carries asleep/inBed/core/deep/rem — and a metric this code has never
* heard of still lands in `f` under whatever HAE called it. Which field a *card* shows is a
* presentation decision, and it lives in frontend/src/lib/vitals-view.js with the labels. That
* split is deliberate: it means a metric added to HAE next year shows up without a server change.
*/
export const VITALS_VERSION = 1;
/** Ledger lives 72 h: the longest overlap a sane automation cadence can span. */
export const LEDGER_MS = 72 * 3600 * 1000;
/** Days kept per metric. A little over a year, so "same day last year" still exists. */
export const RETENTION_DAYS = 400;
export const MAX_WORKOUTS = 300;
/** Sources remembered per metric — decorative, but it answers "which watch sent this?" */
const MAX_SOURCES = 4;
const MAX_LEDGER_KEYS = 20000; // hard ceiling; the time-based prune is the real bound
export function emptyVitals() {
return { v: VITALS_VERSION, updatedAt: 0, last: null, metrics: {}, workouts: [] };
}
/** A stored document that is missing pieces (hand-edited, or written by an older version). */
export function normalizeDoc(doc) {
const d = doc && typeof doc === 'object' && !Array.isArray(doc) ? doc : {};
const out = {
v: VITALS_VERSION,
updatedAt: Number(d.updatedAt) || 0,
last: d.last && typeof d.last === 'object' ? d.last : null,
metrics: {},
workouts: Array.isArray(d.workouts) ? d.workouts.filter(w => w && typeof w === 'object') : []
};
const metrics = d.metrics && typeof d.metrics === 'object' && !Array.isArray(d.metrics) ? d.metrics : {};
for (const [name, m] of Object.entries(metrics)) {
if (!m || typeof m !== 'object') continue;
const days = m.days && typeof m.days === 'object' && !Array.isArray(m.days) ? m.days : {};
out.metrics[name] = {
units: typeof m.units === 'string' ? m.units : '',
sources: Array.isArray(m.sources) ? m.sources.filter(s => typeof s === 'string').slice(0, MAX_SOURCES) : [],
days,
seen: m.seen && typeof m.seen === 'object' && !Array.isArray(m.seen) ? m.seen : {}
};
}
return out;
}
/* ---------- parsing ---------- */
// HAE writes "2021-12-24 00:04:00 +0800", or "2021-12-24 3:04:05 PM -0700" when the phone is on
// a 12-hour clock — and that separator is U+202F (narrow no-break space), not a plain space, which
// is exactly the kind of thing that turns into NaN three weeks later. Both are normalised below.
const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{1,2}):(\d{2}):(\d{2})(?:[\s\u202f\u00a0]*([AaPp])\.?[Mm]\.?)?(?:[\s\u202f\u00a0]*([+-]\d{2}):?(\d{2})|Z)?$/;
/**
* Parse one HAE timestamp.
* @returns {{ms:number, day:string, time:string, raw:string}|null} `day` is the date the phone
* wrote (its own local day), `time` is "HH:MM:SS" in 24-hour form, `ms` an epoch instant.
*/
export function parseHaeDate(value) {
if (typeof value !== 'string') return null;
const raw = value.trim();
const m = DATE_RE.exec(raw);
if (!m) return null;
const [, y, mo, d, h, mi, s, ap, offH, offM] = m;
let hour = Number(h);
if (ap) {
// 12 AM is 00, 12 PM is 12 — the two hours the naive modulo gets wrong.
const pm = ap.toLowerCase() === 'p';
if (hour === 12) hour = pm ? 12 : 0;
else if (pm) hour += 12;
}
if (hour > 23 || Number(mi) > 59 || Number(s) > 59) return null;
const time = `${String(hour).padStart(2, '0')}:${mi}:${s}`;
const day = `${y}-${mo}-${d}`;
const offset = offH ? `${offH}:${offM || '00'}` : 'Z'; // no offset in the payload means UTC
const ms = Date.parse(`${day}T${time}${offset}`);
if (!Number.isFinite(ms)) return null;
return { ms, day, time, raw };
}
/** True when HAE grouped this datapoint onto a boundary rather than sampling it in real time. */
const isMidnight = t => t.time === '00:00:00';
// Fields on a datapoint that are not measurements. Everything else numeric is kept, so a metric
// this file has never seen still stores its numbers instead of being dropped.
const NON_VALUE_KEYS = new Set(['date', 'startDate', 'endDate', 'sleepStart', 'sleepEnd', 'inBedStart', 'inBedEnd', 'source', 'Source', 'value']);
const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null);
/** The numeric measurements on one datapoint, keyed exactly as HAE named them. */
export function fieldsOf(point) {
const out = {};
for (const [k, v] of Object.entries(point)) {
if (NON_VALUE_KEYS.has(k)) continue;
const n = num(v);
if (n != null) out[k] = n;
}
return out;
}
/** The instant of a datapoint: metrics carry `date`, sleep carries `sleepStart`/`startDate`. */
function instantOf(point) {
for (const k of ['date', 'sleepStart', 'startDate', 'inBedStart']) {
const t = parseHaeDate(point[k]);
if (t) return t;
}
return null;
}
const str = v => (typeof v === 'string' ? v : '');
/**
* Validate and normalise an HAE export body into what mergeVitals() expects.
*
* Version 2 wraps everything in `data`; the older flat shape puts the arrays at the top level and
* is accepted too, since it costs one line and a user pasting an old export should not get a
* blank page. A metric with `data: null` is normal (HAE sends the metric because it is selected
* but has no samples) and is dropped here rather than stored as an empty day.
*
* @throws {Error} with `.code` of 'shape' (not an export at all) or 'empty' (an export with
* nothing in it) — server.js turns both into a 400 that names the problem.
*/
export function parsePayload(body) {
if (!body || typeof body !== 'object' || Array.isArray(body)) throw err('shape');
const data = body.data && typeof body.data === 'object' && !Array.isArray(body.data) ? body.data : body;
const rawMetrics = Array.isArray(data.metrics) ? data.metrics : [];
const rawWorkouts = Array.isArray(data.workouts) ? data.workouts : [];
if (!rawMetrics.length && !rawWorkouts.length && !('metrics' in data) && !('workouts' in data)) throw err('shape');
const metrics = [];
for (const m of rawMetrics) {
if (!m || typeof m !== 'object') continue;
const name = str(m.name).trim();
if (!name) continue;
const points = [];
for (const p of Array.isArray(m.data) ? m.data : []) {
if (!p || typeof p !== 'object') continue;
const at = instantOf(p);
if (!at) continue; // a datapoint with no readable date is unusable
const fields = fieldsOf(p);
if (!Object.keys(fields).length) continue; // ...and so is one with no numbers
points.push({ at, fields, source: str(p.source) || str(p.Source) });
}
metrics.push({ name, units: str(m.units), points });
}
const workouts = [];
for (const w of rawWorkouts) {
if (!w || typeof w !== 'object') continue;
const name = str(w.name).trim();
const start = parseHaeDate(w.start);
if (!name || !start) continue;
const end = parseHaeDate(w.end);
const fields = {};
for (const [k, v] of Object.entries(w)) {
if (['name', 'start', 'end', 'route', 'heartRateData', 'heartRateRecovery'].includes(k)) continue;
const q = v && typeof v === 'object' && !Array.isArray(v) ? num(v.qty) : num(v);
if (q == null) continue;
fields[k] = { qty: q, units: v && typeof v === 'object' ? str(v.units) : '' };
}
const mins = end ? Math.round((end.ms - start.ms) / 60000) : null;
workouts.push({
name,
start: start.ms,
end: end ? end.ms : null,
day: start.day,
durMin: mins != null && mins >= 0 ? mins : null,
avgHr: hrAvg(w.heartRateData) ?? fields.heartRate?.qty ?? null,
maxHr: hrMax(w.heartRateData) ?? null,
fields
});
}
if (!metrics.length && !workouts.length) throw err('empty');
return { metrics, workouts };
}
const err = code => Object.assign(new Error(code), { code });
/** Average of HAE's per-second/minute workout heart-rate samples. */
function hrAvg(samples) {
if (!Array.isArray(samples) || !samples.length) return null;
const vals = samples.map(s => num(s?.Avg) ?? num(s?.qty)).filter(v => v != null);
if (!vals.length) return null;
return Math.round((vals.reduce((a, b) => a + b, 0) / vals.length) * 10) / 10;
}
function hrMax(samples) {
if (!Array.isArray(samples) || !samples.length) return null;
const vals = samples.map(s => num(s?.Max) ?? num(s?.qty)).filter(v => v != null);
return vals.length ? Math.max(...vals) : null;
}
/* ---------- merging ---------- */
/** Does this metric payload look like HAE's own day-by-day grouping? */
function dayGrouped(points) {
return points.length > 0 && points.every(p => isMidnight(p.at));
}
const dayKeyOk = k => /^\d{4}-\d{2}-\d{2}$/.test(k);
function addFields(bucket, fields) {
for (const [k, v] of Object.entries(fields)) {
const f = bucket.f[k] || (bucket.f[k] = { n: 0, sum: 0, min: v, max: v, last: v });
f.n++; f.sum += v;
if (v < f.min) f.min = v;
if (v > f.max) f.max = v;
f.last = v;
}
bucket.n++;
}
const bucketFrom = (fields, ts) => {
const b = { n: 0, lastTs: ts, f: {} };
addFields(b, fields);
return b;
};
/**
* Fold one parsed payload into a stored document. Pure: the input document is not modified.
*
* @returns {{doc:object, stats:{metrics:number, points:number, duplicates:number, workouts:number}}}
*/
export function mergeVitals(doc, payload, now = Date.now()) {
const out = normalizeDoc(doc);
const stats = { metrics: 0, points: 0, duplicates: 0, workouts: 0 };
for (const m of payload.metrics) {
if (!m.points.length) continue;
stats.metrics++;
const cur = out.metrics[m.name] || { units: '', sources: [], days: {}, seen: {} };
if (m.units) cur.units = m.units;
const replace = dayGrouped(m.points);
// The ledger is only consulted by the union path, and only for instants recent enough to be
// re-sent by the next automation run — anything older is pruned and can no longer be a repeat.
pruneLedger(cur.seen, now);
for (const p of m.points) {
const key = p.at.day;
if (!dayKeyOk(key)) continue;
if (p.source && !cur.sources.includes(p.source)) {
cur.sources = [p.source, ...cur.sources].slice(0, MAX_SOURCES);
}
if (replace) {
const prev = cur.days[key];
// Nothing to do when the phone re-sends the value we already have (the common case for
// every run after the first). `f` is compared as a whole because a day total and a
// once-a-day gauge both live in it.
if (prev && prev.n === 1 && sameFields(prev.f, p.fields)) { stats.duplicates++; continue; }
cur.days[key] = bucketFrom(p.fields, p.at.ms);
stats.points++;
continue;
}
const id = sampleId(p);
if (cur.seen[id] != null) { stats.duplicates++; continue; }
cur.seen[id] = p.at.ms;
addFields(cur.days[key] || (cur.days[key] = { n: 0, lastTs: p.at.ms, f: {} }), p.fields);
cur.days[key].lastTs = Math.max(cur.days[key].lastTs, p.at.ms);
stats.points++;
}
pruneLedger(cur.seen, now, true);
out.metrics[m.name] = cur;
}
if (payload.workouts.length) {
const seen = new Set(out.workouts.map(w => wkey(w)));
for (const w of payload.workouts) {
const k = wkey(w);
if (seen.has(k)) { stats.duplicates++; continue; }
seen.add(k);
out.workouts.push(w);
stats.workouts++;
}
// Newest first, and the oldest are dropped: a wrist that records every walk produces
// thousands of entries a year, and nobody scrolls past the last few hundred.
out.workouts.sort((a, b) => b.start - a.start);
if (out.workouts.length > MAX_WORKOUTS) out.workouts.length = MAX_WORKOUTS;
}
pruneDays(out, now);
out.updatedAt = now;
out.last = { ts: now, ...stats };
return { doc: out, stats };
}
const wkey = w => `${w.name}|${w.start}|${w.end ?? ''}`;
/** Same numbers as the stored bucket? `raw` is a payload's plain field map, `stored` a bucket's. */
function sameFields(stored, raw) {
const ka = Object.keys(stored), kb = Object.keys(raw);
if (ka.length !== kb.length) return false;
return ka.every(k => raw[k] === stored[k].last);
}
/** A sample's identity: when it happened plus what it says. */
function sampleId(p) {
const f = Object.keys(p.fields).sort().map(k => `${k}:${p.fields[k]}`).join(',');
return `${p.at.raw}|${f}`;
}
function pruneLedger(seen, now, enforceCap = false) {
for (const [k, ts] of Object.entries(seen)) if (now - ts > LEDGER_MS) delete seen[k];
if (!enforceCap) return;
const keys = Object.keys(seen);
if (keys.length <= MAX_LEDGER_KEYS) return;
// Oldest first — a repeat can only be recent, so the tail is what may be given up.
keys.sort((a, b) => seen[a] - seen[b]);
for (const k of keys.slice(0, keys.length - MAX_LEDGER_KEYS)) delete seen[k];
}
function pruneDays(doc, now) {
const oldest = new Date(now - RETENTION_DAYS * 86400000).toISOString().slice(0, 10);
for (const m of Object.values(doc.metrics)) {
for (const day of Object.keys(m.days)) if (day < oldest) delete m.days[day];
}
}
/* ---------- reading ---------- */
/**
* Project a stored document into the compact series the view renders, oldest day first.
* Aggregates are per *field* — `qty.sum` for a counter, `Avg.last` for a rate — so the client
* never has to know how HAE grouped things.
*/
export function vitalsSeries(doc, { days = 90, now = Date.now() } = {}) {
const d = normalizeDoc(doc);
// `days` counts calendar days *including today*, so `days: 1` is today alone. Day keys are the
// phone's own local dates (see the header), which is why this is a plain string comparison
// rather than an instant one: an evening sample in Manila and one in Lima each keep their own
// day, and neither is dragged across a boundary by the server's timezone.
const from = new Date(now - Math.max(0, days - 1) * 86400000).toISOString().slice(0, 10);
const metrics = {};
for (const [name, m] of Object.entries(d.metrics)) {
const out = [];
for (const day of Object.keys(m.days).sort()) {
if (day < from) continue;
const b = m.days[day];
const f = {};
for (const [k, v] of Object.entries(b.f || {})) {
f[k] = { n: v.n, sum: v.sum, min: v.min, max: v.max, last: v.last, avg: v.n ? v.sum / v.n : null };
}
out.push({ day, n: b.n, lastTs: b.lastTs, f });
}
if (out.length) metrics[name] = { units: m.units, sources: m.sources, days: out };
}
return { updatedAt: d.updatedAt, last: d.last, metrics, workouts: d.workouts };
}
+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.
+5
View File
@@ -30,6 +30,7 @@ import Plan from './views/Plan.jsx'
import RoutineEdit from './views/RoutineEdit.jsx'
import Workout from './views/Workout.jsx'
import Stats from './views/Stats.jsx'
import Health from './views/Health.jsx'
import History from './views/History.jsx'
import Library from './views/Library.jsx'
import Muscles from './views/Muscles.jsx'
@@ -159,6 +160,10 @@ function Shell() {
<Route path="/plan/r/:id" element={<RoutineEdit />} />
<Route path="/workout" element={<Workout />} />
<Route path="/stats" element={<Stats />} />
{/* Apple Health metrics the iPhone posts in (api/vitals.js). Read-only, and
per profile: the route is reachable by guest mode too, where it explains how to
connect rather than pretending there is data. */}
<Route path="/health" element={<Health />} />
<Route path="/history" element={<History />} />
<Route path="/library" element={<Library />} />
<Route path="/muscles" element={<Muscles />} />
+3 -1
View File
@@ -14,7 +14,6 @@ export default function TabBar({ onStart }) {
if (!user && !isGuest) return null
const cur = loc.pathname.split('/')[1] || 'home'
const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home') || (cur === 'muscles' && k === 'library')
const startWorkout = () => {
if (!S.active) {
// A weekday can hold several routines; start the combined session if any of them has
@@ -33,6 +32,9 @@ export default function TabBar({ onStart }) {
<nav id="tabbar">
<Tab k="home" icon="house" to="/home" label={t('Home')} />
<Tab k="plan" icon="calendar" to="/plan" label={t('Plan')} />
{/* Apple Health. Next to Plan because both answer "what am I doing about my body", and
second in the bar (not last) because it is a place you go on purpose, not a drawer. */}
<Tab k="health" icon="heart" to="/health" label={t('Health')} />
{/* On the workout screen itself there is nothing to resume, so the button reads as the
tab it is and stays lit (#29); anywhere else it brings you back to the exercise you
were on — the marker is kept in S.active.cur and never moves on its own (#21). */}
+29
View File
@@ -1252,6 +1252,35 @@ body.chips-dragging *{cursor:inherit}
.tile .v{font-size:26px;font-weight:600;letter-spacing:-.026em;margin-top:5px;line-height:1.1}
.tile.tappable:active{background:var(--surface-2)}
/* --- Salud (Apple Health cards) --------------------------------------------
A health card is a tile with three more things in it: a unit, a trend arrow and a four-point
sparkline. The sparkline is what makes the grid readable at a glance — a bare "12,481" says
nothing about whether that is a good week — so it gets its own fixed-height box rather than
being allowed to stretch the card when a metric has only one day of data. */
.vh-card{width:100%;text-align:left;display:block;font:inherit;color:inherit;padding-bottom:10px}
.vh-unit{margin-left:4px;font-size:14px;font-weight:500;color:var(--label-2);letter-spacing:0}
.vh-trend{
float:right;display:inline-flex;align-items:center;gap:1px;
font-size:13px;font-weight:500;letter-spacing:0;
}
.vh-trend .icn{font-size:13px;--icon-stroke:2.2}
.vh-spark{margin:2px -6px -4px;height:36px;overflow:hidden}
.vh-spark-ph{height:36px}
.vh-sheet-top{margin:2px 0 12px}
.vh-chart{padding:6px 4px 2px;margin-bottom:4px}
/* The endpoint and the header are long single tokens: wrap them instead of letting the row
scroll the whole sheet sideways. */
.vh-code{
flex:1;min-width:0;display:block;word-break:break-all;
font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;line-height:1.45;
background:var(--surface-2);color:var(--label);border-radius:var(--r-sm);padding:7px 9px;
}
.vh-err{display:flex;flex-direction:column;align-items:flex-start;gap:4px;color:var(--orange)}
.vh-err .icn{font-size:16px}
.vh-empty{text-align:left}
.vh-empty .ico{font-size:30px;color:var(--acc);display:flex;justify-content:center;margin:4px 0 10px}
/* --- PR badge --- */
.pr{
display:inline-flex;align-items:center;gap:4px;
+10 -1
View File
@@ -26,6 +26,14 @@ const LABELS = {
'auth.pair.create': 'Created a pairing code',
'auth.pair.ok': 'Paired a phone',
'auth.pair.fail': 'Pairing failed',
// Apple Health (Salud): a phone syncing on its own, and the credential it uses. Filed under
// auth.* because that is what they are — a device coming online, and a key minted or retired
// for it — and because the first segment of an event name is also its filter category.
'auth.health.ingest': 'Apple Health sync failed',
'auth.health.ingest.first': 'Started syncing Apple Health',
'auth.health.key.create': 'Created a health ingest key',
'auth.health.key.rotate': 'Replaced the health ingest key',
'auth.health.clear': 'Deleted their health data',
'admin.user.disable': 'Disabled an account',
'admin.user.enable': 'Re-enabled an account',
'admin.user.delete': 'Deleted an account',
@@ -49,7 +57,8 @@ const REASONS = {
'invite-invalid': 'the invite code was used or revoked in the meantime',
'invite-rejected': 'wrong or already-used invite code',
'code-invalid': 'wrong or expired pairing code',
'user-unavailable': 'the profile behind the pairing code is disabled or gone'
'user-unavailable': 'the profile behind the pairing code is disabled or gone',
'bad-payload': 'the body was not a Health Auto Export JSON export'
}
export const auditReason = msg => REASONS[msg] || (msg ? String(msg) : '')
+355
View File
@@ -0,0 +1,355 @@
/* vitals-view.js — turn the stored health aggregates into the cards the Salud view renders.
*
* Everything here is a pure function of the document `GET /api/vitals` returns, which is why it
* is a lib and not inline in the view: the mapping from "what HAE calls a metric" to "what the
* card says" is the part that has to be right for a hundred metrics, and it is much easier to
* test than to click through.
*
* The server stores numbers per *field* without interpreting them (`f: { Avg: {min,sum,max,last} }`),
* on purpose: heart rate arrives as Min/Avg/Max, blood pressure as systolic/diastolic, sleep as
* asleep/inBed/core/deep/rem, and a metric that did not exist when this file was written arrives
* as whatever HAE decided to call it. The catalogue below is the only place that says which of
* those numbers a human wants to see first — so adding a metric is a line here, and losing none.
*/
import { t } from './i18n-core.js'
import { fmtDur, fmtDate } from './format.js'
/** Group order on the screen. Anything not in the catalogue lands in 'other', at the end. */
export const GROUP_ORDER = ['activity', 'heart', 'body', 'sleep', 'vitals', 'other']
const GROUP_LABEL = {
activity: 'Activity', heart: 'Heart', body: 'Body', sleep: 'Sleep', vitals: 'Vitals', other: 'Other'
}
const spec = (label, group, o = {}) => ({
label,
group,
// `field` is a candidate list because the same logical metric is spelled differently by HAE's
// own settings: an aggregated night is `asleep` (hours), a segmented one is `qty` per segment.
fields: [].concat(o.field || 'qty'),
agg: o.agg || 'sum',
unit: o.unit || '',
icon: o.icon || 'dot',
dec: o.dec == null ? 0 : o.dec,
better: o.better || null // 'down' for resting heart rate, 'up' for VO2 max, null = neutral
})
/* The catalogue. Names are HAE's snake_case metric keys as they appear in the JSON export
("Metric Name Format: All metric names use snake_case"). Unknown names are still shown —
humanized, in 'Other' — so an export of everything stays useful the day it arrives. */
export const METRICS = {
// — activity —
step_count: spec('Steps', 'activity', { unit: 'steps', icon: 'figureRun' }),
distance_walking_running: spec('Distance', 'activity', { unit: 'km', dec: 2, icon: 'figureRun' }),
walking_running_distance: spec('Distance', 'activity', { unit: 'km', dec: 2, icon: 'figureRun' }),
flights_climbed: spec('Flights climbed', 'activity', { unit: 'flights', icon: 'arrowUp' }),
apple_exercise_time: spec('Exercise time', 'activity', { unit: 'min', icon: 'timer' }),
apple_stand_time: spec('Stand time', 'activity', { unit: 'min', icon: 'clock' }),
apple_stand_hour: spec('Stand hours', 'activity', { unit: 'h', icon: 'clock' }),
active_energy: spec('Active energy', 'activity', { unit: 'kcal', icon: 'flame', better: 'up' }),
basal_energy_burned: spec('Resting energy', 'activity', { unit: 'kcal', icon: 'flame' }),
physical_effort: spec('Physical effort', 'activity', { unit: '', dec: 1, agg: 'avg', icon: 'bolt' }),
time_in_daylight: spec('Time in daylight', 'activity', { unit: 'min', icon: 'sun' }),
mindful_minutes: spec('Mindful minutes', 'activity', { unit: 'min', icon: 'moon' }),
// — heart —
heart_rate: spec('Heart rate', 'heart', { field: 'Avg', agg: 'avg', unit: 'bpm', icon: 'heart' }),
resting_heart_rate: spec('Resting heart rate', 'heart', { agg: 'avg', unit: 'bpm', icon: 'heart', better: 'down' }),
walking_heart_rate_average: spec('Walking heart rate', 'heart', { agg: 'avg', unit: 'bpm', icon: 'heart', better: 'down' }),
heart_rate_variability: spec('Heart rate variability', 'heart', { agg: 'avg', unit: 'ms', icon: 'bolt', better: 'up' }),
heart_rate_recovery_one_minute: spec('Heart rate recovery', 'heart', { agg: 'avg', unit: 'bpm', icon: 'reset', better: 'up' }),
vo2_max: spec('VO₂ max', 'heart', { dec: 1, icon: 'rocket', better: 'up' }),
cardio_recovery: spec('Cardio recovery', 'heart', { agg: 'avg', unit: 'bpm', icon: 'reset', better: 'up' }),
atrial_fibrillation_burden: spec('AFib burden', 'heart', { agg: 'avg', unit: '%', dec: 1, icon: 'warning', better: 'down' }),
// — body —
weight_body_mass: spec('Weight', 'body', { agg: 'last', unit: 'kg', dec: 1, icon: 'scale' }),
body_mass_index: spec('BMI', 'body', { agg: 'last', dec: 1, icon: 'scale' }),
body_fat_percentage: spec('Body fat', 'body', { agg: 'last', unit: '%', dec: 1, icon: 'scale', better: 'down' }),
lean_body_mass: spec('Lean mass', 'body', { agg: 'last', unit: 'kg', dec: 1, icon: 'arm' }),
waist_circumference: spec('Waist', 'body', { agg: 'last', unit: 'cm', dec: 1, icon: 'scale', better: 'down' }),
height: spec('Height', 'body', { agg: 'last', unit: 'cm', icon: 'person' }),
basal_body_temperature: spec('Basal temperature', 'body', { agg: 'last', unit: '°C', dec: 2, icon: 'flame' }),
apple_sleeping_wrist_temperature: spec('Wrist temperature', 'body', { agg: 'last', unit: '°C', dec: 2, icon: 'flame' }),
// — sleep — (`asleep` when HAE aggregates the night, `qty` when it sends the segments)
sleep_analysis: spec('Sleep', 'sleep', { field: ['asleep', 'qty'], unit: 'h', dec: 1, icon: 'moon' }),
sleep_rem: spec('REM sleep', 'sleep', { agg: 'last', unit: 'h', dec: 1, icon: 'moon' }),
sleep_core: spec('Core sleep', 'sleep', { agg: 'last', unit: 'h', dec: 1, icon: 'moon' }),
sleep_deep: spec('Deep sleep', 'sleep', { agg: 'last', unit: 'h', dec: 1, icon: 'moon' }),
// — vitals —
oxygen_saturation: spec('Blood oxygen', 'vitals', { agg: 'avg', unit: '%', dec: 0, icon: 'target', better: 'up' }),
respiratory_rate: spec('Respiratory rate', 'vitals', { agg: 'avg', unit: 'breaths/min', dec: 1, icon: 'bolt' }),
blood_pressure_systolic: spec('Blood pressure', 'vitals', { agg: 'last', unit: 'mmHg', icon: 'heart', better: 'down' }),
blood_pressure_diastolic: spec('Blood pressure (diastolic)', 'vitals', { agg: 'last', unit: 'mmHg', icon: 'heart', better: 'down' }),
body_temperature: spec('Body temperature', 'vitals', { agg: 'last', unit: '°C', dec: 2, icon: 'flame' }),
blood_glucose: spec('Blood glucose', 'vitals', { agg: 'last', unit: 'mg/dL', icon: 'target' }),
water: spec('Water', 'vitals', { unit: 'L', dec: 2, icon: 'download', better: 'up' }),
dietary_water: spec('Water', 'vitals', { unit: 'L', dec: 2, icon: 'download', better: 'up' }),
uv_exposure: spec('UV exposure', 'vitals', { dec: 1, icon: 'sun' }),
environmental_audio_exposure: spec('Ambient sound', 'vitals', { agg: 'avg', unit: 'dB', icon: 'bolt' }),
headphone_audio_exposure: spec('Headphone level', 'vitals', { agg: 'avg', unit: 'dB', icon: 'bolt', better: 'down' }),
walking_steadiness: spec('Walking steadiness', 'vitals', { agg: 'last', unit: '%', icon: 'figureRun', better: 'up' }),
walking_speed: spec('Walking speed', 'vitals', { agg: 'avg', unit: 'km/h', dec: 1, icon: 'figureRun', better: 'up' }),
walking_step_length: spec('Step length', 'vitals', { agg: 'avg', unit: 'cm', dec: 1, icon: 'figureRun' }),
walking_asymmetry_percentage: spec('Walking asymmetry', 'vitals', { agg: 'avg', unit: '%', dec: 1, icon: 'figureRun', better: 'down' }),
walking_double_support_percentage: spec('Double support', 'vitals', { agg: 'avg', unit: '%', dec: 1, icon: 'figureRun' }),
stair_speed_up: spec('Stair speed up', 'vitals', { agg: 'avg', icon: 'arrowUp' }),
stair_speed_down: spec('Stair speed down', 'vitals', { agg: 'avg', icon: 'arrowDown' })
}
const AGG = {
sum: f => f.sum,
avg: f => f.avg,
last: f => f.last,
min: f => f.min,
max: f => f.max
}
/** "walking_steadiness" → "Walking steadiness", for a metric the catalogue has never heard of. */
export function humanize(name) {
const s = String(name || '').replace(/_/g, ' ').trim()
return s ? s[0].toUpperCase() + s.slice(1) : ''
}
/** The catalogue entry for a metric name, with an honest fallback for anything unknown. */
export function specOf(name) {
if (METRICS[name]) return METRICS[name]
return { label: humanize(name), group: 'other', fields: null, agg: null, unit: '', icon: 'dot', dec: 1, better: null, unknown: true }
}
/**
* One day's number for one metric.
*
* A known metric uses its catalogue rule. An unknown one shows the field with the most samples
* that day — the number the watch actually measured most often — falling back to whichever field
* is there, so nothing is hidden just because nobody wrote a rule for it.
*/
export function valueOfDay(day, s) {
const f = (day && day.f) || {}
const keys = Object.keys(f)
if (!keys.length) return null
if (s.fields) {
const field = s.fields.find(k => f[k] && (AGG[s.agg] || AGG.sum)(f[k]) != null)
if (field) return (AGG[s.agg] || AGG.sum)(f[field])
}
if (s.unknown) {
const best = keys.slice().sort((a, b) => (f[b].n || 0) - (f[a].n || 0))[0]
return f[best].avg ?? f[best].last ?? f[best].sum ?? null
}
return null
}
/** How many days of samples a metric's series covers, for the "n days" captions. */
const pointsOf = series => series.reduce((n, p) => n + (p.n || 0), 0)
/**
* Every metric that has data, as a card.
*
* `delta` compares the newest day with the mean of the other days in the window, not with the day
* before it: one bad morning is not a trend, and a single-day comparison makes the arrow flip
* every time somebody sleeps badly. `trendDays` says how many days went into that mean, so the
* view can stay quiet on a card built from one day.
*/
export function metricCards(data, { days = 90 } = {}) {
const metrics = (data && data.metrics) || {}
const cards = []
for (const [name, m] of Object.entries(metrics)) {
const s = specOf(name)
const series = ((m && m.days) || [])
.map(d => ({ day: d.day, v: valueOfDay(d, s), n: d.n || 0 }))
.filter(p => p.v != null && Number.isFinite(p.v))
if (!series.length) continue
const latest = series[series.length - 1]
const prior = series.slice(0, -1)
const mean = prior.length ? prior.reduce((a, p) => a + p.v, 0) / prior.length : null
cards.push({
name,
label: s.unknown ? s.label : t(s.label),
group: s.group,
unit: s.unit || (m && m.units) || '',
icon: s.icon,
dec: s.dec,
better: s.better,
unknown: !!s.unknown,
value: latest.v,
day: latest.day,
delta: mean != null && mean !== 0 ? (latest.v - mean) / Math.abs(mean) : null,
avg: mean,
trendDays: prior.length,
series,
total: series.reduce((a, p) => a + p.v, 0),
samples: pointsOf(series),
sources: (m && m.sources) || [],
days: series.length,
requestedDays: days
})
}
return sortCards(cards)
}
/** Catalogue order first (Activity, Heart, Body…), then the unknowns alphabetically. Stable. */
export function sortCards(cards) {
const rank = new Map()
Object.keys(METRICS).forEach((k, i) => rank.set(k, i))
return cards.slice().sort((a, b) => {
const ga = GROUP_ORDER.indexOf(a.group), gb = GROUP_ORDER.indexOf(b.group)
if (ga !== gb) return ga - gb
const ra = rank.has(a.name) ? rank.get(a.name) : 1e6
const rb = rank.has(b.name) ? rank.get(b.name) : 1e6
if (ra !== rb) return ra - rb
return a.label.localeCompare(b.label)
})
}
/** Cards bucketed for rendering: only the groups that actually have something in them. */
export function groupedCards(cards) {
return GROUP_ORDER
.map(group => ({ group, label: t(GROUP_LABEL[group]), cards: cards.filter(c => c.group === group) }))
.filter(g => g.cards.length)
}
/** Which way the arrow should point, or null when the metric has no better direction. */
export function trendOf(card) {
if (!card || card.delta == null || card.trendDays < 1 || Math.abs(card.delta) < 0.005) return null
const dir = card.delta > 0 ? 'up' : 'down'
const good = card.better ? (card.better === dir ? 'good' : 'bad') : 'flat'
return { dir, good, pct: Math.abs(card.delta) }
}
/** A card's series shaped for LineChart: one point per day, x = that day's noon. */
export function chartPoints(card) {
return (card?.series || []).map(p => ({ t: Date.parse(p.day + 'T12:00:00'), y: p.v, d: p.day }))
}
/* ---------- units and numbers ---------- */
// HAE's unit strings are compact and sometimes need a human spelling. Values are never converted:
// what the watch measured is what is shown, so a card can never disagree with the Health app.
const UNIT_LABEL = {
count: '', 'count/min': 'bpm', bpm: 'bpm', hr: 'h', min: 'min', kcal: 'kcal', kJ: 'kJ',
kg: 'kg', lb: 'lb', km: 'km', mi: 'mi', m: 'm', cm: 'cm', '%': '%', degC: '°C', degF: '°F',
mmHg: 'mmHg', ms: 'ms', L: 'L', mL: 'mL', 'mg/dL': 'mg/dL', dB: 'dB', flights: 'flights'
}
export const unitLabel = u => (u && UNIT_LABEL[u] != null ? UNIT_LABEL[u] : (u || ''))
/** Numbers are formatted for reading, with the metric's own precision — not the weight setting. */
export function fmtValue(v, dec = 0) {
if (v == null || !Number.isFinite(v)) return '—'
const p = Math.pow(10, dec)
const n = Math.round(v * p) / p
return n.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: dec })
}
/** A day's worth of gap since the last sample, for "last sync" captions. */
export function agoLabel(ts, now = Date.now()) {
if (!ts) return ''
const mins = Math.round((now - ts) / 60000)
if (mins < 2) return t('just now')
if (mins < 60) return t('{0} min ago', mins)
const hours = Math.round(mins / 60)
if (hours < 24) return t('{0} h ago', hours)
return t('{0} d ago', Math.round(hours / 24))
}
/* ---------- the fields behind a card ---------- */
const FIELD_LABEL = {
qty: 'Value', Avg: 'Average', Min: 'Minimum', Max: 'Maximum', sum: 'Total',
asleep: 'Asleep', inBed: 'In bed', awake: 'Awake',
// The sleep stages borrow the metric labels rather than a bare 'Core'/'REM': those keys already
// mean something else in the catalogue (the core muscle group), and a translation key cannot
// mean two things in two screens.
core: 'Core sleep', deep: 'Deep sleep', rem: 'REM sleep',
systolic: 'Systolic', diastolic: 'Diastolic', value: 'Value'
}
const fieldLabel = k => (FIELD_LABEL[k] ? t(FIELD_LABEL[k]) : humanize(k))
/**
* The detail rows for a card's newest day: every field the metric actually carried, with its
* aggregate for that day. This is what makes an unrecognised metric legible — the sheet shows the
* numbers HAE sent under the names HAE used, instead of a card that says "Other: 91".
*/
export function detailRows(card, day, m) {
const stored = ((m && m.days) || []).find(d => d.day === (day || card.day))
if (!stored) return []
const s = specOf(card.name)
const primary = s.fields ? s.fields.find(k => stored.f[k]) : null
return Object.entries(stored.f).map(([k, f]) => ({
key: k,
label: fieldLabel(k),
// The aggregate is per field: a counter's day is its total, a rate's is its average.
value: k === primary || s.unknown
? ((AGG[s.agg] || AGG.sum)(f) ?? f.last)
: f.avg,
agg: k === primary || s.unknown ? (s.agg || 'sum') : 'avg',
min: f.min, max: f.max, n: f.n,
unit: card.unit
}))
}
/* ---------- workouts ---------- */
// HAE names the activity the way Apple does, in Title Case and sometimes with a long tail.
export const workoutIcon = name => {
const n = String(name || '').toLowerCase()
if (/strength|weight|functional|core|hiit|cross/.test(n)) return 'dumbbell'
if (/run|walk|hik|sprint/.test(n)) return 'figureRun'
if (/cycl|bike|spin/.test(n)) return 'bike'
if (/swim/.test(n)) return 'swim'
if (/yoga|pilates|flexib|stretch|cooldown|mind/.test(n)) return 'stretch'
if (/box|kick|martial/.test(n)) return 'boxing'
if (/row|elliptical|stair|ski/.test(n)) return 'machine'
return 'bolt'
}
/**
* The read-only list of what the watch recorded, newest first.
*
* These are deliberately NOT the app's own sessions: they carry no sets, no weights and no reps,
* so folding them into the workout history would put entries into volume, PRs and the recovery
* model that nothing in them can support. They are shown here, next to the metrics they came with.
*/
export function workoutRows(data, { limit = 25 } = {}) {
return ((data && data.workouts) || []).slice(0, limit).map(w => {
const f = w.fields || {}
const energy = f.activeEnergy?.qty ?? f.totalEnergy?.qty ?? null
const units = f.activeEnergy?.units || f.totalEnergy?.units || 'kcal'
const dist = f.distance?.qty ?? null
const distUnits = f.distance?.units || 'km'
return {
key: `${w.name}|${w.start}`,
name: w.name,
icon: workoutIcon(w.name),
day: w.day,
date: fmtDate(w.day),
dur: w.durMin ? fmtDur(w.durMin * 60000) : '',
energy: energy != null ? `${fmtValue(energy, 0)} ${unitLabel(units)}` : '',
distance: dist != null ? `${fmtValue(dist, 2)} ${unitLabel(distUnits)}` : '',
avgHr: w.avgHr != null ? `${fmtValue(w.avgHr, 0)} bpm` : '',
maxHr: w.maxHr != null ? `${fmtValue(w.maxHr, 0)} bpm` : ''
}
})
}
/* ---------- whole-document helpers ---------- */
export const hasVitals = data => !!data && Object.keys(data.metrics || {}).length > 0
/** Which days in the window have anything at all — the strip at the top of the view. */
export function activeDays(data) {
const set = new Set()
for (const m of Object.values((data && data.metrics) || {})) for (const d of m.days || []) set.add(d.day)
return [...set].sort()
}
/**
* The ingest URL to paste into Health Auto Export. Absolute, because the phone is not the page:
* `appBase()` alone would be a path on a device that has never heard of this host.
*/
export function ingestUrl(loc = typeof location !== 'undefined' ? location : null) {
if (!loc) return '/api/vitals/ingest'
const path = (loc.pathname || '/')
const base = path.slice(0, path.lastIndexOf('/') + 1) || '/'
return `${loc.origin || ''}${base}api/vitals/ingest`.replace(/([^:]\/)\/+/g, '$1')
}
+206
View File
@@ -0,0 +1,206 @@
import { describe, it, expect } from 'vitest'
import {
METRICS, specOf, humanize, valueOfDay, metricCards, sortCards, groupedCards, trendOf,
chartPoints, workoutRows, hasVitals, activeDays, ingestUrl, unitLabel, fmtValue, agoLabel,
detailRows, workoutIcon
} from './vitals-view.js'
/* The mapping from HAE's metric names to what a card shows. Worth testing because it is the one
place that decides which number out of Min/Avg/Max a human sees, and because an export of
"everything" is guaranteed to contain metrics nobody has written a rule for yet. */
/** A stored day bucket the way the server writes one. */
const day = (d, f, n = 1) => ({ day: d, n, f })
const bucket = v => ({ n: 1, sum: v, min: v, max: v, last: v, avg: v })
const doc = {
updatedAt: Date.parse('2026-05-04T10:00:00Z'),
last: { ts: Date.parse('2026-05-04T10:00:00Z'), metrics: 3, points: 3, duplicates: 0, workouts: 1 },
metrics: {
step_count: {
units: 'count', sources: ['Apple Watch'],
days: [day('2026-05-01', { qty: bucket(5000) }), day('2026-05-02', { qty: bucket(7000) }), day('2026-05-03', { qty: bucket(12000) })]
},
heart_rate: {
units: 'bpm',
days: [day('2026-05-03', {
Min: { n: 288, sum: 16000, min: 52, max: 62, last: 58, avg: 55.6 },
Avg: { n: 288, sum: 20000, min: 55, max: 96, last: 72, avg: 69.4 },
Max: { n: 288, sum: 26000, min: 80, max: 140, last: 120, avg: 90.3 }
})]
},
weight_body_mass: { units: 'kg', days: [day('2026-05-03', { qty: bucket(80.4) })] },
sleep_analysis: { units: 'hr', days: [day('2026-05-03', { asleep: bucket(7.4), deep: bucket(1.2) })] },
resting_heart_rate: { units: 'bpm', days: [day('2026-05-02', { qty: bucket(58) }), day('2026-05-03', { qty: bucket(52) })] },
some_new_metric: {
units: '%',
days: [day('2026-05-03', { qty: bucket(91), confidence: { n: 3, sum: 1.5, min: 0.4, max: 0.6, last: 0.5, avg: 0.5 } })]
}
},
workouts: [
{ name: 'Functional Strength Training', day: '2026-05-03', start: 1, end: 2, durMin: 45, avgHr: 128.4, maxHr: 172, fields: { activeEnergy: { qty: 320, units: 'kcal' }, distance: { qty: 3.25, units: 'km' } } },
{ name: 'Outdoor Walk', day: '2026-05-02', start: 0, end: 1, durMin: 30, avgHr: null, maxHr: null, fields: {} }
]
}
const card = (data, name) => metricCards(data).find(c => c.name === name)
describe('metricCards', () => {
it('reads the number its catalogue entry names, not the first one in the object', () => {
expect(card(doc, 'heart_rate').value).toBe(69.4) // the day's average, not Min or Max
expect(card(doc, 'heart_rate').unit).toBe('bpm')
expect(card(doc, 'step_count').value).toBe(12000) // the day's total
expect(card(doc, 'weight_body_mass').value).toBe(80.4) // the last reading
expect(card(doc, 'sleep_analysis').value).toBe(7.4) // hours asleep, not the deep stage
expect(card(doc, 'resting_heart_rate').value).toBe(52)
})
it('lands a segmented sleep payload on the same card as an aggregated one', () => {
// `asleep` for an aggregated night, `qty` per segment when HAE summarisation is off.
const segmented = { metrics: { sleep_analysis: { units: 'hr', days: [day('2026-05-03', { qty: { n: 6, sum: 7.1, min: 0.4, max: 2, last: 1.1, avg: 1.18 } })] } } }
expect(card(segmented, 'sleep_analysis').value).toBe(7.1)
})
it('humanizes an unknown metric, puts it in Other, and shows the field with the most samples', () => {
const c = card(doc, 'some_new_metric')
expect(c.label).toBe('Some new metric')
expect(c.group).toBe('other')
expect(c.value).toBe(0.5) // three samples of `confidence` beat one of `qty`
expect(c.unknown).toBe(true)
expect(c.name in METRICS).toBe(false)
expect(specOf('nope_not_a_metric').group).toBe('other')
expect(humanize('walking_steadiness')).toBe('Walking steadiness')
expect(humanize('')).toBe('')
})
it('does not render a card of dashes when the field a metric needs never appeared', () => {
const odd = { metrics: { blood_pressure_systolic: { units: 'mmHg', days: [day('2026-05-03', { diastolic: bucket(82) })] } } }
expect(valueOfDay(odd.metrics.blood_pressure_systolic.days[0], specOf('blood_pressure_systolic'))).toBeNull()
expect(metricCards(odd)).toEqual([])
expect(hasVitals({ metrics: {} })).toBe(false)
expect(hasVitals(doc)).toBe(true)
expect(hasVitals(null)).toBe(false)
})
it('is ordered by group, catalogue metrics before unknowns, and stable', () => {
const cards = metricCards(doc)
expect(cards.map(c => c.group)).toEqual(['activity', 'heart', 'heart', 'body', 'sleep', 'other'])
expect(groupedCards(cards).map(g => g.group)).toEqual(['activity', 'heart', 'body', 'sleep', 'other'])
expect(groupedCards(cards).map(g => g.cards.length)).toEqual([1, 2, 1, 1, 1])
expect(cards.filter(c => c.group === 'heart').map(c => c.name)).toEqual(['heart_rate', 'resting_heart_rate'])
expect(sortCards([{ name: 'b', label: 'B', group: 'other' }, { name: 'a', label: 'A', group: 'other' }]).map(c => c.label)).toEqual(['A', 'B'])
})
it('carries the days, samples and sources a card caption needs', () => {
const steps = card(doc, 'step_count')
expect(steps.days).toBe(3)
expect(steps.samples).toBe(3)
expect(steps.total).toBe(24000)
expect(steps.sources).toEqual(['Apple Watch'])
expect(steps.day).toBe('2026-05-03')
expect(steps.requestedDays).toBe(90)
})
})
describe('trendOf', () => {
it('compares the newest day with the average of the window', () => {
const steps = card(doc, 'step_count')
expect(steps.delta).toBeCloseTo(1, 10) // 12000 against a 6000 mean
expect(steps.trendDays).toBe(2)
expect(trendOf(steps)).toEqual({ dir: 'up', good: 'flat', pct: 1 }) // steps have no better way
})
it('knows which direction is the good one', () => {
expect(trendOf(card(doc, 'resting_heart_rate'))).toMatchObject({ dir: 'down', good: 'good' })
})
it('stays quiet with one day of data, or with a change under half a percent', () => {
const weight = card(doc, 'weight_body_mass')
expect(weight.delta).toBeNull()
expect(weight.trendDays).toBe(0)
expect(trendOf(weight)).toBeNull()
const flat = metricCards({ metrics: { step_count: { units: 'count', days: [day('2026-05-01', { qty: bucket(10000) }), day('2026-05-02', { qty: bucket(10020) })] } } })[0]
expect(trendOf(flat)).toBeNull()
})
})
describe('chartPoints', () => {
it('is one point per day at noon, which is what LineChart wants', () => {
const pts = chartPoints(card(doc, 'step_count'))
expect(pts.map(p => p.d)).toEqual(['2026-05-01', '2026-05-02', '2026-05-03'])
expect(pts.map(p => p.y)).toEqual([5000, 7000, 12000])
expect(pts[0].t).toBe(Date.parse('2026-05-01T12:00:00'))
expect(chartPoints(null)).toEqual([])
})
})
describe('detailRows', () => {
it('shows every field HAE sent, under the name HAE used', () => {
const rows = detailRows(card(doc, 'heart_rate'), undefined, doc.metrics.heart_rate)
expect(rows.map(r => r.key)).toEqual(['Min', 'Avg', 'Max'])
expect(rows.map(r => r.label)).toEqual(['Minimum', 'Average', 'Maximum'])
expect(rows.map(r => r.value)).toEqual([55.6, 69.4, 90.3])
expect(rows[1]).toMatchObject({ min: 55, max: 96, n: 288 })
expect(detailRows(card(doc, 'heart_rate'), undefined, { days: [] })).toEqual([])
})
it('labels a field nobody has a rule for from its own name', () => {
const rows = detailRows(card(doc, 'some_new_metric'), undefined, doc.metrics.some_new_metric)
expect(rows.map(r => r.label)).toEqual(['Value', 'Confidence'])
})
})
describe('workoutRows', () => {
it('carries duration, energy, distance and heart rate, with an icon per activity', () => {
const rows = workoutRows(doc)
expect(rows.length).toBe(2)
expect(rows[0]).toMatchObject({ name: 'Functional Strength Training', icon: 'dumbbell', dur: '45 min', energy: '320 kcal', distance: '3.25 km', avgHr: '128 bpm' })
expect(rows[1]).toMatchObject({ icon: 'figureRun', energy: '', avgHr: '' })
expect(workoutRows(doc, { limit: 1 }).length).toBe(1)
})
it('picks an icon from the activity name', () => {
expect(workoutIcon('Pool Swim')).toBe('swim')
expect(workoutIcon('Indoor Cycling')).toBe('bike')
expect(workoutIcon('Yoga')).toBe('stretch')
expect(workoutIcon('Outdoor Run')).toBe('figureRun')
expect(workoutIcon(undefined)).toBe('bolt')
})
})
describe('days, units and captions', () => {
it('lists every day that has anything, once, oldest first', () => {
expect(activeDays(doc)).toEqual(['2026-05-01', '2026-05-02', '2026-05-03'])
expect(activeDays(null)).toEqual([])
})
it('spells units for a human and keeps the metric\'s own precision', () => {
expect(unitLabel('count')).toBe('')
expect(unitLabel('count/min')).toBe('bpm')
expect(unitLabel('degC')).toBe('°C')
expect(unitLabel('somethingElse')).toBe('somethingElse')
expect(fmtValue(12000)).toBe((12000).toLocaleString(undefined, { maximumFractionDigits: 0 }))
expect(fmtValue(80.44, 1)).toBe('80.4')
expect(fmtValue(7.35, 1)).toBe('7.4')
expect(fmtValue(69.44, 0)).toBe('69')
expect(fmtValue(null)).toBe('—')
expect(fmtValue(NaN)).toBe('—')
})
it('reads the "last sync" caption like a person wrote it', () => {
const now = Date.parse('2026-05-04T10:00:00Z')
expect(agoLabel(now - 30000, now)).toBe('just now')
expect(agoLabel(now - 12 * 60000, now)).toBe('12 min ago')
expect(agoLabel(now - 5 * 3600000, now)).toBe('5 h ago')
expect(agoLabel(now - 3 * 86400000, now)).toBe('3 d ago')
expect(agoLabel(0, now)).toBe('')
})
it('builds an absolute ingest URL that survives a subpath deployment', () => {
expect(ingestUrl({ origin: 'https://gym.example.com', pathname: '/' })).toBe('https://gym.example.com/api/vitals/ingest')
expect(ingestUrl({ origin: 'https://example.com', pathname: '/gym/' })).toBe('https://example.com/gym/api/vitals/ingest')
// A deep link is index.html, never a directory: the base is everything up to the last slash.
expect(ingestUrl({ origin: 'https://example.com', pathname: '/gym/index.html' })).toBe('https://example.com/gym/api/vitals/ingest')
expect(ingestUrl({ origin: 'http://localhost:5173', pathname: '/health' })).toBe('http://localhost:5173/api/vitals/ingest')
})
})
+140
View File
@@ -1273,4 +1273,144 @@ export default {
'Try again': 'Reintentar',
'Start over': 'Empezar de nuevo',
'“{0}” added to your plan': '«{0}» añadida a tu plan',
/* ---------------------------------------------------------------- Salud --
Apple Health (Health Auto Export → /api/vitals/ingest). The metric, group and field labels
below are translated at render time from lib/vitals-view.js, where they live in a catalogue
rather than inside a t() call — a source-string scanner cannot see them, so this block is the
only place they exist and it has to be kept in step with METRICS by hand. */
// groups
'Activity': 'Actividad',
'Heart': 'Corazón',
'Body': 'Cuerpo',
'Sleep': 'Sueño',
'Vitals': 'Vitales',
// 'Other' already exists above (the muscle-balance "Other" group) and means the same thing.
// metrics
'Steps': 'Pasos',
'Distance': 'Distancia',
'Flights climbed': 'Pisos subidos',
'Exercise time': 'Tiempo de ejercicio',
'Stand time': 'Tiempo de pie',
'Stand hours': 'Horas de pie',
'Active energy': 'Energía activa',
'Resting energy': 'Energía en reposo',
'Physical effort': 'Esfuerzo físico',
'Time in daylight': 'Tiempo a la luz del día',
'Mindful minutes': 'Minutos de atención plena',
'Heart rate': 'Frecuencia cardíaca',
'Resting heart rate': 'Frecuencia en reposo',
'Walking heart rate': 'Frecuencia al caminar',
'Heart rate variability': 'Variabilidad cardíaca',
'Heart rate recovery': 'Recuperación cardíaca',
'VO₂ max': 'VO₂ máx',
'Cardio recovery': 'Recuperación cardiovascular',
'AFib burden': 'Carga de fibrilación auricular',
'Weight': 'Peso',
'BMI': 'IMC',
'Body fat': 'Grasa corporal',
'Lean mass': 'Masa magra',
'Waist': 'Cintura',
'Height': 'Altura',
'Basal temperature': 'Temperatura basal',
'Wrist temperature': 'Temperatura de muñeca',
'REM sleep': 'Sueño REM',
'Core sleep': 'Sueño central',
'Deep sleep': 'Sueño profundo',
'Blood oxygen': 'Oxígeno en sangre',
'Respiratory rate': 'Frecuencia respiratoria',
'Blood pressure': 'Presión arterial',
'Blood pressure (diastolic)': 'Presión arterial (diastólica)',
'Body temperature': 'Temperatura corporal',
'Blood glucose': 'Glucosa en sangre',
'Water': 'Agua',
'UV exposure': 'Exposición UV',
'Ambient sound': 'Ruido ambiental',
'Headphone level': 'Nivel de auriculares',
'Walking steadiness': 'Estabilidad al caminar',
'Walking speed': 'Velocidad al caminar',
'Step length': 'Longitud de zancada',
'Walking asymmetry': 'Asimetría al caminar',
'Double support': 'Apoyo doble',
'Stair speed up': 'Velocidad al subir escaleras',
'Stair speed down': 'Velocidad al bajar escaleras',
// the fields inside a metric's detail sheet
'Value': 'Valor',
'Average': 'Media',
'Minimum': 'Mínimo',
'Maximum': 'Máximo',
'Total': 'Total',
'Asleep': 'Dormido',
'In bed': 'En cama',
'Awake': 'Despierto',
// The sleep stages are named through their metric keys instead of bare 'Core'/'Deep'/'REM':
// 'Core' already means the core muscle group elsewhere in this file, and one key cannot mean
// two different things in two screens.
'Deep': 'Profundo',
'REM': 'REM',
'Systolic': 'Sistólica',
'Diastolic': 'Diastólica',
// the screen
'Health': 'Salud',
'From Apple Health on your iPhone': 'Desde Apple Health en tu iPhone',
'Last sync {0}': 'Última sincronización {0}',
'last sync {0}': 'última sincronización {0}',
'just now': 'hace un momento',
'{0} min ago': 'hace {0} min',
'{0} h ago': 'hace {0} h',
'{0} d ago': 'hace {0} d',
'Refresh': 'Actualizar',
'{0} metrics': '{0} métricas',
'Nothing in this range — try a wider one.': 'No hay nada en este rango: prueba con uno más amplio.',
'Workouts from your iPhone': 'Entrenamientos de tu iPhone',
'{0} avg': '{0} de media',
'Read-only on purpose: these carry no sets or weights, so they stay out of your progression, your PRs and the recovery model.': 'Solo lectura a propósito: no traen series ni pesos, así que quedan fuera de tu progresión, tus PRs y el modelo de recuperación.',
'vs your average': 'frente a tu media',
'What the watch sent': 'Lo que envió el reloj',
'{0} samples': '{0} muestras',
'{0} days with data in this range': '{0} días con datos en este rango',
// setup
'Connect Apple Health': 'Conectar Apple Health',
'{0} copied': '{0} copiado',
'Key': 'Clave',
'URL': 'URL',
'Close': 'Cerrar',
'Create an ingest key': 'Crear una clave de ingesta',
'1. The endpoint': '1. El endpoint',
'2. The header': '2. El encabezado',
'3. In Health Auto Export': '3. En Health Auto Export',
'Automation type': 'Tipo de automatización',
'REST API': 'REST API',
'Export format': 'Formato de exportación',
'Export version': 'Versión de exportación',
'Summarize data': 'Resumir datos',
'Time grouping': 'Agrupación temporal',
'Days': 'Días',
'Date range': 'Rango de fechas',
'Previous 7 Days': 'Últimos 7 días',
'Health Auto Export runs an automation on your iPhone and posts to this profile. The key below only works for your account, and only for this: it can add health data and cannot read anything back.': 'Health Auto Export ejecuta una automatización en tu iPhone y envía los datos a este perfil. La clave de aquí abajo solo funciona para tu cuenta y solo para esto: puede añadir datos de salud y no puede leer nada.',
'Grouping by days is what makes a five-minute cadence safe: each sync carries the day\'s total and replaces the previous one, so nothing is ever counted twice. Raw samples work too — they are de-duplicated instead.': 'Agrupar por días es lo que hace segura una cadencia de cinco minutos: cada envío trae el total del día y reemplaza al anterior, así que nada se cuenta dos veces. Las muestras crudas también funcionan: esas se deduplican.',
'Pick a cadence that suits you — every 5 minutes, hourly, or once a day all land the same way.': 'Elige la cadencia que te sirva: cada 5 minutos, cada hora o una vez al día llegan igual de bien.',
'Manage': 'Gestionar',
'Replace the key': 'Reemplazar la clave',
'The old one stops working immediately': 'La anterior deja de funcionar al instante',
'Delete the health data': 'Borrar los datos de salud',
'Keeps your workouts and your key': 'Conserva tus entrenamientos y tu clave',
'Replace the ingest key?': '¿Reemplazar la clave de ingesta?',
'Your iPhone stops syncing until you paste the new key into Health Auto Export. Nothing already stored is lost.': 'Tu iPhone deja de sincronizar hasta que pegues la nueva clave en Health Auto Export. No se pierde nada de lo ya guardado.',
// 'Replace' already exists above, with the same meaning.
'Delete the health data?': '¿Borrar los datos de salud?',
'Every metric and workout that came from your iPhone is removed for good. Your KuentaGYM workouts, your passes and your key are untouched.': 'Se eliminan para siempre todas las métricas y los entrenamientos que vinieron de tu iPhone. Tus entrenamientos de KuentaGYM, tus passkeys y tu clave quedan intactos.',
// empty state and toasts
'No health data yet': 'Todavía no hay datos de salud',
'Nothing here comes from this app: it comes from your iPhone. Set up the automation once and every metric you choose in Health Auto Export shows up on this screen — steps, heart rate, sleep, weight, oxygen, workouts and the rest.': 'Nada de esto lo genera esta app: viene de tu iPhone. Configura la automatización una vez y cada métrica que elijas en Health Auto Export aparecerá en esta pantalla: pasos, frecuencia cardíaca, sueño, peso, oxígeno, entrenamientos y lo demás.',
'Ingest key created': 'Clave de ingesta creada',
'New key created': 'Nueva clave creada',
'Health data deleted': 'Datos de salud borrados',
// the Settings row and the guest-mode explanation
'Apple Health (live sync)': 'Apple Health (sincronización en vivo)',
'Your iPhone posts steps, sleep, heart rate and the rest to your profile': 'Tu iPhone envía pasos, sueño, frecuencia cardíaca y lo demás a tu perfil',
'Apple Health needs a profile': 'Apple Health necesita un perfil',
'Guest mode lives entirely in this browser, and your iPhone can only post to a profile on a server. Create one, then connect Apple Health from here — it takes a minute and nothing you logged as a guest is lost.': 'El modo invitado vive enteramente en este navegador, y tu iPhone solo puede enviar datos a un perfil en un servidor. Crea uno y luego conecta Apple Health desde aquí: toma un minuto y no se pierde nada de lo que registraste como invitado.',
'Create a profile': 'Crear un perfil',
}
+276
View File
@@ -0,0 +1,276 @@
/* Salud — what the watch recorded, as read-only cards.
*
* The data does not come from this app: an iOS automation (Health Auto Export) POSTs Apple Health
* to /api/vitals/ingest, per profile, and this screen draws whatever arrived. Two consequences
* shape everything below.
*
* Nothing here is an input. There is no editing, no goal to set, no weight to log — a card shows
* what the phone said and nothing else, because the moment this screen could write, it would be a
* second source of truth for the same numbers (and the body-weight log already lives in Stats).
*
* It renders what it is given. The catalogue in lib/vitals-view.js gives the ~50 metrics people
* actually track a label, a unit and the aggregate worth showing; anything else still becomes a
* card under Other, labelled from its own HAE name. So "export everything" is a usable screen on
* day one, and the next metric Apple ships does not need a code change to show up.
*/
import { useCallback, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { api } from '../lib/api.js'
import { t } from '../lib/i18n.js'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { confirmSheet } from '../sheets.jsx'
import { Button, Row, Segmented } from '../components/ui.jsx'
import Icon from '../components/Icon.jsx'
import LineChart from '../components/LineChart.jsx'
import {
groupedCards, metricCards, trendOf, chartPoints, workoutRows, hasVitals,
fmtValue, unitLabel, agoLabel, ingestUrl, detailRows
} from '../lib/vitals-view.js'
const RANGES = [
{ value: 7, label: '7d' },
{ value: 30, label: '30d' },
{ value: 90, label: '90d' },
{ value: 365, label: '1a' }
]
/** A trend arrow: green when it moved the way the metric is supposed to move. */
function Trend({ card }) {
const tr = trendOf(card)
if (!tr) return null
const color = tr.good === 'good' ? 'var(--green)' : tr.good === 'bad' ? 'var(--orange)' : 'var(--label-3)'
return <span className="vh-trend" style={{ color }}>
<Icon name={tr.dir === 'up' ? 'arrowUp' : 'arrowDown'} />
{Math.round(tr.pct * 100)}%
</span>
}
/** One card. Everything is a button: the detail sheet is where the chart and the fields live. */
function MetricCard({ card, onOpen }) {
return <button className="tile tappable vh-card" onClick={() => onOpen(card)}>
<div className="l"><Icon name={card.icon} />{card.label}</div>
<div className="v">
{fmtValue(card.value, card.dec)}
{unitLabel(card.unit) ? <span className="vh-unit">{unitLabel(card.unit)}</span> : null}
<Trend card={card} />
</div>
{card.series.length > 1
? <div className="vh-spark"><LineChart points={chartPoints(card)} h={36} axes={false} /></div>
: <div className="vh-spark-ph" />}
</button>
}
/* ---------- the two sheets ---------- */
/**
* The detail sheet: the full chart, then every field HAE sent for the newest day. The second half
* is what makes an unknown metric legible — the numbers under the names HAE used, rather than a
* card that says "91" and nothing about what 91 was.
*/
function MetricSheet({ card, metric, close }) {
const rows = detailRows(card, undefined, metric)
const tr = trendOf(card)
return <>
<h3>{card.label}</h3>
<div className="vh-sheet-top">
<div className="stat-v" style={{ fontSize: 34 }}>
{fmtValue(card.value, card.dec)}
{unitLabel(card.unit) ? <span className="vh-unit">{unitLabel(card.unit)}</span> : null}
</div>
<div className="small dim">
{card.day}
{tr ? ` · ${tr.dir === 'up' ? '+' : '−'}${Math.round(tr.pct * 100)}% ${t('vs your average')}` : ''}
</div>
</div>
<div className="card vh-chart"><LineChart points={chartPoints(card)} h={160} unit={unitLabel(card.unit)} /></div>
{rows.length > 0 && <>
<h4 className="sec">{t('What the watch sent')}</h4>
<div className="list">{rows.map(r => <Row key={r.key} title={r.label}
subtitle={r.n > 1 ? t('{0} samples', r.n) : null}
value={fmtValue(r.value, r.value != null && Math.abs(r.value) < 100 ? 1 : 0) + (unitLabel(r.unit) ? ' ' + unitLabel(r.unit) : '')} />)}</div>
</>}
<div className="small dim" style={{ marginTop: 12 }}>
{t('{0} days with data in this range', card.days)}
{card.sources.length ? ' · ' + card.sources.join(', ') : ''}
</div>
<div style={{ height: 12 }} />
<Button onClick={close}>{t('Close')}</Button>
</>
}
/** Setup: the URL, the header, the settings in Health Auto Export that keep the numbers exact. */
function SetupSheet({ data, onKey, onRotate, onDelete, close }) {
const toast = useUI(s => s.toast)
const url = ingestUrl()
const copy = (text, label) => { navigator.clipboard?.writeText(text).catch(() => {}); toast(t('{0} copied', label)) }
return <>
<h3>{t('Connect Apple Health')}</h3>
<div className="small dim" style={{ lineHeight: 1.5, marginBottom: 14 }}>
{t('Health Auto Export runs an automation on your iPhone and posts to this profile. The key below only works for your account, and only for this: it can add health data and cannot read anything back.')}
</div>
<h4 className="sec">{t('1. The endpoint')}</h4>
<div className="cfgrow"><code className="vh-code">{url}</code>
<button className="iconbtn" onClick={() => copy(url, t('URL'))} aria-label={t('Copy')}><Icon name="clipboard" /></button></div>
<h4 className="sec">{t('2. The header')}</h4>
{data?.key
? <div className="cfgrow"><code className="vh-code">Authorization: Bearer {data.key}</code>
<button className="iconbtn" onClick={() => copy('Bearer ' + data.key, t('Key'))} aria-label={t('Copy')}><Icon name="clipboard" /></button></div>
: <Button variant="primary" icon="key" onClick={onKey}>{t('Create an ingest key')}</Button>}
<h4 className="sec">{t('3. In Health Auto Export')}</h4>
<div className="list">
<Row icon="upload" title={t('Automation type')} value={t('REST API')} />
<Row icon="calendar" title={t('Export format')} value="JSON" />
<Row icon="list" title={t('Export version')} value="2" />
<Row icon="check" title={t('Summarize data')} value={t('On')} />
<Row icon="clock" title={t('Time grouping')} value={t('Days')} />
<Row icon="history" title={t('Date range')} value={t('Previous 7 Days')} />
</div>
<div className="small dim" style={{ marginTop: 10, lineHeight: 1.5 }}>
{t('Grouping by days is what makes a five-minute cadence safe: each sync carries the day\'s total and replaces the previous one, so nothing is ever counted twice. Raw samples work too — they are de-duplicated instead.')}
</div>
<div className="small dim" style={{ marginTop: 8, lineHeight: 1.5 }}>
{t('Pick a cadence that suits you — every 5 minutes, hourly, or once a day all land the same way.')}
</div>
{data?.key && <>
<h4 className="sec">{t('Manage')}</h4>
<div className="list">
<Row icon="reset" title={t('Replace the key')} subtitle={t('The old one stops working immediately')} accessory="chevron" onClick={onRotate} />
<Row icon="trash" iconTint="var(--red)" title={t('Delete the health data')} subtitle={t('Keeps your workouts and your key')} onClick={onDelete} />
</div>
</>}
<div style={{ height: 12 }} />
<Button onClick={close}>{t('Close')}</Button>
</>
}
function Empty({ onSetup }) {
return <div className="card vh-empty">
<div className="ico"><Icon name="heart" /></div>
<h4 className="sec" style={{ marginTop: 6 }}>{t('No health data yet')}</h4>
<div className="small dim" style={{ lineHeight: 1.55, marginBottom: 14 }}>
{t('Nothing here comes from this app: it comes from your iPhone. Set up the automation once and every metric you choose in Health Auto Export shows up on this screen — steps, heart rate, sleep, weight, oxygen, workouts and the rest.')}
</div>
<Button variant="primary" icon="link" onClick={onSetup}>{t('Connect Apple Health')}</Button>
</div>
}
/* ---------- the view ---------- */
export default function Health() {
const nav = useNavigate()
const openSheet = useUI(s => s.openSheet)
const toast = useUI(s => s.toast)
const isGuest = useStore(s => s.isGuest())
const [data, setData] = useState(null)
const [err, setErr] = useState('')
const [days, setDays] = useState(30)
const [loading, setLoading] = useState(true)
const load = useCallback(() => {
setLoading(true)
api('/api/vitals?days=' + days)
.then(d => { setData(d); setErr('') })
.catch(e => setErr(e.message))
.finally(() => setLoading(false))
}, [days])
useEffect(() => { if (!isGuest) load() }, [load, isGuest])
const key = () => api('/api/vitals/key', { method: 'POST' })
.then(r => { setData(d => ({ ...d, key: r.key })); toast(t('Ingest key created')) })
.catch(e => toast(e.message))
const rotate = () => confirmSheet({
title: t('Replace the ingest key?'),
message: t('Your iPhone stops syncing until you paste the new key into Health Auto Export. Nothing already stored is lost.'),
confirmText: t('Replace'), danger: true,
onConfirm: () => api('/api/vitals/key/rotate', { method: 'POST' })
.then(r => { setData(d => ({ ...d, key: r.key })); toast(t('New key created')) })
.catch(e => toast(e.message))
})
const wipe = () => confirmSheet({
title: t('Delete the health data?'),
message: t('Every metric and workout that came from your iPhone is removed for good. Your KuentaGYM workouts, your passes and your key are untouched.'),
confirmText: t('Delete'), danger: true,
onConfirm: () => api('/api/vitals', { method: 'DELETE' })
.then(() => { load(); toast(t('Health data deleted')) })
.catch(e => toast(e.message))
})
const setup = () => openSheet(close => <SetupSheet data={data} onKey={key} onRotate={rotate} onDelete={wipe} close={close} />)
const openMetric = card => openSheet(close => <MetricSheet card={card} metric={data.metrics[card.name]} close={close} />)
/* Guest mode keeps everything in this browser and never talks to a server, so there is nothing
for a phone to post to. Saying so once is friendlier than a 401 the visitor cannot act on. */
if (isGuest) return <>
<div className="hdr"><div><h1>{t('Health')}</h1><div className="sub">{t('From Apple Health on your iPhone')}</div></div></div>
<div className="card vh-empty">
<div className="ico"><Icon name="heart" /></div>
<h4 className="sec" style={{ marginTop: 6 }}>{t('Apple Health needs a profile')}</h4>
<div className="small dim" style={{ lineHeight: 1.55, marginBottom: 14 }}>
{t('Guest mode lives entirely in this browser, and your iPhone can only post to a profile on a server. Create one, then connect Apple Health from here — it takes a minute and nothing you logged as a guest is lost.')}
</div>
<Button variant="primary" icon="person" onClick={() => nav('/settings')}>{t('Create a profile')}</Button>
</div>
</>
const cards = hasVitals(data) ? metricCards(data, { days }) : []
const groups = groupedCards(cards)
const workouts = workoutRows(data, { limit: 20 })
const last = data?.last?.ts
return <>
<div className="hdr">
<div style={{ flex: 1 }}>
<h1>{t('Health')}</h1>
<div className="sub">
{last ? t('Last sync {0}', agoLabel(last)) : t('From Apple Health on your iPhone')}
</div>
</div>
<button className="iconbtn" onClick={setup} aria-label={t('Connect Apple Health')}><Icon name="gear" /></button>
<button className="iconbtn" onClick={load} aria-label={t('Refresh')}><Icon name="reset" /></button>
</div>
{err && <div className="card vh-err"><Icon name="warning" /> {err}<div style={{ height: 8 }} />
<Button size="sm" onClick={load}>{t('Try again')}</Button></div>}
{!err && loading && !data && <div className="empty"><div className="ico"><Icon name="heart" /></div>{t('Loading…')}</div>}
{!err && data && !hasVitals(data) && <Empty onSetup={setup} />}
{!err && hasVitals(data) && <>
<Segmented options={RANGES} value={days} onChange={setDays} className="seg-range" />
<div className="small dim" style={{ margin: '8px 2px 12px' }}>
{t('{0} metrics', cards.length)}{data.last ? ' · ' + t('last sync {0}', agoLabel(data.last.ts)) : ''}
</div>
{groups.map(g => <div key={g.group}>
<h4 className="sec">{g.label}</h4>
<div className="tiles">{g.cards.map(c => <MetricCard key={c.name} card={c} onOpen={openMetric} />)}</div>
</div>)}
{cards.length === 0 && <div className="small dim" style={{ margin: '0 2px 12px' }}>
{t('Nothing in this range — try a wider one.')}
</div>}
{workouts.length > 0 && <>
<h4 className="sec">{t('Workouts from your iPhone')}</h4>
<div className="list">
{workouts.map(w => <Row key={w.key} icon={w.icon} title={w.name}
subtitle={[w.date, w.dur, w.energy, w.distance].filter(Boolean).join(' · ')}
value={w.avgHr ? t('{0} avg', w.avgHr) : null} />)}
</div>
<div className="small dim" style={{ margin: '8px 2px 0', lineHeight: 1.5 }}>
{t('Read-only on purpose: these carry no sets or weights, so they stay out of your progression, your PRs and the recovery model.')}
</div>
</>}
<div style={{ height: 16 }} />
</>}
</>
}
+112
View File
@@ -0,0 +1,112 @@
// @vitest-environment happy-dom
/* Salud has one job: draw whatever the phone sent, and explain itself when nothing has arrived.
A render test rather than a click-through because the screen is almost entirely a function of
the document — the metric catalogue decides the label, the unit and which number is shown, and
the failures worth catching (a card that crashes on a metric nobody wrote a rule for, an empty
profile that renders as a blank screen instead of instead of the setup steps) are exactly the
ones a hand-test with the author's own data never reaches. */
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useStore } from '../store/useStore.js'
const api = vi.fn()
vi.mock('../lib/api.js', () => ({ api: (...args) => api(...args) }))
vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }))
vi.mock('../sheets.jsx', () => ({ confirmSheet: vi.fn() }))
const { default: Health } = await import('./Health.jsx')
const bucket = v => ({ n: 1, sum: v, min: v, max: v, last: v, avg: v })
const day = (d, f, n = 1) => ({ day: d, n, f })
const VITALS = {
ok: true,
days: 30,
key: 'kghealth_TESTKEY',
updatedAt: Date.parse('2026-09-03T22:00:00Z'),
last: { ts: Date.parse('2026-09-03T22:00:00Z'), metrics: 4, points: 9, duplicates: 288, workouts: 1 },
metrics: {
step_count: { units: 'count', sources: ['Apple Watch'], days: [day('2026-09-01', { qty: bucket(9000) }), day('2026-09-02', { qty: bucket(11000) }), day('2026-09-03', { qty: bucket(12481) })] },
heart_rate: { units: 'bpm', sources: ['Apple Watch'], days: [day('2026-09-03', { Avg: { n: 288, sum: 20000, min: 54, max: 96, last: 72, avg: 69.4 } })] },
sleep_analysis: { units: 'hr', sources: ['Apple Watch'], days: [day('2026-09-03', { asleep: bucket(7.4), deep: bucket(1.2) })] },
walking_steadiness: { units: '%', sources: ['iPhone'], days: [day('2026-09-03', { qty: bucket(91) })] },
// A metric the catalogue has never heard of: it must still become a card, in Other, under a
// humanised name — "export everything" is the point of the feature.
some_metric_from_the_future: { units: 'ms', sources: ['Apple Watch'], days: [day('2026-09-03', { qty: { n: 4, sum: 480, min: 100, max: 140, last: 130, avg: 120 } })] }
},
workouts: [
{ name: 'Functional Strength Training', day: '2026-09-03', start: 1, end: 2, durMin: 50, avgHr: 134.5, maxHr: 168, fields: { activeEnergy: { qty: 318, units: 'kcal' } } }
]
}
let host, root
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
api.mockReset()
localStorage.removeItem('gym_guest')
useStore.setState({ user: { id: 'u1', name: 'Test' } })
})
afterEach(() => { act(() => root.unmount()); host.remove() })
const mount = async () => {
await act(async () => { root.render(<Health />) })
await act(async () => {}) // let the fetch's promise settle
}
const text = () => host.textContent
const cards = () => [...host.querySelectorAll('.vh-card')]
describe('Salud', () => {
it('draws one card per metric, grouped, with the number the catalogue says to show', async () => {
api.mockResolvedValue(VITALS)
await mount()
expect(cards().length).toBe(5)
const labels = cards().map(c => c.querySelector('.l').textContent)
expect(labels).toEqual(['Steps', 'Heart rate', 'Sleep', 'Walking steadiness', 'Some metric from the future'])
// Steps show the day's total, heart rate the day's average, sleep hours asleep. The unknown
// metric falls back to the field with the most samples (its average), rather than a dash.
expect(cards()[0].querySelector('.v').textContent).toContain('12,481')
expect(cards()[1].querySelector('.v').textContent).toContain('69')
expect(cards()[1].querySelector('.v').textContent).toContain('bpm')
expect(cards()[2].querySelector('.v').textContent).toContain('7.4')
expect(cards()[3].querySelector('.v').textContent).toContain('91')
expect(cards()[4].querySelector('.v').textContent).toContain('120')
// Group headings, the range control, and the read-only workout list.
expect(text()).toContain('Activity')
expect(text()).toContain('Heart')
expect(text()).toContain('Vitals')
expect(text()).toContain('Other')
expect(text()).toContain('Workouts from your iPhone')
expect(text()).toContain('Functional Strength Training')
expect(text()).toContain('50 min')
expect(text()).toContain('318 kcal')
expect(api).toHaveBeenCalledWith('/api/vitals?days=30')
})
it('offers the setup steps instead of a blank screen when nothing has arrived', async () => {
api.mockResolvedValue({ ok: true, days: 30, key: null, updatedAt: 0, last: null, metrics: {}, workouts: [] })
await mount()
expect(cards().length).toBe(0)
expect(text()).toContain('No health data yet')
expect(text()).toContain('Connect Apple Health')
})
it('says a guest needs a profile rather than showing a 401 it cannot act on', async () => {
localStorage.setItem('gym_guest', '1')
useStore.setState({ user: null })
await mount()
expect(text()).toContain('Apple Health needs a profile')
expect(api).not.toHaveBeenCalled()
})
it('shows the error with a retry instead of pretending there is no data', async () => {
api.mockRejectedValue(new Error('HTTP 500'))
await mount()
expect(text()).toContain('HTTP 500')
expect(text()).toContain('Try again')
expect(text()).not.toContain('No health data yet')
})
})
+5
View File
@@ -383,6 +383,11 @@ export default function Settings() {
{/* ---------- data: fill it, bring things over, back it up, wipe it ---------- */}
<Section title={t('Data')}>
{/* Above the file imports on purpose: this one keeps working after today, while the rows
below it are one-shot reads of an export. */}
<Row icon="heart" iconTint="var(--red)" title={t('Apple Health (live sync)')}
subtitle={t('Your iPhone posts steps, sleep, heart rate and the rest to your profile')}
accessory="chevron" onClick={() => nav('/health')} />
<Row icon="sparkles" iconTint="var(--acc)" title={t('Load starter plan')} accessory="chevron" onClick={starterPlanSheet} />
<Row icon="shuffle" iconTint="var(--teal)" title={t('Import from another app')}
subtitle={t('FitNotes, Strong, Hevy — or body weight from Apple Health')}
+49 -28
View File
@@ -16,41 +16,62 @@ server {
add_header Content-Security-Policy "frame-ancestors 'none'" always;
# API → backend container.
# `^~` so this prefix beats the regex locations below: without it a request for a path such
# as /api/anything.json would be matched by the \.(js|css|json|html)$ block instead and be
# Resolved per request through the container runtime's DNS, not once at start-up: nginx
# otherwise pins the api container's IP when it boots, and a recreated api (new IP) means
# 502 on every /api call until web is restarted too (issue #16). The variable is what makes
# nginx re-resolve; lowercase so the entrypoint's envsubst leaves it alone.
#
# RESOLVER defaults to Docker's embedded DNS, which is where this image usually runs.
# Nothing answers on that address outside Docker, and an unreachable resolver does not
# fail fast — every /api request hangs until it times out. Anywhere else, set RESOLVER to
# the DNS the platform actually provides: on Kubernetes that is the kube-dns/CoreDNS
# service address (`kubectl -n kube-system get svc kube-dns`, commonly 10.96.0.10).
#
# These live at server level, not inside the /api/ location, because there is more than one
# proxied location now (the health ingest takes bigger bodies than everything else) and the
# two must not be allowed to drift: proxy_set_header, proxy_http_version and resolver all
# inherit, so the only per-location difference is proxy_pass and the body limit. The
# CF-Connecting-IP comment below is the security-relevant half of this block — read it
# before moving anything back into a location.
resolver ${RESOLVER} valid=10s ipv6=off;
set $api_upstream http://${BACKEND}:${PORT};
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# $remote_addr, NOT $proxy_add_x_forwarded_for: the latter APPENDS to whatever the client
# sent, and the API reads the first entry — so a client could put any address it liked in
# front of its own and choose what the activity log recorded about it. Overwriting is what
# makes the header mean anything.
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
# Same reasoning, and the API trusts this one FIRST. Empty by default, which drops the
# header entirely, so a direct client cannot forge it. Cloudflare users set
# CF_CONNECTING_IP=$http_cf_connecting_ip to let the real one through — correct only when
# Cloudflare is genuinely in front, because that is what overwrites a client-supplied one.
proxy_set_header CF-Connecting-IP "${CF_CONNECTING_IP}";
# NOTE on the two /api locations below: both are `^~` prefixes, and prefix locations are
# matched longest-first, so the ingest one wins for its own path and nothing else changes.
# `^~` on both so they beat the regex locations further down: without it a request for a path
# such as /api/anything.json would be matched by the \.(js|css|json|html)$ block instead and be
# looked for on disk rather than proxied.
# Apple Health ingest (POST /api/vitals/ingest). Health Auto Export sends whole exports — a
# first sync of a year of raw samples is tens of megabytes — so this one route is allowed the
# API's own VITALS_MAX_BODY (32 MB in api/server.js). It is the ONLY route with that limit:
# nginx buffers a request body before forwarding it, so a bigger cap anywhere else would let
# an unauthenticated caller make web hold 32 MB per request.
location ^~ ${BASE_PATH}/api/vitals/ingest {
client_max_body_size 32m;
proxy_pass $api_upstream;
}
location ^~ ${BASE_PATH}/api/ {
# Match the API's own body limit (MAX_BODY in api/server.js): the whole workout history
# travels in one PUT /api/data, and nginx's 1 MiB default would answer 413 here before the
# API ever saw it — a sync that silently stops once the history grows past 1 MiB.
client_max_body_size 5m;
# Resolved per request through the container runtime's DNS, not once at start-up: nginx
# otherwise pins the api container's IP when it boots, and a recreated api (new IP) means
# 502 on every /api call until web is restarted too (issue #16). The variable is what makes
# nginx re-resolve; lowercase so the entrypoint's envsubst leaves it alone.
#
# RESOLVER defaults to Docker's embedded DNS, which is where this image usually runs.
# Nothing answers on that address outside Docker, and an unreachable resolver does not
# fail fast — every /api request hangs until it times out. Anywhere else, set RESOLVER to
# the DNS the platform actually provides: on Kubernetes that is the kube-dns/CoreDNS
# service address (`kubectl -n kube-system get svc kube-dns`, commonly 10.96.0.10).
resolver ${RESOLVER} valid=10s ipv6=off;
set $api_upstream http://${BACKEND}:${PORT};
proxy_pass $api_upstream;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# $remote_addr, NOT $proxy_add_x_forwarded_for: the latter APPENDS to whatever the client
# sent, and the API reads the first entry — so a client could put any address it liked in
# front of its own and choose what the activity log recorded about it. Overwriting is what
# makes the header mean anything.
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
# Same reasoning, and the API trusts this one FIRST. Empty by default, which drops the
# header entirely, so a direct client cannot forge it. Cloudflare users set
# CF_CONNECTING_IP=$http_cf_connecting_ip to let the real one through — correct only when
# Cloudflare is genuinely in front, because that is what overwrites a client-supplied one.
proxy_set_header CF-Connecting-IP "${CF_CONNECTING_IP}";
}
# The app routes behind the hash (/#/plan, /#/history …), so a path is never a screen, and the
+105 -1
View File
@@ -232,7 +232,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
<p class="api-facts">
<span>OpenAPI 3.1.0</span>
<span>KuentaGYM v1.3.8</span>
<span>30 endpoints</span>
<span>35 endpoints</span>
<span>AGPL-3.0-or-later</span>
</p>
@@ -2196,6 +2196,110 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
</div>
</details>
<details class="ep sch" id="schema-VitalsField">
<summary>
<span class="sch-name"><code>VitalsField</code></span>
<span class="ep-chev" aria-hidden="true"></span>
<span class="ep-sum">One numeric field of one metric for one day, aggregated over the samples that carried it.</span>
</summary>
<div class="ep-body">
<p>A counter's day is its <code>sum</code>; a rate's is its <code>avg</code>; a gauge's is its <code>last</code>. Both are stored so the rule that picks one is a display decision rather than a storage one.</p>
<div class="ptab">
<div class="prow">
<span class="p-name">n</span>
<span class="p-type">integer</span>
<span class="p-desc">Samples that contributed.</span>
</div>
<div class="prow">
<span class="p-name">sum</span>
<span class="p-type">number</span>
<span class="p-desc"></span>
</div>
<div class="prow">
<span class="p-name">min</span>
<span class="p-type">number</span>
<span class="p-desc"></span>
</div>
<div class="prow">
<span class="p-name">max</span>
<span class="p-type">number</span>
<span class="p-desc"></span>
</div>
<div class="prow">
<span class="p-name">last</span>
<span class="p-type">number</span>
<span class="p-desc"></span>
</div>
<div class="prow">
<span class="p-name">avg</span>
<span class="p-type">number</span>
<span class="p-desc"></span>
</div>
</div>
</div>
</details>
<details class="ep sch" id="schema-VitalsDay">
<summary>
<span class="sch-name"><code>VitalsDay</code></span>
<span class="ep-chev" aria-hidden="true"></span>
<span class="ep-sum">One day for one metric, keyed by the date the <i>phone</i> wrote (HAE stamps every sample with its own local offset, so the server never re-derives the day from its own clock).</span>
</summary>
<div class="ep-body">
<div class="ptab">
<div class="prow">
<span class="p-name">day</span>
<span class="p-type">string</span>
<span class="p-desc"></span>
</div>
<div class="prow">
<span class="p-name">n</span>
<span class="p-type">integer</span>
<span class="p-desc">Samples stored for this day.</span>
</div>
<div class="prow">
<span class="p-name">lastTs</span>
<span class="p-type">integer</span>
<span class="p-desc">Epoch ms of the day's newest sample.</span>
</div>
<div class="prow">
<span class="p-name">f</span>
<span class="p-type">object</span>
<span class="p-desc">Field name as HAE wrote it — <code>qty</code>, <code>Avg</code>, <code>asleep</code>, <code>systolic</code>…</span>
</div>
</div>
</div>
</details>
<details class="ep sch" id="schema-VitalsMetric">
<summary>
<span class="sch-name"><code>VitalsMetric</code></span>
<span class="ep-chev" aria-hidden="true"></span>
<span class="ep-sum"></span>
</summary>
<div class="ep-body">
<div class="ptab">
<div class="prow">
<span class="p-name">units</span>
<span class="p-type">string</span>
<span class="p-desc"></span>
</div>
<div class="prow">
<span class="p-name">sources</span>
<span class="p-type">string[]</span>
<span class="p-desc">The apps/devices that reported this metric, newest first.</span>
</div>
<div class="prow">
<span class="p-name">days</span>
<span class="p-type"><a href="#schema-VitalsDay">VitalsDay</a>[]</span>
<span class="p-desc"></span>
</div>
</div>
</div>
</details>
<details class="ep sch" id="schema-AuditEvent">
<summary>
<span class="sch-name"><code>AuditEvent</code></span>