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 (codex): reject truncated image payloads and clamp the stored filename
[._.]/ Adam Eivy0282c33c54e4
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 07ae1b71f7..3713eaf725 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -1278,6 +1278,14 @@ export async function importFileToUploads(tempPath, originalName) {return importFileToDir(tempPath, originalName, PATHS.uploads);}+// Widest supported image signature (WebP needs 12 bytes: `RIFF….WEBP`). A payload+// shorter than this can't hold a complete header for any format we accept.+const MIN_IMAGE_BYTES = 12;++// POSIX NAME_MAX — the per-component filename limit on ext4/APFS/HFS+. A longer+// component makes the write fail with ENAMETOOLONG.+const MAX_FILENAME_BYTES = 255;+/*** Persist a base64-encoded IMAGE into `dir`, deriving the format from the bytes* rather than trusting the client: decode → size cap → magic-byte sniff → force@@ -1306,15 +1314,32 @@ export async function saveImageUpload(dir, { filename, data }, { maxBytes }) {throw new ServerError(`File exceeds maximum size of ${maxBytes / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });}+ // Floor before the sniff, because the per-format signatures are short (a JPEG is+ // 3 bytes, a GIF header 6) and would happily "detect" a truncated payload — which+ // then saves as a success and hands a consumer a path to an unreadable file. 12+ // bytes is the widest signature (WebP's RIFF….WEBP), so anything under it cannot+ // be a complete header for ANY supported format, let alone a complete image.+ if (buffer.length < MIN_IMAGE_BYTES) {+ throw new ServerError('Invalid image file - only PNG, JPEG, GIF, and WebP are supported', { status: 400, code: 'INVALID_FILE_TYPE' });+ }+const detected = detectImageFormat(buffer);if (!detected) {throw new ServerError('Invalid image file - only PNG, JPEG, GIF, and WebP are supported', { status: 400, code: 'INVALID_FILE_TYPE' });}- // The DETECTED extension wins over whatever the client claimed, so the file on- // disk can't advertise a type its bytes contradict.+ // The DETECTED extension always wins over whatever the client claimed, so the+ // file on disk can't advertise a type its bytes contradict. Strip a matching+ // extension off the base rather than appending a second one, then clamp the base+ // so `base + ext` fits NAME_MAX — a caller that prefixes the name (see+ // services/shellImageDrop.js) can otherwise push a legitimately-long client+ // filename past the limit and turn the write into an ENAMETOOLONG 500.const safeName = sanitizeFilename(filename);- const fname = safeName.toLowerCase().endsWith(detected.ext) ? safeName : `${safeName}${detected.ext}`;+ const base = safeName.toLowerCase().endsWith(detected.ext)+ ? safeName.slice(0, -detected.ext.length)+ : safeName;+ // sanitizeFilename leaves only ASCII, so slicing chars is slicing bytes.+ const fname = `${base.slice(0, MAX_FILENAME_BYTES - detected.ext.length)}${detected.ext}`;const filePath = join(dir, fname);if (!isPathInsideDir(dir, filePath)) {throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex c12360f3f6..fe29cabdf7 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';import { readFile, writeFile, rm, mkdir } from 'fs/promises';-import { mkdtempSync, rmSync, writeFileSync } from 'fs';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, readdirSync } from 'fs';import { join } from 'path';import { tmpdir, homedir } from 'os';import { createHash } from 'crypto';@@ -51,6 +51,7 @@ import {ATTACHMENT_ALLOWED_EXTENSIONS,SONGBOOK_ATTACHMENT_EXTENSIONS,saveBase64Upload,+ saveImageUpload,serveLocalFile,loadSlashdoLib,loadSlashdoFile,@@ -1492,6 +1493,80 @@ describe('detectImageFormat', () => {});});+describe('saveImageUpload (shared image upload pipeline)', () => {+ let dir;+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'save-image-test-'));+ });+ afterEach(() => {+ rmSync(dir, { recursive: true, force: true });+ });++ // Exactly MIN_IMAGE_BYTES (12) — the shortest payload the floor accepts.+ const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d]);+ const b64 = (buf) => buf.toString('base64');+ const opts = { maxBytes: 1024 };++ it('persists the bytes verbatim and reports the detected format', async () => {+ const saved = await saveImageUpload(dir, { filename: 'photo.png', data: b64(PNG) }, opts);+ expect(saved.filename).toBe('photo.png');+ expect(saved.size).toBe(12);+ expect(saved.format).toBe('png');+ expect(saved.mime).toBe('image/png');+ expect(readFileSync(saved.filePath)).toEqual(PNG);+ });++ it('rejects a payload over maxBytes with a 400 FILE_TOO_LARGE', async () => {+ await expect(saveImageUpload(dir, { filename: 'photo.png', data: b64(Buffer.alloc(2048)) }, opts))+ .rejects.toMatchObject({ status: 400, code: 'FILE_TOO_LARGE' });+ });++ it('rejects bytes with no recognized image signature', async () => {+ await expect(saveImageUpload(dir, { filename: 'photo.png', data: b64(Buffer.from('not an image!!')) }, opts))+ .rejects.toMatchObject({ status: 400, code: 'INVALID_FILE_TYPE' });+ });++ // The per-format signatures are short (JPEG is 3 bytes, GIF 6) — without an+ // explicit floor a truncated payload "detects" fine and saves as a success,+ // handing the consumer a path to an unreadable file.+ it('rejects a truncated payload whose signature alone would match', async () => {+ for (const truncated of [+ Buffer.from([0xff, 0xd8, 0xff]), // 3-byte JPEG+ Buffer.from([0x47, 0x49, 0x46, 0x38, 0x39, 0x61]), // 6-byte GIF+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), // 8-byte PNG+ ]) {+ await expect(saveImageUpload(dir, { filename: 'photo.png', data: b64(truncated) }, opts))+ .rejects.toMatchObject({ status: 400, code: 'INVALID_FILE_TYPE' });+ }+ expect(readdirSync(dir)).toHaveLength(0);+ });++ it('forces the extension to the detected format, not the claimed one', async () => {+ const saved = await saveImageUpload(dir, { filename: 'photo.jpg', data: b64(PNG) }, opts);+ expect(saved.filename).toBe('photo.jpg.png');+ });++ it('replaces a matching extension case-insensitively instead of doubling it', async () => {+ const saved = await saveImageUpload(dir, { filename: 'PHOTO.PNG', data: b64(PNG) }, opts);+ expect(saved.filename).toBe('PHOTO.png');+ });++ // A caller that prefixes the name can otherwise push a legitimately-long client+ // filename past NAME_MAX and turn the write into an ENAMETOOLONG 500.+ it('clamps the stored name to NAME_MAX, keeping the extension', async () => {+ const saved = await saveImageUpload(dir, { filename: `${'a'.repeat(300)}.png`, data: b64(PNG) }, opts);+ expect(saved.filename.length).toBe(255);+ expect(saved.filename.endsWith('.png')).toBe(true);+ expect(existsSync(saved.filePath)).toBe(true);+ });++ it('strips directory components from a traversal-shaped filename', async () => {+ const saved = await saveImageUpload(dir, { filename: '../../evil.png', data: b64(PNG) }, opts);+ expect(saved.filename).toBe('evil.png');+ expect(saved.filePath.startsWith(dir)).toBe(true);+ });+});+describe('saveBase64Upload (shared attachment upload pipeline)', () => {let dir;beforeEach(() => {