Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(security): refuse uploads whose bytes are ffmpeg playlists
Adam Eivy39cceb7aa979
diff --git a/server/lib/README.md b/server/lib/README.mdindex 72b7268a28..5cce04f02c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -388,12 +388,12 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `homePath.js` | `scrubHomePath(value)` — replace the running user's home-directory prefix with `~` anywhere in a string, so `/Users/<name>/…` never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting `/` as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: `agentRunEvents.js` re-exports it for the CoS ledger, and `scripts/doctor.js` imports it statically because it must load from a bare checkout with no `node_modules` (`scripts/pre-install-entrypoints.test.js` enforces that). || `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore` — a TTL-cached mutable JSON document with serialized `save`/`mutate`; its `load()` is strict (#4115) so a corrupt file rejects instead of being overwritten by the next `mutate`. || `settingsStore.js` | `createSettingsStore(filePath | () => filePath, defaults, { normalize? })` → `{ get, update, path }` — the one owner of a flat per-feature settings document with shipped defaults (`journal-settings.json`, `activity-digest-settings.json`, `goal-scorecard-settings.json`, …). `get()` reads strict (#4115: a corrupt file rejects rather than reading as the defaults, because `update` writes it back), merges the file over `defaults`, then runs `normalize`; `update(patch)` is a serialized `get → apply → atomicWrite` that skips `undefined` values and writes `null` as an explicit clear. Filter client-settable keys BEFORE calling `update`. Reach for `createCachedStore` for an in-place-edited document and `createCollectionStore` for per-record collections. |-| `mimeTypes.js` | MIME tables and extension allowlists (incl. `UPLOAD_AUDIO_EXTENSIONS`, the playable-audio subset of `/api/uploads`), image/video format detection (`detectImageFormat`, `detectVideoFormat`), and filename sanitization. |+| `mimeTypes.js` | MIME tables and extension allowlists (incl. `UPLOAD_AUDIO_EXTENSIONS`, the playable-audio subset of `/api/uploads`), image/video format detection (`detectImageFormat`, `detectVideoFormat`), `detectMediaManifest` (names bytes ffmpeg would open as an HLS/DASH/IMF/concat/SDP manifest that pulls in other files), and filename sanitization. || `paths.js` | Canonical source/install `PATHS`, `dataPath`, and home-directory expansion. || `pathContainment.js` | Dependency-free leaf holding `isPathAtOrInsideDir(dir, path)` (containment where the root itself counts as inside — what a guard policing a whole tree wants, as opposed to `pathSafety.js`'s strict `isPathInsideDir`; case-folded on Windows/macOS) and `canonicalizePath(path)` (realpath of the deepest EXISTING ancestor plus the not-yet-created tail, so a target that does not exist yet still resolves through symlinked ancestors). Split out so `fileCore.js`'s #6176 guard can reach them without dragging `errorHandler.js`/`paths.js` into the closure of every server suite — see the budget in `importScoping.test.js`. Keep it free of non-builtin imports. || `repoPublishPath.js` | `isSymlinkFreeRepoPath(realRepoRoot, absPath, { leaf: 'dir' \| 'file' })` — symlink-aware containment for publishing generated files into a managed app's repo. `lstat`-walks every existing component below the real root and refuses any symlink (dangling or contained), a wrong-kind leaf, or a realpath outside the root; a missing tail is allowed below a verified ancestor. The lexical `isPathInsideDir` cannot see a redirecting directory link (#10894, after #9668). Shared by the chiptune and sprite publishers. || `pathSafety.js` | Filename/traversal validation, path containment, and approved image-asset resolvers. |-| `uploads.js` | Upload staging/import, base64/image persistence, and safe local-file serving. |+| `uploads.js` | Upload staging/import, base64/image persistence, and safe local-file serving. `assertNotMediaManifest(buffer)` / `assertFileNotMediaManifest(path)` refuse media uploads whose bytes are a playlist or manifest before ffmpeg can probe them. || `icloudFile.js` | Guards against blocking reads of **evicted (dataless) cloud files**. macOS Optimize-Mac-Storage offloads a file in an iCloud ubiquity container (or a `~/Library/CloudStorage` File Provider mount); the path and `size` remain but no blocks are local, and the first **data access** BLOCKS in the kernel until materialization completes — indefinitely and uncancellably when iCloud is wedged. Four such reads exhaust libuv's 4-thread fs pool and every later `fs` call in the process queues forever, including the `express.static` read that serves the UI bundle (the whole UI hangs while memory-only routes still answer). Retry-on-error can't help: the read doesn't fail, it hangs. `readIfMaterialized(path, {encoding, label})` screens with a `stat()` (safe — never materializes) and rejects with `err.code === ICLOUD_NOT_MATERIALIZED` instead of issuing the read, kicking a background `brctl download` so the next cycle succeeds; concurrent callers for one path+encoding share a single read. `isUbiquityPath(path)` resolves the containing directory's real path (memoized) rather than substring-matching, so a **symlinked** route into iCloud — `~/Documents/...` under "Desktop & Documents Folders" sync — is still recognized. `isDatalessStats(stats)` is the raw predicate (`size > 0 && blocks === 0`) and is **not safe alone** (a sparse or `decmpfs`-compressed ordinary file matches it); pair it with the platform + cloud-root scoping via `isEvictedStats(path, stats)`, which is what a caller holding a `Stats` should use, or `isSuspectedDataless(path)` which does the `stat` itself. `requestMaterialization(path, {label, retryAfterExit, onFailure})` is the fire-and-forget `brctl download` every brctl caller shares — read paths kick it (default `retryAfterExit: true`) to heal an evicted file, per-path-deduped in a shared in-flight map capped at 4 concurrent children (an evicted vault walk would otherwise fork one per note) and each killed at `DOWNLOAD_DEADLINE_MS` so a wedged `brctl` can't hold every slot for the life of the process; the boot/settings pin in `mortalLoomStore` passes `retryAfterExit: false` so it is NOT tracked in that shared map (it owns a single-sticky-path dedupe at its call site) plus an `onFailure` hook to clear that sticky path on a failed/killed download. `claimBrctlMissingWarning()` returns `true` on the first call only, so the "brctl not found on PATH" warning fires at most once per process across every brctl caller (the fire-and-forget path here and the awaited `materializeAndWait`). `materializeAndWait(path, {label, timeoutMs})` is the **awaited, bounded** counterpart used by WRITE paths (`mortalLoomStore` before overwriting its store, `obsidian.updateNote` before overwriting a note): a write must not silently skip, so it materializes and waits rather than firing and forgetting, bounded by `MATERIALIZE_TIMEOUT_MS` (20s — much tighter than the background `DOWNLOAD_DEADLINE_MS` because a caller is blocked on it) and run in a child process, which is what makes the wait cancellable when the kernel write it replaces would not be. It resolves `true` only on brctl exit-0, which means the download was **accepted, not completed** — always re-screen before trusting the file. Measured (#3706, #3713), and recorded in the module docblock's syscall table: `stat`/`open`/`rename`/`unlink` never materialize, while `read`, `write` (including after `O_TRUNC` — truncating does NOT skip the download), `link`, and `clonefile` all do. `unlink` being free is a measurement, not the POSIX inference — `link` is pure metadata too and it *does* materialize — so delete paths need no screen. The docblock also carries the reproduction recipe: `brctl evict <path>` works (undocumented, like `brctl download`), which is what makes the evict/measure/heal loop scriptable. Consumed by `services/mortalLoomStore.js` and `services/obsidian.js`. || `boundedStateMap.js` | `createBoundedStateMap({ maxSize, ttlMs })` — a `Map` that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on `get`/`set` (no timers); `get` doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state. || `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. |diff --git a/server/lib/mimeTypes.js b/server/lib/mimeTypes.jsindex 64cf9256dc..5865e97afe 100644--- a/server/lib/mimeTypes.js+++ b/server/lib/mimeTypes.js@@ -1,4 +1,4 @@-/** MIME tables, extension policy, and lightweight image format detection. */+/** MIME tables, extension policy, and lightweight media format detection. */import { basename, extname } from 'path';/**@@ -183,6 +183,48 @@ export function detectVideoFormat(buf) {return null;}+// ffmpeg's PROBE_BUF_MAX: no demuxer probe sees past the first MiB.+export const MEDIA_MANIFEST_PROBE_BYTES = 1 << 20;++// Length of a leading ID3v2 tag, which ffmpeg strips before probing.+function id3v2TagLength(buf) {+ if (buf.length < 10 || buf.toString('latin1', 0, 3) !== 'ID3' || buf[3] === 0xff || buf[4] === 0xff) return 0;+ if ((buf[6] | buf[7] | buf[8] | buf[9]) & 0x80) return 0;+ const length = 10 + ((buf[6] << 21) | (buf[7] << 14) | (buf[8] << 7) | buf[9]);+ return buf[5] & 0x10 ? length + 10 : length;+}++/**+ * Name the reference-following format ffmpeg would open these bytes as, or+ * null. ffmpeg picks a demuxer by content, not extension, so a `.mp3`/`.mp4`+ * whose bytes are an HLS playlist, DASH manifest, IMF composition, concat+ * script or SDP session makes a later probe or render read the local media+ * files (or network endpoints) it names; ffmpeg before 6.1 opens an HLS+ * playlist under any extension. Mirrors the demuxer probes: the bytes after+ * one optional ID3v2 tag, with substring probes stopping at the first NUL.+ *+ * @param {Buffer} buf - Leading bytes of the file+ * @returns {'hls'|'concat'|'dash'|'imf'|'sdp'|null}+ */+export function detectMediaManifest(buf) {+ if (!Buffer.isBuffer(buf)) return null;+ const head = buf.subarray(0, MEDIA_MANIFEST_PROBE_BYTES);+ const tagLength = id3v2TagLength(head);+ const views = tagLength > 0 && tagLength < head.length ? [head, head.subarray(tagLength)] : [head];+ for (const view of views) {+ const nul = view.indexOf(0);+ const text = view.toString('latin1', 0, nul === -1 ? view.length : nul);+ const lead = text.replace(/^\xef\xbb\xbf/, '').trimStart();+ if (lead.startsWith('#EXTM3U')) return 'hls';+ if (lead.startsWith('ffconcat version')) return 'concat';+ const lower = text.toLowerCase();+ if (lower.includes('<mpd') && (lower.includes('dash:profile') || lower.includes('3gpp:pss:profile:dash1'))) return 'dash';+ if (lower.includes('<compositionplaylist')) return 'imf';+ if (/(?:^|[\r\n])c=IN IP/.test(text)) return 'sdp';+ }+ return null;+}+/*** Get a file's extension, normalised to lowercase with a leading dot.* Returns null when the filename has no extension.diff --git a/server/lib/mimeTypes.test.js b/server/lib/mimeTypes.test.jsnew file mode 100644index 0000000000..8ebe3ecc09--- /dev/null+++ b/server/lib/mimeTypes.test.js@@ -0,0 +1,40 @@+import { describe, it, expect } from 'vitest';+import { detectMediaManifest } from './mimeTypes.js';++// A minimal ID3v2.4 tag (syncsafe size in bytes 6-9) followed by `body`.+const withId3 = (body, padding = 32) => Buffer.concat([+ Buffer.from([0x49, 0x44, 0x33, 4, 0, 0, 0, 0, 0, padding]), Buffer.alloc(padding), Buffer.from(body),+]);++const PLAYLIST = '#EXTM3U\n#EXTINF:2.0,\n../private/clip.mp4\n#EXT-X-ENDLIST\n';++describe('detectMediaManifest', () => {+ it.each([+ ['an HLS playlist', Buffer.from(PLAYLIST), 'hls'],+ ['an HLS playlist after a UTF-8 BOM and blank lines', Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from(`\n\n${PLAYLIST}`)]), 'hls'],+ ['an HLS playlist behind an ID3v2 tag (ffmpeg strips it before probing)', withId3(PLAYLIST), 'hls'],+ ['a concat script', Buffer.from('ffconcat version 1.0\nfile clip.mp4\n'), 'concat'],+ ['a DASH manifest', Buffer.from('<?xml version="1.0"?><MPD profiles="urn:mpeg:dash:profile:isoff-on-demand:2011">'), 'dash'],+ ['an IMF composition', Buffer.from('<?xml version="1.0"?><CompositionPlaylist><ContentTitle>x</ContentTitle>'), 'imf'],+ ['an SDP session', Buffer.from('v=0\r\no=- 0 0 IN IP4 192.0.2.10\r\nc=IN IP4 192.0.2.10\r\nm=audio 5004 RTP/AVP 0\r\n'), 'sdp'],+ ])('names %s', (_label, bytes, expected) => {+ expect(detectMediaManifest(bytes)).toBe(expected);+ });++ it.each([+ ['an MP3 with an ID3v2 tag', withId3(Buffer.from([0xff, 0xfb, 0x90, 0x00, 0, 0, 0, 0]))],+ ['a WAV header', Buffer.concat([Buffer.from('RIFF'), Buffer.from([36, 0, 0, 0]), Buffer.from('WAVEfmt ')])],+ ['a FLAC header', Buffer.concat([Buffer.from('fLaC'), Buffer.alloc(8)])],+ ['an Ogg page', Buffer.concat([Buffer.from('OggS'), Buffer.alloc(8)])],+ // Real binary media hits a NUL long before any text; ffmpeg's string probes stop there too.+ ['an MP4 whose later bytes carry playlist text', Buffer.concat([Buffer.from([0, 0, 0, 0x18]), Buffer.from('ftypisom'), Buffer.alloc(4), Buffer.from(`${PLAYLIST}<MPD dash:profile`)])],+ ['an MPD mention without a DASH profile', Buffer.from('notes about <MPD> files')],+ ['plain text', Buffer.from('hello uploads')],+ ])('leaves %s alone', (_label, bytes) => {+ expect(detectMediaManifest(bytes)).toBeNull();+ });++ it('returns null for a non-buffer', () => {+ expect(detectMediaManifest('#EXTM3U')).toBeNull();+ });+});diff --git a/server/lib/uploads.js b/server/lib/uploads.jsindex 35a28dffa9..ea63680c29 100644--- a/server/lib/uploads.js+++ b/server/lib/uploads.js@@ -1,14 +1,40 @@/** Upload staging, validation, persistence, and local-file serving helpers. */-import { readFile, stat, unlink } from 'fs/promises';+import { open, readFile, stat, unlink } from 'fs/promises';import { randomUUID } from 'crypto';import { join, resolve as resolvePath } from 'path';import { MIRRORED_MIME_TYPES } from './beeperAttachmentPaths.js';import { ServerError } from './errorHandler.js';import { copyFileGuarded, ensureDir, pathExists, renameGuarded, unlinkGuarded, writeFileGuarded } from './fileCore.js';-import { detectImageFormat, getFileExtension, getMimeType, RISKY_MIME_TYPES, sanitizeFilename } from './mimeTypes.js';+import {+ detectImageFormat, detectMediaManifest, getFileExtension, getMimeType, MEDIA_MANIFEST_PROBE_BYTES,+ RISKY_MIME_TYPES, sanitizeFilename,+} from './mimeTypes.js';import { PATHS } from './paths.js';import { assertSafeFilename, isPathInsideDir } from './pathSafety.js';+// Uploads under these types may later be probed, thumbnailed or rendered by ffmpeg.+const isFfmpegInputExtension = (ext) => /^(audio|video|image)\//.test(getMimeType(ext));++/**+ * Refuse bytes ffmpeg would open as a playlist or manifest naming other files+ * (see `detectMediaManifest`). Apply before persisting any upload a probe,+ * thumbnail or render may later read.+ */+export function assertNotMediaManifest(buffer) {+ const format = detectMediaManifest(buffer);+ if (format) {+ throw new ServerError(`File content is a ${format} playlist or manifest that references other files; upload the media itself`, { status: 400, code: 'INVALID_FILE_TYPE' });+ }+}++/** `assertNotMediaManifest` over the leading bytes of a file on disk. */+export async function assertFileNotMediaManifest(path) {+ const handle = await open(path, 'r');+ const head = Buffer.alloc(MEDIA_MANIFEST_PROBE_BYTES);+ const { bytesRead } = await handle.read(head, 0, head.length, 0).finally(() => handle.close());+ assertNotMediaManifest(head.subarray(0, bytesRead));+}+/*** Move a temp file into `destDir` and return the persisted filename, using the* `/api/uploads` route's naming (`<uuid8>-<sanitized-name>`) so a@@ -27,6 +53,7 @@ export async function importFileToDir(tempPath, originalName, destDir, { extensiif (extensions && !extensions.map((item) => item.toLowerCase()).includes(extension)) {throw new ServerError('Invalid file type', { status: 400, code: 'INVALID_FILE_TYPE' });}+ if (extension && isFfmpegInputExtension(extension)) await assertFileNotMediaManifest(tempPath);await ensureDir(destDir);const id = randomUUID();const filename = `${id.slice(0, 8)}-${sanitizeFilename(originalName)}`;@@ -168,6 +195,7 @@ export async function saveBase64Upload(dir, { filename, data }, { allowedExtensiif (buffer.length > maxBytes) {throw new ServerError(`File exceeds maximum size of ${maxBytes / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });}+ if (isFfmpegInputExtension(ext)) assertNotMediaManifest(buffer);await ensureDir(dir);diff --git a/server/routes/uploads.test.js b/server/routes/uploads.test.jsindex aba0ed14ab..79c114f057 100644--- a/server/routes/uploads.test.js+++ b/server/routes/uploads.test.js@@ -1,6 +1,6 @@import { describe, it, expect, vi, afterAll } from 'vitest';import express from 'express';-import { rmSync, readFileSync } from 'fs';+import { existsSync, readdirSync, rmSync, readFileSync } from 'fs';import { join, dirname } from 'path';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';@@ -196,12 +196,13 @@ describe('uploads routes (#4101)', () => {describe('streamed uploads', () => {+ const multipart = (filename, bytes) => Buffer.concat([+ Buffer.from(`--upload-test\r\nContent-Disposition: form-data; name="file"; filename="${filename}"\r\nContent-Type: video/mp4\r\n\r\n`),+ bytes, Buffer.from('\r\n--upload-test--\r\n'),+ ]);+it('accepts media beyond the JSON ceiling, persists the bytes, and rejects unsupported extensions', async () => {const payload = Buffer.alloc(56 * 1024 * 1024, 7);- const multipart = (filename, bytes) => Buffer.concat([- Buffer.from(`--upload-test\r\nContent-Disposition: form-data; name="file"; filename="${filename}"\r\nContent-Type: video/mp4\r\n\r\n`),- bytes, Buffer.from('\r\n--upload-test--\r\n'),- ]);const res = await request(buildApp()).post('/api/uploads').set('Content-Type', 'multipart/form-data; boundary=upload-test').send(multipart('large.mp4', payload));expect(res.status).toBe(200);@@ -213,4 +214,24 @@ describe('streamed uploads', () => {expect(bad.status).toBe(400);expect(bad.body.code).toBe('INVALID_FILE_TYPE');});++ // ffmpeg 4.4/5.1 open these bytes as HLS whatever the extension and read the+ // local file the playlist names into a probe, thumbnail or render.+ it('refuses media whose bytes are a playlist ffmpeg would follow, in both transports', async () => {+ const playlist = '#EXTM3U\n#EXTINF:2.0,\n../private/clip.mp4\n#EXT-X-ENDLIST\n';+ const stored = () => (existsSync(PATHS.uploads) ? readdirSync(PATHS.uploads) : []).filter((name) => /-(song\.mp3|clip\.mp4)$/.test(name));+ const before = stored();++ const json = await post(buildApp(), 'song.mp3', playlist);+ expect(json.status).toBe(400);+ expect(json.body.code).toBe('INVALID_FILE_TYPE');+ const streamed = await request(buildApp()).post('/api/uploads')+ .set('Content-Type', 'multipart/form-data; boundary=upload-test').send(multipart('clip.mp4', Buffer.from(playlist)));+ expect(streamed.status).toBe(400);+ expect(streamed.body.code).toBe('INVALID_FILE_TYPE');+ expect(stored()).toEqual(before);++ // The same text under a non-media extension never reaches ffmpeg.+ expect((await post(buildApp(), 'playlist-notes.txt', playlist)).status).toBe(200);+ });});diff --git a/server/services/musicVideo/vocalStem.js b/server/services/musicVideo/vocalStem.jsindex f860c61577..effb4c04fe 100644--- a/server/services/musicVideo/vocalStem.js+++ b/server/services/musicVideo/vocalStem.js@@ -28,7 +28,7 @@ import { unlink } from 'fs/promises';import { join } from 'path';import { ServerError } from '../../lib/errorHandler.js';import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';-import { PATHS } from '../../lib/fileUtils.js';+import { assertFileNotMediaManifest, PATHS } from '../../lib/fileUtils.js';import { probeVideoDuration, safeUnder } from '../../lib/ffmpeg.js';import { importUploadedTrack } from '../pipeline/musicLibrary.js';import { getProject, updateProject } from './projects.js';@@ -78,6 +78,8 @@ const audioSourceKey = (project) => `${project?.trackId ?? ''}\u0000${project?.uexport async function attachVocalStem(projectId, { tempPath, originalName }) {try {const project = await requireProject(projectId);+ // Before the probe: ffmpeg would follow a playlist posing as audio.+ await assertFileNotMediaManifest(tempPath);// Lazy: render.js pulls the whole render pipeline.const { resolveMasterAudioPath } = await import('./render.js');const masterPath = await resolveMasterAudioPath(project);diff --git a/server/services/musicVideo/vocalStem.test.js b/server/services/musicVideo/vocalStem.test.jsindex e62c6a36db..0eb9a6fa03 100644--- a/server/services/musicVideo/vocalStem.test.js+++ b/server/services/musicVideo/vocalStem.test.js@@ -1,5 +1,6 @@import { afterAll, expect, it, vi } from 'vitest';import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';import { join } from 'node:path';import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';@@ -39,3 +40,18 @@ it('keeps a stem file and its project reference behind an active backup cut', asrelease();}});++// The stem is probed before it is imported, so the bytes are checked first.+it('refuses a playlist posing as a stem before ffmpeg probes it', async () => {+ const project = await createProject({ name: 'Vocal example', mediaMode: 'code-images' });+ await mkdir(PATHS.data, { recursive: true });+ const tempPath = join(PATHS.data, 'synthetic-playlist.wav');+ await writeFile(tempPath, '#EXTM3U\n#EXTINF:2.0,\n../private/vocals.wav\n#EXT-X-ENDLIST\n');+ probeVideoDuration.mockClear();++ await expect(attachVocalStem(project.id, { tempPath, originalName: 'vocals.wav' }))+ .rejects.toMatchObject({ status: 400, code: 'INVALID_FILE_TYPE' });+ expect(probeVideoDuration).not.toHaveBeenCalled();+ expect((await getProject(project.id)).vocalStemFilename).toBeFalsy();+ expect(existsSync(tempPath)).toBe(false);+});diff --git a/server/services/pipeline/musicLibrary.js b/server/services/pipeline/musicLibrary.jsindex 36c02d010d..6968e21ba3 100644--- a/server/services/pipeline/musicLibrary.js+++ b/server/services/pipeline/musicLibrary.js@@ -26,6 +26,7 @@ import {listDirectoryByExtension,copyFileGuarded,unlinkGuarded,+ assertFileNotMediaManifest,} from '../../lib/fileUtils.js';import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';@@ -135,9 +136,15 @@ export async function listMusicLibrary() {/*** Move an uploaded temp file into the library and return the persisted* filename. Caller (the route) reads `req.file.path` from the multipart- * helper. Returns `{ filename, sizeBytes }`.+ * helper. Returns `{ filename, sizeBytes }`. The upload filter checks only the+ * name and declared type, so the bytes are checked here before ffmpeg can+ * probe or render the stored file; a refused temp file is removed.*/export async function importUploadedTrack(tempPath, originalName) {+ await assertFileNotMediaManifest(tempPath).catch(async (err) => {+ await unlinkGuarded(tempPath).catch(() => {});+ throw err;+ });const filename = buildStoredFilename(originalName);const dest = join(PATHS.music, filename);// The copy is the whole publication: a snapshot copying the library while itdiff --git a/server/services/pipeline/musicLibrary.test.js b/server/services/pipeline/musicLibrary.test.jsindex fd30bf7a8c..20bb3e28e1 100644--- a/server/services/pipeline/musicLibrary.test.js+++ b/server/services/pipeline/musicLibrary.test.js@@ -172,6 +172,16 @@ describe('importUploadedTrack', () => {const { filename } = await importUploadedTrack(tmp, 'a.wav');expect(existsSync(join(FAKE_MUSIC_DIR, filename))).toBe(true);});++ // Track, pipeline and Suno imports all land here; the multipart filter only+ // checked the name, so ffmpeg 4.4/5.1 would follow the playlist on probe.+ it('refuses a playlist posing as audio, stores nothing and removes the temp upload', async () => {+ const tmp = join(TEST_HOME, 'upload-tmp.mp3');+ await writeFile(tmp, '#EXTM3U\n#EXTINF:2.0,\n../private/song.m4a\n#EXT-X-ENDLIST\n');+ await expect(importUploadedTrack(tmp, 'song.mp3')).rejects.toMatchObject({ status: 400, code: 'INVALID_FILE_TYPE' });+ expect(await readdir(FAKE_MUSIC_DIR)).toEqual([]);+ expect(existsSync(tmp)).toBe(false);+ });});describe('statMusicTrack', () => {