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
address review: fix temp-file leaks and DoS gap on dropped multipart parts
Adam Eivy6cdb55f11c46
diff --git a/server/lib/multipart.js b/server/lib/multipart.jsindex 8ca223afd8..f25f17d984 100644--- a/server/lib/multipart.js+++ b/server/lib/multipart.js@@ -103,6 +103,12 @@ function streamMultipart(req, boundary, acceptedNames, maxSize, fileFilter, nextlet endSeen = false; // 'end' event fired but we may still be flushinglet textCharCount = 0;const TEXT_FIELD_TOTAL_CAP = 1024 * 1024; // 1MB cap on aggregate text fields+ // Cap the bytes we'll silently consume from non-matching file parts. Without+ // this, a client could keep the connection busy by streaming a huge file+ // under an unaccepted field name (we just discard the bytes, but the parser+ // would happily read forever). 50MB matches the typical accepted-file cap.+ let droppedFileBytes = 0;+ const DROPPED_FILE_TOTAL_CAP = 50 * 1024 * 1024;// Per-part statelet currentName = null;@@ -249,8 +255,18 @@ function streamMultipart(req, boundary, acceptedNames, maxSize, fileFilter, nextreq.pause();writeStream.once('drain', () => req.resume());}+ } else {+ // Non-matching file: drop bytes, but cap the total so a client+ // can't tie up the connection by sending an unbounded payload+ // under an unaccepted field name.+ droppedFileBytes += chunk.length;+ if (droppedFileBytes > DROPPED_FILE_TOTAL_CAP) {+ const err = new Error(`Unaccepted file part too large (max ${DROPPED_FILE_TOTAL_CAP} bytes)`);+ err.status = 413; err.code = 'PAYLOAD_TOO_LARGE';+ fail(err);+ return false;+ }}- // Non-matching file: drop bytes silently.} else {textCharCount += chunk.length;if (textCharCount > TEXT_FIELD_TOTAL_CAP) {@@ -278,6 +294,11 @@ function streamMultipart(req, boundary, acceptedNames, maxSize, fileFilter, nextwritePath = null;pendingFlush += 1;ws.end(() => {+ // Defensive: a malformed/malicious request can include the same+ // field name twice. Drop the prior temp file before overwriting+ // so it doesn't leak in os.tmpdir().+ const prior = fileResults[fieldName];+ if (prior?.path) unlink(prior.path).catch(() => {});fileResults[fieldName] = { path, originalname: filename, mimetype, size };pendingFlush -= 1;cb();diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 925acd437c..ace8aa87b2 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -195,28 +195,44 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {// Resolution precedence on each frame side: a fresh upload always wins over// a gallery filename so users can override a stale gallery pick by dropping// in a new file without first clearing the picker.+ //+ // Cleanup plumbing: `uploadedTempPath` (single, legacy) is RESERVED for the+ // start-frame upload — that field shape is what already-persisted jobs from+ // before this route change carry, so keeping its semantics stable means+ // those replays still clean up correctly. Every additional upload (today:+ // just `lastImage`) flows through `uploadedTempPaths` as an array. The+ // worker walks both fields when unlinking on terminal events.let sourceImagePath = null;let lastImagePath = null;- const stagedUploads = [];- if (uploads.sourceImage || uploads.lastImage) await ensureDir(PATHS.uploads);+ let uploadedTempPath = null;+ const extraUploadedTempPaths = [];+ if (uploads.sourceImage || uploads.lastImage) {+ // Ensure the durable uploads dir exists before staging. Wrapped in+ // try/catch so a permission/disk failure here still cleans up the+ // multipart temp uploads instead of leaking them in the OS temp dir.+ try {+ await ensureDir(PATHS.uploads);+ } catch (err) {+ await cleanupTempUploads();+ throw new ServerError(+ `Failed to prepare uploads directory: ${err.message}`,+ { status: 500, code: 'VIDEO_GEN_UPLOADS_DIR_FAILED' },+ );+ }+ }if (uploads.sourceImage) {sourceImagePath = await stageUploadDurable(uploads.sourceImage, 'source');- stagedUploads.push(sourceImagePath);+ uploadedTempPath = sourceImagePath;} else if (body.sourceImageFile) {sourceImagePath = resolveGalleryImage(body.sourceImageFile);}if (uploads.lastImage) {lastImagePath = await stageUploadDurable(uploads.lastImage, 'last');- stagedUploads.push(lastImagePath);+ extraUploadedTempPaths.push(lastImagePath);} else if (body.lastImageFile) {// Same path-traversal guard as the start frame.lastImagePath = resolveGalleryImage(body.lastImageFile);}- // Worker cleans up every staged temp file on terminal events. The legacy- // `uploadedTempPath` field stays single (start-frame upload, if any) so- // already-persisted jobs from before this route change still replay- // cleanly; everything else flows through the array.- const [uploadedTempPath = null, ...extraUploadedTempPaths] = stagedUploads;// Native extend (ltx2 runtime): resolve the history id to a video file// path under data/videos/ and forward it as extendFromVideoPath. Rejectdiff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex e737123096..840005354c 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -83,11 +83,17 @@ async function safeUnlinkUpload(path) {// Walks both `uploadedTempPath` (single, start-frame upload) and// `uploadedTempPaths` (array, additional staged uploads such as the FFLF// lastImage) so cleanup paths stay agnostic to which fields contributed.+// Also handles the corrupted-JSON case where `uploadedTempPaths` arrives as+// a single string (treats it as a one-entry array) — defense-in-depth so a+// hand-edited media-jobs.json still gets its staged file unlinked.async function safeUnlinkAllUploads(params) {if (!params) return;await safeUnlinkUpload(params.uploadedTempPath);- if (Array.isArray(params.uploadedTempPaths)) {- for (const p of params.uploadedTempPaths) await safeUnlinkUpload(p);+ const paths = params.uploadedTempPaths;+ if (Array.isArray(paths)) {+ for (const p of paths) await safeUnlinkUpload(p);+ } else if (typeof paths === 'string') {+ await safeUnlinkUpload(paths);}}