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
Reported as "le doy a cualquier actividad y solo me presenta los pasos de hoy… debiera presentarme una medida por hora, y no me da el histórico". Two separate things, and only one of them was the app's fault. **The history was the automation's setting.** With Date Range on its default (`Today`) every sync carries today and nothing else, so there is exactly one day in the file to draw. That is why a card looked frozen: not a rendering bug, a range that was never sent. The setup steps now say `Previous 7 Days` and say why. **The hours were thrown away by us.** Even when the phone sends 288 readings a day, the receiver folded every one of them into a single day aggregate, so "8,123 steps today" was all there could ever be — a number you cannot look into. Worse, the recommended setting was Time Grouping `Days`, which sends one point per metric per day: the intraday detail never arrived in the first place. The recommendation is now `Hours`, and the storage keeps the hours. The merge rule for them is the same shape as the day rule, for the same reason: a payload whose datapoints all sit on the hour is HAE's own hour grouping, and the hour *in progress* grows on every run of a five-minute automation, so it is replaced and never unioned — 500 + 900 + 1,340 steps in one hour is a number no watch recorded. The day is then recomputed as the sum of its hours, which is what keeps the card and the detail from ever disagreeing, and which also makes switching an automation from Days to Hours mid-day converge instead of double-count. Raw samples (real timestamps) still union by instant plus numbers, and they now land in their own hour, which is where intraday detail comes from when nothing is grouped. Three things that would have been silent bugs, caught while writing it: - The hour rule is decided from the **whole payload**, never from one timestamp. A five-minute automation produces samples that sit exactly on the hour, and reading one of those as an hour total wipes the hour it belongs to. There is a test with a 09:00:00 and a 09:05:00 sample in one payload, and it fails against the per-point version of the rule. - A day that arrived as a day total keeps its hours beside it, and a day stored before this existed keeps its aggregate when the first hour shows up — recomputing it from hours it does not have would delete 2,000 steps. Both are mutation-checked (removing either guard fails a test). - A payload grouped by hour writes the ledger row anyway, because a later payload with real minutes can describe the same instant and the union path can only see the ledger. Without it the raw-sample route test double-counts a single sample. The hours are the bulky part of this data, so they are kept for a week (the day aggregates still live the full 400 days), pruned when the night's file is written, and fetched one metric and one day at a time — `GET /api/vitals/hours`. A screen listing forty cards downloads none of them; the day view carries only a count per day, which is what tells the sheet whether it is worth asking. The sheet draws the hours, the days before it (tapping one moves the hour list to that day), and every field the watch sent; when the automation groups by Days it says so instead of leaving a gap where a chart should be. Coverage: 6 new tests in `api/test/vitals.test.js` (19 total) and a route test in `api/test/server-vitals.test.js` (5), the hour/history model in `vitals-view.test.js` (31), three render tests through the real sheet, the route documented in `api/openapi.yaml` and `website/api.html`, and `docs/HEALTH.md` with the settings, the new merge row and the two symptoms now in Troubleshooting.
280 lines
14 KiB
JavaScript
280 lines
14 KiB
JavaScript
/* 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('GET /api/vitals/hours opens one metric\'s day, and only with a session', 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 read = async q => (await (await fetch(`${h.api}/api/vitals/hours?${q}`, { headers: cookie('u_h1') }))).json();
|
|
|
|
// Signed out, and with the write-only ingest key, there is nothing to read here either.
|
|
assert.equal((await fetch(`${h.api}/api/vitals/hours?metric=step_count&day=${today}`)).status, 401);
|
|
assert.equal((await fetch(`${h.api}/api/vitals/hours?metric=step_count&day=${today}`, { headers: { Authorization: `Bearer ${key}` } })).status, 401);
|
|
|
|
// "Time Grouping: Hours" beside a metric the phone totals by day.
|
|
await ingest(h, key, { data: { metrics: [
|
|
{ name: 'step_count', units: 'count', data: [
|
|
{ qty: 500, date: `${today} 08:00:00 +0000` },
|
|
{ qty: 900, date: `${today} 09:00:00 +0000` }
|
|
] },
|
|
{ name: 'weight_body_mass', units: 'kg', data: [{ qty: 80.5, date: `${today} 00:00:00 +0000` }] }
|
|
] } });
|
|
|
|
const hours = await read(`metric=step_count&day=${today}`);
|
|
assert.equal(hours.ok, true);
|
|
assert.deepEqual(hours.hours.map(x => x.h), ['08', '09'], 'oldest hour first');
|
|
assert.deepEqual(hours.hours.map(x => x.f.qty.sum), [500, 900]);
|
|
assert.equal(hours.units, 'count');
|
|
|
|
// The day view still reads a day as one number, and now says whether there is anything behind it.
|
|
const day = (await (await fetch(`${h.api}/api/vitals?days=1`, { headers: cookie('u_h1') })).json()).metrics.step_count.days[0];
|
|
assert.equal(day.f.qty.sum, 1400);
|
|
assert.equal(day.hours, 2);
|
|
|
|
// A metric the phone grouped by day has no hours, and neither does a day nobody sent.
|
|
assert.deepEqual((await read(`metric=weight_body_mass&day=${today}`)).hours, []);
|
|
assert.deepEqual((await read(`metric=step_count&day=2000-01-01`)).hours, []);
|
|
assert.equal((await read(`metric=step_count&day=2000-01-01`)).day, null);
|
|
// A day that is not a date is not looked up at all (nothing here builds a path from input).
|
|
const bogus = await read('metric=step_count&day=not-a-day');
|
|
assert.equal(bogus.day, null);
|
|
assert.deepEqual(bogus.hours, []);
|
|
assert.equal((await read('metric=nope&day=' + today)).metric, null);
|
|
});
|
|
|
|
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);
|
|
});
|