Skip to content

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.

Merge the platform and security batch: the Coach prompt bounded field by field and across the cohort, an ARM-only release APK, backups in their own folder and pruned, the phone refusing an http:// Coach endpoint, the account id in Settings, exercise media kept offline in the web app (#136, #161, #219, #281)

Duarte Santos8b701f4a69cb
diff --cc api/coach/core/payload.js
index ba2854d5d,9147fb945..3f771c495
--- a/api/coach/core/payload.js
+++ b/api/coach/core/payload.js
@@@ -17,12 -17,79 +17,85 @@@ export const CONTRACT = 1
// makes the payload bigger and the reading vaguer, not better.
export const MAX_WEEKS = 12;
export const MAX_SESSIONS = 60;
+// Last-resort ceiling for a free-text note/refine (issue #267). The real limit is the admin's
+// `maxMessageLen`, enforced in jobs.js before a message ever reaches this module — this module
+// stays a pure allowlist with no config import of its own, so it keeps its own constant instead.
+// It has to stay >= config.js's MAX_MESSAGE_LEN_CEILING, or a raised admin limit would still get
+// clipped back down here.
+export const MAX_NOTE_CHARS = 4000;
+ // The ceiling on a whole payload, as JSON characters, which the server checks before a job
+ // leaves (jobs.js). Every field below is bounded on its own; this is the backstop for how many
+ // of them there are, and for a field added later that nobody bounded. A deliberately extreme
+ // history (30 routines of 12 exercises, 200 custom exercises, 60 twelve-exercise sessions in
+ // the review window) builds a review of about 240k; ordinary ones stay under 50k.
+ export const MAX_PAYLOAD_CHARS = 300_000;
+
+ /* ---------- 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);
+
+ /* ---------- what the plan and the log hold, bounded by type ----------
+ The plan, the logged sets, the body-weight series and the exercise ids come from the same
+ client-written state as the profile, and PUT /api/data checks no more than that workouts and
+ routines are arrays. A field copied as it came is a field that can carry a megabyte of text
+ into the prompt, so each one is read by what it is meant to be. Anything else reads as
+ absent, as a wrong-typed profile field does. */
+ // The app's own ids are uid() (13 characters) or a four-digit catalogue number; 64 is room for
+ // any id an import or an older build ever wrote, and no room for a paragraph.
+ export const ID_MAX = 64;
+ // The progression engine's policies (frontend/src/lib/progression.js POLICIES, validate.js).
+ const POLICIES = ['off', 'linear', 'greyskull', 'double', 'time'];
+ const ident = v => (typeof v === 'string' ? v.slice(0, ID_MAX) : typeof v === 'number' && Number.isFinite(v) ? v : null);
+ const policy = v => (POLICIES.includes(v) ? v : null);
+ // A finite number, or a number written as a short string (the app writes numbers, but a
+ // hand-made import may not, and the model reads "20" as well as 20). Kept as given rather than
+ // converted, so a Coach change's `before` still equals what the plan holds.
+ const NUMERIC = /^-?\d{1,9}(\.\d{1,6})?$/;
+ const num = v => ((typeof v === 'number' && Number.isFinite(v)) || (typeof v === 'string' && NUMERIC.test(v)) ? v : undefined);
+ // A date is the ISO day every screen writes; anything else is not a date.
+ const day = v => (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}/.test(v) ? v.slice(0, 10) : null);
+ const list = v => (Array.isArray(v) ? v : []);
+ 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 same
@@@ -412,16 -498,13 +515,13 @@@ export function build(S, opts = {})
workouts: workouts.map((w, i) => (i >= detailFrom ? cleanWorkout(w) : compactWorkout(w)))
};
p.aggregates = aggregates(S, workouts);
- p.bodyweight = {
- goal: S.targetW ?? null,
- series: (S.bodyweight || []).filter(b => !p.window.from || b.d >= p.window.from).map(b => ({ d: b.d, w: b.w }))
- };
+ p.bodyweight = { goal: num(S.targetW) ?? null, series: weighIns(S, p.window.from, null) };
- if (opts.note) p.userNote = String(opts.note).slice(0, 1000);
+ if (opts.note) p.userNote = String(opts.note).slice(0, MAX_NOTE_CHARS);
- if (opts.cohort) p.cohort = opts.cohort;
+ if (opts.cohort) p.cohort = cleanCohort(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 --cc frontend/src/lib/pt-br-locale.test.js
index 60357613b,6b231c779..0a016630c
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@@ -27,21 -27,11 +27,21 @@@ describe('Brazilian Portuguese locale'
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(680)
- expect(inherited).toHaveLength(676)
- // If this fails, review the changed keys and wording before accepting a new hash. From
+ // Every override names a real source string, so the two sets partition pt-PT's keys between
+ // them and the fingerprint below covers everything not overridden. A typo'd override key
+ // would otherwise sit in the file translating nothing.
+ const stray = Object.keys(PT_BR_OVERRIDES).filter(key => !(key in pt))
+ expect(stray, 'override keys that are not pt-PT keys').toEqual([])
+ expect(Object.keys(PT_BR_OVERRIDES).length + inherited.length).toBe(Object.keys(pt).length)
+ // …and each one really reaches the pack, whatever the spread order does.
+ for (const [key, value] of Object.entries(PT_BR_OVERRIDES)) expect(ptBR[key], key).toBe(value)
+
+ // The counts themselves are read off the pack rather than pinned here: a new UI string lands
+ // in pt.js and pt-BR.js together and moves both, and a number in a test that every new string
+ // has to be taught is a number nobody reads. What the numbers stood for is asserted above.
+ // If the hash fails, review the changed keys and wording before accepting a new one. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('2e0935fb1e2cf1185e473b07ef176c5e03ae330a3836d35af99eb6b1a7a31707')
- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('7688ac3352bc6cef5f181a7cd7fe3eae75046c77f78d46b85188e67cd4fe731f')
++ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('fb67e0870032b779637f003205443fe51a060d68f763b7c8b75d8b943956bfa6')
})
test('does not leak European Portuguese UI terms', () => {
diff --cc frontend/src/views/CoachSetup.jsx
index a0b3828aa,b462b3741..2a2031668
--- a/frontend/src/views/CoachSetup.jsx
+++ b/frontend/src/views/CoachSetup.jsx
@@@ -66,9 -75,7 +75,10 @@@ export default function CoachSetup()
const prepare = async () => {
const v = validateBaseUrl(meta.baseUrl ? baseUrl : '')
if (!v.ok) return toast(v.error)
+ // An empty field passes the validator on purpose: for a provider with a fixed endpoint,
+ // empty means the default. This one has no default, so empty is nowhere to call.
+ if (meta.baseUrl && !meta.defaultBase && !v.value) return toast(t('Enter the endpoint URL'))
+ if (isCleartext(v.value)) return toast(cleartextRefused())
if (!meta.keyOptional && !key.trim() && !hasKey) return toast(t('Enter your API key'))
setBusy(true); setStep(0)
try {
@@@ -86,14 -93,10 +96,16 @@@
}
const save = async () => {
+ // The same check "List models" makes. The endpoint field stays editable after a successful
+ // listing, and taking `.value` off an unchecked result turned a typo into `baseUrl: null` —
+ // saved, "The Coach is on", and the phone pointed at nothing.
+ const v = validateBaseUrl(meta.baseUrl ? baseUrl : '')
+ if (!v.ok) return toast(v.error)
+ if (meta.baseUrl && !meta.defaultBase && !v.value) return toast(t('Enter the endpoint URL'))
const chosen = model || meta.defaultModel
if (!chosen) return toast(t('Pick a model'))
+ // The endpoint can still be edited after the models were listed.
- if (meta.baseUrl && isCleartext(baseUrl)) return toast(cleartextRefused())
++ if (isCleartext(v.value)) return toast(cleartextRefused())
setBusy(true)
try {
// The mode first, the key second: the settings file is the cheap, reliable write, the