Skip to content

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

fix: prevent active sprite reference uploads (#5647)

Adam Eivy81358960e76b
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index 46c861a03a..aa2e180f15 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -63,6 +63,7 @@ import {
SONGBOOK_ATTACHMENT_EXTENSIONS,
saveBase64Upload,
saveImageUpload,
+ importFileToDir,
serveLocalFile,
watchForFile,
} from './fileUtils.js';
@@ -79,6 +80,26 @@ beforeAll(async () => {
realFsPromises = await vi.importActual('fs/promises');
});
+describe('importFileToDir', () => {
+ let dir;
+ let source;
+
+ beforeEach(async () => {
+ dir = mkdtempSync(join(tmpdir(), 'import-file-test-'));
+ source = join(dir, 'source.bin');
+ await writeFile(source, 'fixture');
+ });
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ it('rejects a persisted extension outside an explicit allowlist', async () => {
+ await expect(importFileToDir(source, 'payload.svg', join(dir, 'dest'), { extensions: ['.png'] }))
+ .rejects.toMatchObject({ status: 400, code: 'INVALID_FILE_TYPE' });
+ });
+});
+
const restoreFsMocks = () => {
for (const name of ['readFile', 'rename', 'readdir', 'mkdir', 'stat']) {
fsPromises[name].mockReset();
diff --git a/server/lib/uploads.js b/server/lib/uploads.js
index 6dd3480d03..aaa50afaa4 100644
--- a/server/lib/uploads.js
+++ b/server/lib/uploads.js
@@ -16,9 +16,16 @@ import { assertSafeFilename, isPathInsideDir } from './pathSafety.js';
* copyFile + unlink instead of rename — the source usually lives in
* `os.tmpdir()`, which may sit on a different filesystem (rename across devices
* throws EXDEV on Linux); copy works regardless. The temp unlink is best-effort
- * cleanup. Returns `{ filename, sizeBytes }`.
+ * cleanup. When `extensions` is supplied, the persisted name must use one of
+ * those extensions. A persisted extension determines the Content-Type for
+ * files that may live under a static mount, so it must never come from a
+ * client-supplied filename. Returns `{ filename, sizeBytes }`.
*/
-export async function importFileToDir(tempPath, originalName, destDir) {
+export async function importFileToDir(tempPath, originalName, destDir, { extensions } = {}) {
+ const extension = getFileExtension(originalName);
+ if (extensions && !extensions.map((item) => item.toLowerCase()).includes(extension)) {
+ throw new ServerError('Invalid file type', { status: 400, code: 'INVALID_FILE_TYPE' });
+ }
await ensureDir(destDir);
const filename = `${randomUUID().slice(0, 8)}-${sanitizeFilename(originalName)}`;
const dest = join(destDir, filename);
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index b7d59fb075..0b08bb8a0f 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -91,6 +91,11 @@ const router = Router();
const MAX_REFERENCE_UPLOAD_BYTES = 20 * 1024 * 1024;
const ACCEPTED_REFERENCE_MIME = new Set(['image/png', 'image/jpeg', 'image/webp']);
+const REFERENCE_MIME_TO_EXT = {
+ 'image/png': '.png',
+ 'image/jpeg': '.jpg',
+ 'image/webp': '.webp',
+};
/**
* Validate + resolve the `:trackId` path param to a registered track id (#3136).
@@ -289,7 +294,10 @@ router.post('/:id/reference/generate', referenceUpload, asyncHandler(async (req,
// The service moves the file on success, so the unlink is a harmless
// ENOENT there.
const file = req.files?.referenceImage;
- const upload = file ? { tempPath: file.path, originalname: file.originalname } : null;
+ const upload = file ? {
+ tempPath: file.path,
+ ext: REFERENCE_MIME_TO_EXT[(file.mimetype || '').toLowerCase()],
+ } : null;
if (upload) res.on('close', () => { unlink(upload.tempPath).catch(() => {}); });
const body = validateRequest(spriteReferenceGenerateSchema, req.body ?? {});
// A design upload seeds the identity root, which is always the turnaround
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index 8e0bdb47f7..2f0cd96a0c 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -549,12 +549,12 @@ describe('sprites routes', () => {
// Build a multipart/form-data body with one file part + text fields —
// exercises the real streamMultipart path (the fileFilter signature bug
// class is invisible to JSON-only tests).
- const buildMultipart = (boundary, { fileBytes = Buffer.from('\x89PNGfake'), mime = 'image/png', fields = {} } = {}) => {
+ const buildMultipart = (boundary, { fileBytes = Buffer.from('\x89PNGfake'), filename = 'design.png', mime = 'image/png', fields = {} } = {}) => {
const parts = [];
for (const [k, v] of Object.entries(fields)) {
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`));
}
- parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="referenceImage"; filename="design.png"\r\nContent-Type: ${mime}\r\n\r\n`));
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="referenceImage"; filename="${filename}"\r\nContent-Type: ${mime}\r\n\r\n`));
parts.push(fileBytes);
parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
return Buffer.concat(parts);
@@ -584,7 +584,7 @@ describe('sprites routes', () => {
expect(reference.startReferenceGeneration).toHaveBeenCalledWith(
'pioneer',
expect.objectContaining({ target: 'turnaround', designPrompt: 'a ranger' }),
- expect.objectContaining({ originalname: 'design.png', tempPath: expect.any(String) }),
+ expect.objectContaining({ ext: '.png', tempPath: expect.any(String) }),
);
});
@@ -626,6 +626,21 @@ describe('sprites routes', () => {
expect(reference.startReferenceGeneration).not.toHaveBeenCalled();
});
+ it('POST /:id/reference/generate derives a safe extension instead of forwarding the client filename', async () => {
+ const boundary = '----spritetest-safe-extension';
+ const res = await request(app)
+ .post('/api/sprites/pioneer/reference/generate')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(buildMultipart(boundary, { filename: 'payload.svg', fields: { target: 'turnaround' } }));
+ expect(res.status).toBe(200);
+ expect(reference.startReferenceGeneration).toHaveBeenCalledWith(
+ 'pioneer',
+ expect.objectContaining({ target: 'turnaround' }),
+ expect.objectContaining({ ext: '.png', tempPath: expect.any(String) }),
+ );
+ expect(reference.startReferenceGeneration.mock.calls[0][2]).not.toHaveProperty('originalname');
+ });
+
it('POST /:id/reference/generate rejects a non-queueable mode', async () => {
const r = await request(app).post('/api/sprites/pioneer/reference/generate')
.send({ target: 'main', mode: 'external' });
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index 3d51232279..108fa861ce 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -646,10 +646,15 @@ const lockedSeedArtifact = (manifest) => (
async function resolveSeedSource(recordId, body, upload) {
if (upload) {
// Shared temp-import (uuid-prefixed name, EXDEV-safe copy+unlink) — the
- // upload persists in the record dir as design provenance so a locked
- // candidate stays traceable to the upload that guided it.
+ // persisted extension derives from the accepted multipart MIME, never the
+ // client filename, because this directory is served as a static asset.
const uploadsDir = join(spriteDir(recordId), 'reference', 'uploads');
- const { filename } = await importFileToDir(upload.tempPath, upload.originalname || 'design-reference.png', uploadsDir);
+ const { filename } = await importFileToDir(
+ upload.tempPath,
+ `design-reference${upload.ext || '.png'}`,
+ uploadsDir,
+ { extensions: ['.png', '.jpg', '.jpeg', '.webp'] },
+ );
return { initImagePath: join(uploadsDir, filename), designReferencePath: `reference/uploads/${filename}` };
}
if (body.initImageGalleryFile) {
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
index e12f2e9cb8..de951c492a 100644
--- a/server/services/sprites/reference.test.js
+++ b/server/services/sprites/reference.test.js
@@ -209,18 +209,28 @@ describe('startReferenceGeneration', () => {
expect(manifest.designPrompt).toBe('a wiry ranger');
});
- it('persists an uploaded design reference and records it in the tag provenance', async () => {
+ it('persists an uploaded design reference with a server-derived extension and records it in the tag provenance', async () => {
const id = newId();
await createCharacter(id);
const tmp = join(TEST_ROOT, 'upload-tmp.png');
await writeCandidatePng(tmp);
- await startReferenceGeneration(id, { target: 'turnaround' }, { tempPath: tmp, originalname: 'concept.png' });
+ await startReferenceGeneration(id, { target: 'turnaround' }, { tempPath: tmp, originalname: 'concept.svg', ext: '.png' });
const call = enqueueJob.mock.calls[0][0];
- expect(call.params.spriteRef.designReferencePath).toMatch(/^reference\/uploads\/.+concept\.png$/);
+ expect(call.params.spriteRef.designReferencePath).toMatch(/^reference\/uploads\/.+design-reference\.png$/);
expect(call.params.initImagePath).toContain(join('reference', 'uploads'));
expect(call.params.initImageStrength).toBe(0.65);
});
+ it('maps an image/webp design upload to .webp regardless of the client filename', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const tmp = join(TEST_ROOT, 'upload-tmp.webp');
+ await writeCandidatePng(tmp);
+ await startReferenceGeneration(id, { target: 'turnaround' }, { tempPath: tmp, originalname: 'payload.html', ext: '.webp' });
+ expect(enqueueJob.mock.calls[0][0].params.spriteRef.designReferencePath)
+ .toMatch(/^reference\/uploads\/.+design-reference\.webp$/);
+ });
+
it('refuses the main and anchors before the turnaround is locked, and south always', async () => {
const id = newId();
await createCharacter(id);