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.

Media: the byte-level helpers for photos and videos of custom exercises — refs, sniffing, the GIF and MP4 scrub, SHA-256 and a store-only zip

Duarte Santosd025e1e7ba94
diff --git a/frontend/src/lib/audit.js b/frontend/src/lib/audit.js
index ff126f93d..ddb72eadd 100644
--- a/frontend/src/lib/audit.js
+++ b/frontend/src/lib/audit.js
@@ -52,7 +52,11 @@ const LABELS = {
'admin.invite.create': 'Created an invite code',
'admin.invite.revoke': 'Revoked an invite code',
'admin.audit.clear': 'Cleared the activity log',
- 'admin.denied': 'Blocked from the admin dashboard'
+ 'admin.denied': 'Blocked from the admin dashboard',
+ // Photos and videos of custom exercises: "Reset everything" clearing a profile's files, and the
+ // upload or clean-up throttle pausing a profile (`msg` says which).
+ 'media.sweep': 'Cleared unused photos and videos',
+ 'media.throttled': 'Too many photo or video requests'
}
// An unknown event is shown raw rather than dropped or rendered as "undefined": a dashboard
// that is one version behind the server should still say *something* truthful.
@@ -80,7 +84,10 @@ const REASONS = {
// What an `auth.throttled` pause was for.
'password': 'wrong passwords or reset codes',
'signup': 'wrong invite codes on password signup',
- 'link': 'wrong one-time device codes'
+ 'link': 'wrong one-time device codes',
+ // What a `media.throttled` pause was for.
+ 'upload': 'photo and video uploads',
+ 'sweep': 'clearing unused photos and videos'
}
export const auditReason = msg => REASONS[msg] || (msg ? String(msg) : '')
diff --git a/frontend/src/lib/audit.test.js b/frontend/src/lib/audit.test.js
index 2384cbcb0..6d8a3ebf5 100644
--- a/frontend/src/lib/audit.test.js
+++ b/frontend/src/lib/audit.test.js
@@ -35,8 +35,10 @@ describe('auditCat', () => {
it('survives a missing event name', () => {
expect(auditCat(undefined)).toBe('')
})
- it('puts every known event in exactly auth or admin', () => {
- expect([...new Set(EVENTS.map(auditCat))].sort()).toEqual(['admin', 'auth'])
+ // `media` is the third: the photo and video clean-up and throttle. It has no chip of its own —
+ // those rows show under All, and a throttle under Failed.
+ it('puts every known event in auth, admin or media', () => {
+ expect([...new Set(EVENTS.map(auditCat))].sort()).toEqual(['admin', 'auth', 'media'])
})
})
diff --git a/frontend/src/lib/media-limits.js b/frontend/src/lib/media-limits.js
new file mode 100644
index 000000000..e31bf99cc
--- /dev/null
+++ b/frontend/src/lib/media-limits.js
@@ -0,0 +1,43 @@
+/* How big a photo, GIF or video of a custom exercise may be, and the device-side constants.
+ *
+ * The caps are the server's to set (MEDIA_* in .env, handed out as `media` in GET /api/config):
+ * when the server says, its numbers win, so the editor refuses a file here rather than after an
+ * upload the server would refuse anyway. Without a server — a guest, the demo, a phone in local
+ * mode — the defaults below apply; they are the server's defaults too (api/media.js mediaLimits).
+ * Every MB is 2^20 bytes on both sides, and the server's values may be fractional.
+ */
+
+export const MB = 1024 * 1024
+
+export const DEFAULT_LIMITS = Object.freeze({
+ imageMB: 2, // a photo after it has been re-encoded here
+ rawPhotoMB: 40, // a photo as picked, before decoding; the pixel guard below applies as well
+ gifMB: 8,
+ videoMB: 40, // videos are not transcoded, so this is the file as picked
+ videoSec: 60,
+ quotaMB: 200 // per profile on the server; 0 = no cap
+})
+
+export const IMAGE_MAX_EDGE = 1600 // px, the long edge of a stored photo
+export const POSTER_EDGE = 480 // px, the long edge of every poster (list thumbnails)
+export const LOOP_MAX_SEC = 15 // a video up to this long loops silently like a GIF
+export const MAX_PHOTO_MP = 52 // megapixels a photo may have before it is even decoded
+export const LOCAL_CACHE_MAX_MB = 300 // signed in: the local copies beyond this are evicted
+export const LOCAL_GC_GRACE_MS = 3600000 // a file picked in the last hour is never collected
+export const BG_UPLOAD_METERED_MAX_MB = 5 // bigger uploads wait for a connection that is not metered
+
+const pos = v => typeof v === 'number' && Number.isFinite(v) && v > 0
+
+/** The limits in force: the server's `config.media` over the defaults, one number at a time. */
+export function limitsFrom(config) {
+ const m = config && typeof config === 'object' ? config.media : null
+ const out = { ...DEFAULT_LIMITS }
+ if (!m || typeof m !== 'object') return out
+ for (const k of ['imageMB', 'gifMB', 'videoMB', 'videoSec']) if (pos(m[k])) out[k] = m[k]
+ // 0 is a real answer for the quota (no cap), not a missing one.
+ if (typeof m.quotaMB === 'number' && Number.isFinite(m.quotaMB) && m.quotaMB >= 0) out.quotaMB = m.quotaMB
+ return out
+}
+
+/** "2", "0.5", "40" — a cap as the error message says it. */
+export const fmtMB = mb => String(Math.round(mb * 10) / 10)
diff --git a/frontend/src/lib/media-refs.js b/frontend/src/lib/media-refs.js
new file mode 100644
index 000000000..143e9f54f
--- /dev/null
+++ b/frontend/src/lib/media-refs.js
@@ -0,0 +1,165 @@
+/* The photo, GIF or video of a custom exercise, as the state holds it — and its 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,
+ * on the server under DATA_DIR/uploads/<uid>/<sha256>.<ext> (api/media.js). Everything here is
+ * pure and has no imports, so the store, the sync, the editor and the tests can all use it.
+ *
+ * MediaRef = { kind: 'image'|'gif'|'video', hash, mime, size, width, height,
+ * dur?, codec?, poster?: { hash, mime, size, width, height }, at }
+ *
+ * A ref comes from outside whenever a state does: another device, a backup file, a plan file, a
+ * hand-edited profile. So nothing trusts one as it stands. normalizeMediaRef() is the gate every
+ * reader goes through, and anything it refuses is shown as "no media". cleanUrl() is the same
+ * gate for the link, and it runs both when a link is saved and when one is opened.
+ */
+
+export const HASH_RE = /^[0-9a-f]{64}$/
+
+/* The seven types that are ever stored, the same list as api/media.js MEDIA_TYPES. `playExt` is
+ the name a file gets in the phone's own folder: the WebView's local server types a file by its
+ extension, and it hands out .mov as something the <video> element will not play, while the same
+ bytes named .mp4 play (a MOV and an MP4 are the same container). */
+export const MEDIA_MIMES = {
+ 'image/jpeg': { kind: 'image', category: 'still', ext: 'jpg', playExt: 'jpg' },
+ 'image/png': { kind: 'image', category: 'still', ext: 'png', playExt: 'png' },
+ 'image/webp': { kind: 'image', category: 'still', ext: 'webp', playExt: 'webp' },
+ 'image/gif': { kind: 'gif', category: 'still', ext: 'gif', playExt: 'gif' },
+ 'video/mp4': { kind: 'video', category: 'video', ext: 'mp4', playExt: 'mp4' },
+ 'video/quicktime': { kind: 'video', category: 'video', ext: 'mov', playExt: 'mp4' },
+ 'video/webm': { kind: 'video', category: 'video', ext: 'webm', playExt: 'webm' }
+}
+// A poster is always a still this app encoded itself, so only the two formats the encoder writes.
+const POSTER_MIMES = new Set(['image/webp', 'image/jpeg'])
+export const CODECS = ['avc1', 'hvc1', 'av01', 'vp09', 'vp8', 'vp9', 'other']
+
+const MB = 1024 * 1024
+const MAX_SIZE = 200 * MB
+const MAX_EDGE = 16384
+const MAX_DUR = 3600
+const MAX_URL = 2048
+
+const intIn = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi
+
+function cleanPoster(p) {
+ if (!p || typeof p !== 'object') return null
+ if (typeof p.hash !== 'string' || !HASH_RE.test(p.hash)) return null
+ if (!POSTER_MIMES.has(p.mime)) return null
+ if (!intIn(p.size, 1, MAX_SIZE) || !intIn(p.width, 1, MAX_EDGE) || !intIn(p.height, 1, MAX_EDGE)) return null
+ return { hash: p.hash, mime: p.mime, size: p.size, width: p.width, height: p.height }
+}
+
+/**
+ * A well-formed MediaRef, rebuilt from its known fields only, or null. null means "no media" to
+ * every reader: a bad hash, a mime outside the allowlist or one that does not match `kind`, a
+ * size outside 1 B..200 MB, a dimension outside 1..16384, a length outside 0..3600 s, or a codec
+ * nobody knows. A malformed poster is dropped on its own; the main file still stands.
+ */
+export function normalizeMediaRef(ref) {
+ if (!ref || typeof ref !== 'object' || Array.isArray(ref)) return null
+ const type = typeof ref.mime === 'string' ? MEDIA_MIMES[ref.mime] : null
+ if (!type || ref.kind !== type.kind) return null
+ if (typeof ref.hash !== 'string' || !HASH_RE.test(ref.hash)) return null
+ if (!intIn(ref.size, 1, MAX_SIZE) || !intIn(ref.width, 1, MAX_EDGE) || !intIn(ref.height, 1, MAX_EDGE)) return null
+ const out = { kind: ref.kind, hash: ref.hash, mime: ref.mime, size: ref.size, width: ref.width, height: ref.height }
+ if (ref.dur != null) {
+ if (typeof ref.dur !== 'number' || !Number.isFinite(ref.dur) || ref.dur < 0 || ref.dur > MAX_DUR) return null
+ out.dur = Math.round(ref.dur * 10) / 10
+ }
+ if (ref.codec != null) {
+ if (ref.kind !== 'video' || !CODECS.includes(ref.codec)) return null
+ out.codec = ref.codec
+ }
+ const poster = cleanPoster(ref.poster)
+ if (poster) out.poster = poster
+ out.at = typeof ref.at === 'number' && Number.isFinite(ref.at) && ref.at > 0 ? Math.round(ref.at) : 0
+ return out
+}
+
+/** The media of a custom exercise as it may be shown, or null. */
+export const mediaOf = ex => (ex && ex.media ? normalizeMediaRef(ex.media) : null)
+
+/**
+ * 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.
+ */
+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
+ add(m)
+ add(m.poster)
+ }
+ return out
+}
+
+/**
+ * The same hashes in the order the sync wants them, posters first: a poster is what every list
+ * 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.
+ */
+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
+ const p = m.poster
+ if (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 })
+ }
+ if (typeof m.hash === 'string' && HASH_RE.test(m.hash) && !mains.has(m.hash)) {
+ mains.set(m.hash, { hash: m.hash, mime: m.mime, size: m.size, poster: false })
+ }
+ }
+ for (const h of posters.keys()) mains.delete(h)
+ return [...posters.values(), ...mains.values()]
+}
+
+/**
+ * A link as it may be stored and opened: http(s) only, no user name or password in it, at most
+ * 2048 characters — or null. A bare "youtube.com/watch?v=…" gets https:// in front, the way people
+ * paste links (#246). Anything else with a scheme of its own (javascript:, data:, mailto:, a
+ * custom app scheme) is refused rather than guessed at. It runs at save and again at render,
+ * because a plan file or a backup can bring any string in.
+ */
+export function cleanUrl(raw) {
+ if (typeof raw !== 'string') return null
+ let s = raw.trim()
+ if (!s || s.length > MAX_URL) return null
+ if (!/^https?:\/\//i.test(s)) {
+ if (/^[a-z0-9+.-]+:/i.test(s)) return null
+ s = 'https://' + s
+ }
+ let u
+ try { u = new URL(s) } catch { return null }
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return null
+ if (!u.hostname || u.username || u.password) return null
+ return u.href.length <= MAX_URL ? u.href : null
+}
+
+// Hosts whose pages are, in practice, a video: the card then says "Watch video" instead of
+// "Open link". Only the wording changes — nothing is fetched or embedded either way.
+const VIDEO_HOSTS = ['youtube.com', 'youtu.be', 'vimeo.com', 'tiktok.com', 'instagram.com']
+
+/** 'video' for a link to a video site, 'link' for anything else, null for no usable link. */
+export function linkKind(url) {
+ const u = cleanUrl(url)
+ if (!u) return null
+ const host = new URL(u).hostname.toLowerCase()
+ return VIDEO_HOSTS.some(d => host === d || host.endsWith('.' + d)) ? 'video' : 'link'
+}
+
+/** m:ss for a length in seconds ("0:07", "1:05"). */
+export function fmtClip(sec) {
+ const s = Math.max(0, Math.round(Number(sec) || 0))
+ return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0')
+}
diff --git a/frontend/src/lib/media-refs.test.js b/frontend/src/lib/media-refs.test.js
new file mode 100644
index 000000000..b4fb61958
--- /dev/null
+++ b/frontend/src/lib/media-refs.test.js
@@ -0,0 +1,144 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { normalizeMediaRef, referencedHashes, referencedFiles, cleanUrl, linkKind, mediaOf, fmtClip, HASH_RE } from './media-refs.js'
+
+const A = 'a'.repeat(64)
+const B = 'b'.repeat(64)
+const C = 'c'.repeat(64)
+const ref = over => ({ kind: 'image', hash: A, mime: 'image/webp', size: 1000, width: 800, height: 600, poster: { hash: B, mime: 'image/webp', size: 100, width: 480, height: 360 }, at: 1, ...over })
+
+describe('normalizeMediaRef', () => {
+ it('keeps a well-formed ref and nothing else of it', () => {
+ expect(normalizeMediaRef({ ...ref(), name: 'IMG_0001.HEIC', gps: '47.3,8.5' })).toEqual(ref())
+ })
+
+ it('refuses a bad hash, a mime outside the list, and a kind that does not match the mime', () => {
+ expect(normalizeMediaRef(ref({ hash: 'A'.repeat(64) }))).toBeNull()
+ expect(normalizeMediaRef(ref({ hash: A.slice(1) }))).toBeNull()
+ expect(normalizeMediaRef(ref({ mime: 'image/svg+xml' }))).toBeNull()
+ expect(normalizeMediaRef(ref({ mime: 'text/html' }))).toBeNull()
+ expect(normalizeMediaRef(ref({ kind: 'video' }))).toBeNull()
+ expect(normalizeMediaRef(ref({ kind: 'gif' }))).toBeNull()
+ expect(normalizeMediaRef(ref({ kind: 'gif', mime: 'image/gif' }))).not.toBeNull()
+ })
+
+ it('refuses sizes, dimensions and lengths out of range', () => {
+ expect(normalizeMediaRef(ref({ size: 0 }))).toBeNull()
+ expect(normalizeMediaRef(ref({ size: 200 * 1024 * 1024 + 1 }))).toBeNull()
+ expect(normalizeMediaRef(ref({ size: 1.5 }))).toBeNull()
+ expect(normalizeMediaRef(ref({ width: 0 }))).toBeNull()
+ expect(normalizeMediaRef(ref({ height: 16385 }))).toBeNull()
+ expect(normalizeMediaRef(ref({ kind: 'video', mime: 'video/mp4', dur: 3601 }))).toBeNull()
+ expect(normalizeMediaRef(ref({ kind: 'video', mime: 'video/mp4', dur: -1 }))).toBeNull()
+ expect(normalizeMediaRef(ref({ kind: 'video', mime: 'video/mp4', dur: 'long' }))).toBeNull()
+ expect(normalizeMediaRef(ref({ kind: 'video', mime: 'video/mp4', dur: 12.345 })).dur).toBe(12.3)
+ })
+
+ it('knows the codecs, other included, and only on a video', () => {
+ for (const codec of ['avc1', 'hvc1', 'av01', 'vp09', 'vp8', 'vp9', 'other']) {
+ expect(normalizeMediaRef(ref({ kind: 'video', mime: 'video/mp4', codec }))?.codec).toBe(codec)
+ }
+ expect(normalizeMediaRef(ref({ kind: 'video', mime: 'video/mp4', codec: 'mjpeg' }))).toBeNull()
+ expect(normalizeMediaRef(ref({ codec: 'avc1' }))).toBeNull()
+ })
+
+ it('drops a malformed poster and keeps the main file', () => {
+ const r = normalizeMediaRef(ref({ poster: { hash: B, mime: 'image/gif', size: 1, width: 1, height: 1 } }))
+ expect(r.hash).toBe(A)
+ expect(r.poster).toBeUndefined()
+ expect(normalizeMediaRef(ref({ poster: { hash: 'x' } })).poster).toBeUndefined()
+ })
+
+ it('treats anything that is not an object as no media', () => {
+ for (const v of [null, undefined, 3, 'x', [], [ref()]]) expect(normalizeMediaRef(v)).toBeNull()
+ expect(mediaOf({ media: ref() })).toEqual(ref())
+ expect(mediaOf({})).toBeNull()
+ expect(mediaOf(null)).toBeNull()
+ })
+})
+
+describe('referencedHashes', () => {
+ // The same answers as api/media.js referencedHashes: the server keeps and the client keeps the
+ // same set. The fixture is the api tests' own.
+ const fixture = JSON.parse(readFileSync(new URL('../../../api/test/fixtures/media-refs.json', import.meta.url), 'utf8'))
+ for (const c of fixture.referencedHashes) {
+ it(`parity: ${c.name}`, () => {
+ expect([...referencedHashes(c.state)].sort()).toEqual([...c.expect].sort())
+ })
+ }
+
+ it('lists the files posters first, each once, with what the state says of them', () => {
+ const S = { customEx: [
+ { id: 'x', media: ref() },
+ { id: 'y', media: ref({ hash: C, poster: { hash: B, mime: 'image/webp', size: 100, width: 480, height: 360 } }) },
+ { id: 'z', media: { hash: 'nope' } }
+ ] }
+ expect(referencedFiles(S)).toEqual([
+ { hash: B, mime: 'image/webp', size: 100, poster: true },
+ { hash: A, mime: 'image/webp', size: 1000, poster: false },
+ { hash: C, mime: 'image/webp', size: 1000, poster: false }
+ ])
+ })
+
+ it('a small photo whose poster is the file itself is listed once', () => {
+ const S = { customEx: [{ id: 'x', media: ref({ poster: { hash: A, mime: 'image/webp', size: 1000, width: 400, height: 300 } }) }] }
+ expect(referencedFiles(S).map(f => f.hash)).toEqual([A])
+ })
+})
+
+describe('cleanUrl', () => {
+ // #246's cases.
+ it('accepts http and https links as they are', () => {
+ expect(cleanUrl('https://www.youtube.com/watch?v=123')).toBe('https://www.youtube.com/watch?v=123')
+ expect(cleanUrl('http://example.com/guide')).toBe('http://example.com/guide')
+ })
+ it('puts https:// in front of a bare address', () => {
+ expect(cleanUrl('youtube.com/watch?v=123')).toBe('https://youtube.com/watch?v=123')
+ expect(cleanUrl('www.vimeo.com/456')).toBe('https://www.vimeo.com/456')
+ expect(cleanUrl(' youtu.be/abc ')).toBe('https://youtu.be/abc')
+ })
+ it('refuses other schemes, whatever the case', () => {
+ for (const u of ['javascript:alert(1)', 'JaVaScRiPt:alert(1)', 'data:text/html,<h1>hi</h1>', 'vbscript:msgbox(1)', 'file:///etc/passwd', 'mailto:[email protected]', 'intent://x#Intent;end', 'blob:https://x/y']) {
+ expect(cleanUrl(u), u).toBeNull()
+ }
+ })
+ it('refuses empty strings and anything that is not a string', () => {
+ for (const u of ['', ' ', null, undefined, 3, {}, ['https://x.com']]) expect(cleanUrl(u)).toBeNull()
+ })
+ it('refuses a link with a user name or password in it', () => {
+ expect(cleanUrl('https://user:[email protected]/x')).toBeNull()
+ expect(cleanUrl('https://[email protected]/x')).toBeNull()
+ })
+ it('refuses a link over 2048 characters', () => {
+ expect(cleanUrl('https://example.com/' + 'a'.repeat(2020))).toBe('https://example.com/' + 'a'.repeat(2020))
+ expect(cleanUrl('https://example.com/' + 'a'.repeat(2100))).toBeNull()
+ })
+ it('refuses what does not parse', () => {
+ expect(cleanUrl('https://exa mple.com')).toBeNull()
+ expect(cleanUrl('https://')).toBeNull()
+ })
+})
+
+describe('linkKind', () => {
+ it('calls the big video sites video, their subdomains included, and everything else a link', () => {
+ for (const u of ['https://www.youtube.com/watch?v=x', 'youtu.be/x', 'https://m.youtube.com/shorts/x', 'https://vimeo.com/1', 'https://www.tiktok.com/@a/video/1', 'https://www.instagram.com/reel/x']) {
+ expect(linkKind(u), u).toBe('video')
+ }
+ expect(linkKind('https://exrx.net/WeightExercises')).toBe('link')
+ expect(linkKind('https://notyoutube.com/x')).toBe('link')
+ expect(linkKind('https://youtube.com.evil.example/x')).toBe('link')
+ expect(linkKind('javascript:alert(1)')).toBeNull()
+ })
+})
+
+describe('small helpers', () => {
+ it('writes a clip length as m:ss', () => {
+ expect(fmtClip(7)).toBe('0:07')
+ expect(fmtClip(65.4)).toBe('1:05')
+ expect(fmtClip(undefined)).toBe('0:00')
+ })
+ it('matches only lowercase sha256 hex', () => {
+ expect(HASH_RE.test(A)).toBe(true)
+ expect(HASH_RE.test(A.toUpperCase())).toBe(false)
+ })
+})
diff --git a/frontend/src/lib/media-samples.test-util.js b/frontend/src/lib/media-samples.test-util.js
new file mode 100644
index 000000000..59a729dc5
--- /dev/null
+++ b/frontend/src/lib/media-samples.test-util.js
@@ -0,0 +1,124 @@
+/* Tiny synthetic media files for the media tests: just enough structure for the magic bytes, the
+ header reads, the GIF block walk and the MP4 box walk, built in code so the repo carries no
+ binary fixtures and every test says exactly which bytes it feeds in. The api side has its own
+ (api/test/media-samples.mjs); these add what only the client reads — dimensions, GIF frames,
+ tracks and sample tables. Not a *.test.js file, so vitest does not run it on its own. */
+
+export const bytes = (...parts) => {
+ const arrs = parts.map(p => (typeof p === 'string' ? latin1(p) : p instanceof Uint8Array ? p : Uint8Array.from(p)))
+ const out = new Uint8Array(arrs.reduce((n, a) => n + a.length, 0))
+ let o = 0
+ for (const a of arrs) { out.set(a, o); o += a.length }
+ return out
+}
+export const latin1 = s => Uint8Array.from(s, c => c.charCodeAt(0) & 0xff)
+const u16be = n => [(n >>> 8) & 0xff, n & 0xff]
+const u16le = n => [n & 0xff, (n >>> 8) & 0xff]
+const u32be = n => [(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff]
+const u24le = n => [n & 0xff, (n >>> 8) & 0xff, (n >>> 16) & 0xff]
+export const fill = (n, v = 0x55) => new Uint8Array(n).fill(v)
+
+/* ---- stills ---- */
+// A JPEG with an APP1 (EXIF-ish) segment before its SOF0 frame header.
+export const jpeg = (w = 640, h = 480) => bytes(
+ [0xff, 0xd8],
+ [0xff, 0xe1], u16be(2 + 12), 'Exif\0\0GPS...',
+ [0xff, 0xc0], u16be(17), [8], u16be(h), u16be(w), [3], fill(9, 1),
+ [0xff, 0xda], u16be(2), fill(20)
+)
+export const png = (w = 300, h = 200) => bytes([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], u32be(13), 'IHDR', u32be(w), u32be(h), [8, 6, 0, 0, 0], fill(20))
+export const webpVp8 = (w = 320, h = 240) => bytes('RIFF', [0, 0, 0, 0], 'WEBP', 'VP8 ', [0, 0, 0, 0], [0x10, 0x02, 0x00], [0x9d, 0x01, 0x2a], u16le(w), u16le(h), fill(10))
+export const webpVp8l = (w = 100, h = 50) => {
+ const bits = ((w - 1) & 0x3fff) | (((h - 1) & 0x3fff) << 14)
+ return bytes('RIFF', [0, 0, 0, 0], 'WEBP', 'VP8L', [0, 0, 0, 0], [0x2f], [bits & 0xff, (bits >>> 8) & 0xff, (bits >>> 16) & 0xff, (bits >>> 24) & 0xff], fill(10))
+}
+export const webpVp8x = (w = 4000, h = 3000) => bytes('RIFF', [0, 0, 0, 0], 'WEBP', 'VP8X', [10, 0, 0, 0], [0x10, 0, 0, 0], u24le(w - 1), u24le(h - 1), fill(10))
+
+/* ---- GIF ---- */
+const subBlocks = data => {
+ const out = []
+ for (let i = 0; i < data.length; i += 255) { const part = data.subarray(i, i + 255); out.push([part.length], part) }
+ out.push([0])
+ return bytes(...out)
+}
+export const gce = delayCs => bytes([0x21, 0xf9, 4, 0x04], u16le(delayCs), [0, 0])
+export const frame = (w, h) => bytes([0x2c], u16le(0), u16le(0), u16le(w), u16le(h), [0], [2], subBlocks(fill(6, 0x11)))
+export const appExt = (id, data = fill(3, 1)) => bytes([0x21, 0xff, 11], id, subBlocks(data))
+export const comment = text => bytes([0x21, 0xfe], subBlocks(latin1(text)))
+export const plainText = () => bytes([0x21, 0x01], subBlocks(fill(12, 0x20)))
+/** A GIF: `delays` (in 1/100 s) makes one frame each; extra blocks go in the order given. */
+export function gif({ w = 40, h = 30, delays = [10, 10], blocks = null, trailer = true } = {}) {
+ const head = bytes('GIF89a', u16le(w), u16le(h), [0x80, 0, 0], fill(6, 0)) // a 2-colour global table
+ const body = blocks || [appExt('NETSCAPE2.0', bytes([1], u16le(0))), ...delays.flatMap(d => [gce(d), frame(w, h)])]
+ return bytes(head, ...body, trailer ? [0x3b] : [])
+}
+
+/* ---- ISO-BMFF ---- */
+export function box(type, ...parts) {
+ const body = bytes(...parts)
+ return bytes(u32be(8 + body.length), type, body)
+}
+const fullBox = (type, ...parts) => box(type, [0, 0, 0, 0], ...parts)
+export const ftyp = (brand = 'isom') => box('ftyp', brand, [0, 0, 0, 0], 'isommp41')
+export const mvhd = (seconds = 5, timescale = 1000) => box('mvhd', [0, 0, 0, 0], u32be(0), u32be(0), u32be(timescale), u32be(Math.round(seconds * timescale)), fill(80, 0))
+// A tkhd, version 0, with the display size in 16.16 and an identity (or a 90°) matrix.
+export function tkhd(w, h, { rotate = false } = {}) {
+ const matrix = rotate
+ ? [...u32be(0), ...u32be(0x10000), ...u32be(0), ...u32be(0xffff0000), ...u32be(0), ...u32be(0), ...u32be(0), ...u32be(0), ...u32be(0x40000000)]
+ : [...u32be(0x10000), ...u32be(0), ...u32be(0), ...u32be(0), ...u32be(0x10000), ...u32be(0), ...u32be(0), ...u32be(0), ...u32be(0x40000000)]
+ return box('tkhd', [0, 0, 0, 3], fill(20, 0), fill(8, 0), fill(8, 0), matrix, u32be(w * 65536), u32be(h * 65536))
+}
+export const hdlr = type => fullBox('hdlr', u32be(0), type, fill(12, 0), [0])
+const stsd = fourcc => fullBox('stsd', u32be(1), box(fourcc, fill(6, 0), u16be(1), fill(16, 0), u16be(0), u16be(0), fill(50, 0)))
+/**
+ * A trak whose samples sit at `offsets` (one chunk each) with `sizes`. The offsets are absolute
+ * file positions, so mp4() computes them after laying out ftyp and moov.
+ */
+export function trak({ handler = 'vide', fourcc = 'avc1', w = 0, h = 0, rotate = false, offsets = [], sizes = [], extra = [] }) {
+ return box('trak',
+ tkhd(w, h, { rotate }),
+ box('mdia', hdlr(handler), box('minf', box('stbl',
+ stsd(fourcc),
+ fullBox('stsz', u32be(0), u32be(sizes.length), ...sizes.map(u32be)),
+ fullBox('stsc', u32be(1), u32be(1), u32be(1), u32be(1)),
+ fullBox('stco', u32be(offsets.length), ...offsets.map(u32be))
+ ))),
+ ...extra)
+}
+/**
+ * An MP4 (brand isom) or MOV (brand 'qt '): ftyp, moov, then mdat holding one sample per track
+ * in `tracks` ([{ handler, fourcc, w, h, payload: Uint8Array }]). `moovExtra` goes into moov
+ * after the traks (udta, meta), `top` after mdat (uuid, meta). Returns { file, sampleAt } where
+ * sampleAt[i] is the offset of track i's sample in the file.
+ */
+export function mp4({ brand = 'isom', seconds = 5, tracks = [{ handler: 'vide', fourcc: 'avc1', w: 1920, h: 1080, payload: fill(64, 0x77) }], moovExtra = [], top = [], rotate = false } = {}) {
+ const build = offsets => box('moov', mvhd(seconds), ...tracks.map((t, i) => trak({ ...t, rotate: t.handler === 'vide' && rotate, offsets: [offsets[i]], sizes: [t.payload.length] })), ...moovExtra)
+ const head = ftyp(brand)
+ // Lay moov out once to learn its size, then again with the real offsets (sizes do not change).
+ const size = build(tracks.map(() => 0)).length
+ let at = head.length + size + 8
+ const offsets = tracks.map(t => { const o = at; at += t.payload.length; return o })
+ const moov = build(offsets)
+ const mdat = box('mdat', ...tracks.map(t => t.payload))
+ return { file: bytes(head, moov, mdat, ...top), sampleAt: offsets }
+}
+
+/* ---- WebM ---- */
+const ebmlEl = (id, body) => {
+ const b = body instanceof Uint8Array ? body : Uint8Array.from(body)
+ const size = b.length < 0x7f ? [0x80 | b.length] : [0x40 | (b.length >>> 8), b.length & 0xff]
+ return bytes(id, size, b)
+}
+export function webm({ docType = 'webm', w = 640, h = 360, codec = 'V_VP9', durationMs = 4000 } = {}) {
+ const header = ebmlEl([0x1a, 0x45, 0xdf, 0xa3], bytes(ebmlEl([0x42, 0x86], [1]), ebmlEl([0x42, 0x82], latin1(docType))))
+ const dur = new Uint8Array(8)
+ new DataView(dur.buffer).setFloat64(0, durationMs)
+ const info = ebmlEl([0x15, 0x49, 0xa9, 0x66], bytes(ebmlEl([0x2a, 0xd7, 0xb1], [0x0f, 0x42, 0x40]), durationMs == null ? [] : ebmlEl([0x44, 0x89], dur)))
+ const video = ebmlEl([0xe0], bytes(ebmlEl([0xb0], u16be(w)), ebmlEl([0xba], u16be(h))))
+ const audio = ebmlEl([0xae], bytes(ebmlEl([0x83], [2]), ebmlEl([0x86], latin1('A_OPUS'))))
+ const vtrack = ebmlEl([0xae], bytes(ebmlEl([0x83], [1]), ebmlEl([0x86], latin1(codec)), video))
+ const tracksEl = ebmlEl([0x16, 0x54, 0xae, 0x6b], bytes(audio, vtrack))
+ // An unknown-size Segment, the way MediaRecorder writes it, then a cluster.
+ const segment = bytes([0x18, 0x53, 0x80, 0x67, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], info, tracksEl, ebmlEl([0x1f, 0x43, 0xb6, 0x75], fill(20)))
+ return bytes(header, segment)
+}
diff --git a/frontend/src/lib/media-sniff.js b/frontend/src/lib/media-sniff.js
new file mode 100644
index 000000000..a0e807572
--- /dev/null
+++ b/frontend/src/lib/media-sniff.js
@@ -0,0 +1,554 @@
+/* What a picked file really is, and the few things this app reads or changes inside one.
+ *
+ * Pure byte work on Uint8Arrays, with no DOM and no imports, so all of it runs in the tests.
+ *
+ * - sniffKind: the type from the first bytes alone, never from the name or file.type. It follows
+ * api/media.js sniffMedia rule for rule, so a device never uploads something the server would
+ * refuse, and additionally knows HEIC/AVIF photos, which are only ever re-encoded.
+ * - imageDims: a photo's size from its header, for the pixel guard that runs before any decode.
+ * - inspectGif / cleanGif: a GIF's frames and length, and a copy without the blocks that carry
+ * text and metadata (comments, XMP, ICC), keeping the loop blocks.
+ * - inspectMp4 / scrubMp4: an MP4/MOV's brand, length, size and codec, and the metadata scrub —
+ * udta/meta/uuid boxes and the samples of tracks that are neither sound nor picture (timed
+ * metadata, an action camera's GPS track) are zeroed IN PLACE. Nothing moves, so every offset
+ * in the file stays valid and the video plays exactly as before.
+ * - inspectWebm: size, codec and (when written) length of a WebM, which has no scrub (deferred).
+ */
+
+const ascii = (b, off, len) => {
+ if (off < 0 || off + len > b.length) return ''
+ let s = ''
+ for (let i = 0; i < len; i++) s += String.fromCharCode(b[off + i])
+ return s
+}
+const at = (b, off, bytes) => bytes.every((x, i) => b[off + i] === x)
+const u16be = (b, o) => (b[o] << 8) | b[o + 1]
+const u16le = (b, o) => b[o] | (b[o + 1] << 8)
+const u32be = (b, o) => ((b[o] << 24) >>> 0) + (b[o + 1] << 16) + (b[o + 2] << 8) + b[o + 3]
+const u24le = (b, o) => b[o] | (b[o + 1] << 8) | (b[o + 2] << 16)
+// A 64-bit field as a Number. Nothing real comes near 2^53; past it the file is broken anyway.
+const u64be = (b, o) => u32be(b, o) * 4294967296 + u32be(b, o + 4)
+const i32be = (b, o) => u32be(b, o) | 0
+
+// The same list as api/media.js MP4_BRANDS: brands nobody vouched for (M4A audio, a 3GPP brand
+// the server does not know) are refused on both sides.
+const MP4_BRANDS = new Set([
+ 'isom', 'iso2', 'iso3', 'iso4', 'iso5', 'iso6', 'mp41', 'mp42', 'avc1', 'M4V ', 'M4VP',
+ 'dash', 'mmp4', 'MSNV', '3gp4', '3gp5', '3gp6', '3g2a'
+])
+// HEIF/AVIF stills: accepted as input only — decoded and re-encoded like any photo.
+const HEIF_BRANDS = new Set(['heic', 'heix', 'heim', 'heis', 'hevc', 'mif1', 'msf1', 'avif', 'avis'])
+
+// An EBML variable-length integer at b[i]. IDs keep their length marker, sizes drop it. A size of
+// all ones means "unknown" (a live recording that never went back to write it).
+function vint(b, i, keepMarker) {
+ if (i >= b.length || b[i] === 0) return null
+ const first = b[i]
+ let len = 1
+ while (!(first & (0x80 >> (len - 1)))) len++
+ if (len > 8 || i + len > b.length) return null
+ let v = keepMarker ? first : first & (0xff >> len)
+ let allOnes = v === (0xff >> len)
+ for (let k = 1; k < len; k++) { v = v * 256 + b[i + k]; if (b[i + k] !== 0xff) allOnes = false }
+ return { value: v, len, unknown: !keepMarker && allOnes }
+}
+function ebmlDocType(b) {
+ const hs = vint(b, 4, false)
+ if (!hs) return null
+ let i = 4 + hs.len
+ const end = Math.min(b.length, i + hs.value)
+ while (i < end) {
+ const id = vint(b, i, true)
+ const sz = id && vint(b, i + id.len, false)
+ if (!sz) return null
+ const body = i + id.len + sz.len
+ if (id.value === 0x4282) {
+ if (body + sz.value > b.length) return null
+ return ascii(b, body, sz.value).replace(/\0+$/, '')
+ }
+ i = body + sz.value
+ }
+ return null
+}
+
+/**
+ * { mime, kind, category, input? } from the first bytes, or null. `input: true` marks a type
+ * that is read here but never stored or uploaded as it is (HEIC/AVIF — the server refuses them).
+ * Everything else is refused: SVG and XML, HTML, PDF, ZIP, BMP, TIFF, ICO, M4A, Matroska.
+ */
+export function sniffKind(bytes) {
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || [])
+ if (at(b, 0, [0xff, 0xd8, 0xff])) return { mime: 'image/jpeg', kind: 'image', category: 'still' }
+ if (at(b, 0, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return { mime: 'image/png', kind: 'image', category: 'still' }
+ const sig = ascii(b, 0, 6)
+ if (sig === 'GIF87a' || sig === 'GIF89a') return { mime: 'image/gif', kind: 'gif', category: 'still' }
+ if (ascii(b, 0, 4) === 'RIFF' && ascii(b, 8, 4) === 'WEBP') return { mime: 'image/webp', kind: 'image', category: 'still' }
+ if (ascii(b, 4, 4) === 'ftyp') {
+ const brand = ascii(b, 8, 4)
+ if (brand === 'qt ') return { mime: 'video/quicktime', kind: 'video', category: 'video' }
+ if (MP4_BRANDS.has(brand)) return { mime: 'video/mp4', kind: 'video', category: 'video' }
+ if (HEIF_BRANDS.has(brand)) return { mime: brand.startsWith('avi') ? 'image/avif' : 'image/heic', kind: 'image', category: 'still', input: true }
+ return null
+ }
+ if (at(b, 0, [0x1a, 0x45, 0xdf, 0xa3])) {
+ return ebmlDocType(b) === 'webm' ? { mime: 'video/webm', kind: 'video', category: 'video' } : null
+ }
+ return null
+}
+
+/* ---------------------------------------------------------------- still images */
+
+/**
+ * { width, height } of a JPEG (its SOFn frame header), PNG (IHDR), WebP (VP8, VP8L or VP8X) or
+ * GIF (logical screen), or null. Read before any decode: a 100-megapixel photo would take a phone
+ * a few hundred MB just to open, so it is refused on these numbers instead.
+ */
+export function imageDims(bytes) {
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || [])
+ const s = sniffKind(b)
+ if (!s) return null
+ if (s.mime === 'image/png') {
+ if (b.length < 24 || ascii(b, 12, 4) !== 'IHDR') return null
+ return dims(u32be(b, 16), u32be(b, 20))
+ }
+ if (s.mime === 'image/gif') return b.length >= 10 ? dims(u16le(b, 6), u16le(b, 8)) : null
+ if (s.mime === 'image/webp') {
+ const chunk = ascii(b, 12, 4)
+ if (chunk === 'VP8 ' && b.length >= 30) return dims(u16le(b, 26) & 0x3fff, u16le(b, 28) & 0x3fff)
+ if (chunk === 'VP8L' && b.length >= 25 && b[20] === 0x2f) {
+ const bits = b[21] | (b[22] << 8) | (b[23] << 16) | (b[24] << 24)
+ return dims((bits & 0x3fff) + 1, ((bits >>> 14) & 0x3fff) + 1)
+ }
+ if (chunk === 'VP8X' && b.length >= 30) return dims(u24le(b, 24) + 1, u24le(b, 27) + 1)
+ return null
+ }
+ if (s.mime === 'image/jpeg') {
+ let i = 2
+ while (i + 4 <= b.length) {
+ if (b[i] !== 0xff) return null
+ const m = b[i + 1]
+ if (m === 0xff) { i++; continue } // fill byte
+ if (m === 0xd8 || m === 0x01 || (m >= 0xd0 && m <= 0xd7)) { i += 2; continue } // no length
+ if (m === 0xd9 || m === 0xda) return null // end, or image data before any frame header
+ const len = u16be(b, i + 2)
+ if (len < 2) return null
+ // SOF0..SOF15, minus DHT (C4), JPG (C8) and DAC (CC), which share the range.
+ if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) {
+ if (i + 9 > b.length) return null
+ return dims(u16be(b, i + 7), u16be(b, i + 5))
+ }
+ i += 2 + len
+ }
+ return null
+ }
+ return null
+}
+const dims = (width, height) => (width > 0 && height > 0 ? { width, height } : null)
+
+/* ---------------------------------------------------------------- GIF */
+
+// Walks a GIF's blocks and calls `on(kind, start, end, extra)` for each, in order: 'head' (the
+// header, the logical screen and the global colour table), 'ext' (an extension, label in extra),
+// 'image' (a descriptor, its colour table and its data) and 'end' (the trailer). Throws on a
+// block that runs past the end of the file.
+function walkGif(b, on) {
+ if (b.length < 13) throw new Error('gif: too short')
+ let i = 13
+ if (b[10] & 0x80) i += 3 * (1 << ((b[10] & 7) + 1))
+ if (i > b.length) throw new Error('gif: colour table')
+ on('head', 0, i)
+ const subBlocks = j => {
+ while (true) {
+ if (j >= b.length) throw new Error('gif: truncated')
+ const n = b[j]
+ j += 1 + n
+ if (n === 0) return j
+ }
+ }
+ while (i < b.length) {
+ const t = b[i]
+ if (t === 0x3b) { on('end', i, i + 1); return }
+ if (t === 0x21) {
+ if (i + 2 > b.length) throw new Error('gif: truncated')
+ const end = subBlocks(i + 2)
+ if (end > b.length) throw new Error('gif: truncated')
+ on('ext', i, end, b[i + 1])
+ i = end
+ } else if (t === 0x2c) {
+ if (i + 10 > b.length) throw new Error('gif: truncated')
+ let j = i + 10
+ if (b[i + 9] & 0x80) j += 3 * (1 << ((b[i + 9] & 7) + 1))
+ j += 1 // LZW minimum code size
+ const end = subBlocks(j)
+ if (end > b.length) throw new Error('gif: truncated')
+ on('image', i, end)
+ i = end
+ } else throw new Error('gif: unknown block')
+ }
+ on('end', b.length, b.length) // no trailer: the file simply stops after a whole block
+}
+
+/**
+ * { width, height, frames, durMs } of a GIF, or null for one that does not parse. A frame
+ * delay of 0 counts as 10 ms, so a GIF of zero-delay frames still has a length.
+ */
+export function inspectGif(bytes) {
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || [])
+ if (sniffKind(b)?.mime !== 'image/gif') return null
+ let frames = 0, durMs = 0, delay = null
+ try {
+ walkGif(b, (kind, start, end, label) => {
+ if (kind === 'ext' && label === 0xf9 && end - start >= 8) delay = u16le(b, start + 4)
+ if (kind === 'image') { frames++; durMs += delay ? delay * 10 : 10; delay = null }
+ })
+ } catch { if (!frames) return null }
+ if (!frames) return null
+ return { width: u16le(b, 6), height: u16le(b, 8), frames, durMs }
+}
+
+// The application blocks a GIF needs to keep looping; every other one (XMP, ICC profiles, an
+// editor's own data) is metadata.
+const LOOP_APPS = new Set(['NETSCAPE2.0', 'ANIMEXTS1.0'])
+
+/**
+ * A copy of a GIF with its comment (0xFE), plain-text (0x01) and non-loop application blocks
+ * (XMP, ICC and the like) left out. Graphic control blocks, frames and the loop block stay, so
+ * it animates exactly as before. A graphic control block that belonged to a dropped plain-text
+ * block goes with it, so its delay cannot land on the next frame. Throws on a GIF that does not
+ * parse; one that simply stops after a whole block gets its trailer.
+ */
+export function cleanGif(bytes) {
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || [])
+ if (sniffKind(b)?.mime !== 'image/gif') throw new Error('gif: not a gif')
+ const keep = []
+ let gce = null
+ walkGif(b, (kind, start, end, label) => {
+ if (kind === 'head') { keep.push([start, end]); return }
+ if (kind === 'end') { keep.push(null); return }
+ if (kind === 'image') { if (gce) keep.push(gce); gce = null; keep.push([start, end]); return }
+ if (label === 0xf9) { gce = [start, end]; return }
+ if (label === 0x01) { gce = null; return }
+ if (label === 0xff && b[start + 2] === 11 && LOOP_APPS.has(ascii(b, start + 3, 11))) keep.push([start, end])
+ })
+ const total = keep.reduce((n, r) => n + (r ? r[1] - r[0] : 1), 0)
+ const out = new Uint8Array(total)
+ let o = 0
+ for (const r of keep) {
+ if (!r) { out[o++] = 0x3b; continue }
+ out.set(b.subarray(r[0], r[1]), o)
+ o += r[1] - r[0]
+ }
+ return out
+}
+
+/* ---------------------------------------------------------------- MP4 / MOV */
+
+const MAX_BOXES = 10000
+const MAX_DEPTH = 8
+// Boxes whose children are boxes, as far down as anything here needs to look.
+const CONTAINERS = new Set(['moov', 'trak', 'mdia', 'minf', 'stbl', 'edts', 'dinf', 'mvex'])
+
+// The box whose header starts at `pos` and which must end by `end`. size 1 = a 64-bit size
+// follows, size 0 = it runs to `end`. A box that would reach past its parent means a broken file.
+function boxAt(b, pos, end) {
+ if (end - pos < 8) return null
+ let size = u32be(b, pos)
+ let head = 8
+ if (size === 1) {
+ if (end - pos < 16) return null
+ size = u64be(b, pos + 8)
+ head = 16
+ } else if (size === 0) size = end - pos
+ if (size < head || pos + size > end) return null
+ return { type: ascii(b, pos + 4, 4), start: pos, body: pos + head, end: pos + size }
+}
+
+// Every box in b[start, end), depth first, as { type, start, body, end, depth, parent }. Throws
+// on a box that overruns its parent, more than 10k boxes, or nesting deeper than 8.
+function walkBoxes(b, start, end, visit, counter = { n: 0 }, depth = 0, parent = null) {
+ if (depth > MAX_DEPTH) throw new Error('mp4: nested too deep')
+ let pos = start
+ while (pos < end) {
+ if (end - pos < 8) {
+ // Trailing zero padding after the last box is common and harmless.
+ if (depth === 0 && b.subarray(pos, end).every(x => x === 0)) return
+ throw new Error('mp4: truncated box')
+ }
+ if (++counter.n > MAX_BOXES) throw new Error('mp4: too many boxes')
+ const box = boxAt(b, pos, end)
+ if (!box) throw new Error('mp4: box overruns its parent')
+ box.depth = depth
+ box.parent = parent
+ const descend = visit(box) !== false
+ if (descend && CONTAINERS.has(box.type)) walkBoxes(b, box.body, box.end, visit, counter, depth + 1, box)
+ pos = box.end
+ }
+}
+
+const child = (b, box, type) => {
+ let found = null
+ let pos = box.body
+ while (pos < box.end && !found) {
+ const c = boxAt(b, pos, box.end)
+ if (!c) return null
+ if (c.type === type) found = c
+ pos = c.end
+ }
+ return found
+}
+const path = (b, box, ...types) => types.reduce((cur, t) => (cur ? child(b, cur, t) : null), box)
+
+const CODEC_OF = { avc1: 'avc1', avc3: 'avc1', hvc1: 'hvc1', hev1: 'hvc1', av01: 'av01', vp09: 'vp09', vp08: 'vp8' }
+
+// What one trak holds: its handler, its first sample entry, its display size, and the sample
+// table boxes the scrub needs.
+function readTrak(b, trak) {
+ const out = { handler: null, fourcc: null, width: 0, height: 0, stbl: null }
+ const hdlr = path(b, trak, 'mdia', 'hdlr')
+ if (hdlr && hdlr.end - hdlr.body >= 12) out.handler = ascii(b, hdlr.body + 8, 4)
+ const stbl = path(b, trak, 'mdia', 'minf', 'stbl')
+ out.stbl = stbl
+ const stsd = stbl && child(b, stbl, 'stsd')
+ if (stsd && stsd.end - stsd.body >= 16) {
+ out.fourcc = ascii(b, stsd.body + 12, 4)
+ // A visual sample entry's own width and height: the fallback when tkhd says 0.
+ const e = stsd.body + 8
+ if (out.handler === 'vide' && e + 36 <= stsd.end) { out.sw = u16be(b, e + 32); out.sh = u16be(b, e + 34) }
+ }
+ const tkhd = child(b, trak, 'tkhd')
+ if (tkhd) {
+ const v = b[tkhd.body]
+ const m = tkhd.body + (v === 1 ? 52 : 40) // the transformation matrix
+ const wOff = tkhd.body + (v === 1 ? 88 : 76)
+ if (wOff + 8 <= tkhd.end) {
+ let w = Math.round(u32be(b, wOff) / 65536)
+ let h = Math.round(u32be(b, wOff + 4) / 65536)
+ // A phone filming upright stores the sensor's landscape size and a 90° matrix (a = d = 0):
+ // what is seen is the other way round.
+ if (m + 16 <= tkhd.end && i32be(b, m) === 0 && i32be(b, m + 16) === 0) [w, h] = [h, w]
+ out.width = w
+ out.height = h
+ }
+ }
+ if (out.handler === 'vide' && (!out.width || !out.height) && out.sw && out.sh) { out.width = out.sw; out.height = out.sh }
+ return out
+}
+
+// The movie header's length in seconds: mvhd, or for a fragmented file (mvhd says 0) mvex/mehd.
+function movieSeconds(b, moov) {
+ const mvhd = child(b, moov, 'mvhd')
+ if (!mvhd) return undefined
+ const v = b[mvhd.body]
+ let scale, dur
+ if (v === 1) {
+ if (mvhd.body + 32 > mvhd.end) return undefined
+ scale = u32be(b, mvhd.body + 20); dur = u64be(b, mvhd.body + 24)
+ if (dur >= 0xffffffffffff) dur = 0
+ } else {
+ if (mvhd.body + 20 > mvhd.end) return undefined
+ scale = u32be(b, mvhd.body + 12); dur = u32be(b, mvhd.body + 16)
+ if (dur === 0xffffffff) dur = 0
+ }
+ if (!scale) return undefined
+ if (!dur) {
+ const mehd = path(b, moov, 'mvex', 'mehd')
+ if (mehd && mehd.body + 8 <= mehd.end) {
+ const wide = b[mehd.body] === 1 && mehd.body + 12 <= mehd.end
+ dur = wide ? u64be(b, mehd.body + 4) : u32be(b, mehd.body + 4)
+ }
+ }
+ return dur ? Math.round((dur / scale) * 1000) / 1000 : null
+}
+
+function topLevel(b) {
+ const boxes = []
+ let pos = 0, n = 0
+ while (pos < b.length) {
+ if (b.length - pos < 8 && b.subarray(pos).every(x => x === 0)) break
+ if (++n > MAX_BOXES) throw new Error('mp4: too many boxes')
+ const box = boxAt(b, pos, b.length)
+ if (!box) throw new Error('mp4: box overruns the file')
+ boxes.push(box)
+ pos = box.end
+ }
+ return boxes
+}
+
+/**
+ * { brand, durationSec, width, height, codec, handlers } of an MP4/MOV, or null for anything
+ * that is not a well-formed one: ftyp not first, no moov, a box overrunning its parent.
+ * durationSec is null when the file does not say; width/height are what is seen (a 90° matrix
+ * swaps them); codec is the video track's first sample entry reduced to
+ * avc1 | hvc1 | av01 | vp09 | vp8 | other; handlers lists every trak's handler type.
+ */
+export function inspectMp4(bytes) {
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || [])
+ try {
+ const top = topLevel(b)
+ if (!top.length || top[0].type !== 'ftyp' || top[0].end - top[0].body < 4) return null
+ const moov = top.find(x => x.type === 'moov')
+ if (!moov) return null
+ const durationSec = movieSeconds(b, moov)
+ if (durationSec === undefined) return null
+ const traks = []
+ let pos = moov.body
+ while (pos < moov.end) {
+ const c = boxAt(b, pos, moov.end)
+ if (!c) return null
+ if (c.type === 'trak') traks.push(readTrak(b, c))
+ pos = c.end
+ }
+ const video = traks.find(t => t.handler === 'vide')
+ return {
+ brand: ascii(b, top[0].body, 4),
+ durationSec,
+ width: video?.width || 0,
+ height: video?.height || 0,
+ codec: video ? (CODEC_OF[video.fourcc] || 'other') : null,
+ handlers: traks.map(t => t.handler)
+ }
+ } catch { return null }
+}
+
+// Handlers whose samples are the video itself: picture, sound, and the timecode track editors add.
+const KEEP_HANDLERS = new Set(['vide', 'soun', 'tmcd'])
+const MAX_SAMPLES = 5_000_000
+
+// [offset, size] of every sample of a trak, from its sample table (stsz + stsc + stco/co64).
+// Throws on a table that is malformed or points outside the file.
+function sampleRanges(b, stbl) {
+ const stsz = child(b, stbl, 'stsz')
+ const stsc = child(b, stbl, 'stsc')
+ const stco = child(b, stbl, 'stco') || child(b, stbl, 'co64')
+ if (!stsz || !stsc || !stco) {
+ // A track with no samples at all has nothing to zero; a partial table is a broken file.
+ if (!stsz && !stsc && !stco) return []
+ throw new Error('mp4: incomplete sample table')
+ }
+ const wide = stco.type === 'co64'
+ const nChunks = u32be(b, stco.body + 4)
+ if (stco.body + 8 + nChunks * (wide ? 8 : 4) > stco.end) throw new Error('mp4: chunk table')
+ const chunkAt = i => (wide ? u64be(b, stco.body + 8 + i * 8) : u32be(b, stco.body + 8 + i * 4))
+ const fixed = u32be(b, stsz.body + 4)
+ const nSamples = u32be(b, stsz.body + 8)
+ if (nSamples > MAX_SAMPLES) throw new Error('mp4: too many samples')
+ if (!fixed && stsz.body + 12 + nSamples * 4 > stsz.end) throw new Error('mp4: size table')
+ const sizeOf = i => (fixed || u32be(b, stsz.body + 12 + i * 4))
+ const nRuns = u32be(b, stsc.body + 4)
+ if (stsc.body + 8 + nRuns * 12 > stsc.end) throw new Error('mp4: chunk runs')
+ const runs = []
+ for (let r = 0; r < nRuns; r++) {
+ const o = stsc.body + 8 + r * 12
+ runs.push({ first: u32be(b, o), per: u32be(b, o + 4) })
+ }
+ const out = []
+ let s = 0
+ for (let r = 0; r < runs.length && s < nSamples; r++) {
+ const last = r + 1 < runs.length ? runs[r + 1].first - 1 : nChunks
+ if (runs[r].first < 1 || last > nChunks || runs[r].per > MAX_SAMPLES) throw new Error('mp4: chunk runs')
+ for (let c = runs[r].first; c <= last && s < nSamples; c++) {
+ let off = chunkAt(c - 1)
+ for (let k = 0; k < runs[r].per && s < nSamples; k++) {
+ const size = sizeOf(s++)
+ if (off + size > b.length) throw new Error('mp4: sample outside the file')
+ out.push([off, size])
+ off += size
+ }
+ }
+ }
+ return out
+}
+
+/**
+ * Zeroes, IN PLACE, what in an MP4/MOV can say where and by whom it was filmed, and returns the
+ * same array. (a) Every udta and meta box under moov, and every top-level meta and uuid box,
+ * becomes a 'free' box of the same size with a zeroed body: QuickTime's location and the
+ * phone's make and model live there. (b) Every sample of a track that is neither picture nor
+ * sound (timed metadata, an action camera's GPS and sensor tracks) is zeroed where it sits in
+ * mdat; the track itself stays. No size changes, so stco/co64 stay right and the video and
+ * sound bytes are untouched. Throws on a file that does not parse or whose sample tables point
+ * outside it — such a file is refused rather than kept with its metadata.
+ */
+export function scrubMp4(bytes) {
+ const b = bytes
+ const top = topLevel(b)
+ if (!top.length || top[0].type !== 'ftyp') throw new Error('mp4: no ftyp')
+ const blank = box => {
+ b[box.start + 4] = 0x66; b[box.start + 5] = 0x72; b[box.start + 6] = 0x65; b[box.start + 7] = 0x65 // 'free'
+ b.fill(0, box.body, box.end)
+ }
+ const traks = []
+ const counter = { n: 0 }
+ for (const box of top) {
+ if (box.type === 'meta' || box.type === 'uuid') { blank(box); continue }
+ if (box.type !== 'moov') continue
+ walkBoxes(b, box.body, box.end, c => {
+ if (c.type === 'udta' || c.type === 'meta') { blank(c); return false }
+ if (c.type === 'trak') traks.push(c)
+ return true
+ }, counter, 1, box)
+ }
+ // Sample ranges are read before anything is zeroed: blanking a box never touches a sample
+ // table, but reading them all first means a table that fails halfway leaves no track zeroed.
+ const doomed = []
+ for (const trak of traks) {
+ const t = readTrak(b, trak)
+ if (KEEP_HANDLERS.has(t.handler) || !t.stbl) continue
+ doomed.push(...sampleRanges(b, t.stbl))
+ }
+ for (const [off, size] of doomed) b.fill(0, off, off + size)
+ return b
+}
+
+/* ---------------------------------------------------------------- WebM */
+
+const EBML_WALK_MAX = 1 << 20 // the track headers sit before the first cluster
+
+/**
+ * { width, height, codec, durationSec } of a WebM from its header elements (Segment → Info and
+ * Tracks), read from at most the first MB, or null. A recording that never wrote its length
+ * (MediaRecorder) gives durationSec null.
+ */
+export function inspectWebm(bytes) {
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || [])
+ if (sniffKind(b)?.mime !== 'video/webm') return null
+ const limit = Math.min(b.length, EBML_WALK_MAX)
+ const out = { width: 0, height: 0, codec: null, durationSec: null }
+ let scale = 1000000, dur = null
+ const readUint = (i, n) => { let v = 0; for (let k = 0; k < n; k++) v = v * 256 + b[i + k]; return v }
+ const readFloat = (i, n) => {
+ const dv = new DataView(b.buffer, b.byteOffset + i, n)
+ return n === 4 ? dv.getFloat32(0) : n === 8 ? dv.getFloat64(0) : null
+ }
+ // Masters worth descending into: Segment, Info, Tracks, TrackEntry, Video.
+ const MASTER = new Set([0x18538067, 0x1549a966, 0x1654ae6b, 0xae, 0xe0])
+ const walk = (start, end, depth) => {
+ let i = start
+ while (i < end && i < limit) {
+ const id = vint(b, i, true)
+ const sz = id && vint(b, i + id.len, false)
+ if (!sz) return
+ const body = i + id.len + sz.len
+ const stop = sz.unknown ? end : Math.min(end, body + sz.value)
+ if (id.value === 0x1f43b675) return // the first Cluster: every header is behind us
+ if (MASTER.has(id.value) && depth < 6) {
+ walk(body, stop, depth + 1)
+ } else if (body + sz.value <= b.length) {
+ // Only the video track has a V_ codec and a PixelWidth, so audio tracks pass by.
+ if (id.value === 0x2ad7b1) scale = readUint(body, sz.value) // TimecodeScale
+ else if (id.value === 0x4489) dur = readFloat(body, sz.value) // Duration
+ else if (id.value === 0x86) { // CodecID
+ const c = ascii(b, body, sz.value).replace(/\0+$/, '')
+ if (c.startsWith('V_') && !out.codec) out.codec = c === 'V_VP8' ? 'vp8' : c === 'V_VP9' ? 'vp9' : c === 'V_AV1' ? 'av01' : 'other'
+ }
+ else if (id.value === 0xb0 && !out.width) out.width = readUint(body, sz.value) // PixelWidth
+ else if (id.value === 0xba && !out.height) out.height = readUint(body, sz.value) // PixelHeight
+ }
+ if (sz.unknown) return
+ i = body + sz.value
+ }
+ }
+ try { walk(0, b.length, 0) } catch { return null }
+ if (dur != null && Number.isFinite(dur) && dur > 0) out.durationSec = Math.round((dur * scale) / 1e6) / 1000
+ return out
+}
diff --git a/frontend/src/lib/media-sniff.test.js b/frontend/src/lib/media-sniff.test.js
new file mode 100644
index 000000000..186528e00
--- /dev/null
+++ b/frontend/src/lib/media-sniff.test.js
@@ -0,0 +1,205 @@
+import { describe, it, expect } from 'vitest'
+import { sniffKind, imageDims, inspectGif, cleanGif, inspectMp4, scrubMp4, inspectWebm } from './media-sniff.js'
+import { bytes, latin1, fill, jpeg, png, webpVp8, webpVp8l, webpVp8x, gif, gce, frame, appExt, comment, plainText, box, ftyp, mp4, webm } from './media-samples.test-util.js'
+
+const has = (hay, needle) => {
+ const n = latin1(needle)
+ outer: for (let i = 0; i + n.length <= hay.length; i++) {
+ for (let k = 0; k < n.length; k++) if (hay[i + k] !== n[k]) continue outer
+ return true
+ }
+ return false
+}
+
+describe('sniffKind', () => {
+ it('knows each stored type by its bytes', () => {
+ expect(sniffKind(jpeg()).mime).toBe('image/jpeg')
+ expect(sniffKind(png()).mime).toBe('image/png')
+ expect(sniffKind(gif()).mime).toBe('image/gif')
+ expect(sniffKind(gif()).kind).toBe('gif')
+ expect(sniffKind(bytes('GIF87a', fill(20))).mime).toBe('image/gif')
+ expect(sniffKind(webpVp8()).mime).toBe('image/webp')
+ expect(sniffKind(mp4().file)).toMatchObject({ mime: 'video/mp4', kind: 'video', category: 'video' })
+ expect(sniffKind(mp4({ brand: 'qt ' }).file).mime).toBe('video/quicktime')
+ expect(sniffKind(webm()).mime).toBe('video/webm')
+ })
+
+ it('reads HEIC and AVIF photos as input only', () => {
+ expect(sniffKind(ftyp('heic'))).toMatchObject({ mime: 'image/heic', kind: 'image', input: true })
+ expect(sniffKind(ftyp('mif1'))).toMatchObject({ mime: 'image/heic', input: true })
+ expect(sniffKind(ftyp('avif'))).toMatchObject({ mime: 'image/avif', input: true })
+ })
+
+ it('refuses SVG, HTML, PDF, ZIP, BMP, TIFF, ICO, M4A and Matroska', () => {
+ for (const b of [
+ latin1('<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg"/>'),
+ latin1('<svg onload="alert(1)">'),
+ latin1('<!doctype html><script>alert(1)</script>'),
+ latin1('%PDF-1.7\n'),
+ bytes([0x50, 0x4b, 0x03, 0x04], fill(20)),
+ bytes('BM', fill(40)),
+ bytes([0x49, 0x49, 0x2a, 0x00], fill(20)),
+ bytes([0, 0, 1, 0, 1, 0], fill(20)),
+ ftyp('M4A '),
+ ftyp('abcd'),
+ webm({ docType: 'matroska' }),
+ new Uint8Array(0)
+ ]) expect(sniffKind(b)).toBeNull()
+ })
+})
+
+describe('imageDims', () => {
+ it('reads JPEG past an EXIF segment, PNG, the three WebP flavours and GIF', () => {
+ expect(imageDims(jpeg(4032, 3024))).toEqual({ width: 4032, height: 3024 })
+ expect(imageDims(png(300, 200))).toEqual({ width: 300, height: 200 })
+ expect(imageDims(webpVp8(320, 240))).toEqual({ width: 320, height: 240 })
+ expect(imageDims(webpVp8l(100, 50))).toEqual({ width: 100, height: 50 })
+ expect(imageDims(webpVp8x(9000, 7000))).toEqual({ width: 9000, height: 7000 })
+ expect(imageDims(gif({ w: 64, h: 48 }))).toEqual({ width: 64, height: 48 })
+ })
+ it('gives null for what it cannot read', () => {
+ expect(imageDims(latin1('<svg/>'))).toBeNull()
+ expect(imageDims(bytes([0xff, 0xd8, 0xff, 0xda], fill(10)))).toBeNull()
+ expect(imageDims(mp4().file)).toBeNull()
+ })
+})
+
+describe('inspectGif', () => {
+ it('counts frames and adds their delays, a delay of 0 counting as 10 ms', () => {
+ expect(inspectGif(gif({ w: 40, h: 30, delays: [10, 20, 0] }))).toEqual({ width: 40, height: 30, frames: 3, durMs: 100 + 200 + 10 })
+ expect(inspectGif(gif({ delays: [5] })).frames).toBe(1)
+ })
+ it('reads a GIF that stops after a whole block, and refuses what is not one', () => {
+ expect(inspectGif(gif({ delays: [10, 10], trailer: false })).frames).toBe(2)
+ expect(inspectGif(png())).toBeNull()
+ expect(inspectGif(bytes('GIF89a', [1, 0, 1, 0, 0, 0, 0], [0x99]))).toBeNull()
+ })
+})
+
+describe('cleanGif', () => {
+ const dirty = gif({ blocks: [
+ appExt('NETSCAPE2.0', bytes([1, 0, 0])),
+ comment('shot on my phone at home'),
+ appExt('XMP DataXMP', latin1('<x:xmpmeta><exif:GPSLatitude>47.3</exif:GPSLatitude></x:xmpmeta>')),
+ appExt('ICCRGBG1012', fill(40, 0x42)),
+ gce(10), frame(40, 30),
+ gce(20), plainText(),
+ gce(30), frame(40, 30)
+ ] })
+
+ it('drops comments, XMP and ICC, keeps the loop block and every frame', () => {
+ const out = cleanGif(dirty)
+ expect(has(out, 'NETSCAPE2.0')).toBe(true)
+ expect(has(out, 'shot on my phone')).toBe(false)
+ expect(has(out, 'GPSLatitude')).toBe(false)
+ expect(has(out, 'XMP Data')).toBe(false)
+ expect(has(out, 'ICCRGBG1')).toBe(false)
+ expect(out[out.length - 1]).toBe(0x3b)
+ const info = inspectGif(out)
+ expect(info.frames).toBe(2)
+ // The control block that belonged to the dropped plain-text block went with it.
+ expect(info.durMs).toBe(100 + 300)
+ })
+ it('keeps ANIMEXTS1.0 too, and gives a GIF without a trailer one', () => {
+ const out = cleanGif(gif({ blocks: [appExt('ANIMEXTS1.0', bytes([1, 0, 0])), gce(10), frame(4, 4)], trailer: false }))
+ expect(has(out, 'ANIMEXTS1.0')).toBe(true)
+ expect(out[out.length - 1]).toBe(0x3b)
+ })
+ it('throws on a GIF cut off inside a block', () => {
+ const g = gif()
+ expect(() => cleanGif(g.subarray(0, g.length - 8))).toThrow()
+ })
+})
+
+describe('inspectMp4', () => {
+ it('reads length, the display size from tkhd, the codec and every handler', () => {
+ const { file } = mp4({ seconds: 12.5, tracks: [
+ { handler: 'vide', fourcc: 'avc1', w: 1920, h: 1080, payload: fill(10) },
+ { handler: 'soun', fourcc: 'mp4a', payload: fill(10) },
+ { handler: 'meta', fourcc: 'mebx', payload: fill(10) }
+ ] })
+ expect(inspectMp4(file)).toEqual({ brand: 'isom', durationSec: 12.5, width: 1920, height: 1080, codec: 'avc1', handlers: ['vide', 'soun', 'meta'] })
+ })
+ it('turns an upright phone video round, and names HEVC, AV1 and the rest', () => {
+ expect(inspectMp4(mp4({ rotate: true }).file)).toMatchObject({ width: 1080, height: 1920 })
+ const codec = fourcc => inspectMp4(mp4({ tracks: [{ handler: 'vide', fourcc, w: 640, h: 360, payload: fill(4) }] }).file).codec
+ expect(codec('hvc1')).toBe('hvc1')
+ expect(codec('hev1')).toBe('hvc1')
+ expect(codec('avc3')).toBe('avc1')
+ expect(codec('av01')).toBe('av01')
+ expect(codec('vp09')).toBe('vp09')
+ expect(codec('mp4v')).toBe('other')
+ expect(inspectMp4(mp4({ brand: 'qt ' }).file).brand).toBe('qt ')
+ })
+ it('refuses a file without ftyp first, without moov, or with a box overrunning the file', () => {
+ const { file } = mp4()
+ expect(inspectMp4(file.subarray(24))).toBeNull()
+ expect(inspectMp4(bytes(ftyp(), box('mdat', fill(10))))).toBeNull()
+ expect(inspectMp4(file.subarray(0, file.length - 5))).toBeNull()
+ })
+})
+
+describe('scrubMp4', () => {
+ const GPS = latin1('+47.3769+008.5417/ GPS FIX')
+ const build = () => mp4({
+ tracks: [
+ { handler: 'vide', fourcc: 'avc1', w: 640, h: 360, payload: fill(64, 0x77) },
+ { handler: 'soun', fourcc: 'mp4a', payload: fill(32, 0x66) },
+ { handler: 'meta', fourcc: 'gpmd', payload: bytes(GPS, fill(8, 0x33)) },
+ { handler: 'tmcd', fourcc: 'tmcd', payload: fill(4, 0x22) }
+ ],
+ moovExtra: [box('udta', box('\xa9xyz', latin1('+47.3769+008.5417/')), box('\xa9mak', latin1('Apple'))), box('meta', fill(4, 0), latin1('com.apple.quicktime.location.ISO6709'))],
+ top: [box('uuid', fill(16, 0xbe), latin1('<xmp>GPS</xmp>'))]
+ })
+
+ it('zeroes the metadata boxes and the samples of the GPS track, and nothing else', () => {
+ const { file, sampleAt } = build()
+ const before = file.slice()
+ const out = scrubMp4(file)
+ expect(out).toBe(file) // in place
+ expect(out.length).toBe(before.length)
+ expect(has(out, '47.3769')).toBe(false)
+ expect(has(out, 'Apple')).toBe(false)
+ expect(has(out, 'com.apple.quicktime.location')).toBe(false)
+ expect(has(out, '<xmp>')).toBe(false)
+ expect(has(out, 'udta')).toBe(false)
+ expect(has(out, 'uuid')).toBe(false)
+ // Picture, sound and timecode samples are byte for byte what they were.
+ for (const [i, len] of [[0, 64], [1, 32], [3, 4]]) {
+ expect(out.subarray(sampleAt[i], sampleAt[i] + len)).toEqual(before.subarray(sampleAt[i], sampleAt[i] + len))
+ }
+ expect(out.subarray(sampleAt[2], sampleAt[2] + GPS.length + 8).every(x => x === 0)).toBe(true)
+ // Still a file the inspector reads the same way.
+ expect(inspectMp4(out)).toMatchObject({ durationSec: 5, width: 640, height: 360, codec: 'avc1', handlers: ['vide', 'soun', 'meta', 'tmcd'] })
+ })
+
+ it('refuses a sample table that points outside the file, and leaves the file as it was', () => {
+ const { file } = mp4({ tracks: [{ handler: 'meta', fourcc: 'gpmd', payload: fill(16, 0x33) }] })
+ // Point the one chunk offset past the end of the file.
+ const stco = [...Array(file.length - 4).keys()].find(i => file[i] === 0x73 && file[i + 1] === 0x74 && file[i + 2] === 0x63 && file[i + 3] === 0x6f)
+ const off = stco + 4 + 4 + 4
+ new DataView(file.buffer).setUint32(off, file.length + 10)
+ const before = file.slice()
+ expect(() => scrubMp4(file)).toThrow()
+ expect(file).toEqual(before)
+ })
+
+ it('refuses what is not an MP4', () => {
+ expect(() => scrubMp4(png())).toThrow()
+ })
+})
+
+describe('inspectWebm', () => {
+ it('reads size, codec and length from the header elements', () => {
+ expect(inspectWebm(webm({ w: 1280, h: 720, codec: 'V_VP9', durationMs: 4000 }))).toEqual({ width: 1280, height: 720, codec: 'vp9', durationSec: 4 })
+ expect(inspectWebm(webm({ codec: 'V_VP8' })).codec).toBe('vp8')
+ expect(inspectWebm(webm({ codec: 'V_AV1' })).codec).toBe('av01')
+ })
+ it('gives a null length for a recording that never wrote one', () => {
+ expect(inspectWebm(webm({ durationMs: null })).durationSec).toBeNull()
+ })
+ it('refuses Matroska and everything else', () => {
+ expect(inspectWebm(webm({ docType: 'matroska' }))).toBeNull()
+ expect(inspectWebm(mp4().file)).toBeNull()
+ })
+})
diff --git a/frontend/src/lib/sha256.js b/frontend/src/lib/sha256.js
new file mode 100644
index 000000000..477f45a09
--- /dev/null
+++ b/frontend/src/lib/sha256.js
@@ -0,0 +1,109 @@
+/* SHA-256 as lowercase hex — the name every photo and video is stored and fetched under.
+ *
+ * crypto.subtle does it natively, but only in a secure context: an instance reached over plain
+ * http on a LAN address (http://192.168.1.10:8080, a common self-hosted setup) has no
+ * crypto.subtle at all. There the pure-JS fallback below runs instead, block by block over the
+ * file in slices, so a 40 MB video is never copied into one more buffer than it has to be. Both
+ * paths give the same answer; sha256.test.js checks the fallback against known vectors and
+ * against subtle.
+ */
+
+const K = new Uint32Array([
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
+])
+
+/** An incremental SHA-256: update(bytes) as often as needed, then hex(). */
+export function createSha256() {
+ const H = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19])
+ const W = new Uint32Array(64)
+ const buf = new Uint8Array(64)
+ let bufLen = 0
+ let total = 0
+
+ const block = (b, o) => {
+ for (let i = 0; i < 16; i++) W[i] = (b[o + i * 4] << 24) | (b[o + i * 4 + 1] << 16) | (b[o + i * 4 + 2] << 8) | b[o + i * 4 + 3]
+ for (let i = 16; i < 64; i++) {
+ const x = W[i - 15], y = W[i - 2]
+ const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3)
+ const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10)
+ W[i] = (W[i - 16] + s0 + W[i - 7] + s1) | 0
+ }
+ let a = H[0], b1 = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7]
+ for (let i = 0; i < 64; i++) {
+ const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7))
+ const ch = (e & f) ^ (~e & g)
+ const t1 = (h + S1 + ch + K[i] + W[i]) | 0
+ const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10))
+ const maj = (a & b1) ^ (a & c) ^ (b1 & c)
+ const t2 = (S0 + maj) | 0
+ h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b1; b1 = a; a = (t1 + t2) | 0
+ }
+ H[0] += a; H[1] += b1; H[2] += c; H[3] += d; H[4] += e; H[5] += f; H[6] += g; H[7] += h
+ }
+
+ return {
+ update(bytes) {
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
+ total += b.length
+ let i = 0
+ if (bufLen) {
+ const take = Math.min(64 - bufLen, b.length)
+ buf.set(b.subarray(0, take), bufLen)
+ bufLen += take
+ i = take
+ if (bufLen < 64) return this
+ block(buf, 0)
+ bufLen = 0
+ }
+ for (; i + 64 <= b.length; i += 64) block(b, i)
+ if (i < b.length) { buf.set(b.subarray(i), 0); bufLen = b.length - i }
+ return this
+ },
+ hex() {
+ const bits = total * 8
+ const pad = new Uint8Array(((bufLen < 56 ? 56 : 120) - bufLen) + 8)
+ pad[0] = 0x80
+ // The length in bits, big-endian, as two 32-bit halves (a file is far below 2^53 bits).
+ const hi = Math.floor(bits / 4294967296), lo = bits >>> 0
+ const n = pad.length
+ pad[n - 8] = hi >>> 24; pad[n - 7] = hi >>> 16; pad[n - 6] = hi >>> 8; pad[n - 5] = hi
+ pad[n - 4] = lo >>> 24; pad[n - 3] = lo >>> 16; pad[n - 2] = lo >>> 8; pad[n - 1] = lo
+ this.update(pad)
+ return Array.from(H, x => x.toString(16).padStart(8, '0')).join('')
+ }
+ }
+}
+
+const SLICE = 4 * 1024 * 1024
+
+/** sha256 of bytes in pure JS. */
+export function sha256HexJs(bytes) {
+ return createSha256().update(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)).hex()
+}
+
+/**
+ * Lowercase hex SHA-256 of a Uint8Array, an ArrayBuffer or a Blob. `subtle` is injectable for
+ * the tests; null forces the fallback.
+ */
+export async function sha256Hex(input, { subtle = globalThis.crypto?.subtle } = {}) {
+ const isBlob = typeof Blob !== 'undefined' && input instanceof Blob
+ if (subtle && typeof subtle.digest === 'function') {
+ try {
+ const data = isBlob ? await input.arrayBuffer() : input
+ const d = await subtle.digest('SHA-256', data)
+ return Array.from(new Uint8Array(d), x => x.toString(16).padStart(2, '0')).join('')
+ } catch { /* an insecure context can expose subtle and still refuse: fall through */ }
+ }
+ const h = createSha256()
+ if (isBlob) {
+ for (let o = 0; o < input.size; o += SLICE) h.update(new Uint8Array(await input.slice(o, o + SLICE).arrayBuffer()))
+ } else h.update(input instanceof Uint8Array ? input : new Uint8Array(input))
+ return h.hex()
+}
diff --git a/frontend/src/lib/sha256.test.js b/frontend/src/lib/sha256.test.js
new file mode 100644
index 000000000..421e94d19
--- /dev/null
+++ b/frontend/src/lib/sha256.test.js
@@ -0,0 +1,40 @@
+import { describe, it, expect } from 'vitest'
+import { sha256Hex, sha256HexJs, createSha256 } from './sha256.js'
+
+const enc = s => new TextEncoder().encode(s)
+// FIPS 180-2 / NIST vectors.
+const VECTORS = [
+ ['', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'],
+ ['abc', 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'],
+ ['abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1'],
+ ['abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', 'cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1']
+]
+
+describe('sha256', () => {
+ it('the fallback matches the published vectors', () => {
+ for (const [msg, hex] of VECTORS) expect(sha256HexJs(enc(msg))).toBe(hex)
+ })
+
+ it('the fallback matches a million a’s fed in odd pieces', () => {
+ const h = createSha256()
+ const piece = enc('a'.repeat(997))
+ let left = 1000000
+ while (left > 0) { const n = Math.min(left, piece.length); h.update(piece.subarray(0, n)); left -= n }
+ expect(h.hex()).toBe('cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0')
+ })
+
+ it('the fallback and subtle agree on every length around a block boundary, for bytes and Blobs', async () => {
+ for (const n of [55, 56, 63, 64, 65, 119, 120, 128, 5000]) {
+ const b = new Uint8Array(n).map((_, i) => (i * 31 + n) & 0xff)
+ const native = await sha256Hex(b)
+ expect(await sha256Hex(b, { subtle: null })).toBe(native)
+ expect(await sha256Hex(new Blob([b]), { subtle: null })).toBe(native)
+ expect(await sha256Hex(new Blob([b]))).toBe(native)
+ }
+ })
+
+ it('falls back when subtle is there but refuses (an insecure context)', async () => {
+ const subtle = { digest: () => Promise.reject(new Error('insecure')) }
+ expect(await sha256Hex(enc('abc'), { subtle })).toBe(VECTORS[1][1])
+ })
+})
diff --git a/frontend/src/lib/zip.js b/frontend/src/lib/zip.js
new file mode 100644
index 000000000..9993efc27
--- /dev/null
+++ b/frontend/src/lib/zip.js
@@ -0,0 +1,181 @@
+/* The smallest zip this app needs: store-only (no compression), written from Blob parts and read
+ * back as Blob slices.
+ *
+ * "Export with photos & videos" writes one (lib/backup-media.js), and "Import backup" reads one.
+ * Photos, GIFs and videos are already compressed, so deflate would cost a dependency and buy
+ * nothing; the JSON beside them is small. Nothing is ever joined into one big string or buffer:
+ * the zip is a Blob made of header bytes and the original file Blobs, and reading one only slices
+ * the picked File, so a backup with 150 MB of videos costs no more memory than its headers.
+ *
+ * What readZip refuses, and why: any compression method but "stored" (this app never writes
+ * one — an archiver repacked the file), encryption, more than 2000 entries, a name with '..' or a
+ * leading '/', and more than 1 GB in total. ZIP64 is neither written nor read: an export over
+ * 4 GB or 65,535 files is refused rather than written broken.
+ */
+
+export class ZipError extends Error {
+ constructor(code, message) { super(message || code); this.code = code }
+}
+
+let TABLE = null
+const table = () => {
+ if (TABLE) return TABLE
+ TABLE = new Uint32Array(256)
+ for (let n = 0; n < 256; n++) {
+ let c = n
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
+ TABLE[n] = c >>> 0
+ }
+ return TABLE
+}
+
+/** CRC-32 (the zip one) of a Uint8Array, continuing from `crc` for data read in pieces. */
+export function crc32(bytes, crc = 0) {
+ const t = table()
+ let c = (crc ^ 0xffffffff) >>> 0
+ for (let i = 0; i < bytes.length; i++) c = t[(c ^ bytes[i]) & 0xff] ^ (c >>> 8)
+ return (c ^ 0xffffffff) >>> 0
+}
+
+const SLICE = 4 * 1024 * 1024
+async function crcOfBlob(blob) {
+ let crc = 0
+ for (let o = 0; o < blob.size; o += SLICE) crc = crc32(new Uint8Array(await blob.slice(o, o + SLICE).arrayBuffer()), crc)
+ return crc
+}
+
+const LIMIT_32 = 0xffffffff
+const MAX_ENTRIES_WRITE = 65535
+
+function dosTime(d) {
+ return {
+ time: (d.getHours() << 11) | (d.getMinutes() << 5) | Math.floor(d.getSeconds() / 2),
+ date: (Math.max(0, d.getFullYear() - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate()
+ }
+}
+
+/**
+ * A store-only zip of `entries` ([{ name, blob }]) as one Blob. Names are written as UTF-8 (flag
+ * bit 11), so a name any archiver shows as written. Throws ZipError('too-large') past what a zip
+ * without ZIP64 can hold.
+ */
+export async function zipStore(entries, { now = new Date() } = {}) {
+ if (entries.length > MAX_ENTRIES_WRITE) throw new ZipError('too-large')
+ const enc = new TextEncoder()
+ const { time, date } = dosTime(now)
+ const parts = []
+ const central = []
+ let offset = 0
+ for (const { name, blob } of entries) {
+ const nameBytes = enc.encode(name)
+ const size = blob.size
+ if (size > LIMIT_32) throw new ZipError('too-large')
+ const crc = await crcOfBlob(blob)
+ const local = new DataView(new ArrayBuffer(30))
+ local.setUint32(0, 0x04034b50, true)
+ local.setUint16(4, 20, true) // version needed: 2.0
+ local.setUint16(6, 0x0800, true) // UTF-8 names
+ local.setUint16(8, 0, true) // stored
+ local.setUint16(10, time, true)
+ local.setUint16(12, date, true)
+ local.setUint32(14, crc, true)
+ local.setUint32(18, size, true)
+ local.setUint32(22, size, true)
+ local.setUint16(26, nameBytes.length, true)
+ local.setUint16(28, 0, true)
+ parts.push(local.buffer, nameBytes, blob)
+ const cd = new DataView(new ArrayBuffer(46))
+ cd.setUint32(0, 0x02014b50, true)
+ cd.setUint16(4, 20, true)
+ cd.setUint16(6, 20, true)
+ cd.setUint16(8, 0x0800, true)
+ cd.setUint16(10, 0, true)
+ cd.setUint16(12, time, true)
+ cd.setUint16(14, date, true)
+ cd.setUint32(16, crc, true)
+ cd.setUint32(20, size, true)
+ cd.setUint32(24, size, true)
+ cd.setUint16(28, nameBytes.length, true)
+ cd.setUint32(42, offset, true) // the rest (extra, comment, disk, attributes) stays 0
+ central.push(cd.buffer, nameBytes)
+ offset += 30 + nameBytes.length + size
+ if (offset > LIMIT_32) throw new ZipError('too-large')
+ }
+ const cdSize = central.reduce((n, p) => n + p.byteLength, 0)
+ const end = new DataView(new ArrayBuffer(22))
+ end.setUint32(0, 0x06054b50, true)
+ end.setUint16(8, entries.length, true)
+ end.setUint16(10, entries.length, true)
+ end.setUint32(12, cdSize, true)
+ end.setUint32(16, offset, true)
+ return new Blob([...parts, ...central, end.buffer], { type: 'application/zip' })
+}
+
+export const MAX_ENTRIES = 2000
+export const MAX_TOTAL = 1024 * 1024 * 1024
+const EOCD_SEARCH = 65557 // 22-byte record + the largest possible comment
+
+const readBytes = async (file, start, end) => new Uint8Array(await file.slice(start, end).arrayBuffer())
+
+/** Whether a file starts like a zip (PK\x03\x04). */
+export async function looksLikeZip(file) {
+ const b = await readBytes(file, 0, 4)
+ return b.length === 4 && b[0] === 0x50 && b[1] === 0x4b && b[2] === 0x03 && b[3] === 0x04
+}
+
+/**
+ * The entries of a store-only zip as [{ name, size, blob }], each blob a slice of `file` (a File
+ * or Blob) — nothing is read beyond the headers. Throws ZipError with code 'not-zip',
+ * 'compressed' (repacked by an archiver), 'encrypted', 'too-many', 'bad-name' or 'too-large'.
+ */
+export async function readZip(file) {
+ const size = file.size
+ const tailStart = Math.max(0, size - EOCD_SEARCH)
+ const tail = await readBytes(file, tailStart, size)
+ let eocd = -1
+ for (let i = tail.length - 22; i >= 0; i--) {
+ if (tail[i] === 0x50 && tail[i + 1] === 0x4b && tail[i + 2] === 0x05 && tail[i + 3] === 0x06) { eocd = i; break }
+ }
+ if (eocd < 0) throw new ZipError('not-zip')
+ const e = new DataView(tail.buffer, tail.byteOffset + eocd, 22)
+ const count = e.getUint16(10, true)
+ const cdSize = e.getUint32(12, true)
+ const cdOffset = e.getUint32(16, true)
+ if (count === 0xffff || cdOffset === LIMIT_32) throw new ZipError('too-large') // ZIP64
+ if (count > MAX_ENTRIES) throw new ZipError('too-many')
+ if (cdOffset + cdSize > size) throw new ZipError('not-zip')
+ const cd = await readBytes(file, cdOffset, cdOffset + cdSize)
+ const dv = new DataView(cd.buffer, cd.byteOffset, cd.byteLength)
+ const dec = new TextDecoder()
+ const out = []
+ let total = 0
+ let p = 0
+ for (let n = 0; n < count; n++) {
+ if (p + 46 > cd.length || dv.getUint32(p, true) !== 0x02014b50) throw new ZipError('not-zip')
+ const flags = dv.getUint16(p + 8, true)
+ const method = dv.getUint16(p + 10, true)
+ const csize = dv.getUint32(p + 20, true)
+ const usize = dv.getUint32(p + 24, true)
+ const nameLen = dv.getUint16(p + 28, true)
+ const extraLen = dv.getUint16(p + 30, true)
+ const commentLen = dv.getUint16(p + 32, true)
+ const localOffset = dv.getUint32(p + 42, true)
+ if (p + 46 + nameLen > cd.length) throw new ZipError('not-zip')
+ const name = dec.decode(cd.subarray(p + 46, p + 46 + nameLen))
+ p += 46 + nameLen + extraLen + commentLen
+ if (flags & 1) throw new ZipError('encrypted')
+ if (method !== 0) throw new ZipError('compressed')
+ if (csize !== usize) throw new ZipError('compressed')
+ if (name.startsWith('/') || name.includes('\\') || name.split('/').includes('..')) throw new ZipError('bad-name')
+ total += usize
+ if (total > MAX_TOTAL) throw new ZipError('too-large')
+ if (name.endsWith('/')) continue // a folder entry holds nothing
+ const lh = await readBytes(file, localOffset, localOffset + 30)
+ const lv = new DataView(lh.buffer, lh.byteOffset, lh.byteLength)
+ if (lh.length < 30 || lv.getUint32(0, true) !== 0x04034b50) throw new ZipError('not-zip')
+ const start = localOffset + 30 + lv.getUint16(26, true) + lv.getUint16(28, true)
+ if (start + usize > size) throw new ZipError('not-zip')
+ out.push({ name, size: usize, blob: file.slice(start, start + usize) })
+ }
+ return out
+}
diff --git a/frontend/src/lib/zip.test.js b/frontend/src/lib/zip.test.js
new file mode 100644
index 000000000..234aa9106
--- /dev/null
+++ b/frontend/src/lib/zip.test.js
@@ -0,0 +1,63 @@
+import { describe, it, expect } from 'vitest'
+import { zipStore, readZip, looksLikeZip, crc32, ZipError, MAX_ENTRIES } from './zip.js'
+
+const text = async blob => new TextDecoder().decode(new Uint8Array(await blob.arrayBuffer()))
+const u8 = async blob => new Uint8Array(await blob.arrayBuffer())
+
+// A zip laid out by hand: one local header and central record per entry, for the refusals.
+function handZip(entries, { method = 0, flags = 0x0800, count } = {}) {
+ const enc = new TextEncoder()
+ const parts = [], cd = []
+ let off = 0
+ for (const { name, data } of entries) {
+ const n = enc.encode(name)
+ const lh = new DataView(new ArrayBuffer(30))
+ lh.setUint32(0, 0x04034b50, true); lh.setUint16(6, flags, true); lh.setUint16(8, method, true)
+ lh.setUint32(18, data.length, true); lh.setUint32(22, data.length, true); lh.setUint16(26, n.length, true)
+ parts.push(new Uint8Array(lh.buffer), n, data)
+ const c = new DataView(new ArrayBuffer(46))
+ c.setUint32(0, 0x02014b50, true); c.setUint16(8, flags, true); c.setUint16(10, method, true)
+ c.setUint32(20, data.length, true); c.setUint32(24, data.length, true); c.setUint16(28, n.length, true); c.setUint32(42, off, true)
+ cd.push(new Uint8Array(c.buffer), n)
+ off += 30 + n.length + data.length
+ }
+ const cdSize = cd.reduce((s, p) => s + p.length, 0)
+ const e = new DataView(new ArrayBuffer(22))
+ e.setUint32(0, 0x06054b50, true); e.setUint16(8, count ?? entries.length, true); e.setUint16(10, count ?? entries.length, true)
+ e.setUint32(12, cdSize, true); e.setUint32(16, off, true)
+ return new Blob([...parts, ...cd, new Uint8Array(e.buffer)])
+}
+const refusal = async blob => { try { await readZip(blob); return null } catch (e) { return e instanceof ZipError ? e.code : 'other' } }
+
+describe('zip', () => {
+ it('the CRC of "abc" is 0x352441C2', () => {
+ expect(crc32(new TextEncoder().encode('abc'))).toBe(0x352441c2)
+ })
+
+ it('round-trips names (UTF-8 included) and bytes, and says it is a zip', async () => {
+ const bin = new Uint8Array(70000).map((_, i) => i & 0xff)
+ const z = await zipStore([
+ { name: 'opengym-backup.json', blob: new Blob(['{"workouts":[]}']) },
+ { name: 'media/übung.bin', blob: new Blob([bin]) },
+ { name: 'empty.txt', blob: new Blob([]) }
+ ])
+ expect(z.type).toBe('application/zip')
+ expect(await looksLikeZip(z)).toBe(true)
+ expect(await looksLikeZip(new Blob(['{"a":1}']))).toBe(false)
+ const back = await readZip(z)
+ expect(back.map(e => [e.name, e.size])).toEqual([['opengym-backup.json', 15], ['media/übung.bin', 70000], ['empty.txt', 0]])
+ expect(await text(back[0].blob)).toBe('{"workouts":[]}')
+ expect(await u8(back[1].blob)).toEqual(bin)
+ })
+
+ it('refuses a compressed entry, an encrypted one, a name that climbs out, and too many entries', async () => {
+ const data = new Uint8Array([1, 2, 3])
+ expect(await refusal(handZip([{ name: 'a.txt', data }], { method: 8 }))).toBe('compressed')
+ expect(await refusal(handZip([{ name: 'a.txt', data }], { flags: 0x0801 }))).toBe('encrypted')
+ expect(await refusal(handZip([{ name: '../../evil.sh', data }]))).toBe('bad-name')
+ expect(await refusal(handZip([{ name: 'media/../x', data }]))).toBe('bad-name')
+ expect(await refusal(handZip([{ name: '/etc/passwd', data }]))).toBe('bad-name')
+ expect(await refusal(handZip([{ name: 'a.txt', data }], { count: MAX_ENTRIES + 1 }))).toBe('too-many')
+ expect(await refusal(new Blob(['not a zip at all']))).toBe('not-zip')
+ })
+})