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
refactor: route uploads.js through saveBase64Upload/serveLocalFile (#4101)
[._.]/ Adam Eivy83ee1fbeab47
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 061eb8a427..217f70b562 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -1306,8 +1306,9 @@ export async function saveImageUpload(dir, { filename, data }, { maxBytes }) {* Throws ServerError with the exact status/code/message contract the* attachment routes established (`INVALID_FILE_TYPE`, `FILE_TOO_LARGE`,* `INVALID_FILENAME` — all 400), so refactored routes keep their pinned- * responses. Consolidates `routes/attachments.js` and- * `routes/brainSongbook.js` (uploads.js has a different shape — see #4101).+ * responses. Consolidates `routes/attachments.js`, `routes/brainSongbook.js`,+ * and `routes/uploads.js` — the last keeps its own richer response shape+ * (`originalName` / `sizeFormatted` / `createdAt`) around these fields.** @param {string} dir - Destination directory (created if missing).* @param {{ filename: string, data: string }} upload - Original filename +diff --git a/server/routes/uploads.js b/server/routes/uploads.jsindex 6ad7be2d35..cad4b43c90 100644--- a/server/routes/uploads.js+++ b/server/routes/uploads.js@@ -4,24 +4,36 @@*/import { Router } from 'express';-import { writeFile, unlink, readdir, stat } from 'fs/promises';-import { existsSync } from 'fs';+import { unlink, readdir, stat } from 'fs/promises';import { join, resolve } from 'path';-import { v4 as uuidv4 } from '../lib/uuid.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { ensureDir, PATHS, RISKY_MIME_TYPES, sanitizeFilename, getFileExtension, getMimeType, isPathInsideDir } from '../lib/fileUtils.js';+import {+ pathExists, PATHS, sanitizeFilename, getFileExtension, getMimeType,+ EXTENSION_MIME_MAP, isPathInsideDir, saveBase64Upload, serveLocalFile,+} from '../lib/fileUtils.js';import { MAX_BASE64_UPLOAD_BYTES } from '../lib/uploadLimits.js';const UPLOADS_DIR = PATHS.uploads;const router = Router();+// This is the GENERIC upload bucket (recordings, gallery videos, reference+// audio, arbitrary drops from the Uploads page), so it allows every extension+// the shared MIME map knows rather than a route-specific subset like+// ATTACHMENT_ALLOWED_EXTENSIONS / SONGBOOK_ATTACHMENT_EXTENSIONS. Derived from+// the map instead of a second literal so the two can never drift.+const UPLOAD_ALLOWED_EXTENSIONS = new Set(Object.keys(EXTENSION_MIME_MAP));+// Bounded by the JSON body limit, not by any uploads-specific rule — see// lib/uploadLimits.js.const MAX_FILE_SIZE = MAX_BASE64_UPLOAD_BYTES;/**- * Format file size for display+ * Format file size for display. Deliberately NOT lib/fileUtils.js's+ * `formatBytes` — that one rounds KB to whole units ("1 KB"), while the+ * `sizeFormatted` / `freedSpaceFormatted` fields this route has always+ * returned carry one decimal ("1.0 KB"), and the Uploads page renders them+ * verbatim.*/function formatSize(bytes) {if (bytes < 1024) return `${bytes} B`;@@ -42,50 +54,30 @@ router.post('/', asyncHandler(async (req, res) => {throw new ServerError('filename is required', { status: 400, code: 'VALIDATION_ERROR' });}- // Decode base64 and validate size- const buffer = Buffer.from(data, 'base64');- if (buffer.length > MAX_FILE_SIZE) {- throw new ServerError(`File exceeds maximum size of ${MAX_FILE_SIZE / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });- }-- // Ensure uploads directory exists- if (!existsSync(UPLOADS_DIR)) {- await ensureDir(UPLOADS_DIR);- }-- const id = uuidv4();- const safeName = sanitizeFilename(filename);- const ext = getFileExtension(safeName);- // Create unique filename with UUID prefix to avoid collisions- const fname = `${id.slice(0, 8)}-${safeName}`;- const filepath = join(UPLOADS_DIR, fname);-- // Double-check path is within uploads directory (defense in depth)- if (!isPathInsideDir(UPLOADS_DIR, filepath)) {- throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });- }-- await writeFile(filepath, buffer);-- const mimeType = getMimeType(ext);+ // Shared pipeline: allowlist → decode → size cap → `<uuid8>-name` → write.+ const saved = await saveBase64Upload(UPLOADS_DIR, { filename, data }, {+ allowedExtensions: UPLOAD_ALLOWED_EXTENSIONS,+ maxBytes: MAX_FILE_SIZE,+ });- console.log(`📤 File uploaded: ${fname} (${formatSize(buffer.length)}, ${mimeType})`);+ console.log(`📤 File uploaded: ${saved.filename} (${formatSize(saved.size)}, ${saved.mime})`);res.json({- id,- filename: fname,+ id: saved.id,+ filename: saved.filename,originalName: filename,- path: `/api/uploads/${encodeURIComponent(fname)}`,- size: buffer.length,- sizeFormatted: formatSize(buffer.length),- mimeType,+ // API-relative URL only — never the absolute FS path (leaks install layout).+ path: `/api/uploads/${encodeURIComponent(saved.filename)}`,+ size: saved.size,+ sizeFormatted: formatSize(saved.size),+ mimeType: saved.mime,createdAt: new Date().toISOString()});}));// GET /api/uploads - List all uploadsrouter.get('/', asyncHandler(async (req, res) => {- if (!existsSync(UPLOADS_DIR)) {+ if (!(await pathExists(UPLOADS_DIR))) {return res.json({ uploads: [], totalSize: 0, totalSizeFormatted: '0 B' });}@@ -100,6 +92,7 @@ router.get('/', asyncHandler(async (req, res) => {return {filename,+ // API-relative URL only — never the absolute FS path (leaks install layout).path: `/api/uploads/${encodeURIComponent(filename)}`,size: stats.size,sizeFormatted: formatSize(stats.size),@@ -122,27 +115,11 @@ router.get('/', asyncHandler(async (req, res) => {// GET /api/uploads/:filename - Serve a filerouter.get('/:filename', asyncHandler(async (req, res) => {- const { filename } = req.params;- const safeFilename = sanitizeFilename(filename);- const filepath = resolve(UPLOADS_DIR, safeFilename);-- if (!isPathInsideDir(UPLOADS_DIR, filepath)) {- throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });- }-- if (!existsSync(filepath)) {- throw new ServerError('File not found', { status: 404, code: 'NOT_FOUND' });- }-- const ext = getFileExtension(safeFilename);- const mimeType = getMimeType(ext);-- res.set('X-Content-Type-Options', 'nosniff');- if (RISKY_MIME_TYPES.has(mimeType)) {- res.set('Content-Disposition', `attachment; filename="${safeFilename}"`);- }-- res.type(mimeType).sendFile(filepath);+ // Shared pipeline: sanitize → containment guard → existence → nosniff ++ // attachment disposition for risky MIME types → sendFile.+ await serveLocalFile(res, UPLOADS_DIR, req.params.filename, {+ missingError: { message: 'File not found', code: 'NOT_FOUND' },+ });}));// DELETE /api/uploads/:filename - Delete a file@@ -155,7 +132,7 @@ router.delete('/:filename', asyncHandler(async (req, res) => {throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });}- if (!existsSync(filepath)) {+ if (!(await pathExists(filepath))) {throw new ServerError('File not found', { status: 404, code: 'NOT_FOUND' });}@@ -175,7 +152,7 @@ router.delete('/', asyncHandler(async (req, res) => {throw new ServerError('Add ?confirm=true to delete all uploads', { status: 400, code: 'CONFIRMATION_REQUIRED' });}- if (!existsSync(UPLOADS_DIR)) {+ if (!(await pathExists(UPLOADS_DIR))) {return res.json({ success: true, deleted: 0, freedSpace: 0 });}diff --git a/server/routes/uploads.test.js b/server/routes/uploads.test.jsnew file mode 100644index 0000000000..1998aea4a6--- /dev/null+++ b/server/routes/uploads.test.js@@ -0,0 +1,195 @@+import { describe, it, expect, vi, afterAll } from 'vitest';+import express from 'express';+import { rmSync, readFileSync } from 'fs';+import { join, dirname } from 'path';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Point the uploads root at a throwaway temp dir but keep every real helper —+// this suite is here to prove the shared saveBase64Upload / serveLocalFile+// pipeline still produces uploads.js's OWN response shape (#4101), so mocking+// those helpers out would defeat the point.+vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ const { mkdtempSync } = await import('fs');+ const { tmpdir } = await import('os');+ const { join: joinPath } = await import('path');+ const root = mkdtempSync(joinPath(tmpdir(), 'portos-uploads-'));+ return { ...actual, PATHS: { ...actual.PATHS, uploads: joinPath(root, 'uploads') } };+});++import { PATHS, EXTENSION_MIME_MAP } from '../lib/fileUtils.js';+import uploadRoutes from './uploads.js';++const buildApp = () => {+ const app = express();+ app.use(express.json({ limit: '20mb' }));+ app.use('/api/uploads', uploadRoutes);+ app.use(errorMiddleware);+ return app;+};++const post = (app, filename, body = 'hello uploads') =>+ request(app).post('/api/uploads').send({ data: Buffer.from(body).toString('base64'), filename });++describe('uploads routes (#4101)', () => {+ afterAll(() => rmSync(dirname(PATHS.uploads), { recursive: true, force: true }));++ it('POST returns the full uploads response shape, not the attachments one', async () => {+ const app = buildApp();+ const before = Date.now();+ const res = await post(app, 'my notes.txt', 'hello uploads');++ expect(res.status).toBe(200);+ // Exact key set — the Uploads page and the gallery picker read these.+ expect(Object.keys(res.body).sort()).toEqual([+ 'createdAt', 'filename', 'id', 'mimeType', 'originalName', 'path', 'size', 'sizeFormatted',+ ]);+ expect(res.body.id).toMatch(/^[0-9a-f-]{36}$/);+ // `<uuid8>-<sanitized-name>`: the space in the original name is sanitized.+ expect(res.body.filename).toBe(`${res.body.id.slice(0, 8)}-my_notes.txt`);+ expect(res.body.originalName).toBe('my notes.txt');+ expect(res.body.path).toBe(`/api/uploads/${encodeURIComponent(res.body.filename)}`);+ expect(res.body.path).not.toContain(PATHS.uploads);+ expect(res.body.size).toBe(13);+ expect(res.body.sizeFormatted).toBe('13 B');+ expect(res.body.mimeType).toBe('text/plain');+ expect(Date.parse(res.body.createdAt)).toBeGreaterThanOrEqual(before);++ // The bytes actually landed under the uploads dir with that name.+ expect(readFileSync(join(PATHS.uploads, res.body.filename), 'utf8')).toBe('hello uploads');+ });++ it('formats KB with one decimal (formatBytes would say "1 KB")', async () => {+ const res = await post(buildApp(), 'padded.txt', 'x'.repeat(1536));+ expect(res.status).toBe(200);+ expect(res.body.size).toBe(1536);+ expect(res.body.sizeFormatted).toBe('1.5 KB');+ });++ it('accepts every extension in the shared MIME map, including audio/video/archives', async () => {+ const app = buildApp();+ for (const ext of ['.mp4', '.wav', '.mid', '.zip', '.ico', '.env']) {+ // These are exactly the families ATTACHMENT_ALLOWED_EXTENSIONS excludes,+ // so this fails the moment someone swaps in the narrow attachment set.+ const res = await post(app, `clip${ext}`);+ expect(res.status, `${ext} should be accepted`).toBe(200);+ expect(res.body.mimeType).toBe(EXTENSION_MIME_MAP[ext]);+ }+ });++ it('rejects an extension outside the MIME map with INVALID_FILE_TYPE', async () => {+ const res = await post(buildApp(), 'payload.exe');+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('INVALID_FILE_TYPE');+ });++ it('rejects a filename with no extension at all', async () => {+ const res = await post(buildApp(), 'README');+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('INVALID_FILE_TYPE');+ });++ it('rejects a missing data / filename with VALIDATION_ERROR', async () => {+ const app = buildApp();+ const noData = await request(app).post('/api/uploads').send({ filename: 'a.txt' });+ expect(noData.status).toBe(400);+ expect(noData.body.code).toBe('VALIDATION_ERROR');++ const noName = await request(app).post('/api/uploads').send({ data: 'aGk=' });+ expect(noName.status).toBe(400);+ expect(noName.body.code).toBe('VALIDATION_ERROR');+ });++ it('GET :filename serves the bytes with nosniff and no attachment disposition for safe types', async () => {+ const app = buildApp();+ const created = await post(app, 'served.txt', 'served body');++ const res = await request(app).get(`/api/uploads/${encodeURIComponent(created.body.filename)}`);+ expect(res.status).toBe(200);+ expect(res.headers['x-content-type-options']).toBe('nosniff');+ expect(res.headers['content-type']).toContain('text/plain');+ expect(res.headers['content-disposition']).toBeUndefined();+ });++ it('GET :filename forces an attachment disposition for risky types (HTML)', async () => {+ const app = buildApp();+ const created = await post(app, 'page.html', '<b>hi</b>');++ const res = await request(app).get(`/api/uploads/${encodeURIComponent(created.body.filename)}`);+ expect(res.status).toBe(200);+ expect(res.headers['x-content-type-options']).toBe('nosniff');+ expect(res.headers['content-disposition']).toBe(`attachment; filename="${created.body.filename}"`);+ });++ it('GET :filename 404s with this route\'s own message, not the attachment default', async () => {+ const res = await request(buildApp()).get('/api/uploads/nope.txt');+ expect(res.status).toBe(404);+ expect(res.body.code).toBe('NOT_FOUND');+ expect(res.body.error).toBe('File not found');+ });++ it('GET list returns API-relative paths plus the formatted totals', async () => {+ const app = buildApp();+ const created = await post(app, 'listed.txt', 'listed body');++ const res = await request(app).get('/api/uploads');+ expect(res.status).toBe(200);+ expect(res.body.count).toBe(res.body.uploads.length);+ expect(res.body.totalSize).toBe(res.body.uploads.reduce((sum, up) => sum + up.size, 0));++ const entry = res.body.uploads.find(up => up.filename === created.body.filename);+ expect(entry).toBeDefined();+ expect(Object.keys(entry).sort()).toEqual([+ 'createdAt', 'filename', 'mimeType', 'modifiedAt', 'path', 'size', 'sizeFormatted',+ ]);+ expect(entry.size).toBe(11);+ expect(entry.sizeFormatted).toBe('11 B');+ expect(entry.mimeType).toBe('text/plain');+ for (const up of res.body.uploads) {+ expect(up.path).toBe(`/api/uploads/${encodeURIComponent(up.filename)}`);+ expect(up.path).not.toContain(PATHS.uploads);+ }+ });++ it('DELETE :filename returns the deleted size and 404s the second time', async () => {+ const app = buildApp();+ const created = await post(app, 'doomed.txt', 'doomed');++ const res = await request(app).delete(`/api/uploads/${encodeURIComponent(created.body.filename)}`);+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ success: true, filename: created.body.filename, size: 6 });++ const again = await request(app).delete(`/api/uploads/${encodeURIComponent(created.body.filename)}`);+ expect(again.status).toBe(404);+ expect(again.body.code).toBe('NOT_FOUND');+ });++ // Runs last on purpose: it empties the shared temp uploads dir.+ it('DELETE all requires ?confirm=true and reports freed space', async () => {+ const app = buildApp();++ const unconfirmed = await request(app).delete('/api/uploads');+ expect(unconfirmed.status).toBe(400);+ expect(unconfirmed.body.code).toBe('CONFIRMATION_REQUIRED');+ // The 400 must not have deleted anything.+ expect((await request(app).get('/api/uploads')).body.count).toBeGreaterThan(0);++ // Clear whatever earlier cases left behind, then measure one known file.+ await request(app).delete('/api/uploads?confirm=true');+ await post(app, 'sweep.txt', 'sweep me');++ const res = await request(app).delete('/api/uploads?confirm=true');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({+ success: true,+ deleted: 1,+ freedSpace: 8,+ freedSpaceFormatted: '8 B',+ });++ const after = await request(app).get('/api/uploads');+ expect(after.body.uploads).toEqual([]);+ expect(after.body.totalSizeFormatted).toBe('0 B');+ });+});