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

+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) => {