Merge #166: the twelve Astra findings (#160) — api, built-in Coach, frontend, nginx (kurktchiev)

This commit is contained in:
Duarte Santos committed 2026-09-12 13:04:24 +02:00
commit 3b51f7acce
37 files changed
+1443 -62

No files matched your search

+5 -3
View File
@@ -113,11 +113,13 @@ Read this before hosting openGym for anyone other than yourself.
server connects out to and it comes from whoever is signed in, so `/api/push/*` would otherwise
be a request-forgery lever from inside the Docker network. It must be `https:`, and the
connection is refused at socket level if the host resolves to a loopback, private, link-local
(including cloud metadata) or CGNAT address — enforced in the agent's DNS lookup, not in a
prior pass, so there is no rebinding window (`api/server.js:86-119`). Sends have a 10 s timeout
(including cloud metadata) or CGNAT address — enforced in the agent's DNS lookup for hostnames,
so there is no rebinding window, and for literal IP addresses — which never go through that
lookup — by the same address check at subscribe time and again before every send, applied to
every textual form of the address (`api/server.js:93-223`). Sends have a 10 s timeout
(a stalling endpoint used to hang the request handler indefinitely), run at most 6 at a time,
and each account is capped at 20 subscriptions, so one small request cannot become an unbounded
burst of outbound connections (`api/server.js:84`).
burst of outbound connections (`api/server.js:108-110`).
- **There is an activity log.** Sign-ins, sign-outs, failed and refused attempts, and every admin
action are appended to `./data/audit.log`, one JSON object per line, and shown in the admin
dashboard. It is on by default (`AUDIT_LOG=0` disables it) and capped at `AUDIT_MAX` events /
+23 -5
View File
@@ -14,15 +14,21 @@ import * as cfgStore from './config.js';
const TICK_MS = 60000;
/** Weekly cadence fires within the minute; everyWorkouts fires as soon as the count is met. */
export function isDue(coach, S, now) {
/** Weekly cadence fires within the minute; everyWorkouts fires as soon as the count is met.
* `reviewedAt` is when the server last finished a review for this person: the client stamps
* lastReview only once someone acts on a proposal, and a review nobody has opened yet — or
* one that found nothing to change — still read those workouts. */
export function isDue(coach, S, now, reviewedAt = 0) {
const cadence = coach.cadence;
if (!cadence || cadence === 'off') return false;
const lastAt = coach.lastReview?.at || 0;
const lastAt = Math.max(coach.lastReview?.at || 0, reviewedAt);
// Nothing new to read is the most common reason not to run, and it applies to both modes.
const workouts = S.workouts || [];
const since = workouts.filter(w => !lastAt || (w.end || 0) > lastAt || w.d > new Date(lastAt).toISOString().slice(0, 10));
// A workout's `end` is on the same clock as the review's timestamp; its `d` is the phone's
// local day, which can run ahead of the server's UTC day, so the date only stands in for a
// workout that has no end.
const since = workouts.filter(w => !lastAt || (w.end ? w.end > lastAt : w.d > new Date(lastAt).toISOString().slice(0, 10)));
if (!since.length) return false;
if (cadence.everyWorkouts) {
@@ -50,9 +56,21 @@ export function startCadence(deps) {
const S = jobs.readState(user.id);
const coach = S?.coach;
if (!coach?.consent?.agreedAt) continue; // consent revoked ⇒ cadence stops
// A job still running, or a proposal nobody has answered, is not a reason for another:
// a second review would only replace the first unread. status() also retires an
// expired proposal, which a phone that stays closed never polls for.
const st = jobs.status(user.id);
if (st.job || st.pending) continue;
// Reviewed means the model read those workouts and answered — with a proposal, with
// "nothing to change", or with an answer that failed validation and was paid for all the
// same. A call that never reached it (timeout, no runtime, consent, switched off) is retried.
const reviewedAt = Math.max(0, ...jobs.readUser(user.id).history
.filter(h => h.kind === 'review' && (h.outcome === 'ready' || h.outcome === 'nochange'
|| (h.outcome === 'failed' && h.errorClass === 'unusable')))
.map(h => h.at || 0));
const tz = coach.cadence?.weekly ? (S.reminder?.tz || 'UTC') : null;
const now = tz ? deps.userNow(tz) : null;
if (!isDue(coach, S, now)) continue;
if (!isDue(coach, S, now, reviewedAt)) continue;
jobs.enqueue(user.id, { kind: 'review', trigger: 'scheduled' });
console.log('coach: scheduled review queued for', user.id);
} catch (e) {
+1
View File
@@ -81,6 +81,7 @@ const DEFAULTS = {
providerOptions: {}, // { [provider]: { baseUrl } }
boundUid: {}, // instance mode: { [provider]: the profile its credential bound to }
caps: { perProfileDaily: 10, instanceDaily: 0 }, // 0 = unlimited
daily: null, // { date, count }: jobs enqueued today across every profile
// Anonymous medians across profiles that opt in ("compare with others"). Off by default: it
// is the one feature where one person's numbers feed into what another person sees.
community: false,
+2
View File
@@ -42,6 +42,8 @@ async function call(fetchImpl, url, init, timeoutMs, signal) {
const ctl = new AbortController();
const onOuter = () => ctl.abort();
if (signal) signal.addEventListener('abort', onOuter, { once: true });
// An abort that already landed (during a retry pause, say) must not let a fresh request leave.
if (signal && signal.aborted) ctl.abort();
const timer = setTimeout(() => ctl.abort(), timeoutMs);
try {
return await fetchImpl(url, { ...init, signal: ctl.signal });
+48 -11
View File
@@ -63,9 +63,22 @@ function patchUser(uid, patch) {
writeUser(uid, rec);
return rec;
}
/** Consent revoked, profile deleted, "reset everything" — no server-side residue (FR-51). */
/** Consent revoked, profile deleted, "reset everything" — no server-side residue (FR-51).
* Today's job count is the one thing that stays: it is the spending record the daily cap
* reads, not the profile's data, and forgetting must not hand out a fresh cap; the record
* outlives the day only until the next job or forget touches it, and counts for nothing once
* the date has passed. A job still waiting in the queue is dropped here; one already mid-call
* is cancelled where the adapter can be (the HTTP ones — a spawned runtime runs to its end),
* and either way finishes without writing anything back (see finish). */
export function clearUser(uid) {
const { daily } = readUser(uid);
try { fs.unlinkSync(userFile(uid)); } catch { /* nothing to clear */ }
if (daily?.date === todayISO()) writeUser(uid, { ...EMPTY, daily });
const queued = queue.findIndex(j => j.uid === uid);
if (queued >= 0) { queue.splice(queued, 1); inflight.delete(uid); }
aborts.get(uid)?.abort();
forgetSeq.set(uid, (forgetSeq.get(uid) || 0) + 1);
invalidateCohort();
}
/** Every profile with a state file — the population a cohort is drawn from. */
@@ -107,9 +120,16 @@ export function capState(uid) {
const used = rec.daily?.date === todayISO() ? rec.daily.count : 0;
return { used, limit: caps.perProfileDaily || 0 };
}
function instanceUsedToday() {
// The instance-wide count is kept the same way in coach.json, not read off the job log: the
// log keeps its last hundred entries, and a count that stops at a hundred is not a cap.
function bumpInstanceDaily() {
const cur = cfgStore.load().daily;
const d = todayISO();
return (cfgStore.load().log || []).filter(e => (e.at || '').slice(0, 10) === d).length;
cfgStore.save({ daily: cur?.date === d ? { date: d, count: cur.count + 1 } : { date: d, count: 1 } });
}
function instanceUsedToday() {
const daily = cfgStore.load().daily;
return daily?.date === todayISO() ? daily.count : 0;
}
/* ---------- status ---------- */
@@ -148,6 +168,8 @@ function archive(uid, rec, outcome) {
const queue = [];
let running = 0;
const inflight = new Set(); // uids with a job queued or running (FR-07 single-flight)
const forgetSeq = new Map(); // uid → bumped by every clearUser; a job carries the value it saw at enqueue
const aborts = new Map(); // uid → AbortController of the provider call in flight, for clearUser to pull
class CoachError extends Error {
constructor(code, message) { super(message); this.code = code; }
@@ -197,10 +219,12 @@ export function enqueue(uid, opts) {
// of the owner's provider account, and queueing twenty jobs spends it whether or not the
// twentieth ever finishes.
bumpDaily(uid);
bumpInstanceDaily();
const job = {
id: crypto.randomBytes(8).toString('hex'),
uid,
forgetSeq: forgetSeq.get(uid) || 0,
kind: opts.kind, // 'create' | 'review' | 'debrief'
trigger: opts.trigger || 'manual', // 'manual' | 'scheduled'
workoutId: opts.workoutId ? String(opts.workoutId).slice(0, 40) : null,
@@ -228,6 +252,14 @@ function pump() {
}
function finish(job, result) {
cfgStore.logJob({
at: new Date().toISOString(), uid: job.uid, kind: job.kind, trigger: job.trigger,
outcome: result.outcome, errorClass: result.errorClass || null,
ms: Date.now() - job.startedAt, detail: result.detail || null
});
// Forgotten while it ran: the record is gone and stays gone, and nobody is notified. The
// job still ran and still spent, which is why the instance log above keeps its line.
if ((forgetSeq.get(job.uid) || 0) !== job.forgetSeq) return;
const rec = readUser(job.uid);
const history = [...(rec.history || []), {
id: job.id, kind: job.kind, trigger: job.trigger, outcome: result.outcome,
@@ -244,11 +276,6 @@ function finish(job, result) {
pending: result.pending !== undefined ? result.pending : rec.pending,
history
});
cfgStore.logJob({
at: new Date().toISOString(), uid: job.uid, kind: job.kind, trigger: job.trigger,
outcome: result.outcome, errorClass: result.errorClass || null,
ms: Date.now() - job.startedAt, detail: result.detail || null
});
if (result.outcome === 'ready' && onProposal) {
try { onProposal(job.uid, result.pending, job); } catch (e) { console.error('coach notify failed', e); }
}
@@ -266,6 +293,10 @@ async function execute(job) {
const S = readState(job.uid);
if (!S) return finish(job, { outcome: 'failed', errorClass: 'nostate' });
// Checked again here, not only at enqueue: a job can wait behind two others, and consent
// withdrawn or the Coach switched off in the meantime means no payload leaves for it.
if (!S.coach?.consent?.agreedAt) return finish(job, { outcome: 'failed', errorClass: 'consent' });
if (!cfgStore.isEnabled()) return finish(job, { outcome: 'failed', errorClass: 'off' });
const cfg = cfgStore.load();
const adapter = adapterFor(cfg.provider);
@@ -292,17 +323,22 @@ async function execute(job) {
// An HTTPS provider has no child process, so no directory for one to live in either.
const jobDir = adapter.spawns === false ? null : fs.mkdtempSync(path.join(os.tmpdir(), 'coach-'));
const env = cfgStore.jobEnv(jobDir || os.tmpdir(), cfgStore.credentialFor(job.uid));
const ctl = new AbortController();
aborts.set(job.uid, ctl);
try {
const ids = jobDir && unprivilegedIds();
if (ids) fs.chownSync(jobDir, ids.uid, ids.gid);
const attempt = await runPipeline({
adapter, cfg, kind: job.kind, payload, model: cfgStore.modelFor(cfg), timeoutMs: TIMEOUT_MS,
// The HTTP adapters take the fetch they are given; the runtime adapters ignore it.
invokeOpts: { jobDir, env, fetch: fetchFor(TIMEOUT_MS) }
// The HTTP adapters take the fetch and the abort signal they are given; the runtime
// adapters ignore both.
invokeOpts: { jobDir, env, fetch: fetchFor(TIMEOUT_MS), signal: ctl.signal }
});
if (!attempt.ok) {
return finish(job, { outcome: 'failed', errorClass: attempt.errorClass, detail: attempt.detail });
// Cancelled by a forget, not failed by the provider: the log must not blame the job budget.
const errorClass = ctl.signal.aborted ? 'forgotten' : attempt.errorClass;
return finish(job, { outcome: 'failed', errorClass, detail: attempt.detail });
}
if (attempt.nochange) {
return finish(job, { outcome: 'nochange', pending: null, detail: null, reading: attempt.reading });
@@ -320,6 +356,7 @@ async function execute(job) {
};
return finish(job, { outcome: 'ready', pending });
} finally {
aborts.delete(job.uid);
if (jobDir) fs.rmSync(jobDir, { recursive: true, force: true });
}
}
+2 -1
View File
@@ -179,7 +179,8 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {
? { ok: true, dropped: false, why: 'this provider runs no child process' }
: canDropPrivileges(),
// Counts and outcomes only — never intake answers, payloads or proposals (FR-12/A4).
jobsToday: log.filter(e => (e.at || '').slice(0, 10) === today).length,
// The same counter the instance cap reads, so the card and the cap cannot disagree.
jobsToday: cfg.daily?.date === today ? cfg.daily.count : 0,
lastSuccess: cfgStore.lastSuccess(),
lastError: cfgStore.lastError(),
recent: log.slice(-20).reverse().map(e => ({ at: e.at, kind: e.kind, trigger: e.trigger, outcome: e.outcome, errorClass: e.errorClass, ms: e.ms }))
+10 -4
View File
@@ -386,7 +386,8 @@ paths:
Bumps the account's session version, which invalidates **every** cookie and
Bearer token ever issued for it — on every device, including a copy someone
walked off with. Passkeys are untouched; signing back in works immediately.
Also clears the caller's own cookie.
Also clears the caller's own cookie. Unredeemed pairing codes for the account
are voided too.
responses:
'200':
description: All sessions revoked.
@@ -518,11 +519,15 @@ paths:
oneOf: [{ type: number }, { type: 'null' }]
description: Echo of the pushed state's `_ts`, if present.
'400':
description: '`state` missing or not an object.'
description: >-
`state` missing or not an object, or `workouts`/`routines` set to anything
other than an array or null.
content:
application/json:
schema: { $ref: '#/components/schemas/Error' }
example: { error: "state required" }
examples:
missing: { value: { error: "state required" } }
invalid: { value: { error: "invalid state" } }
'401': { $ref: '#/components/responses/Unauthorized' }
/api/push/public-key:
@@ -1135,7 +1140,8 @@ components:
description: |
The whole app state as one blob. The server treats it as opaque (it only
strips `active` on save and reads a few fields for reminders and the admin
dashboard) — the schema below is **representative, not enforced**, and grows
dashboard) — the schema below is **representative, not enforced** (except
`workouts` and `routines`, which must be arrays (or null) when present), and grows
with the app. Conflict resolution is client-side via `_ts`.
properties:
_ts:
+78 -24
View File
@@ -6,6 +6,7 @@ import fs from 'node:fs';
import path from 'node:path';
import https from 'node:https';
import dns from 'node:dns';
import net from 'node:net';
import {
generateRegistrationOptions, verifyRegistrationResponse,
generateAuthenticationOptions, verifyAuthenticationResponse
@@ -96,7 +97,10 @@ webpush.setVapidDetails(VAPID_SUBJECT, vapid.publicKey, vapid.privateKey);
1. PUSH_AGENT rejects any connection to a private/loopback/link-local address at the moment
the socket is opened. Validating the URL alone would leave a DNS-rebinding window — the
name is resolved a second time inside web-push — so the check has to live in the lookup
the request itself uses, not in a prior pass.
the request itself uses, not in a prior pass. A literal IP address never goes through
that lookup at all — Node hands it straight to connect() — so literals are judged by
pushEndpointError instead: at subscribe, and again in sendPush for an endpoint that got
into db.json some other way.
2. PUSH_TIMEOUT_MS: an endpoint that accepts TCP and then stalls used to hang the request
handler that awaited it, indefinitely. web-push sets no timeout of its own.
3. PUSH_CONCURRENCY: one small request must not turn into an unbounded burst of outbound
@@ -119,14 +123,37 @@ function isPrivateAddr(ip) {
if (a >= 224) return true; // multicast + reserved
return false;
}
const m6 = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(v);
if (m6) return isPrivateAddr(m6[1]); // IPv4-mapped IPv6
if (v === '::' || v === '::1') return true; // unspecified, loopback
if (/^fe[89ab]/.test(v)) return true; // link-local
if (/^f[cd]/.test(v)) return true; // unique local
// IPv6 is judged on its eight groups, never on the text: the same address arrives as
// `::ffff:127.0.0.1` from dns.lookup, as `::ffff:7f00:1` from new URL, and in whatever
// spelling a caller chose, and a rule keyed to one spelling misses the others.
const g = ipv6Groups(v);
if (!g) return false;
if (g.slice(0, 5).every(x => x === 0) && g[5] === 0xffff) { // IPv4-mapped IPv6
return isPrivateAddr(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
}
if (g.slice(0, 7).every(x => x === 0) && g[7] <= 1) return true; // unspecified, loopback
if ((g[0] & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
if ((g[0] & 0xfe00) === 0xfc00) return true; // unique local fc00::/7
return false;
}
// The eight 16-bit groups of an IPv6 literal in any textual form — compressed, zero-padded,
// upper-case, with a dotted IPv4 tail — or null when the string is not one.
function ipv6Groups(v) {
if (!net.isIPv6(v)) return null;
let s = v.replace(/%.*$/, ''); // zone id
const m4 = /:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(s);
if (m4) {
const [a, b, c, d] = m4[1].split('.').map(Number);
s = s.slice(0, -m4[1].length) + ((a << 8) | b).toString(16) + ':' + ((c << 8) | d).toString(16);
}
const [head, tail = ''] = s.split('::');
const groups = head ? head.split(':') : [];
const rest = tail ? tail.split(':') : [];
if (s.includes('::')) while (groups.length + rest.length < 8) groups.push('0');
return groups.concat(rest).map(x => parseInt(x, 16));
}
// Same shape as dns.lookup, so https.Agent can use it directly.
function guardedLookup(hostname, options, cb) {
dns.lookup(hostname, options, (err, address, family) => {
@@ -141,15 +168,16 @@ function guardedLookup(hostname, options, cb) {
const PUSH_AGENT = new https.Agent({ lookup: guardedLookup, keepAlive: false });
// Cheap pre-check so a bad endpoint is refused at subscribe time with a useful message, rather
// than silently never delivering. PUSH_AGENT is what actually enforces the address rule.
// than silently never delivering. For a hostname PUSH_AGENT is what actually enforces the address
// rule; for a literal address this is the check, which is why sendPush runs it again.
function pushEndpointError(raw) {
let u;
try { u = new URL(String(raw || '')); } catch { return 'endpoint is not a valid URL'; }
if (u.protocol !== 'https:') return 'endpoint must be an https:// URL';
if (u.username || u.password) return 'endpoint must not carry credentials';
// A literal address can be judged right here, which turns the common case into a clear error
// at subscribe time instead of a delivery that quietly never happens. Hostnames are left to
// PUSH_AGENT, which is the check that actually has to hold.
// A literal address is judged right here — and only here: Node hands a literal straight to
// connect() without consulting the Agent's lookup. Hostnames are left to PUSH_AGENT, which is
// the check that has to hold against rebinding.
const host = u.hostname.replace(/^\[|\]$/g, '');
if (/^[0-9.]+$/.test(host) || host.includes(':')) {
if (isPrivateAddr(host)) return 'endpoint must not point at a private address';
@@ -166,6 +194,14 @@ async function sendPush(userId, payload) {
const worker = async () => {
while (next < subs.length) {
const sub = subs[next++];
// Re-judged before every send: PUSH_AGENT never sees a literal address, so an endpoint
// that is private (however it got into db.json) is dropped here rather than connected to.
const bad = pushEndpointError(sub.endpoint);
if (bad) {
console.error('push endpoint refused', userId, bad);
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true;
continue;
}
// urgency 'high' is the one lever we have over delivery speed — iOS/Android throttle
// low-urgency background push more aggressively under battery-saving modes. TTL is left
// at the library default (long) so a briefly-offline device still gets it once reconnected,
@@ -230,19 +266,26 @@ function userNow(tz) {
setInterval(() => {
for (const user of db.users) {
if (!db.subs.some(s => s.userId === user.id)) continue;
const S = readState(user.id);
if (!S?.reminder?.on) continue;
const now = userNow(S.reminder.tz || 'UTC');
if (!now || S.reminder.time !== now.hhmm) continue;
if (user.lastReminder === now.date) continue;
if ((S.workouts || []).some(w => w.d === now.date)) continue;
const rid = effectiveRoutineId(S, now.date);
if (!rid) continue; // rest day — nothing planned
const routine = (S.routines || []).find(r => r.id === rid);
console.log('reminder firing', user.id, rid);
user.lastReminder = now.date;
saveDb();
sendPush(user.id, dayReminderPush(S.lang, routine));
// One user's state file is one user's problem: a shape this tick cannot read is logged and
// skipped, not allowed to take the process — and everyone else's reminders — down with it.
// PUT /api/data refuses the obvious shapes, but a file already on disk answers to nobody.
try {
const S = readState(user.id);
if (!S?.reminder?.on) continue;
const now = userNow(S.reminder.tz || 'UTC');
if (!now || S.reminder.time !== now.hhmm) continue;
if (user.lastReminder === now.date) continue;
if ((S.workouts || []).some(w => w.d === now.date)) continue;
const rid = effectiveRoutineId(S, now.date);
if (!rid) continue; // rest day — nothing planned
const routine = (S.routines || []).find(r => r.id === rid);
console.log('reminder firing', user.id, rid);
user.lastReminder = now.date;
saveDb();
sendPush(user.id, dayReminderPush(S.lang, routine));
} catch (e) {
console.error('reminder tick', user.id, e);
}
}
// Checked every 10s (not 60s) — ticks aren't aligned to the top of the minute, so a 60s
// interval could sit on your target minute for up to 59s before noticing. 10s caps that at ~9s.
@@ -716,6 +759,8 @@ const routes = {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
user.sv = sessionVersion(user) + 1;
// An unredeemed pairing code is a session-in-waiting for this account; it goes too.
for (const [k, v] of pairings) if (v.uid === user.id) pairings.delete(k);
saveDb();
audit(req, 'auth.logout.all', { user });
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
@@ -766,6 +811,11 @@ const routes = {
if (!user) return json(res, 401, { error: 'not signed in' });
const body = await readBody(req);
if (!body.state || typeof body.state !== 'object') return json(res, 400, { error: 'state required' });
// The reminder tick and the admin routes iterate these two on the server's side, so a truthy
// non-array would throw there on every pass for as long as it sat on disk. Absent or null is
// fine — every client fills its own defaults.
const list = v => v == null || Array.isArray(v);
if (!list(body.state.workouts) || !list(body.state.routines)) return json(res, 400, { error: 'invalid state' });
delete body.state.active; // in-progress workouts stay device-local
atomicWrite(stateFile(user.id), JSON.stringify(body.state));
json(res, 200, { ok: true, ts: body.state._ts || null });
@@ -1012,7 +1062,11 @@ http.createServer(async (req, res) => {
});
return res.end();
}
const url = new URL(req.url, 'http://x');
// A target that does not parse (`//`, `//api%2Fhealth`) is a bad request, not a server error —
// and the try below only covers the route handler, so it is refused here.
let url;
try { url = new URL(req.url, 'http://x'); }
catch { return json(res, 400, { error: 'bad request' }); }
const key = req.method + ' ' + url.pathname;
const handler = routes[key];
if (!handler) return json(res, 404, { error: 'not found' });
+16 -1
View File
@@ -18,10 +18,12 @@ const { attemptOnce } = await import('../coach/core/pipeline.js');
const { HTTP_PROVIDERS, validateBaseUrl } = await import('../coach/core/providers.js');
const { SYSTEM_PROMPT } = await import('../coach/core/system-prompt.js');
/** A fetch that records what it was asked and answers from a script. */
/** A fetch that records what it was asked and answers from a script. Like the real one, it
* refuses an already-aborted signal without putting anything on the wire. */
function fakeFetch(answers) {
const calls = [];
const f = async (url, init) => {
if (init.signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError' });
calls.push({ url, method: init.method, headers: init.headers || {}, body: init.body ? JSON.parse(init.body) : null });
const a = typeof answers === 'function' ? answers(calls.length, url, init) : answers[Math.min(calls.length, answers.length) - 1];
if (a instanceof Error) throw a;
@@ -168,6 +170,19 @@ test('a transient status (429, 5xx, 529) is retried twice with the same request,
assert.equal(f.calls.length, 1);
});
test('an abort that lands during a retry pause sends nothing more and ends as a timeout', async () => {
// A forget mid-backoff: the payload must not go out a second time, and the job must drain
// now rather than wait for the next attempt to time out.
const ac = new AbortController();
const f = fakeFetch([{ status: 429, body: { error: { message: 'slow down' } } }]);
const p = openai.invoke({ cfg: {}, prompt: 'P', env, fetch: f, signal: ac.signal, retryDelayMs: 10000 });
await new Promise(r => setTimeout(r, 20)); // the first 429 is back and the pause has begun
ac.abort();
const r = await p;
assert.equal(f.calls.length, 1, 'the payload is not sent again');
assert.equal(r.timedOut, true);
});
test('a body that is not JSON on an error still yields a readable stderr', async () => {
const f = fakeFetch([{ status: 502, body: '<html>bad gateway</html>' }]);
const r = await gemini.invoke({ cfg: {}, prompt: 'P', env, fetch: f });
+227
View File
@@ -0,0 +1,227 @@
/* What bounds the Coach's spend, pinned against the real queue and the fixture provider.
*
* Forget keeps today's per-profile count. The instance count is reserved at enqueue and is
* not read off the capped job log. A scheduled review covers a batch of workouts once, on the
* workout's own clock rather than the phone's local date, and an answer the model was paid
* for counts as that review even when it was unusable. */
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { tempData, writeState, sampleState } from './helpers.mjs';
const DIR = tempData();
const cfg = await import('../coach/config.js');
const jobs = await import('../coach/jobs.js');
const cadence = await import('../coach/cadence.js');
const { forcePrivilegeVerdict } = await import('../coach/adapters/spawn.js');
cfg.save({ enabled: true, provider: 'fixture' });
forcePrivilegeVerdict({ ok: true, dropped: false, why: 'pinned by the test suite' });
const today = new Date().toISOString().slice(0, 10);
const userFile = uid => `${DIR}/coach/${uid}.json`;
async function settle(uid, ms = 15000) {
const until = Date.now() + ms;
while (Date.now() < until) {
const s = jobs.status(uid);
if (!s.job) return s;
await new Promise(r => setTimeout(r, 25));
}
throw new Error('job never finished');
}
const lastOutcome = uid => jobs.readUser(uid).history.at(-1);
/* ---------- the per-profile cap survives forget ---------- */
test('forgetting a profile does not hand it a fresh daily cap', async () => {
const uid = 'u-forget-cap';
writeState(DIR, uid, sampleState());
cfg.save({ caps: { perProfileDaily: 1, instanceDaily: 0 } });
try {
jobs.enqueue(uid, { kind: 'review' });
await settle(uid);
assert.equal(jobs.capState(uid).used, 1);
jobs.clearUser(uid);
const s = jobs.status(uid);
assert.equal(s.pending, null, 'the proposal is gone');
assert.deepEqual(jobs.readUser(uid).history, [], 'the history is gone');
assert.equal(s.cap.used, 1, 'the day\'s count is a spending record, not the profile\'s data');
assert.throws(() => jobs.enqueue(uid, { kind: 'review' }), e => e.code === 'cap');
} finally {
cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 0 } });
}
});
test('with nothing spent today, forget leaves no file at all', () => {
const uid = 'u-forget-empty';
jobs.setShare(uid, true);
assert.ok(fs.existsSync(userFile(uid)));
jobs.clearUser(uid);
assert.equal(fs.existsSync(userFile(uid)), false);
// Yesterday's count is already worth nothing to the cap, so it does not keep the file either.
fs.writeFileSync(userFile(uid), JSON.stringify({ daily: { date: '2000-01-01', count: 5 }, history: [] }));
jobs.clearUser(uid);
assert.equal(fs.existsSync(userFile(uid)), false);
});
/* ---------- the instance cap ---------- */
test('the instance cap is reserved at enqueue, so a job still running already counts', async () => {
cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 1 }, daily: null, log: [] });
try {
writeState(DIR, 'u-inst-1', sampleState());
writeState(DIR, 'u-inst-2', sampleState());
jobs.enqueue('u-inst-1', { kind: 'review' });
assert.ok(jobs.status('u-inst-1').job, 'the first job is on its way');
assert.throws(() => jobs.enqueue('u-inst-2', { kind: 'review' }), e => e.code === 'cap',
'the second profile is refused before the first job has finished');
await settle('u-inst-1');
assert.equal(lastOutcome('u-inst-1').outcome, 'ready');
assert.deepEqual(cfg.load().daily, { date: today, count: 1 });
} finally {
cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 0 } });
}
});
test('the instance count is not bounded by the length of the job log', () => {
const uid = 'u-inst-150';
writeState(DIR, uid, sampleState());
cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 150 }, daily: { date: today, count: 150 }, log: [] });
try {
assert.throws(() => jobs.enqueue(uid, { kind: 'review' }), e => e.code === 'cap',
'a hundred and fifty jobs today trip a cap of a hundred and fifty, empty log or not');
// Yesterday's count is nobody's business today.
cfg.save({ daily: { date: '2000-01-01', count: 150 } });
assert.doesNotThrow(() => jobs.enqueue(uid, { kind: 'review' }));
assert.deepEqual(cfg.load().daily, { date: today, count: 1 });
} finally {
cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 0 } });
}
return settle(uid);
});
/* ---------- scheduled reviews ---------- */
/** startCadence arms a setInterval; take the callback so the tests can tick it by hand. */
function captureTick(deps) {
const real = globalThis.setInterval;
let fn = null;
globalThis.setInterval = f => { fn = f; return { unref() {} }; };
try { cadence.startCadence(deps); } finally { globalThis.setInterval = real; }
return fn;
}
// `end` lands a second past now, so the workout is after any review that has just finished.
const newWorkout = id => ({ ...sampleState().workouts[0], id, d: today, start: Date.now() - 60000, end: Date.now() + 1000 });
test('a scheduled review reads a batch of workouts once, not once per tick', async () => {
const uid = 'u-cadence';
const S = sampleState({ coach: { ...sampleState().coach, cadence: { everyWorkouts: 1 } } });
writeState(DIR, uid, S);
const tick = captureTick({ users: () => [{ id: uid }], userNow: () => ({ date: today, hhmm: '18:00', weekday: 4 }) });
process.env.FIXTURE_MODE = 'nochange';
try {
tick();
assert.ok(jobs.status(uid).job, 'the first tick queues a review');
tick();
await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'nochange');
assert.equal(lastOutcome(uid).trigger, 'scheduled');
// The phone never opened, so lastReview in the synced state is still unset — and the same
// workout must not be reviewed again on every tick until the daily cap is gone.
tick(); tick(); tick();
assert.equal(jobs.status(uid).job, null);
assert.equal(jobs.readUser(uid).history.length, 1);
assert.equal(jobs.capState(uid).used, 1);
// A new workout is new news.
S.workouts.push(newWorkout('w2'));
writeState(DIR, uid, S);
tick();
assert.ok(jobs.status(uid).job, 'a fresh workout is due');
await settle(uid);
assert.equal(jobs.readUser(uid).history.length, 2);
} finally {
delete process.env.FIXTURE_MODE;
}
});
test('a workout the phone dated tomorrow is not re-read once the review has covered it', async () => {
const uid = 'u-cadence-tz';
// The phone stamps `d` in its own timezone: a morning session in Tokyo already carries
// tomorrow's date by the server's UTC clock. Its `end` is on the clock the review is timed on.
const tomorrow = new Date(Date.now() + 86400000).toISOString().slice(0, 10);
const S = sampleState({ coach: { ...sampleState().coach, cadence: { everyWorkouts: 1 } } });
S.workouts.push({ ...newWorkout('w-ahead'), d: tomorrow, start: Date.now() - 45 * 60000, end: Date.now() - 60000 });
writeState(DIR, uid, S);
const tick = captureTick({ users: () => [{ id: uid }], userNow: () => ({ date: today, hhmm: '18:00', weekday: 4 }) });
process.env.FIXTURE_MODE = 'nochange';
try {
tick();
await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'nochange');
tick();
assert.equal(jobs.status(uid).job, null, 'the review already read that workout, whatever date the phone gave it');
assert.equal(jobs.readUser(uid).history.length, 1);
} finally {
delete process.env.FIXTURE_MODE;
}
});
test('an answer the model was paid for counts as the review, even when it was unusable', async () => {
const uid = 'u-cadence-unusable';
const S = sampleState({ coach: { ...sampleState().coach, cadence: { everyWorkouts: 1 } } });
writeState(DIR, uid, S);
const tick = captureTick({ users: () => [{ id: uid }], userNow: () => ({ date: today, hhmm: '18:00', weekday: 4 }) });
process.env.FIXTURE_MODE = 'invalid';
try {
tick();
await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'failed');
assert.equal(lastOutcome(uid).errorClass, 'unusable');
tick();
assert.equal(jobs.status(uid).job, null, 'the model read those workouts; sending them again pays twice for the same data');
assert.equal(jobs.capState(uid).used, 1);
// A call that never reached the model read nothing, so the same workouts are asked about again.
process.env.FIXTURE_MODE = 'crash';
S.workouts.push(newWorkout('w2'));
writeState(DIR, uid, S);
tick();
await settle(uid);
assert.equal(lastOutcome(uid).errorClass, 'provider');
tick();
assert.ok(jobs.status(uid).job, 'a provider that fell over is retried on the next tick');
await settle(uid);
} finally {
delete process.env.FIXTURE_MODE;
}
});
test('a proposal nobody has answered is not replaced by the next scheduled review', async () => {
const uid = 'u-cadence-pending';
const S = sampleState({ coach: { ...sampleState().coach, cadence: { everyWorkouts: 1 } } });
writeState(DIR, uid, S);
const tick = captureTick({ users: () => [{ id: uid }], userNow: () => ({ date: today, hhmm: '18:00', weekday: 4 }) });
tick();
const first = await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'ready');
assert.ok(first.pending, 'a proposal is waiting');
S.workouts.push(newWorkout('w2'));
writeState(DIR, uid, S);
tick();
assert.equal(jobs.status(uid).job, null, 'not while the proposal is unread');
assert.equal(jobs.status(uid).pending.id, first.pending.id, 'the unread proposal is still the same one');
// Once it is answered, the workout logged since is due.
jobs.resolvePending(uid, { dismissed: true });
tick();
assert.ok(jobs.status(uid).job, 'the workout since the last review is due');
await settle(uid);
assert.equal(jobs.readUser(uid).history.filter(h => h.outcome === 'ready').length, 2);
});
+7
View File
@@ -101,3 +101,10 @@ test('the admin switch decides whether the prompt ever sees a cohort', () => {
assert.equal(cohort.cohortForPayload('a'), null);
cfg.save({ community: true });
});
test('forgetting a profile takes it out of the room at once, cache or no cache', () => {
assert.equal(cohort.computeCohort('a').people, 4);
jobs.clearUser('b');
assert.equal(jobs.isSharing('b'), false);
assert.equal(cohort.computeCohort('a').people, 3);
});
+159
View File
@@ -115,6 +115,165 @@ test('forgetting a profile leaves no server-side residue', async () => {
assert.deepEqual(jobs.readUser(uid).history, []);
});
/* ---------- forget while a job is live ----------
A provider on localhost that parks every request until the test lets it answer, so a job
can be caught mid-call or still waiting for a slot. */
async function holdingProvider() {
const http = await import('node:http');
const held = [], seen = [];
const server = http.createServer((req, res) => {
let body = '';
req.on('data', c => { body += c; });
req.on('end', () => { seen.push(JSON.parse(body || '{}')); held.push(res); });
// A caller that hangs up mid-call takes its parked response with it.
res.on('close', () => { const i = held.indexOf(res); if (i >= 0) held.splice(i, 1); });
});
await new Promise(r => server.listen(0, '127.0.0.1', r));
/** Exactly n requests parked with the provider — 0 means every caller has gone. */
const until = async n => {
const t = Date.now() + 15000;
while (held.length !== n && Date.now() < t) await new Promise(r => setTimeout(r, 25));
assert.equal(held.length, n, `${n} request(s) with the provider`);
};
const answer = content => {
for (const res of held.splice(0)) {
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ choices: [{ finish_reason: 'stop', message: { content } }] }));
}
};
const use = () => cfg.save({ enabled: true, provider: 'compatible', providerOptions: { compatible: { baseUrl: `http://127.0.0.1:${server.address().port}` } }, models: { compatible: 'local-model' } });
// Parked responses hold their sockets open; a failing test must not hold node --test with them.
const close = () => { cfg.save({ provider: 'fixture' }); server.close(); server.closeAllConnections(); };
return { seen, held, until, answer, use, close };
}
const NOCHANGE = '{"coach_contract":1,"nochange":true,"reading":"Steady."}';
/** The job's own end, as opposed to status() going quiet: the instance log gains its line. */
async function logged(n) {
const t = Date.now() + 15000;
while (cfg.load().log.length < n && Date.now() < t) await new Promise(r => setTimeout(r, 25));
assert.equal(cfg.load().log.length, n);
}
test('forgetting a profile mid-job cancels the call and frees its slot at once', async () => {
const p = await holdingProvider();
const notified = [];
jobs.setProposalHook(uid => notified.push(uid));
try {
p.use();
const uid = 'u-forget-live';
writeState(DIR, uid, sampleState());
jobs.enqueue(uid, { kind: 'review' });
await p.until(1);
assert.equal(jobs.status(uid).job.state, 'running');
const before = cfg.load().log.length;
const t0 = Date.now();
jobs.clearUser(uid);
assert.equal(jobs.status(uid).job, null);
// The provider is never answered: the call goes with the record, so the job drains now
// rather than when the provider gets round to it or the five-minute timeout does.
await logged(before + 1);
assert.ok(Date.now() - t0 < 5000, `drained in ${Date.now() - t0} ms`);
await p.until(0);
assert.equal(cfg.load().log.at(-1).outcome, 'failed', 'the job ran and is counted');
assert.equal(cfg.load().log.at(-1).errorClass, 'forgotten', 'the log names the cancellation, not a provider timeout');
assert.deepEqual(jobs.readUser(uid).pending, null, 'nothing is held for someone who asked to be forgotten');
assert.deepEqual(jobs.readUser(uid).history, [], 'the record is not recreated');
assert.deepEqual(notified, [], 'nobody is told about it');
assert.equal(jobs.capState(uid).used, 1);
// Single-flight went with the job: the profile can ask again straight away, not once the
// provider hold is over.
assert.doesNotThrow(() => jobs.enqueue(uid, { kind: 'review' }), 'the slot is free again');
await p.until(1);
p.answer(NOCHANGE);
await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'nochange');
} finally {
jobs.setProposalHook(null);
p.close();
}
});
test('a runtime that cannot be cancelled still has its late answer discarded after a forget', async () => {
// The fixture CLI is a child process, and the abort signal means nothing to one: it runs to
// its answer, which then has nobody to belong to.
const uid = 'u-forget-spawned';
writeState(DIR, uid, sampleState());
const notified = [];
jobs.setProposalHook(u => notified.push(u));
try {
jobs.enqueue(uid, { kind: 'review' });
assert.equal(jobs.status(uid).job.state, 'running');
jobs.clearUser(uid);
// The line this job writes to the instance log, not the next line anyone writes there.
const mine = () => cfg.load().log.find(e => e.uid === uid);
for (const t = Date.now() + 15000; !mine() && Date.now() < t;) await new Promise(r => setTimeout(r, 25));
assert.equal(mine()?.outcome, 'ready', 'the job ran to its answer and is counted');
assert.deepEqual(jobs.readUser(uid).pending, null, 'the proposal is not held for someone who asked to be forgotten');
assert.deepEqual(jobs.readUser(uid).history, []);
assert.deepEqual(notified, [], 'nobody is told about it');
} finally {
jobs.setProposalHook(null);
}
});
test('forgetting a profile whose job is still queued drops it before anything leaves', async () => {
const p = await holdingProvider();
try {
p.use();
// Two other profiles hold both execution slots, so the third waits.
for (const u of ['u-slot-1', 'u-slot-2']) { writeState(DIR, u, sampleState()); jobs.enqueue(u, { kind: 'review' }); }
await p.until(2);
const uid = 'u-forget-queued';
writeState(DIR, uid, sampleState());
jobs.enqueue(uid, { kind: 'review' });
assert.equal(jobs.status(uid).job.state, 'queued');
jobs.clearUser(uid);
assert.equal(jobs.status(uid).job, null);
p.answer(NOCHANGE);
await settle('u-slot-1'); await settle('u-slot-2');
await new Promise(r => setTimeout(r, 200)); // a job still queued would have started by now
assert.equal(p.seen.length, 2, 'the forgotten profile\'s payload never reached the provider');
assert.equal(jobs.status(uid).job, null);
assert.deepEqual(jobs.readUser(uid).history, []);
// Single-flight was released with the job, so the profile can ask again.
jobs.enqueue(uid, { kind: 'review' });
await p.until(1);
p.answer(NOCHANGE);
await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'nochange');
} finally { p.close(); }
});
test('consent withdrawn, or the Coach switched off, while a job waits: no payload leaves', async () => {
const p = await holdingProvider();
try {
p.use();
for (const u of ['u-slot-3', 'u-slot-4']) { writeState(DIR, u, sampleState()); jobs.enqueue(u, { kind: 'review' }); }
await p.until(2);
writeState(DIR, 'u-revoked', sampleState());
writeState(DIR, 'u-switched-off', sampleState());
jobs.enqueue('u-revoked', { kind: 'review' });
jobs.enqueue('u-switched-off', { kind: 'review' });
assert.equal(jobs.status('u-switched-off').job.state, 'queued');
// Consent gone from the synced state — no forget call, so the record itself stays and says
// what happened. Then the admin switches the Coach off before a slot frees.
writeState(DIR, 'u-revoked', sampleState({ coach: {} }));
cfg.save({ enabled: false });
p.answer(NOCHANGE);
await settle('u-revoked'); await settle('u-switched-off');
assert.equal(p.seen.length, 2, 'neither queued job reached the provider');
assert.equal(lastOutcome('u-revoked').outcome, 'failed');
assert.equal(lastOutcome('u-revoked').errorClass, 'consent');
assert.equal(lastOutcome('u-switched-off').outcome, 'failed');
assert.equal(lastOutcome('u-switched-off').errorClass, 'off');
} finally { cfg.save({ enabled: true }); p.close(); }
});
test('a job interrupted by a restart is reported as failed, not left spinning', () => {
const uid = 'u-restart';
fs.mkdirSync(`${DIR}/coach`, { recursive: true });
+85
View File
@@ -0,0 +1,85 @@
/* "Sign out everywhere" (POST /api/logout/all) has to take the account's outstanding pairing
codes with it: a code is a session-in-waiting, and one minted before the sign-out could
otherwise be redeemed for a fresh token carrying the new session version. Real server.js in a
child. */
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, sv) => ({ Cookie: `gymsid=${mintSession(uid, sv)}` });
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_test_1', name: 'One', created: new Date().toISOString() },
{ id: 'u_test_2', name: 'Two', created: new Date().toISOString() }
];
async function startServer(t) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-pair-'));
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' }
});
const h = { api: `http://127.0.0.1:${port}`, 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;
}
test('logout/all invalidates the account\'s outstanding pairing codes and nobody else\'s', async t => {
const h = await startServer(t);
const post = (p, headers, body) => fetch(`${h.api}${p}`, { method: 'POST', headers, body: body && JSON.stringify(body) });
const create = async (uid, sv) => {
const r = await post('/api/pair/create', cookie(uid, sv));
assert.equal(r.status, 200);
return (await r.json()).code;
};
const redeem = code => post('/api/pair/redeem', {}, { code });
// control: mint and redeem with nothing in between
assert.equal((await redeem(await create('u_test_1', 0))).status, 200);
// a code minted before "sign out everywhere" is refused after it
const stale = await create('u_test_1', 0);
const other = await create('u_test_2', 0);
assert.equal((await post('/api/logout/all', cookie('u_test_1', 0))).status, 200);
const r = await redeem(stale);
assert.equal(r.status, 400);
assert.deepEqual(await r.json(), { error: 'invalid or expired code' });
// the other account's code is untouched
assert.equal((await redeem(other)).status, 200);
// and a code minted after the sign-out (session version 1 now) redeems for a token of that version
const fresh = await redeem(await create('u_test_1', 1));
assert.equal(fresh.status, 200);
const { token } = await fresh.json();
assert.match(token.split('.')[0], /^u_test_1:\d+:1$/);
});
+104
View File
@@ -0,0 +1,104 @@
/* The push endpoint private-address rule, judged on every textual form of an IP literal. new URL
canonicalizes `[::ffff:127.0.0.1]` to `[::ffff:7f00:1]`, and Node never consults an Agent's
custom lookup for a literal host, so a literal that slips the subscribe-time check is one the
send path will actually connect to. Both ends are covered here: subscribe refuses, and a
private literal already sitting in db.json is refused at send time without a socket being
opened. Real server.js in a child. */
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) {
const payload = `${uid}:${Date.now() + 86400000}:0`;
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
}
const cookie = { Cookie: `gymsid=${mintSession('u_test_1')}` };
// Real-shaped keys (65-byte P-256 point, 16-byte auth secret): web-push validates them before it
// opens a socket, and the send-time test below is only meaningful if the socket would have opened.
const keys = {
p256dh: crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).publicKey.export({ type: 'spki', format: 'der' }).subarray(-65).toString('base64url'),
auth: crypto.randomBytes(16).toString('base64url')
};
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)); });
});
async function startServer(t, subs = []) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-push-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
users: [{ id: 'u_test_1', name: 'One', created: new Date().toISOString() }], 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' }
});
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;
}
test('subscribe refuses every spelling of a private IP literal and accepts public ones', async t => {
const h = await startServer(t);
const subscribe = endpoint => fetch(`${h.api}/api/push/subscribe`, {
method: 'POST', headers: cookie, body: JSON.stringify({ subscription: { endpoint, keys } })
});
const privateForms = [
'https://[::ffff:127.0.0.1]/x', // mapped loopback, dotted
'https://[::ffff:7f00:1]/x', // mapped loopback, hex (what new URL makes of the above)
'https://[0:0:0:0:0:ffff:7f00:1]/x', // mapped loopback, fully expanded
'https://[::ffff:169.254.169.254]/x', // mapped link-local (cloud metadata)
'https://[::FFFF:C0A8:0101]/x', // mapped 192.168.1.1, upper-case, zero-padded
'https://[::ffff:10.0.0.1]/x', // mapped private
'https://[0:0:0:0:0:0:0:1]/x', // loopback, expanded
'https://[::1]/x', // loopback, compressed
'https://[fe80::1]/x', // link-local
'https://[fd00::1]/x', // unique local
'https://127.0.0.1/x' // plain IPv4 (the case that always worked)
];
for (const ep of privateForms) {
const r = await subscribe(ep);
assert.equal(r.status, 400, ep);
assert.deepEqual(await r.json(), { error: 'endpoint must not point at a private address' }, ep);
}
for (const ep of ['https://[::ffff:8.8.8.8]/x', 'https://[::ffff:808:808]/x', 'https://[2606:4700::1111]/x', 'https://8.8.8.8/x', 'https://push.example/x']) {
assert.equal((await subscribe(ep)).status, 200, ep);
}
});
test('a private literal already stored as an endpoint is refused at send time, never connected to, and dropped', async t => {
// stands in for whatever else lives on the api container's network
const hits = [];
const target = net.createServer(s => { hits.push(s.remoteAddress); s.destroy(); });
await new Promise(r => target.listen(0, '127.0.0.1', r));
t.after(() => target.close());
const endpoint = `https://[::ffff:7f00:1]:${target.address().port}/x`;
const h = await startServer(t, [{ userId: 'u_test_1', endpoint, keys, created: new Date().toISOString() }]);
const r = await fetch(`${h.api}/api/push/test`, { method: 'POST', headers: cookie });
assert.equal(r.status, 200);
assert.deepEqual(hits, [], 'no socket reached the private address');
assert.match(h.log, /push endpoint refused u_test_1/);
const db = JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8'));
assert.equal(db.subs.length, 0, 'the unusable subscription is gone from db.json');
});
+115
View File
@@ -0,0 +1,115 @@
/* Two halves of the same rule — a state whose `workouts` or `routines` is not an array must not
be able to take the api down:
- PUT /api/data refuses the shape at the door (every real client sends arrays or leaves the
field out, so nothing legitimate changes);
- a file that got onto disk anyway is logged and skipped by the reminder tick, which runs
outside the per-route try/catch, and the users after it still get their reminders.
Real server.js in a child. The tick runs every 10 s, so the second
test waits on the log rather than on a fixed sleep. */
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) {
const payload = `${uid}:${Date.now() + 86400000}:0`;
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
}
const cookie = { Cookie: `gymsid=${mintSession('u_test_1')}` };
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_test_1', name: 'One', created: new Date().toISOString() },
{ id: 'u_test_2', name: 'Two', created: new Date().toISOString() }
];
async function startServer(t, subs = []) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-reminder-'));
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' }
});
const h = { api: `http://127.0.0.1:${port}`, dataDir, child, 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;
}
test('PUT /api/data refuses a state whose workouts or routines is not an array', async t => {
const h = await startServer(t);
const put = state => fetch(`${h.api}/api/data`, { method: 'PUT', headers: cookie, body: JSON.stringify({ state }) });
const file = path.join(h.dataDir, 'state-u_test_1.json');
for (const bad of [{ workouts: {} }, { workouts: 'abc' }, { workouts: 7 }, { workouts: true }, { routines: {} }, { routines: 'r1' }, { workouts: [], routines: {} }]) {
const r = await put({ _ts: 1, ...bad });
assert.equal(r.status, 400, JSON.stringify(bad));
assert.deepEqual(await r.json(), { error: 'invalid state' }, JSON.stringify(bad));
}
assert.equal(fs.existsSync(file), false, 'nothing landed on disk');
// the shapes real clients send still go through: arrays, the field left out, or null
assert.equal((await put({ _ts: 2, workouts: [], routines: [] })).status, 200);
assert.equal((await put({ _ts: 3 })).status, 200);
assert.equal((await put({ _ts: 4, workouts: null, routines: null })).status, 200);
assert.equal(JSON.parse(fs.readFileSync(file, 'utf8'))._ts, 4);
});
test('a non-array workouts on disk is logged and skipped by the reminder tick; the next user still fires', async t => {
const keys = { p256dh: 'p', auth: 'a' };
// localhost resolves to a loopback address, which PUSH_AGENT refuses — the send that follows the
// reminder fails locally and quietly, with no socket leaving this machine
const subs = USERS.map(u => ({ userId: u.id, endpoint: 'https://localhost/x', keys, created: new Date().toISOString() }));
const h = await startServer(t, subs);
const routines = [{ id: 'r1', name: 'Full body', emoji: '💪', ex: [] }];
const week = { 0: 'r1', 1: 'r1', 2: 'r1', 3: 'r1', 4: 'r1', 5: 'r1', 6: 'r1' };
// hh:mm exactly the way server.js userNow() derives it, so the reminder is "now" in UTC
const nowHHMM = () => {
const parts = new Intl.DateTimeFormat('en-CA', { timeZone: 'UTC', hour12: false, hour: '2-digit', minute: '2-digit' }).formatToParts(new Date());
const g = type => parts.find(p => p.type === type)?.value;
return `${g('hour')}:${g('minute')}`;
};
// The tick re-reads each state file every pass and only acts when the reminder is for the
// current minute, so both files are rewritten with "now" until the log shows the tick has done
// its work — a minute rolling over mid-wait cannot make it miss.
const seed = () => {
const reminder = { on: true, time: nowHHMM(), tz: 'UTC' };
fs.writeFileSync(path.join(h.dataDir, 'state-u_test_1.json'), JSON.stringify({ reminder, routines, week, workouts: {} }));
fs.writeFileSync(path.join(h.dataDir, 'state-u_test_2.json'), JSON.stringify({ reminder, routines, week, workouts: [] }));
};
const done = () => /reminder tick u_test_1/.test(h.log) && /reminder firing u_test_2 r1/.test(h.log);
const deadline = Date.now() + 30000;
while (Date.now() < deadline && !done() && h.child.exitCode === null) {
seed();
await new Promise(r => setTimeout(r, 500));
}
assert.equal(h.child.exitCode, null, `server exited:\n${h.log}`);
assert.match(h.log, /reminder tick u_test_1 TypeError/, h.log);
assert.match(h.log, /reminder firing u_test_2 r1/, h.log);
assert.equal((await fetch(`${h.api}/api/health`)).status, 200);
const db = JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8'));
assert.ok(db.users.find(u => u.id === 'u_test_2').lastReminder, 'the good user\'s reminder was recorded');
});
+64
View File
@@ -0,0 +1,64 @@
/* A request target that does not parse as a URL (`//`, `//api%2Fhealth`) must get a 400 from the
listener and leave the process running — the parse sits before the per-route try/catch, so a
throw there is an unhandled rejection and a dead api container. Raw sockets, because
fetch() refuses to send such targets in the first place. Real server.js in a child. */
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 freePort = () => new Promise(r => {
const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
});
async function startServer(t) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-url-'));
fs.writeFileSync(path.join(dataDir, 'secret'), crypto.randomBytes(32).toString('hex'), { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ 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' }
});
const h = { api: `http://127.0.0.1:${port}`, port, child, 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;
}
// One request over a bare TCP socket, target written verbatim; resolves with the raw response.
function rawGet(port, target) {
return new Promise((resolve, reject) => {
let out = '';
const s = net.connect(port, '127.0.0.1', () => s.write(`GET ${target} HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n`));
s.on('data', d => out += d);
s.on('end', () => resolve(out));
s.on('error', reject);
});
}
test('an unparseable request target is a 400, and the server keeps answering afterwards', async t => {
const h = await startServer(t);
for (const target of ['//', '//api%2Fhealth', '//api%2F/health']) {
const res = await rawGet(h.port, target);
assert.match(res, /^HTTP\/1\.1 400 /, `${target} ->\n${res || '(no response)'}\n${h.log}`);
}
// a normal target still parses and still routes
assert.match(await rawGet(h.port, '/api/health'), /^HTTP\/1\.1 200 /);
assert.equal((await fetch(`${h.api}/api/health`)).status, 200);
assert.equal(h.child.exitCode, null, `server exited:\n${h.log}`);
});
+3 -1
View File
@@ -80,7 +80,9 @@ gym.example.com {
### Option C — Traefik / nginx / Nginx Proxy Manager
Route `gym.example.com` (HTTPS) → `web:80` (or `<docker-host>:8080`). Any reverse proxy works —
openGym only needs the browser to reach it over `https://gym.example.com`.
openGym only needs the browser to reach it over `https://gym.example.com`. If that proxy caps
request bodies (nginx does, at 1 MiB by default), allow at least 5 MiB on `/api/` — the app syncs
its whole history in one PUT; the bundled web image already allows 5 MiB, matching the API.
Then set your domain in `.env` and restart:
+1 -1
View File
@@ -27,7 +27,7 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(631)
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(633)
expect(inherited).toHaveLength(634)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
+2
View File
@@ -344,6 +344,8 @@ export default {
'Reset everything?': 'Alles zurücksetzen?',
'Reset everything': 'Alles zurücksetzen',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Löscht Plan, Trainings und Körpergewicht auf diesem Gerät. Das kann nicht rückgängig gemacht werden.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Löscht Plan, Trainings und Körpergewicht aus deinem Profil auf diesem Server und auf allen angemeldeten Geräten. Das kann nicht rückgängig gemacht werden.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Synchronisierung fehlgeschlagen: Der Server hat den Upload als zu groß abgelehnt. Deine Änderungen sind noch nicht auf dem Server angekommen.',
'Delete everything': 'Alles löschen',
'All data reset': 'Alle Daten zurückgesetzt',
'Backup exported': 'Backup exportiert',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': '¿Restablecer todo?',
'Reset everything': 'Restablecer todo',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina tu plan, entrenamientos y peso corporal en este dispositivo. No se puede deshacer.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Elimina tu plan, entrenamientos y peso corporal de tu perfil en este servidor y en todos los dispositivos con sesión iniciada. No se puede deshacer.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Error de sincronización: el servidor rechazó la subida por ser demasiado grande. Tus cambios no han llegado al servidor.',
'Delete everything': 'Eliminar todo',
'All data reset': 'Todos los datos restablecidos',
'Backup exported': 'Copia exportada',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'Tout réinitialiser ?',
'Reset everything': 'Tout réinitialiser',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Supprime ton plan, tes séances et ton poids corporel sur cet appareil. Irréversible.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Supprime ton plan, tes séances et ton poids corporel de ton profil sur ce serveur et sur tous les appareils connectés. Irréversible.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Échec de la synchronisation : le serveur a refusé l’envoi, trop volumineux. Tes modifications n’ont pas atteint le serveur.',
'Delete everything': 'Tout supprimer',
'All data reset': 'Toutes les données réinitialisées',
'Backup exported': 'Sauvegarde exportée',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'सब कुछ रीसेट करें?',
'Reset everything': 'सब कुछ रीसेट करें',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'इस डिवाइस पर आपकी योजना, वर्कआउट और वज़न हट जाएँगे। इसे पूर्ववत नहीं किया जा सकता।',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'इस सर्वर पर आपकी प्रोफ़ाइल से और साइन इन किए हुए सभी डिवाइस से आपकी योजना, वर्कआउट और वज़न हट जाएँगे। इसे पूर्ववत नहीं किया जा सकता।',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'सिंक विफल: सर्वर ने अपलोड को बहुत बड़ा बताकर अस्वीकार कर दिया। आपके बदलाव सर्वर तक नहीं पहुँचे हैं।',
'Delete everything': 'सब हटाएँ',
'All data reset': 'सारा डेटा रीसेट',
'Backup exported': 'बैकअप निर्यात हुआ',
+2
View File
@@ -335,6 +335,8 @@ export default {
'Reset everything?': 'Mindent visszaállítasz?',
'Reset everything': 'Minden visszaállítása',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Törli a terved, edzéseid és testsúlyod ezen az eszközön. Ez nem vonható vissza.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Törli a terved, edzéseid és testsúlyod a profilodból ezen a szerveren és minden bejelentkezett eszközön. Ez nem vonható vissza.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'A szinkronizálás nem sikerült: a szerver túl nagynak találta a feltöltést és elutasította. A módosításaid nem jutottak el a szerverre.',
'Delete everything': 'Minden törlése',
'All data reset': 'Minden adat visszaállítva',
'Backup exported': 'Biztonsági mentés exportálva',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'Azzerare tutto?',
'Reset everything': 'Azzera tutto',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina piano, allenamenti e peso corporeo su questo dispositivo. Irreversibile.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Elimina piano, allenamenti e peso corporeo dal tuo profilo su questo server e su tutti i dispositivi connessi. Irreversibile.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Sincronizzazione fallita: il server ha rifiutato il caricamento perché troppo grande. Le tue modifiche non hanno raggiunto il server.',
'Delete everything': 'Elimina tutto',
'All data reset': 'Tutti i dati azzerati',
'Backup exported': 'Backup esportato',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': '전부 초기화할까요?',
'Reset everything': '전부 초기화',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': '이 기기의 계획, 운동, 체중을 삭제합니다. 되돌릴 수 없어요.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': '이 서버의 프로필과 로그인된 모든 기기에서 계획, 운동, 체중을 삭제합니다. 되돌릴 수 없어요.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': '동기화 실패: 서버가 업로드가 너무 크다며 거부했습니다. 변경 내용이 서버에 반영되지 않았습니다.',
'Delete everything': '전부 삭제',
'All data reset': '모든 데이터 초기화됨',
'Backup exported': '백업 내보냄',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'Zresetować wszystko?',
'Reset everything': 'Zresetuj wszystko',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Usuwa plan, treningi i masę ciała na tym urządzeniu. Nie można tego cofnąć.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Usuwa plan, treningi i masę ciała z profilu na tym serwerze i ze wszystkich zalogowanych urządzeń. Nie można tego cofnąć.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Synchronizacja nie powiodła się: serwer odrzucił przesyłanie jako zbyt duże. Twoje zmiany nie dotarły na serwer.',
'Delete everything': 'Usuń wszystko',
'All data reset': 'Wszystkie dane zresetowane',
'Backup exported': 'Kopia wyeksportowana',
+2
View File
@@ -114,6 +114,8 @@ export const PT_BR_OVERRIDES = {
'Reset everything?': 'Redefinir tudo?',
'Reset everything': 'Redefinir tudo',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Exclui seu plano, seus treinos e seu peso corporal deste dispositivo. Esta ação não pode ser desfeita.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Exclui seu plano, seus treinos e seu peso corporal do seu perfil neste servidor e de todos os dispositivos conectados. Esta ação não pode ser desfeita.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'A sincronização falhou: o servidor recusou o envio por ser grande demais. Suas alterações não chegaram ao servidor.',
'Delete everything': 'Excluir tudo',
'Backup exported': 'Backup exportado',
'Import backup?': 'Importar backup?',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'Repor tudo?',
'Reset everything': 'Repor tudo',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina o teu plano, treinos e peso corporal neste dispositivo. Não pode ser anulado.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Elimina o teu plano, treinos e peso corporal do teu perfil neste servidor e em todos os dispositivos com sessão iniciada. Não pode ser anulado.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'A sincronização falhou: o servidor recusou o envio por ser demasiado grande. As tuas alterações não chegaram ao servidor.',
'Delete everything': 'Eliminar tudo',
'All data reset': 'Todos os dados repostos',
'Backup exported': 'Cópia exportada',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'Сбросить всё?',
'Reset everything': 'Сбросить всё',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Удаляет план, тренировки и вес тела на этом устройстве. Отменить нельзя.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Удаляет план, тренировки и вес тела из профиля на этом сервере и со всех устройств, где выполнен вход. Отменить нельзя.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Синхронизация не удалась: сервер отклонил загрузку как слишком большую. Твои изменения не дошли до сервера.',
'Delete everything': 'Удалить всё',
'All data reset': 'Все данные сброшены',
'Backup exported': 'Копия экспортирована',
+2
View File
@@ -335,6 +335,8 @@ export default {
'Reset everything?': 'รีเซ็ตทุกอย่าง?',
'Reset everything': 'รีเซ็ตทุกอย่าง',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'จะลบแผน, การออกกำลังกาย และน้ำหนักตัวบนเครื่องนี้ ไม่สามารถย้อนกลับได้',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'จะลบแผน, การออกกำลังกาย และน้ำหนักตัวออกจากโปรไฟล์ของคุณบนเซิร์ฟเวอร์นี้ และจากทุกอุปกรณ์ที่เข้าสู่ระบบอยู่ ไม่สามารถย้อนกลับได้',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'ซิงค์ไม่สำเร็จ: เซิร์ฟเวอร์ปฏิเสธการอัปโหลดเพราะข้อมูลใหญ่เกินไป การเปลี่ยนแปลงของคุณยังไม่ถึงเซิร์ฟเวอร์',
'Delete everything': 'ลบทุกอย่าง',
'All data reset': 'รีเซ็ตข้อมูลทั้งหมดแล้ว',
'Backup exported': 'ส่งออกข้อมูลสำรองแล้ว',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'Her şey sıfırlansın mı?',
'Reset everything': 'Her şeyi sıfırla',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Bu cihazdaki planını, antrenmanlarını ve vücut ağırlığını siler. Geri alınamaz.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Bu sunucudaki profilinden ve oturum açılmış tüm cihazlardan planını, antrenmanlarını ve vücut ağırlığını siler. Geri alınamaz.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Eşitleme başarısız: sunucu yüklemeyi çok büyük diye reddetti. Değişikliklerin sunucuya ulaşmadı.',
'Delete everything': 'Her şeyi sil',
'All data reset': 'Tüm veriler sıfırlandı',
'Backup exported': 'Yedek dışa aktarıldı',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': '重置所有内容?',
'Reset everything': '重置所有内容',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': '删除本设备上的计划、训练和体重。无法撤销。',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': '从此服务器上的档案以及所有已登录设备中删除计划、训练和体重。无法撤销。',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': '同步失败:服务器拒绝了上传,内容过大。你的更改尚未同步到服务器。',
'Delete everything': '全部删除',
'All data reset': '所有数据已重置',
'Backup exported': '备份已导出',
+58 -9
View File
@@ -1,6 +1,7 @@
import { create } from 'zustand'
import { api, setRemoteAuth } from '../lib/api.js'
import { localTZ } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { registerCustom } from '../lib/exercises.js'
import { DEMO, DEMO_SEEDED } from '../lib/demo.js'
import { guestAllowed } from '../lib/guest.js'
@@ -92,6 +93,7 @@ export function restoredStateFor(local, remote, dirty = false) {
export const useStore = create((set, get) => {
let pushTm = null
let saveTm = null
let toldTooLarge = false
initReminderSync(() => get().S)
@@ -102,8 +104,12 @@ export const useStore = create((set, get) => {
saveTm = setTimeout(() => { saveTm = null; nativeSave(get().S); syncReminder(get().S) }, 800)
}
const persist = (S, push = true) => {
S._ts = Date.now()
// `_ts` is when this device last changed the data — it decides which copy wins on the next
// pull (restoredStateFor). A copy merely adopted from the server or the file mirror keeps the
// stamp it came with: re-stamping a read would make an unchanged copy look newer than a real
// change made on another device, and push it over that change.
const persist = (S, push = true, stamp = true) => {
if (stamp) S._ts = Date.now()
registerCustom(S.customEx)
localStorage.setItem(KEY, JSON.stringify(S))
set({ S })
@@ -133,13 +139,31 @@ export const useStore = create((set, get) => {
}
})
// Everything a sign-out leaves behind on this device, whichever way it was triggered.
// The owner check in setUser only runs in the tab that signs in. Another tab of the same
// browser still holding the previous profile would keep writing that profile's data over the
// shared copy and push it under the new session's cookie — so it drops the profile, and
// whoever signs in there passes the same check. The owner key is written last on both a
// sign-in and a sign-out, so on a new owner the copy in storage is already the wiped one; with
// no owner (a sign-out) this tab falls back to defaults rather than read the key at all — the
// previous profile's data must not stay here whichever key's event lands first.
window.addEventListener('storage', e => {
if (e.key !== 'gym_owner') return
const user = get().user
if (!user || e.newValue === user.id) return
clearTimeout(pushTm)
pushTm = null
set({ user: null, S: e.newValue ? loadState() : clone(DEF) })
})
// Everything a sign-out leaves behind on this device, whichever way it was triggered. The owner
// goes last, after the wiped copy is written — the storage listener above relies on the order.
const clearLocalSession = () => {
get().setUser(null)
localStorage.removeItem('gym_guest')
localStorage.removeItem('gym_dirty')
localStorage.removeItem(KEY)
persist(clone(DEF), false)
localStorage.removeItem('gym_owner')
}
return {
@@ -194,16 +218,41 @@ export const useStore = create((set, get) => {
},
setUser(u) {
if (u) { localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest') }
else localStorage.removeItem('gym_user')
if (u) {
// The local copy belongs to whoever last signed in here. When a session expires or is
// revoked elsewhere, boot() only drops the user and the data stays; a different profile
// signing in next must not inherit it (pullState would push it into that account, and
// carry the in-progress workout along). A proper sign-out clears the owner, so a guest's
// data still moves into a freshly created profile.
const owner = localStorage.getItem('gym_owner')
if (owner && owner !== u.id) {
localStorage.removeItem('gym_dirty')
localStorage.removeItem(KEY)
persist(clone(DEF), false)
}
localStorage.setItem('gym_owner', u.id)
localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest')
} else localStorage.removeItem('gym_user')
set({ user: u })
},
async pushState() {
if (!get().user) return
clearTimeout(pushTm)
try { await api('/api/data', { method: 'PUT', body: JSON.stringify({ state: get().S }) }); localStorage.removeItem('gym_dirty') }
catch (e) { localStorage.setItem('gym_dirty', '1') }
try { await api('/api/data', { method: 'PUT', body: JSON.stringify({ state: get().S }) }); localStorage.removeItem('gym_dirty'); toldTooLarge = false }
catch (e) {
localStorage.setItem('gym_dirty', '1')
// A 413 comes from the proxy in front of the API (nginx: client_max_body_size), which
// caps the request body. Every later push is at least as big, so nothing reaches the
// server until the limit is raised — said once per refusal streak; gym_dirty keeps the
// retries going. useUI imports this store, hence the lazy import.
if (e.status === 413 && !toldTooLarge) {
toldTooLarge = true
import('./useUI.js')
.then(({ useUI }) => useUI.getState().toast(t('Sync failed: the server refused the upload as too large. Your changes have not reached the server.')))
.catch(() => {})
}
}
},
async pullState() {
try {
@@ -212,7 +261,7 @@ export const useStore = create((set, get) => {
const dirty = localStorage.getItem('gym_dirty') === '1'
const restored = restoredStateFor(S, state, dirty)
if (restored) {
persist(restored, false)
persist(restored, false, false)
} else if (hasData(S)) { await get().pushState() }
} catch (e) { /* offline — keep local */ }
},
@@ -297,7 +346,7 @@ export const useStore = create((set, get) => {
const saved = await nativeLoad()
const S = get().S
if (saved && (!hasData(S) || (saved._ts || 0) >= (S._ts || 0))) {
persist(Object.assign(clone(DEF), saved), false)
persist(Object.assign(clone(DEF), saved), false, false)
} else if (hasData(S)) {
nativeSave(S) // first run after an update from a file-less version: seed the mirror
}
+229 -1
View File
@@ -3,12 +3,18 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../lib/api.js', () => ({ api: vi.fn() }))
// pushState reaches the toast through a lazy import of useUI (which imports this store) — the
// tests only need to see that it was asked, not a rendered toast.
const { toast } = vi.hoisted(() => ({ toast: vi.fn() }))
vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast }) } }))
import { api } from '../lib/api.js'
import { DEF, restoredStateFor, useStore } from './useStore.js'
import { DEF, hasData, restoredStateFor, useStore } from './useStore.js'
const clone = value => JSON.parse(JSON.stringify(value))
const routine = id => ({ id, name: id, ex: [] })
const workout = id => ({ id, d: '2026-09-01', entries: [] })
const httpError = status => Object.assign(new Error('HTTP ' + status), { status })
beforeEach(() => {
localStorage.clear()
@@ -104,4 +110,226 @@ describe('saved workout state sync and restore', () => {
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['local'])
expect(api).toHaveBeenCalledTimes(1)
})
it('an adopted server state keeps the timestamp it came with', async () => {
const remote = { ...clone(DEF), _ts: 20, routines: [routine('remote')] }
useStore.setState({ S: clone(DEF), user: { id: 'user-1' }, ready: true })
api.mockResolvedValue({ state: remote })
await useStore.getState().pullState()
expect(useStore.getState().S._ts).toBe(20)
expect(JSON.parse(localStorage.getItem('gym_state_v1'))._ts).toBe(20)
})
// Device B logs a workout at T1 and pushes it 1.5 s later; device A reloads inside that window
// and adopts the server copy from T0 < T1. If adopting re-stamped A's copy with its own clock,
// A's next reload would see the server (T1) as older and push its stale copy over B's workout.
it('an unchanged adopted copy does not push over a newer change from another device', async () => {
useStore.setState({ S: clone(DEF), user: { id: 'user-1' }, ready: true })
api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 1000000, workouts: [workout('w1')] } })
await useStore.getState().pullState()
expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1'])
api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 1010000, workouts: [workout('w1'), workout('w2-from-B')] } })
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(2)
expect(api.mock.calls.every(([, opts]) => !opts)).toBe(true) // two GETs, no PUT
expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1', 'w2-from-B'])
expect(useStore.getState().S._ts).toBe(1010000)
})
})
// The saved copy is owned by whoever last signed in on this device. An expired or revoked session
// only drops the user (boot's 401 path), so the data is still here when the next profile signs in.
describe('signing in as a different profile', () => {
const active = { id: 'A-active', d: '2026-09-01', routineId: 'A', name: 'A', entries: [] }
const signInAsAThenExpire = () => {
useStore.getState().setUser({ id: 'A', name: 'A' })
useStore.getState().replaceState({ ...clone(DEF), _ts: 20, routines: [routine('A-routine')], bodyweight: [{ d: '2026-09-01', kg: 80 }], active })
useStore.getState().setUser(null)
expect(hasData(useStore.getState().S)).toBe(true)
}
it('does not move the previous profile data into a brand-new account', async () => {
signInAsAThenExpire()
api.mockResolvedValue({ state: null })
useStore.getState().setUser({ id: 'B', name: 'B' })
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(1) // the GET only — nothing was pushed under B
expect(useStore.getState().S.routines).toEqual([])
expect(useStore.getState().S.bodyweight).toEqual([])
expect(useStore.getState().S.active).toBeNull()
expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines).toEqual([])
expect(localStorage.getItem('gym_owner')).toBe('B')
})
it('adopts the new profile own state even when it is older or a push failed after expiry', async () => {
signInAsAThenExpire()
localStorage.setItem('gym_dirty', '1') // a debounced push that hit the 401
const remoteB = { ...clone(DEF), _ts: 10, routines: [routine('B-routine')], active: null }
api.mockResolvedValue({ state: remoteB })
useStore.getState().setUser({ id: 'B', name: 'B' })
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(1)
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['B-routine'])
expect(useStore.getState().S.active).toBeNull() // A's in-progress workout is not carried over
expect(localStorage.getItem('gym_dirty')).toBeNull()
})
it('the same profile signing in again keeps and pushes its newer local copy', async () => {
signInAsAThenExpire()
api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 10, routines: [routine('remote')] } }).mockResolvedValueOnce({})
useStore.getState().setUser({ id: 'A', name: 'A' })
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(2)
expect(JSON.parse(api.mock.calls[1][1].body).state.routines.map(r => r.id)).toEqual(['A-routine'])
expect(useStore.getState().S.active).toEqual(active)
})
// The check above runs in the tab that signs in. A second tab of the same browser still holding
// A learns about B through the storage event the sign-in fires.
it('a tab still holding the previous profile drops it when another profile signs in elsewhere', async () => {
vi.useFakeTimers()
try {
useStore.getState().setUser({ id: 'A', name: 'A' })
useStore.getState().replaceState({ ...clone(DEF), _ts: 20, routines: [routine('A-routine')], active }, true) // arms a push
api.mockResolvedValue({})
// B's setUser in the other tab: it wiped the copy, wrote defaults, then recorded the owner.
// B's own data only lands there after its pull — this tab never re-reads it.
localStorage.setItem('gym_state_v1', JSON.stringify({ ...clone(DEF), _ts: 30 }))
localStorage.setItem('gym_owner', 'B')
window.dispatchEvent(new StorageEvent('storage', { key: 'gym_owner', oldValue: 'A', newValue: 'B' }))
expect(useStore.getState().user).toBeNull()
expect(hasData(useStore.getState().S)).toBe(false)
expect(useStore.getState().S.active).toBeNull()
vi.advanceTimersByTime(3000) // the push armed under A must not fire under B's cookie
useStore.getState().update(s => { s.routines.push(routine('typed-after')) })
vi.advanceTimersByTime(3000)
await useStore.getState().pushState()
expect(api).not.toHaveBeenCalled()
expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines.map(r => r.id)).toEqual(['typed-after'])
} finally { vi.useRealTimers() }
})
// A sign-out elsewhere removes the owner. Storage events arrive per key, so this tab may see
// the owner go while gym_state_v1 still holds A's copy — it must not keep that copy either way.
it('a tab still holding the previous profile drops its data when that profile signs out elsewhere', async () => {
useStore.getState().setUser({ id: 'A', name: 'A' })
useStore.getState().replaceState({ ...clone(DEF), _ts: 20, routines: [routine('A-routine')], bodyweight: [{ d: '2026-09-01', kg: 80 }], active })
api.mockResolvedValue({ state: null })
localStorage.removeItem('gym_owner') // gym_state_v1 still holds A's copy at this instant
window.dispatchEvent(new StorageEvent('storage', { key: 'gym_owner', oldValue: 'A', newValue: null }))
expect(useStore.getState().user).toBeNull()
expect(hasData(useStore.getState().S)).toBe(false)
expect(useStore.getState().S.active).toBeNull()
useStore.getState().setUser({ id: 'C', name: 'C' })
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(1) // the GET only — nothing of A's was pushed under C
expect(api.mock.calls[0][1]).toBeUndefined()
expect(hasData(useStore.getState().S)).toBe(false)
})
// The listener above reacts to the owner key alone, so the wiped copy has to be in storage
// before the owner is removed — the same order setUser uses when it records a new owner.
it('signing out removes the owner only after the wiped copy is written', async () => {
useStore.getState().setUser({ id: 'A', name: 'A' })
useStore.getState().replaceState({ ...clone(DEF), _ts: 20, routines: [routine('A-routine')] })
api.mockResolvedValue({})
const desc = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
const real = globalThis.localStorage
const writes = []
const recording = new Proxy(real, {
get(target, prop) {
const v = Reflect.get(target, prop)
if (prop === 'setItem' || prop === 'removeItem') return (...args) => { writes.push(prop + ' ' + args[0]); return v.apply(target, args) }
return typeof v === 'function' ? v.bind(target) : v
},
})
Object.defineProperty(globalThis, 'localStorage', { value: recording, configurable: true })
try { await useStore.getState().signOut() }
finally { Object.defineProperty(globalThis, 'localStorage', desc) }
expect(globalThis.localStorage).toBe(real)
expect(writes).toContain('removeItem gym_owner')
expect(writes.lastIndexOf('removeItem gym_owner')).toBeGreaterThan(writes.lastIndexOf('setItem gym_state_v1'))
expect(writes.lastIndexOf('removeItem gym_owner')).toBeGreaterThan(writes.lastIndexOf('removeItem gym_state_v1'))
expect(localStorage.getItem('gym_owner')).toBeNull()
expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines).toEqual([])
})
it('a storage event for another key or the same profile changes nothing', () => {
useStore.getState().setUser({ id: 'A', name: 'A' })
useStore.getState().replaceState({ ...clone(DEF), _ts: 20, routines: [routine('A-routine')] })
window.dispatchEvent(new StorageEvent('storage', { key: 'gym_state_v1', newValue: '{}' }))
window.dispatchEvent(new StorageEvent('storage', { key: 'gym_owner', oldValue: 'A', newValue: 'A' }))
expect(useStore.getState().user).toEqual({ id: 'A', name: 'A' })
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['A-routine'])
})
it('guest data built after a sign-out still moves into a newly created profile', async () => {
api.mockResolvedValue({})
useStore.getState().setUser({ id: 'A', name: 'A' })
await useStore.getState().signOut()
expect(localStorage.getItem('gym_owner')).toBeNull()
expect(hasData(useStore.getState().S)).toBe(false)
useStore.getState().update(s => { s.routines.push(routine('guest')) }, false)
api.mockClear()
useStore.getState().setUser({ id: 'B', name: 'B' })
expect(hasData(useStore.getState().S)).toBe(true) // what the register sheet checks before pushing
await useStore.getState().pushState()
expect(api).toHaveBeenCalledTimes(1)
expect(api.mock.calls[0][1].method).toBe('PUT')
expect(JSON.parse(api.mock.calls[0][1].body).state.routines.map(r => r.id)).toEqual(['guest'])
})
})
describe('push failures', () => {
it('says once that the server refused the upload as too large, and keeps the copy dirty', async () => {
useStore.setState({ S: { ...clone(DEF), routines: [routine('local')] }, user: { id: 'user-1' }, ready: true })
api.mockRejectedValueOnce(httpError(401))
await useStore.getState().pushState()
expect(localStorage.getItem('gym_dirty')).toBe('1')
expect(toast).not.toHaveBeenCalled()
api.mockRejectedValueOnce(httpError(413))
await useStore.getState().pushState()
await vi.waitFor(() => expect(toast).toHaveBeenCalledTimes(1))
expect(toast.mock.calls[0][0]).toMatch(/too large/)
expect(localStorage.getItem('gym_dirty')).toBe('1')
api.mockRejectedValueOnce(httpError(413))
await useStore.getState().pushState()
await new Promise(r => setTimeout(r, 0))
expect(toast).toHaveBeenCalledTimes(1)
// A push that goes through ends the streak: the next refusal is news again.
api.mockResolvedValueOnce({})
await useStore.getState().pushState()
expect(localStorage.getItem('gym_dirty')).toBeNull()
api.mockRejectedValueOnce(httpError(413))
await useStore.getState().pushState()
await vi.waitFor(() => expect(toast).toHaveBeenCalledTimes(2))
})
})
+21 -1
View File
@@ -13,6 +13,7 @@ import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
import { DEMO, REPO } from '../lib/demo.js'
import { MOBILE, isAndroid, shareExport, syncReminder } from '../lib/mobile.js'
import { checkForUpdate, downloadAndInstall } from '../lib/update.js'
import { forgetCoach } from '../lib/coach-api.js'
import { ConnectSheet } from './MobileOnboarding.jsx'
import { starterPlanSheet, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet, menuSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
@@ -158,6 +159,25 @@ export default function Settings() {
catch (e) { toast(t('Could not sign out everywhere — you are still signed in.')) }
},
})
// Signed in, the empty state is pushed to the profile like any other change, so the wipe
// reaches the server and every device that syncs with it — the dialog has to say so. The Coach
// keeps its data outside S in two homes that can both be in use on one phone: a file per
// profile on the server, and — when it runs with the phone's own key — a file on the device.
// Each is cleared on its own; forgetCoach() alone would pick one by mode. A failed call must
// not stop the reset.
const resetEverything = () => confirmSheet({
title: t('Reset everything?'),
message: user
? t('Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.')
: t('Deletes your plan, workouts and body weight on this device. This cannot be undone.'),
confirmText: t('Delete everything'), danger: true,
onConfirm: () => {
if (user) api('/api/coach/forget', { method: 'POST', body: '{}' }).catch(() => {})
if (coachLocal?.mode === 'byok') forgetCoach().catch(() => {})
replaceState(JSON.parse(JSON.stringify(DEF)), true)
nav('/home'); toast(t('All data reset'))
},
})
return <div className="narrow">
<div className="hdr">
@@ -350,7 +370,7 @@ export default function Settings() {
subtitle={t('Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.')}>
<Switch checked={!!S.autoBackup} onChange={v => update(s => { s.autoBackup = v })} />
</Row>}
<Row icon="trash" iconTint="var(--red)" title={t('Reset everything')} danger onClick={() => confirmSheet({ title: t('Reset everything?'), message: t('Deletes your plan, workouts and body weight on this device. This cannot be undone.'), confirmText: t('Delete everything'), danger: true, onConfirm: () => { replaceState(JSON.parse(JSON.stringify(DEF)), true); nav('/home'); toast(t('All data reset')) } })} />
<Row icon="trash" iconTint="var(--red)" title={t('Reset everything')} danger onClick={resetEverything} />
</Section>
<input ref={fileRef} type="file" accept=".json,application/json" style={{ display: 'none' }} onChange={doImport} />
{/* Reset after reading so picking the same file twice still fires onChange. */}
+153
View File
@@ -0,0 +1,153 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Settings from './Settings.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
// "Reset everything" is one dialog with two truths. A guest's data lives in this browser only.
// A signed-in profile pushes the empty state to the server like any other change, so the wipe
// reaches every device that syncs with it — and the Coach's own files have to go too: the
// per-profile one on the server, and the device one when the Coach runs with the phone's own key.
const mocks = vi.hoisted(() => {
const state = { S: null, user: null, coachLocal: null }
state.replaceState = vi.fn()
state.confirmSheet = vi.fn()
state.forgetCoach = vi.fn(() => Promise.resolve({ ok: true }))
state.api = vi.fn(() => Promise.resolve({ ok: true }))
state.toast = vi.fn()
state.snapshot = () => ({
S: state.S,
user: state.user,
coachLocal: state.coachLocal,
update: mut => {
const next = structuredClone(state.S)
mut(next)
state.S = next
},
replaceState: state.replaceState, setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
})
return state
})
vi.mock('../store/useStore.js', () => {
const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
useStore.getState = mocks.snapshot
return { useStore, DEF: { reminder: { time: '17:30' }, workouts: [] }, hasData: () => false }
})
vi.mock('../store/useUI.js', () => {
const snap = () => ({ toast: (...a) => mocks.toast(...a), openSheet: vi.fn() })
const useUI = selector => selector ? selector(snap()) : snap()
useUI.getState = snap
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../lib/api.js', () => ({
api: (...a) => mocks.api(...a), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,
}))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('../lib/coach-api.js', () => ({ forgetCoach: (...a) => mocks.forgetCoach(...a) }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
starterPlanSheet: vi.fn(), confirmSheet: (...a) => mocks.confirmSheet(...a), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: vi.fn(),
}))
globalThis.__APP_VERSION__ ??= 'test'
let host, root
beforeEach(() => {
mocks.S = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',
gifSize: 'full', workouts: [], routines: [], exWeights: {},
}
mocks.user = null
mocks.coachLocal = null
mocks.replaceState.mockClear()
mocks.confirmSheet.mockClear()
mocks.forgetCoach.mockClear()
mocks.api.mockClear()
mocks.toast.mockClear()
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const mount = () => act(() => root.render(<Settings />))
const resetRow = () => [...host.querySelectorAll('.lrow')].find(r => r.textContent.includes('Reset everything'))
const openDialog = () => {
act(() => { resetRow().click() })
expect(mocks.confirmSheet).toHaveBeenCalledTimes(1)
return mocks.confirmSheet.mock.calls[0][0]
}
const serverForgetCalls = () => mocks.api.mock.calls.filter(([path]) => path === '/api/coach/forget')
describe('Settings — reset everything', () => {
it('guest: says the wipe is local, resets to the defaults, never calls the Coach', () => {
mount()
const dialog = openDialog()
expect(dialog.title).toBe('Reset everything?')
expect(dialog.message).toBe('Deletes your plan, workouts and body weight on this device. This cannot be undone.')
act(() => { dialog.onConfirm() })
expect(mocks.replaceState).toHaveBeenCalledTimes(1)
expect(mocks.replaceState.mock.calls[0]).toEqual([{ reminder: { time: '17:30' }, workouts: [] }, true])
expect(serverForgetCalls()).toHaveLength(0)
expect(mocks.forgetCoach).not.toHaveBeenCalled()
expect(mocks.toast).toHaveBeenCalledWith('All data reset')
})
it('signed in: says the wipe reaches the server and every device, and forgets the Coach on the server too', () => {
mocks.user = { uid: 'u1', name: 'Ana' }
mount()
const dialog = openDialog()
expect(dialog.message).toBe('Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.')
act(() => { dialog.onConfirm() })
expect(serverForgetCalls()).toHaveLength(1)
expect(serverForgetCalls()[0][1]).toEqual({ method: 'POST', body: '{}' })
expect(mocks.forgetCoach).not.toHaveBeenCalled() // no device Coach here
expect(mocks.replaceState).toHaveBeenCalledTimes(1)
expect(mocks.replaceState.mock.calls[0][1]).toBe(true)
expect(mocks.toast).toHaveBeenCalledWith('All data reset')
})
it('signed in: a failing Coach call does not block the reset', async () => {
mocks.user = { uid: 'u1', name: 'Ana' }
mocks.api.mockRejectedValueOnce(new Error('offline'))
mount()
const dialog = openDialog()
await act(async () => { dialog.onConfirm(); await Promise.resolve() })
expect(serverForgetCalls()).toHaveLength(1)
expect(mocks.replaceState).toHaveBeenCalledTimes(1)
expect(mocks.toast).toHaveBeenCalledWith('All data reset')
})
// A paired phone running the Coach with its own key has Coach data in both homes.
it('paired phone with its own key: clears the Coach on the server and on the device', () => {
mocks.user = { uid: 'u1', name: 'Ana' }
mocks.coachLocal = { mode: 'byok', provider: 'anthropic' }
mount()
const dialog = openDialog()
act(() => { dialog.onConfirm() })
expect(serverForgetCalls()).toHaveLength(1)
expect(mocks.forgetCoach).toHaveBeenCalledTimes(1)
expect(mocks.replaceState).toHaveBeenCalledTimes(1)
expect(mocks.toast).toHaveBeenCalledWith('All data reset')
})
it('own key, no server: clears the device Coach without touching the server', () => {
mocks.coachLocal = { mode: 'byok', provider: 'anthropic' }
mount()
const dialog = openDialog()
act(() => { dialog.onConfirm() })
expect(serverForgetCalls()).toHaveLength(0)
expect(mocks.forgetCoach).toHaveBeenCalledTimes(1)
expect(mocks.replaceState).toHaveBeenCalledTimes(1)
})
})
+4
View File
@@ -20,6 +20,10 @@ server {
# as /api/anything.json would be matched by the \.(js|css|json|html)$ block instead and be
# looked for on disk rather than proxied.
location ^~ /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 Docker'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