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
Media: a logged workout's photos and videos keep their files on the server and on the device
Duarte Santos9f3b1b702dcb
diff --git a/SECURITY.md b/SECURITY.mdindex 84a814afc..9e2b61ee5 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -168,7 +168,8 @@ Read this before hosting openGym for anyone other than yourself.and each account is capped at 20 subscriptions, so one small request cannot become an unboundedburst of outbound connections (`api/server.js:108-110`).- **An uploaded photo or video can only be one of seven file types, and only its owner gets it- back.** People can attach one photo, GIF or short video to an exercise they made. The server+ back.** People can attach one photo, GIF or short video to an exercise they made, and up to+ six to a workout they logged. The serverdecides what a file is from its first bytes, never from its name or the type the clientdeclared, and stores JPEG, PNG, WebP, GIF, MP4, MOV and WebM only — SVG, HTML and everythingelse is refused. It never decodes a file, so there is no image or video parser to attack. Eachdiff --git a/api/media.js b/api/media.jsindex 100ecb286..dbea20253 100644--- a/api/media.js+++ b/api/media.js@@ -274,21 +274,27 @@ export function mp4Info(fd, size) {/* ---------------------------------------------------------------- references *//**- * Every blob a state refers to: customEx[].media.hash and customEx[].media.poster.hash.- * Deliberately loose — each field counts on its own as long as it is a well-formed hash, even- * when the rest of the ref would not pass the client's normalizeMediaRef. This set decides what- * is KEPT, so erring towards more is the safe direction. frontend/src/lib/media-refs.js has to- * agree with it; api/test/fixtures/media-refs.json pins both to the same answers.+ * Every blob a state refers to: customEx[].media.hash and .poster.hash, and the same two of every+ * entry of workouts[].media (the photos and videos of a logged workout). Deliberately loose —+ * each field counts on its own as long as it is a well-formed hash, even when the rest of the ref+ * would not pass the client's normalizeMediaRef, and a workout's list counts past the client's+ * cap of six. This set decides what is KEPT, so erring towards more is the safe direction.+ * `active` is not walked: PUT /api/data drops it before the state is stored.+ * frontend/src/lib/media-refs.js has to agree with it; api/test/fixtures/media-refs.json pins+ * both to the same answers.*/export function referencedHashes(state) {const out = new Set();- const list = state && typeof state === 'object' && Array.isArray(state.customEx) ? state.customEx : [];+ if (!state || typeof state !== 'object') return out;+ const isObj = v => !!v && typeof v === 'object' && !Array.isArray(v);const add = r => { if (r && typeof r === 'object' && typeof r.hash === 'string' && HASH_RE.test(r.hash)) out.add(r.hash); };- for (const c of list) {- const m = c && typeof c === 'object' ? c.media : null;- if (!m || typeof m !== 'object') continue;- add(m);- add(m.poster);+ const ref = m => { add(m); add(m.poster); };+ for (const c of Array.isArray(state.customEx) ? state.customEx : []) {+ if (isObj(c) && isObj(c.media)) ref(c.media);+ }+ for (const w of Array.isArray(state.workouts) ? state.workouts : []) {+ if (!isObj(w) || !Array.isArray(w.media)) continue;+ for (const m of w.media) if (isObj(m)) ref(m);}return out;}diff --git a/api/openapi.yaml b/api/openapi.yamlindex e364a32a2..930acfe65 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -139,7 +139,8 @@ tags:description: Admin dashboard — requires an admin session (`ADMIN_UIDS` or `admin:true`)- name: mediadescription: >-- The photo, GIF or video of a user's own custom exercise. Stored per profile and named+ The photo, GIF or video of a user's own custom exercise, and the photos and videos+ attached to a logged workout. Stored per profile (one quota for both) and namedby the SHA-256 of its bytes; the state only carries a `MediaRef`. Every route here is a404 when the instance runs with `MEDIA_UPLOADS=0`.- name: coach@@ -3088,8 +3089,9 @@ components:type: objectdescription: >-What the state knows of an uploaded file. The bytes are behind- `GET /api/media/{hash}`; the server keeps a file as long as some `customEx[].media.hash`- or `.poster.hash` of the profile's state names it, and for `MEDIA_GC_GRACE_DAYS` after.+ `GET /api/media/{hash}`; the server keeps a file as long as some `customEx[].media.hash`,+ `workouts[].media[].hash` or `.poster.hash` of either in the profile's state names it, and+ for `MEDIA_GC_GRACE_DAYS` after.required: [kind, hash, mime, size, width, height, at]properties:kind: { type: string, enum: [image, gif, video], description: '`gif` means animated; a one-frame GIF is an `image`.' }@@ -3175,6 +3177,17 @@ components:rpe: { type: number }additionalProperties: trueadditionalProperties: true+ media:+ type: array+ maxItems: 6+ items:+ $ref: '#/components/schemas/MediaRef'+ description: >-+ Photos and videos attached to this workout (a progress photo, a form-check clip) —+ at most six in the app. Refs only; the bytes are behind `/api/media/{hash}`, and the+ server keeps every file any entry here names (the GC walks this list as it walks+ each custom exercise's `media`).+ _ts: { type: number, description: 'When this workout was last edited after it was logged, ms — for merging two devices'' copies.' }additionalProperties: trueRoutine:diff --git a/api/test/fixtures/media-refs.json b/api/test/fixtures/media-refs.jsonindex f1b673b36..5b7d66139 100644--- a/api/test/fixtures/media-refs.json+++ b/api/test/fixtures/media-refs.json@@ -1,5 +1,5 @@{- "about": "Which blob hashes a state references. api/media.js referencedHashes() and frontend/src/lib/media-refs.js referencedHashes() must both give `expect` (compared as sorted lists) for every `state` here: the server keeps and the client keeps exactly this set. Each of customEx[].media.hash and customEx[].media.poster.hash counts on its own when it matches /^[0-9a-f]{64}$/ — deliberately looser than normalizeMediaRef, because this set decides what is kept.",+ "about": "Which blob hashes a state references. api/media.js referencedHashes() and frontend/src/lib/media-refs.js referencedHashes() must both give `expect` (compared as sorted lists) for every `state` here: the server keeps and the client keeps exactly this set. Each of customEx[].media.hash, customEx[].media.poster.hash and the same two of every entry of workouts[].media counts on its own when it matches /^[0-9a-f]{64}$/ — deliberately looser than normalizeMediaRef, because this set decides what is kept.","referencedHashes": [{"name": "no state at all",@@ -384,7 +384,7 @@"expect": []},{- "name": "only customEx is a source: media-like fields elsewhere do not count",+ "name": "customEx[].media and workouts[].media are the only sources: media-like fields elsewhere (a routine's exercise, a workout entry) do not count","state": {"routines": [{@@ -424,6 +424,450 @@],"customEx": []},+ "expect": [],+ "about": "A workout entry's own `media` is not a place media live; only the workout's `media` list is."+ },+ {+ "name": "a workout's photo and video with their posters",+ "state": {+ "workouts": [+ {+ "id": "w1",+ "d": "2026-09-20",+ "start": 1,+ "end": 2,+ "entries": [],+ "media": [+ {+ "kind": "image",+ "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1,+ "poster": {+ "hash": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ "mime": "image/webp",+ "size": 100,+ "width": 480,+ "height": 360+ }+ },+ {+ "kind": "video",+ "hash": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",+ "mime": "video/mp4",+ "size": 500000,+ "width": 1280,+ "height": 720,+ "dur": 8.2,+ "codec": "avc1",+ "at": 2,+ "poster": {+ "hash": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",+ "mime": "image/webp",+ "size": 100,+ "width": 480,+ "height": 270+ }+ }+ ]+ }+ ]+ },+ "expect": [+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",+ "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"+ ]+ },+ {+ "name": "a blob referenced only by a workout is kept (no customEx at all)",+ "state": {+ "unit": "kg",+ "workouts": [+ {+ "id": "w1",+ "d": "2026-09-20",+ "start": 1,+ "end": 2,+ "entries": [],+ "media": [+ {+ "kind": "video",+ "hash": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",+ "mime": "video/mp4",+ "size": 500000,+ "width": 1280,+ "height": 720,+ "dur": 8.2,+ "codec": "avc1",+ "at": 2+ }+ ]+ }+ ]+ },+ "expect": [+ "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"+ ]+ },+ {+ "name": "workouts that is not a list",+ "state": {+ "workouts": {+ "w1": {+ "id": "w1",+ "d": "2026-09-20",+ "start": 1,+ "end": 2,+ "entries": [],+ "media": [+ {+ "kind": "image",+ "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ }+ ]+ }+ }+ },+ "expect": []+ },+ {+ "name": "workout entries that are not workouts are skipped",+ "state": {+ "workouts": [+ null,+ 3,+ "w",+ [],+ {+ "id": "w1",+ "d": "2026-09-20",+ "start": 1,+ "end": 2,+ "entries": [],+ "media": [+ {+ "kind": "image",+ "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ }+ ]+ }+ ]+ },+ "expect": [+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ ]+ },+ {+ "name": "a workout media field that is not a list does not count",+ "state": {+ "workouts": [+ {+ "id": "w1",+ "d": "2026-09-20",+ "start": 1,+ "end": 2,+ "entries": [],+ "media": {+ "kind": "image",+ "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ }+ },+ {+ "id": "w2",+ "d": "2026-09-20",+ "start": 1,+ "end": 2,+ "entries": [],+ "media": "x"+ },+ {+ "id": "w3",+ "d": "2026-09-20",+ "start": 1,+ "end": 2,+ "entries": [],+ "media": null+ }+ ]+ },+ "expect": []+ },+ {+ "name": "workout media items that are not refs are skipped, the others count",+ "state": {+ "workouts": [+ {+ "id": "w1",+ "d": "2026-09-20",+ "start": 1,+ "end": 2,+ "entries": [],+ "media": [+ null,+ 1,+ "x",+ [+ {+ "kind": "image",+ "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ }+ ],+ {+ "hash": "nope"+ },+ {+ "kind": "image",+ "hash": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1,+ "poster": {+ "hash": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",+ "mime": "image/webp",+ "size": 100,+ "width": 480,+ "height": 360+ }+ },+ {+ "poster": {+ "hash": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"+ }+ }+ ]+ }+ ]+ },+ "expect": [+ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"+ ]+ },+ {+ "name": "a workout's list counts past the app's cap of six",+ "state": {+ "workouts": [+ {+ "id": "w1",+ "d": "2026-09-20",+ "start": 1,+ "end": 2,+ "entries": [],+ "media": [+ {+ "kind": "image",+ "hash": "0000000000000000000000000000000000000000000000000000000000000000",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ },+ {+ "kind": "image",+ "hash": "1111111111111111111111111111111111111111111111111111111111111111",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ },+ {+ "kind": "image",+ "hash": "2222222222222222222222222222222222222222222222222222222222222222",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ },+ {+ "kind": "image",+ "hash": "3333333333333333333333333333333333333333333333333333333333333333",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ },+ {+ "kind": "image",+ "hash": "4444444444444444444444444444444444444444444444444444444444444444",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ },+ {+ "kind": "image",+ "hash": "5555555555555555555555555555555555555555555555555555555555555555",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ },+ {+ "kind": "image",+ "hash": "6666666666666666666666666666666666666666666666666666666666666666",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ }+ ]+ }+ ]+ },+ "expect": [+ "0000000000000000000000000000000000000000000000000000000000000000",+ "1111111111111111111111111111111111111111111111111111111111111111",+ "2222222222222222222222222222222222222222222222222222222222222222",+ "3333333333333333333333333333333333333333333333333333333333333333",+ "4444444444444444444444444444444444444444444444444444444444444444",+ "5555555555555555555555555555555555555555555555555555555555555555",+ "6666666666666666666666666666666666666666666666666666666666666666"+ ]+ },+ {+ "name": "the same file on an exercise and on two workouts counts once",+ "state": {+ "customEx": [+ {+ "id": "cx1",+ "n": "Sandbag carry cx1",+ "bp": "back",+ "custom": true,+ "media": {+ "kind": "image",+ "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1,+ "poster": {+ "hash": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ "mime": "image/webp",+ "size": 100,+ "width": 480,+ "height": 360+ }+ }+ }+ ],+ "workouts": [+ {+ "id": "w1",+ "d": "2026-09-20",+ "start": 1,+ "end": 2,+ "entries": [],+ "media": [+ {+ "kind": "image",+ "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1,+ "poster": {+ "hash": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ "mime": "image/webp",+ "size": 100,+ "width": 480,+ "height": 360+ }+ }+ ]+ },+ {+ "id": "w2",+ "d": "2026-09-20",+ "start": 1,+ "end": 2,+ "entries": [],+ "media": [+ {+ "kind": "image",+ "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ },+ {+ "kind": "video",+ "hash": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",+ "mime": "video/mp4",+ "size": 500000,+ "width": 1280,+ "height": 720,+ "dur": 8.2,+ "codec": "avc1",+ "at": 2+ }+ ]+ }+ ]+ },+ "expect": [+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"+ ]+ },+ {+ "name": "the session in progress is not a source (the server never stores it)",+ "state": {+ "active": {+ "id": "w9",+ "entries": [],+ "media": [+ {+ "kind": "image",+ "hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "mime": "image/webp",+ "size": 1000,+ "width": 800,+ "height": 600,+ "at": 1+ }+ ]+ },+ "workouts": []+ },"expect": []}]diff --git a/api/test/media-gc.test.js b/api/test/media-gc.test.jsindex 5e197eff9..f21f33272 100644--- a/api/test/media-gc.test.js+++ b/api/test/media-gc.test.js@@ -247,3 +247,36 @@ test('a new upload nobody references yet is marked, so the grace also covers a pawait h.store.receive('u1', M.sha(b), M.fakeReq(b));assert.deepEqual(h.marks('u1'), { [M.sha(a)]: h.clock.t }, 'the referenced one is not marked');});++// The photos and videos of a logged workout (workouts[].media) keep their files exactly like an+// exercise's picture: a file only a workout refers to is never swept, and taking it off the+// workout starts its grace like any other.+const wref = (...hashes) => ({ workouts: [{ id: 'w1', d: '2026-09-20', start: 1, end: 2, entries: [], media: hashes.map((h, i) => ({ kind: 'image', hash: h, mime: 'image/jpeg', size: 1, width: 1, height: 1, at: i + 1 })) }] });++test('a file referenced only by a workout is never swept, whatever the grace', t => {+ const h = setup(t);+ const photo = h.place('u1', M.jpeg()), gone = h.place('u1', M.jpeg(3000));+ h.S.set('u1', wref(photo));+ assert.equal(h.store.noteState('u1', wref(photo)), true, 'the other file gets its mark');+ assert.deepEqual(Object.keys(h.marks('u1')), [gone]);+ h.clock.t += 365 * DAY;+ assert.deepEqual(h.store.sweep('u1'), { removed: 1, freedBytes: 3000, skipped: false });+ assert.deepEqual(h.store.sweep('u1', { graceMs: 0 }), { removed: 0, freedBytes: 0, skipped: false });+ assert.deepEqual(h.files('u1'), [`${photo}.jpg`]);+});++test('a photo taken off a workout is marked by the next state push and swept after the grace', t => {+ const h = setup(t);+ const a = h.place('u1', M.jpeg()), b = h.place('u1', M.jpeg(2000));+ h.S.set('u1', wref(a, b));+ assert.equal(h.store.noteState('u1', wref(a, b)), false);+ // The owner removes b from the workout; the push lands.+ h.S.set('u1', wref(a));+ assert.equal(h.store.noteState('u1', wref(a)), true);+ assert.deepEqual(h.marks('u1'), { [b]: h.clock.t });+ h.clock.t += 14 * DAY - 1;+ assert.equal(h.store.sweep('u1').removed, 0, 'inside the grace another device may still show it');+ h.clock.t += 1;+ assert.deepEqual(h.store.sweep('u1'), { removed: 1, freedBytes: 2000, skipped: false });+ assert.deepEqual(h.files('u1'), [`${a}.jpg`]);+});diff --git a/api/test/payload.test.js b/api/test/payload.test.jsindex 72c3094b8..2f1e665fd 100644--- a/api/test/payload.test.js+++ b/api/test/payload.test.js@@ -286,3 +286,21 @@ test('a custom exercise\'s photo, video and link never reach the payload', () =>const slice = payload.librarySlice(S, [], { keep: ['cx1'] }).find(e => e.id === 'cx1');assert.deepEqual(slice, { id: 'cx1', n: 'Sandbag carry', bp: 'back', custom: true }, 'the library slice keeps a custom exercise to four fields');});++/* A logged workout's own photos and videos (workouts[].media) — progress photos, form-check+ clips — are the most personal files in the profile. No job sends them, their hashes, their+ posters or even the fact that there are any. */+test('a workout\'s photos and videos never reach the payload', () => {+ const HASH = 'a1'.repeat(32), POSTER = 'b2'.repeat(32), PHOTO = 'c3'.repeat(32);+ const S = sampleState();+ S.workouts[0].media = [+ { kind: 'video', hash: HASH, mime: 'video/quicktime', size: 9000000, width: 1080, height: 1920, dur: 14, codec: 'hvc1', poster: { hash: POSTER, mime: 'image/jpeg', size: 30000, width: 270, height: 480 }, at: 1 },+ { kind: 'image', hash: PHOTO, mime: 'image/webp', size: 300000, width: 1200, height: 1600, at: 2 }+ ];+ for (const kind of ['create', 'review', 'debrief']) {+ const json = JSON.stringify(payload.build(S, { handle: handleFor('user-wmedia'), kind, workoutId: 'w1' }));+ for (const leak of [HASH, POSTER, PHOTO, '"media"', '"poster"', 'video/quicktime', 'image/webp', 'hvc1']) {+ assert.ok(!json.includes(leak), `${kind} payload leaked ${leak}`);+ }+ }+});diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.mdindex 8e53a24ba..558235b7d 100644--- a/docs/SELF_HOSTING.md+++ b/docs/SELF_HOSTING.md@@ -348,7 +348,9 @@ a passkey scope and can see each other's credentials. Give each its own hostname### Photos and videos of custom exercisesAnyone signed in can give an exercise they made one photo, GIF or short video (and, separately,-a link, which the server never fetches). The file is uploaded to this server and stored under+a link, which the server never fetches), and attach up to six photos or videos to a logged+workout — a progress photo, a form-check clip. Both kinds share one quota and one set of limits.+The file is uploaded to this server and stored under`./data/uploads/<profile id>/`, named by its SHA-256. Only its owner can download it again — noadmin route, no Coach and no shared plan reads it. It is on by default, with these limits, allset in `.env`:diff --git a/frontend/src/lib/backup-media.js b/frontend/src/lib/backup-media.jsindex 5b0129ec3..d1ef0f3b3 100644--- a/frontend/src/lib/backup-media.js+++ b/frontend/src/lib/backup-media.js@@ -1,4 +1,4 @@-/* Backups that carry the photos and videos of custom exercises.+/* Backups that carry the photos and videos of custom exercises and of logged workouts.** "Export backup (JSON)" stays what it always was: the state, with each exercise's small* reference to its file and never the file. "Export with photos & videos" writes a store-only zip@@ -18,7 +18,7 @@* and links go through the same gates as everywhere else (sanitizeCustomMedia).*/import { zipStore, readZip, looksLikeZip } from './zip.js'-import { referencedFiles, normalizeMediaRef, cleanUrl, MEDIA_MIMES } from './media-refs.js'+import { referencedFiles, normalizeMediaRef, workoutMediaOf, cleanUrl, MEDIA_MIMES } from './media-refs.js'import { sniffKind } from './media-sniff.js'import { sha256Hex } from './sha256.js'import { mediaStore } from './media-store.js'@@ -31,21 +31,29 @@ const README = `openGym backup with photos and videos=====================================opengym-backup.json your data - the same file "Export backup (JSON)" writes.-media/ the photos, GIFs and videos of your own exercises, each named- by its SHA-256, plus the small previews shown in lists.+media/ the photos, GIFs and videos of your own exercises and of your+ workouts, each named by its SHA-256, plus the small previews+ shown in lists.To bring it back: openGym -> Settings -> Import backup, and pick this .zip as it is.Do not unpack and re-zip it: the app reads zips that are stored, not compressed.`-/** The customEx media refs and links of an imported state, kept only where they pass the same- * checks as anywhere else; the rest of the state is left as it is. Mutates and returns it. */+/** The media refs and links of an imported state — each custom exercise's picture and link, each+ * logged workout's photos and videos — kept only where they pass the same checks as anywhere+ * else (a workout's list also deduplicated and capped, workoutMediaOf); the rest of the state is+ * left as it is. Mutates and returns it. */export function sanitizeCustomMedia(state) {for (const c of Array.isArray(state?.customEx) ? state.customEx : []) {if (!c || typeof c !== 'object') continueif ('media' in c) { const m = normalizeMediaRef(c.media); if (m) c.media = m; else delete c.media }if ('url' in c) { const u = cleanUrl(c.url); if (u) c.url = u; else delete c.url }}+ for (const w of Array.isArray(state?.workouts) ? state.workouts : []) {+ if (!w || typeof w !== 'object' || !('media' in w)) continue+ const list = workoutMediaOf(w)+ if (list.length) w.media = list; else delete w.media+ }return state}diff --git a/frontend/src/lib/backup-media.test.js b/frontend/src/lib/backup-media.test.jsindex 1ec8c195d..03db36b83 100644--- a/frontend/src/lib/backup-media.test.js+++ b/frontend/src/lib/backup-media.test.js@@ -85,4 +85,37 @@ describe('import', () => {it('sanitizeCustomMedia leaves a state without custom exercises alone', () => {expect(sanitizeCustomMedia({ workouts: [] })).toEqual({ workouts: [] })})++ it('a workout\'s photos and videos come in through the same gates: bad refs dropped, one per file, at most six', () => {+ const ok = n => ({ kind: 'image', hash: String(n).repeat(64), mime: 'image/webp', size: 10, width: 4, height: 3, at: 1 })+ const S = { workouts: [+ { id: 'w1', media: [ok(1), { ...ok(2), mime: 'text/html' }, ok(1), ok(3), ok(4), ok(5), ok(6), ok(7), ok(8)] },+ { id: 'w2', media: 'x' },+ { id: 'w3' }+ ] }+ sanitizeCustomMedia(S)+ expect(S.workouts[0].media.map(m => m.hash[0])).toEqual(['1', '3', '4', '5', '6', '7'])+ expect('media' in S.workouts[1]).toBe(false)+ expect(S.workouts[2]).toEqual({ id: 'w3' })+ })+})++describe('a workout\'s photos and videos in the zip', () => {+ it('are exported next to the exercises\' and come back in from the zip', async () => {+ const media = createMediaStore(memoryBackend())+ const photo = jpeg(), clip = mp4().file+ const p = await refFor(photo, 'image/jpeg')+ const v = await refFor(clip, 'video/mp4', 'video')+ await media.put(p.hash, new Blob([photo]), { mime: 'image/jpeg' })+ await media.put(v.hash, new Blob([clip]), { mime: 'video/mp4' })+ const S = { ...stateWith([]), workouts: [{ id: 'w1', d: '2026-09-20', start: 1, end: 2, entries: [], media: [p, v] }] }+ const out = await exportBackupZip(S, { media })+ expect(out).toMatchObject({ included: 2, missing: 0 })+ const read = await readBackupFile(new File([out.blob], 'backup.zip'))+ expect(read.state.workouts[0].media).toEqual([p, v])+ expect(read.files.map(f => f.hash).sort()).toEqual([p.hash, v.hash].sort())+ const into = createMediaStore(memoryBackend())+ expect(await storeBackupMedia(read.files, { media: into })).toEqual({ stored: 2, skipped: 0 })+ expect(await into.get(v.hash)).toMatchObject({ mime: 'video/mp4', pending: true })+ })})diff --git a/frontend/src/lib/media-owed.js b/frontend/src/lib/media-owed.jsindex 54bcb66c8..f6f6e6630 100644--- a/frontend/src/lib/media-owed.js+++ b/frontend/src/lib/media-owed.js@@ -12,7 +12,7 @@* publishes what it last learned (usage on the server, what is waiting) for Settings and the* sign-out sheet.*/-import { HASH_RE } from './media-refs.js'+import { HASH_RE, stateMediaRefs } from './media-refs.js'import { getMediaStore } from './media-store.js'let pending = new Set()@@ -37,23 +37,21 @@ function watch() {export function loadPending() { watch() }/**- * How many custom exercises of `S` have a photo or video (or its poster) that the server has not- * confirmed. Counted per exercise, not per file, because that is what the sentence counts- * ("2 photos or videos have not reached your server yet"); one exercise's main file and poster- * are one photo to the person holding it.+ * How many photos and videos of `S` — a custom exercise's, or one attached to a logged workout —+ * have a file (or its poster) that the server has not confirmed. Counted per photo or video, not+ * per file, because that is what the sentence counts ("2 photos or videos have not reached your+ * server yet"); a main file and its poster are one photo to the person holding it.*/-const hasMedia = S => (Array.isArray(S?.customEx) ? S.customEx : []).some(c => c && typeof c === 'object' && c.media && typeof c.media === 'object')+const hasMedia = S => stateMediaRefs(S).length > 0export function pendingRefCount(S) {- const list = Array.isArray(S?.customEx) ? S.customEx : []+ const refs = stateMediaRefs(S)// A copy without media has nothing to count, and does not need the store opened to say so.- if (!hasMedia(S)) return 0+ if (!refs.length) return 0watch()if (!pending.size) return 0const seen = new Set()- for (const c of list) {- const m = c && typeof c === 'object' ? c.media : null- if (!m || typeof m !== 'object') continue+ for (const m of refs) {const main = typeof m.hash === 'string' && HASH_RE.test(m.hash) ? m.hash : nullconst poster = m.poster && typeof m.poster.hash === 'string' && HASH_RE.test(m.poster.hash) ? m.poster.hash : nullif ((main && pending.has(main)) || (poster && pending.has(poster))) seen.add(main || poster)diff --git a/frontend/src/lib/media-refs.js b/frontend/src/lib/media-refs.jsindex 143e9f54f..bda7ca5fe 100644--- a/frontend/src/lib/media-refs.js+++ b/frontend/src/lib/media-refs.js@@ -1,4 +1,5 @@-/* The photo, GIF or video of a custom exercise, as the state holds it — and its link.+/* The photo, GIF or video of a custom exercise, and the photos and videos of a logged workout,+ * as the state holds them — and an exercise's link.** The state never carries the bytes, only a MediaRef of a few hundred bytes (see the shape* below). The bytes live in the device's local media store (lib/media-store.js) and, signed in,@@ -79,19 +80,67 @@ export function normalizeMediaRef(ref) {/** The media of a custom exercise as it may be shown, or null. */export const mediaOf = ex => (ex && ex.media ? normalizeMediaRef(ex.media) : null)+/**+ * How many photos and videos one logged workout keeps. Every ref travels in the whole-document+ * push that each of the account's devices downloads (about 300 bytes each, plus its poster's+ * files on every device that shows it), so the list is bounded like everything else in the+ * state: six is a progress photo from a few angles plus a couple of form-check clips, one or two+ * rows of thumbnails on a phone. A workout with more has to drop one first.+ */+export const WORKOUT_MEDIA_MAX = 6++/**+ * The photos and videos of a logged workout as they may be shown: each passes normalizeMediaRef,+ * a file listed twice shows once, and never more than WORKOUT_MEDIA_MAX (a hand-edited or+ * foreign copy can hold anything). Oldest first, the order they were added in.+ */+export function workoutMediaOf(w) {+ const raw = w && typeof w === 'object' && Array.isArray(w.media) ? w.media : []+ const out = []+ const seen = new Set()+ for (const r of raw) {+ const m = normalizeMediaRef(r)+ if (!m || seen.has(m.hash)) continue+ seen.add(m.hash)+ out.push(m)+ if (out.length >= WORKOUT_MEDIA_MAX) break+ }+ return out+}++/**+ * Every MediaRef-like object a state holds, as it stands (not normalised): each custom+ * exercise's `media` and each entry of each logged workout's `media` list. The one walk behind+ * referencedHashes, referencedFiles and the owed count, so they can never disagree about where+ * media live. The session in progress is not walked: it never syncs (the server drops `active`),+ * media are only ever attached to a saved workout, and the history editor's copy of one leaves+ * them on the saved record (lib/session-edit.js).+ */+export function stateMediaRefs(state) {+ const out = []+ if (!state || typeof state !== 'object') return out+ const isObj = v => !!v && typeof v === 'object' && !Array.isArray(v)+ for (const c of Array.isArray(state.customEx) ? state.customEx : []) {+ if (isObj(c) && isObj(c.media)) out.push(c.media)+ }+ for (const w of Array.isArray(state.workouts) ? state.workouts : []) {+ if (!isObj(w) || !Array.isArray(w.media)) continue+ for (const m of w.media) if (isObj(m)) out.push(m)+ }+ return out+}+/*** Every blob hash a state refers to, the same answer as api/media.js referencedHashes (the shared- * fixture api/test/fixtures/media-refs.json pins both). Deliberately looser than- * normalizeMediaRef: each of media.hash and media.poster.hash counts on its own as long as it is a- * well-formed hash, because this set decides what is KEPT, and keeping too much is the safe side.+ * fixture api/test/fixtures/media-refs.json pins both): customEx[].media and every entry of+ * workouts[].media. Deliberately looser than normalizeMediaRef and workoutMediaOf: each hash and+ * poster hash counts on its own as long as it is well-formed, and a workout's list counts past+ * its cap, because this set decides what is KEPT, and keeping too much is the safe side.*/export function referencedHashes(state) {const out = new Set()- const list = state && typeof state === 'object' && Array.isArray(state.customEx) ? state.customEx : []const add = r => { if (r && typeof r === 'object' && typeof r.hash === 'string' && HASH_RE.test(r.hash)) out.add(r.hash) }- for (const c of list) {- const m = c && typeof c === 'object' ? c.media : null- if (!m || typeof m !== 'object') continue+ for (const m of stateMediaRefs(state)) {add(m)add(m.poster)}@@ -103,15 +152,13 @@ export function referencedHashes(state) {* shows, so it is the file another device most wants soon, and it is small. Each hash comes with* what the state says about it — { hash, mime, size, poster } — which is what a download is* checked against. The first ref that names a hash decides; two exercises with the same file- * describe it the same way unless someone edited one by hand.+ * describe it the same way unless someone edited one by hand (an exercise's picture added to a+ * workout too is one file).*/export function referencedFiles(state) {const posters = new Map()const mains = new Map()- const list = state && typeof state === 'object' && Array.isArray(state.customEx) ? state.customEx : []- for (const c of list) {- const m = c && typeof c === 'object' ? c.media : null- if (!m || typeof m !== 'object') continue+ for (const m of stateMediaRefs(state)) {const p = m.posterif (p && typeof p === 'object' && typeof p.hash === 'string' && HASH_RE.test(p.hash) && !posters.has(p.hash)) {posters.set(p.hash, { hash: p.hash, mime: p.mime, size: p.size, poster: true })diff --git a/frontend/src/lib/media-sync.js b/frontend/src/lib/media-sync.jsindex d5c2d64c0..941f7bf8d 100644--- a/frontend/src/lib/media-sync.js+++ b/frontend/src/lib/media-sync.js@@ -1,4 +1,4 @@-/* Photos and videos of custom exercises between this device and its server.+/* Photos and videos of custom exercises and of logged workouts between this device and its server.** ONE mechanism for every move between modes, keyed by content hash and safe to repeat: ask the* server which of the state's files it lacks (POST /api/media/missing), then send the ones this@@ -35,6 +35,9 @@ const SETTLE_BUDGET_MS = 60000const MISSING_CHUNK = 1000const UPLOAD_BACKOFF = [1, 2, 5, 15, 60].map(m => m * MIN)const MISSING_BACKOFF = [30000, 2 * MIN, 10 * MIN, 30 * MIN]+// How many of the latest workouts with photos or videos get their posters made local ahead of+// time: the history's first screens, a few KB each.+const RECENT_WORKOUT_POSTERS = 20// Refusals that will not change by trying again: the file stays here, pending, and is not// offered again until someone asks (the Settings row).const REJECTED = new Set(['media-too-large', 'media-type', 'media-invalid', 'media-too-long', 'proxy-too-large', 'hash-mismatch'])@@ -319,8 +322,10 @@ export function createMediaSync(deps = {}) {/*** Makes the posters and files of every custom exercise in the plan and in the session in- * progress local, so they show without a network. Signed in only (nothing to fetch from- * otherwise), and only on a connection that is not metered (prefetchAllowed).+ * progress local, so they show without a network — and the posters of the photos and videos+ * of the most recent workouts that have some (RECENT_WORKOUT_POSTERS), so the history's+ * thumbnails do too; their main files come down when one is opened. Signed in only (nothing to+ * fetch from otherwise), and only on a connection that is not metered (prefetchAllowed).*/function startCustomMediaPrefetch({ delay = 8000 } = {}) {if (!store) return () => {}@@ -332,7 +337,9 @@ export function createMediaSync(deps = {}) {;(S?.routines || []).forEach(r => (r?.ex || []).forEach(e => { if (e?.id) ids.add(e.id) }));(S?.active?.entries || []).forEach(en => { if (en?.id) ids.add(en.id) })const used = { customEx: (S?.customEx || []).filter(c => c && ids.has(c.id)) }- return referencedFiles(used)+ const withMedia = (Array.isArray(S?.workouts) ? S.workouts : []).filter(w => Array.isArray(w?.media) && w.media.length)+ const posters = referencedFiles({ workouts: withMedia.slice(-RECENT_WORKOUT_POSTERS) }).filter(f => f.poster)+ return [...referencedFiles(used), ...posters]}const runPrefetch = async () => {timer = null@@ -350,7 +357,7 @@ export function createMediaSync(deps = {}) {const schedule = () => { clearTimeout(timer); timer = setTimeout(runPrefetch, delay) }let seen = store.getState().Sconst unsub = store.subscribe(s => {- if (s.S?.routines === seen?.routines && s.S?.active === seen?.active && s.S?.customEx === seen?.customEx) return+ if (s.S?.routines === seen?.routines && s.S?.active === seen?.active && s.S?.customEx === seen?.customEx && s.S?.workouts === seen?.workouts) returnseen = s.Sschedule()})diff --git a/frontend/src/lib/media-sync.test.js b/frontend/src/lib/media-sync.test.jsindex fc5c77a31..cec131a37 100644--- a/frontend/src/lib/media-sync.test.js+++ b/frontend/src/lib/media-sync.test.js@@ -418,3 +418,41 @@ describe('in a browser tab, not the installed app', () => {} finally { stop() }})})++// A logged workout's photos and videos (workouts[].media) go through the very same sync: the+// server is asked about them and sent what it lacks, the local clean-up keeps them, and the most+// recent workouts' posters are made local ahead so the history shows them offline.+describe('a workout\'s photos and videos', () => {+ const workoutWith = (...refs) => ({ id: 'w1', d: '2026-09-20', start: 1, end: 2, entries: [], media: refs })++ it('are uploaded when the server lacks them, posters first', async () => {+ await put(hex('a')); await put(hex('b'))+ const S = { customEx: [], workouts: [workoutWith(refOf(hex('a'), hex('b')))] }+ await make(appStore({ S })).syncMedia()+ expect(JSON.parse(api.mock.calls[0][1].body).hashes).toEqual([hex('b'), hex('a')])+ expect(apiUpload.mock.calls.map(c => c[0])).toEqual(['/api/media/' + hex('b'), '/api/media/' + hex('a')])+ expect(media.pendingNow().size).toBe(0)+ })++ it('the local clean-up keeps a file only a workout refers to', async () => {+ await put(hex('a')); await put(hex('c'))+ clock += 2 * 3600000+ await make(appStore({ S: { customEx: [], workouts: [workoutWith(refOf(hex('a')))] }, user: null })).localMediaGc()+ expect((await media.list()).map(r => r.hash)).toEqual([hex('a')])+ })++ it('the posters of recent workouts are made local ahead; their main files wait to be opened', async () => {+ const poster = jpeg()+ const ph = await sha256Hex(poster)+ apiBlob.mockResolvedValue(new Blob([poster]))+ const ref = refOf(hex('a'), null, { kind: 'video', mime: 'video/mp4', size: 5 * MB, width: 1280, height: 720 })+ ref.poster = { hash: ph, mime: 'image/jpeg', size: poster.length, width: 640, height: 480 }+ const S = { customEx: [], routines: [], workouts: [workoutWith(ref)] }+ const stop = make(appStore({ S })).startCustomMediaPrefetch({ delay: 0 })+ try {+ for (let i = 0; i < 50 && !(await media.has(ph)); i++) await new Promise(r => setTimeout(r, 10))+ expect(await media.get(ph)).toMatchObject({ mime: 'image/jpeg', pending: false })+ expect(apiBlob.mock.calls.map(c => c[0])).toEqual(['/api/media/' + ph])+ } finally { stop() }+ })+})diff --git a/frontend/src/store/useStore.media.test.jsx b/frontend/src/store/useStore.media.test.jsxindex 154ea977d..bbcef054b 100644--- a/frontend/src/store/useStore.media.test.jsx+++ b/frontend/src/store/useStore.media.test.jsx@@ -132,3 +132,45 @@ describe('owed photos and videos', () => {expect(await media.list()).toEqual([])})})++// A workout's own photos and videos (workouts[].media) ride the very same rules: owed while the+// server lacks them, stashed with the copy on a forced sign-out, and their files kept for it.+describe('owed photos and videos of a logged workout', () => {+ const V = 'c'.repeat(64)+ const VP = 'd'.repeat(64)+ const clip = { kind: 'video', hash: V, mime: 'video/mp4', size: 3, width: 8, height: 6, dur: 7, poster: { hash: VP, mime: 'image/webp', size: 3, width: 8, height: 6 }, at: 2 }+ const withWorkoutMedia = () => ({ ...clone(DEF), _ts: 100, workouts: [{ id: 'w1', d: '2026-09-20', start: 1, end: 2, name: 'Push', entries: [], media: [clone(ref), clone(clip)] }] })+ async function signedIn() {+ await media.put(A, new Blob(['abc']), { mime: 'image/webp', pending: false })+ await media.put(P, new Blob(['abc']), { mime: 'image/webp', pending: false })+ await media.put(V, new Blob(['abc']), { mime: 'video/mp4', pending: true })+ await media.put(VP, new Blob(['abc']), { mime: 'image/webp', pending: true })+ useStore.setState({ S: withWorkoutMedia(), user: USER, ready: true, sync: { ...fresh } })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ api.mockImplementation(async (path, o) => (o?.method === 'PUT' ? { ok: true, rev: 2 } : { ok: true }))+ }++ it('a clip that has not reached the server is owed, counted once with its poster', async () => {+ await signedIn()+ expect(useStore.getState().unsyncedChanges()).toMatchObject({ owed: true, media: 1 })+ expect((await useStore.getState().signOut())).toMatchObject({ owed: true, media: 1 })+ expect(useStore.getState().user).toEqual(USER)+ })++ it('going ahead anyway stashes the workout with its media, and every one of its files stays', async () => {+ await signedIn()+ const r = await useStore.getState().signOut({ force: true })+ expect(r).toMatchObject({ owed: true, media: 1, stashed: true })+ expect(useStore.getState().S.workouts).toEqual([])+ expect(await useStore.getState().stashedMediaHashes()).toEqual(new Set([A, P, V, VP]))+ await new Promise(r => setTimeout(r, 20))+ for (const h of [A, P, V, VP]) expect(await media.has(h)).toBe(true)+ })++ it('once the server has it, nothing is owed', async () => {+ await signedIn()+ await media.markSynced(V)+ await media.markSynced(VP)+ expect(useStore.getState().unsyncedChanges()).toEqual({ owed: false, count: 0 })+ })+})diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.jsindex 7a2cdc874..0eb77a959 100644--- a/mcp/test/tools.test.js+++ b/mcp/test/tools.test.js@@ -900,3 +900,29 @@ describe('preview_session', () => {expect(() => call('preview_session', { routine_id: 'nope' })).toThrow(/no routine with id/)})})++/* ---------- a workout's photos and videos ---------- */++// workouts[].media — progress photos and form-check clips — are the owner's own files. The MCP+// bridge answers from the same state file, so it must not pass on a single hash, poster or even+// the key: an LLM client has nothing to do with them.+describe('workout photos and videos never leave through MCP', () => {+ const HASH = 'a1'.repeat(32), POSTER = 'b2'.repeat(32)+ test('no tool answer carries them', () => {+ for (const w of S.workouts) {+ w.media = [{ kind: 'video', hash: HASH, mime: 'video/mp4', size: 900000, width: 720, height: 1280, dur: 9, codec: 'avc1', poster: { hash: POSTER, mime: 'image/webp', size: 9000, width: 270, height: 480 }, at: 1 }]+ }+ _seedStateForTests(S)+ const newest = call('list_workouts', {}).workouts[0]+ const answers = [+ call('list_workouts', {}),+ call('get_workout', newest.id ? { workout_id: newest.id } : { date: newest.date }),+ call('muscle_balance', { period: 'all' }),+ call('muscle_balance', { period: 'month' }),+ ]+ for (const a of answers) {+ const json = JSON.stringify(a)+ for (const leak of [HASH, POSTER, '"media"', '"poster"', 'video/mp4']) expect(json).not.toContain(leak)+ }+ })+})diff --git a/scripts/build-api-docs.mjs b/scripts/build-api-docs.mjsindex fdb5b6809..bc51b8348 100644--- a/scripts/build-api-docs.mjs+++ b/scripts/build-api-docs.mjs@@ -128,7 +128,7 @@ const TAGS = {data: { title: 'Data', side: 'State sync' },push: { title: 'Push', side: 'Notifications & rest timer' },activity: { title: 'Activity', side: 'Live presence' },- media: { title: 'Media', side: 'Photos & videos of your own exercises' },+ media: { title: 'Media', side: 'Photos & videos of your exercises & workouts' },// A tag missing from this map renders nowhere at all, silently — so every tag in the// spec needs a line here.coach: { title: 'AI Coach', side: 'Plans, reviews, debriefs' },