Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Coach hardening: what a person typed is cut to the intake screen's limits before it reaches a prompt
Duarte Santos1af67e45283c
diff --git a/api/coach/core/library.js b/api/coach/core/library.jsindex 8058e03dc..a589fb1ca 100644--- a/api/coach/core/library.js+++ b/api/coach/core/library.js@@ -28,7 +28,10 @@ const slim = e => ({ id: e.id, n: e.n, bp: e.bp, ...(e.custom ? { custom: true }export function librarySlice(S, equipment, { keep = [], max = MAX_LIBRARY } = {}) {const wanted = (equipment || []).map(x => String(x).toLowerCase());- const customs = (S.customEx || []).map(c => ({ id: c.id, n: c.n, bp: c.bp, tg: null, eq: 'custom', custom: true }));+ // A custom exercise's name and body part are whatever the person typed, and they ride into+ // every prompt: cut to the bounds payload.js gives every other name (NAME_MAX, 80).+ const cut = (v, n) => (typeof v === 'string' ? v.slice(0, n) : v);+ const customs = (S.customEx || []).map(c => ({ id: c.id, n: cut(c.n, 80), bp: cut(c.bp, 40), tg: null, eq: 'custom', custom: true }));// No equipment stated (or "everything") ⇒ the whole catalogue. Filtering to nothing would// leave the Coach unable to propose anything at all, which is a worse failure than a// slightly larger payload.diff --git a/api/coach/core/payload.js b/api/coach/core/payload.jsindex a1c144526..083a5c894 100644--- a/api/coach/core/payload.js+++ b/api/coach/core/payload.js@@ -18,6 +18,51 @@ export const CONTRACT = 1;export const MAX_WEEKS = 12;export const MAX_SESSIONS = 60;+/* ---------- what a person typed, bounded ----------+ Every free-text field below rides into the prompt, and the prompt is paid for by whoever runs+ the instance: the Coach spends one instance-wide key. The intake screen caps what it lets you+ type, but this module never sees that screen. It reads the profile from a POST body or from+ the synced state, and a client can fill either with megabytes (the only server limit is the+ 5 MB body cap). So the text is cut here, the one place both the server and the phone build a+ payload, to the limits the intake screen shows (CoachIntake.jsx). The system prompt already+ reads this text as data rather than instruction (common rule 3); the bound is about size.+ A field of the wrong type reads as absent rather than as "[object Object]". */+export const PROFILE_TEXT_MAX = { limitations: 600, likes: 300, dislikes: 300, notes: 600 };+// Goal and experience are enum words today (strength, returning, ...); 40 leaves room for new+// ones without letting either carry a paragraph.+export const PROFILE_WORD_MAX = 40;+// The equipment taxonomy has 28 values, the longest 20 characters.+export const PROFILE_EQUIPMENT_MAX = 40;+// Routine, workout and custom-exercise names have no length limit in the app. The Coach writes+// its own names at 40 (validate.js); twice that keeps any name a person would really type.+export const NAME_MAX = 80;+const text = (v, n) => (typeof v === 'string' ? v.slice(0, n) : '');+const word = (v, n) => (typeof v === 'string' && v ? v.slice(0, n) : null);+// Zero reads as absent, as `|| null` always made it; anything else is clamped into range.+const count = (v, lo, hi) => {+ const n = typeof v === 'number' || typeof v === 'string' ? Number(v) : NaN;+ return Number.isFinite(n) && n ? Math.min(hi, Math.max(lo, Math.round(n))) : null;+};+// A weekday is 0-6, as a number or a one-digit string; null must not turn into Sunday.+const weekday = d => (typeof d === 'number' ? d : typeof d === 'string' && /^\d$/.test(d) ? Number(d) : NaN);+function cleanProfile(profile) {+ const days = Array.isArray(profile.preferredDays) ? profile.preferredDays : [];+ const equipment = Array.isArray(profile.equipment) ? profile.equipment : [];+ return {+ goal: word(profile.goal, PROFILE_WORD_MAX),+ experience: word(profile.experience, PROFILE_WORD_MAX),+ daysPerWeek: count(profile.daysPerWeek, 1, 7),+ // Weekdays 0-6, each once: seven entries is the whole week, so anything past that is noise.+ preferredDays: [...new Set(days.map(weekday).filter(d => Number.isInteger(d) && d >= 0 && d <= 6))],+ sessionMin: count(profile.sessionMin, 1, 24 * 60),+ equipment: equipment.filter(e => typeof e === 'string' && e).slice(0, PROFILE_EQUIPMENT_MAX).map(e => e.slice(0, PROFILE_WORD_MAX)),+ limitations: text(profile.limitations, PROFILE_TEXT_MAX.limitations),+ likes: text(profile.likes, PROFILE_TEXT_MAX.likes),+ dislikes: text(profile.dislikes, PROFILE_TEXT_MAX.dislikes),+ notes: text(profile.notes, PROFILE_TEXT_MAX.notes)+ };+}+/* ---------- the data categories the consent screen names (FR-09/10) ----------Kept here, next to the code that acts on it, and rendered by the consent UI from the samelist — a screen that drifts from the payload is worse than no screen. */@@ -144,8 +189,12 @@ export function canonicalPlan(S) {}export function cleanPlan(S) {+ // Names and emoji are typed by the person, so they are cut like the profile's text. An emoji+ // is one grapheme, but a ZWJ family or a flag spells it with up to a dozen code units.const routines = (S.routines || []).map(r => ({- id: r.id, name: r.name, emoji: r.emoji, ...(r.prog ? { prog: r.prog } : {}), ex: (r.ex || []).map(cleanEx)+ id: r.id, name: r.name == null ? r.name : text(String(r.name), NAME_MAX),+ emoji: r.emoji == null ? r.emoji : text(String(r.emoji), 16),+ ...(r.prog ? { prog: r.prog } : {}), ex: (r.ex || []).map(cleanEx)}));const week = {};[1, 2, 3, 4, 5, 6, 0].forEach(d => { if (S.week?.[d]?.length) week[d] = [].concat(S.week[d]); });@@ -242,7 +291,7 @@ const fmtSet = s => {function compactWorkout(w) {return {d: w.d,- name: w.name || null,+ name: word(w.name, NAME_MAX),minutes: w.end && w.start ? Math.round((w.end - w.start) / 60000) : null,prs: (w.prs || []).length,compact: true,@@ -268,9 +317,9 @@ function compactWorkout(w) {function cleanWorkout(w) {return {d: w.d,- name: w.name || null,+ name: word(w.name, NAME_MAX),minutes: w.end && w.start ? Math.round((w.end - w.start) / 60000) : null,- ...(w.rating ? { rating: w.rating } : {}),+ ...(w.rating ? { rating: typeof w.rating === 'number' ? w.rating : text(String(w.rating), 20) } : {}),...(w.note ? { note: String(w.note).slice(0, 300) } : {}),prs: (w.prs || []).length,entries: (w.entries || []).map(en => ({@@ -337,30 +386,22 @@ export function build(S, opts = {}) {task: opts.kind === 'review' ? 'review' : opts.kind === 'debrief' ? 'debrief' : 'create',meta: {profile: opts.handle,- lang: S.lang || 'en',- unit: S.unit || 'kg',+ // Both are short codes in any real state; cut anyway, since the state is the client's.+ lang: word(S.lang, 16) || 'en',+ unit: word(S.unit, 8) || 'kg',effortScale: effortOf(S),today: iso(new Date())},- coachProfile: profile ? {- goal: profile.goal || null,- experience: profile.experience || null,- daysPerWeek: profile.daysPerWeek || null,- preferredDays: profile.preferredDays || [],- sessionMin: profile.sessionMin || null,- equipment: profile.equipment || [],- limitations: profile.limitations || '',- likes: profile.likes || '',- dislikes: profile.dislikes || '',- notes: profile.notes || ''- } : null,+ coachProfile: profile && typeof profile === 'object' ? cleanProfile(profile) : null,plan: cleanPlan(S)};// What the user already turned down, so the Coach does not re-propose it without new// evidence (FR-26). Summaries only — the log's full before/after stays on the device.const declined = (coach.log || [])- .flatMap(e => (e.decisions || []).filter(d => d.status === 'rejected').map(d => ({ type: d.type, why: d.why })))+ // `why` was the Coach's own sentence, but it comes back from the synced state, which the+ // client writes; it is cut at the length the intake allows a note.+ .flatMap(e => (e.decisions || []).filter(d => d.status === 'rejected').map(d => ({ type: word(d.type, PROFILE_WORD_MAX), why: text(d.why, PROFILE_TEXT_MAX.notes) }))).slice(-15);if (declined.length) p.previouslyDeclined = declined;@@ -402,9 +443,9 @@ export function build(S, opts = {}) {if (opts.note) p.userNote = String(opts.note).slice(0, 1000);if (opts.cohort) p.cohort = opts.cohort;// A review names mostly what is already trained; 60 candidates is plenty for a swap.- p.library = librarySlice(S, profile?.equipment, { keep: trainedIds(S, workouts), max: 60 });+ p.library = librarySlice(S, p.coachProfile?.equipment, { keep: trainedIds(S, workouts), max: 60 });} else {- p.library = librarySlice(S, profile?.equipment, { keep: trainedIds(S, S.workouts || []) });+ p.library = librarySlice(S, p.coachProfile?.equipment, { keep: trainedIds(S, S.workouts || []) });// Creation for a returning user: what they have actually handled, so proposed baselines// start from evidence rather than optimism (B2/FR-20).const best = {};diff --git a/api/test/payload-bounds.test.js b/api/test/payload-bounds.test.jsnew file mode 100644index 000000000..af1ce0d64--- /dev/null+++ b/api/test/payload-bounds.test.js@@ -0,0 +1,120 @@+/* What a person typed is bounded before it reaches a prompt.+ *+ * The intake screen caps its text fields, but payload.build reads the profile from a POST body+ * or from the synced state, and a client can put megabytes in either. The Coach runs on the+ * instance's own key, so an unbounded field is a bill someone else pays. These tests feed the+ * builder far more than any screen allows, through both doors, and check what comes out. */+import test from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import { tempData, sampleState } from './helpers.mjs';++tempData();+const payload = await import('../coach/core/payload.js');++const HUGE = 'x'.repeat(200_000);+const hugeProfile = () => ({+ goal: 'strength' + HUGE,+ experience: 'regular' + HUGE,+ daysPerWeek: '99',+ preferredDays: [...Array(5000)].map((_, i) => i % 9).concat(['1', 'Monday', null, 2.5]),+ sessionMin: 1e9,+ equipment: [...Array(5000)].map((_, i) => (i === 0 ? 'dumbbell' : 'eq' + i + HUGE.slice(0, 500))),+ limitations: HUGE, likes: HUGE, dislikes: HUGE, notes: HUGE+});++function assertBounded(cp) {+ assert.equal(cp.limitations.length, 600);+ assert.equal(cp.likes.length, 300);+ assert.equal(cp.dislikes.length, 300);+ assert.equal(cp.notes.length, 600);+ assert.equal(cp.goal.length, payload.PROFILE_WORD_MAX);+ assert.ok(cp.goal.startsWith('strength'));+ assert.equal(cp.experience.length, payload.PROFILE_WORD_MAX);+ assert.equal(cp.daysPerWeek, 7, 'clamped to a week');+ assert.deepEqual(cp.preferredDays, [0, 1, 2, 3, 4, 5, 6], 'weekdays only, each once');+ assert.equal(cp.sessionMin, 24 * 60, 'clamped to a day');+ assert.equal(cp.equipment.length, payload.PROFILE_EQUIPMENT_MAX);+ assert.equal(cp.equipment[0], 'dumbbell');+ assert.ok(cp.equipment.every(e => e.length <= payload.PROFILE_WORD_MAX));+}++test('an intake posted with megabytes of text is cut to what the intake screen allows', () => {+ const p = payload.build(sampleState(), { handle: 'h'.repeat(16), kind: 'create', intake: hugeProfile() });+ assertBounded(p.coachProfile);+ assert.ok(JSON.stringify(p).length < 100_000, 'the whole payload stays small');+});++test('a profile synced into the state is cut the same way, for a review and a debrief too', () => {+ const S = sampleState();+ S.coach.profile = hugeProfile();+ for (const kind of ['create', 'review', 'debrief']) {+ const p = payload.build(S, { handle: 'h'.repeat(16), kind });+ assertBounded(p.coachProfile);+ assert.ok(JSON.stringify(p).length < 100_000, kind + ' payload stays small');+ }+});++test('a profile of the wrong shape reads as absent instead of crashing or leaking an object', () => {+ const p = payload.build(sampleState(), {+ handle: 'h'.repeat(16), kind: 'create',+ intake: { goal: { $x: 1 }, experience: 7, daysPerWeek: 'many', preferredDays: 'mon', sessionMin: '', equipment: 'dumbbell', limitations: { a: 1 }, likes: ['x'], dislikes: 3, notes: null }+ });+ assert.deepEqual(p.coachProfile, {+ goal: null, experience: null, daysPerWeek: null, preferredDays: [], sessionMin: null,+ equipment: [], limitations: '', likes: '', dislikes: '', notes: ''+ });+ // A bare-string equipment used to reach librarySlice's .map and throw; now it is no filter.+ assert.ok(p.library.length > 0);+});++test('weekdays are read as weekdays: nothing becomes Sunday, and zero days or minutes read as unset', () => {+ const p = payload.build(sampleState(), {+ handle: 'h'.repeat(16), kind: 'create',+ intake: { goal: 'muscle', preferredDays: [null, '', false, '3', 5, 5, 7, -1, 'Sunday'], daysPerWeek: 0, sessionMin: '0' }+ });+ assert.deepEqual(p.coachProfile.preferredDays, [3, 5]);+ assert.equal(p.coachProfile.daysPerWeek, null);+ assert.equal(p.coachProfile.sessionMin, null);+});++test('a real intake passes through unchanged', () => {+ const intake = {+ goal: 'muscle', experience: 'returning', daysPerWeek: 4, preferredDays: [1, 2, 4, 5], sessionMin: 75,+ equipment: ['dumbbell', 'barbell'], limitations: 'Left shoulder clicks overhead.', likes: 'deadlifts', dislikes: 'lunges', notes: 'Arms by spring.'+ };+ const p = payload.build(sampleState(), { handle: 'h'.repeat(16), kind: 'create', intake });+ assert.deepEqual(p.coachProfile, intake);+});++test('names, the declined log and the meta codes are bounded too, since the state is the client\'s', () => {+ const S = sampleState({ lang: 'en' + HUGE, unit: 'kg' + HUGE });+ S.routines[0].name = 'Push' + HUGE;+ S.routines[0].emoji = '💪' + HUGE;+ S.workouts[0].name = 'Push' + HUGE;+ S.workouts[0].rating = 'great' + HUGE;+ S.customEx = [{ id: 'cx1', n: 'Sandbag' + HUGE, bp: 'back' + HUGE }];+ S.coach.log = [{ decisions: [{ status: 'rejected', type: 'sets' + HUGE, why: 'no' + HUGE }] }];+ for (const kind of ['create', 'review', 'debrief']) {+ const p = payload.build(S, { handle: 'h'.repeat(16), kind });+ assert.ok(JSON.stringify(p).length < 100_000, kind + ' payload stays small');+ assert.equal(p.plan.routines[0].name.length, payload.NAME_MAX);+ assert.ok(p.plan.routines[0].emoji.length <= 16);+ assert.ok(p.meta.lang.length <= 16 && p.meta.unit.length <= 8);+ assert.ok(p.previouslyDeclined[0].why.length <= 600);+ if (p.library) assert.ok(p.library[0].n.length <= payload.NAME_MAX && p.library[0].bp.length <= 40);+ const w = p.window?.workouts[0] || p.session;+ if (w) assert.ok(w.name.length <= payload.NAME_MAX && w.rating.length <= 20);+ }+});++// The server's limits are the screen's limits. If someone lengthens a field on the intake+// screen, this says the payload would now cut what the person was allowed to type.+test('the limits match the intake screen', () => {+ const src = fs.readFileSync(new URL('../../frontend/src/views/CoachIntake.jsx', import.meta.url), 'utf8');+ for (const [field, max] of Object.entries(payload.PROFILE_TEXT_MAX)) {+ const m = src.match(new RegExp('maxLength=\\{(\\d+)\\} value=\\{p\\.' + field + '\\}'));+ assert.ok(m, field + ' has a maxLength on the intake screen');+ assert.equal(Number(m[1]), max, field);+ }+});