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

refactor(fileUtils): promote resolveGalleryImage helper, dedupe 5 sites

[._.]/ Adam Eivyd3244c1ec320
diff --git a/PLAN.md b/PLAN.md
index c5f646326a..48ef14bbbf 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -93,7 +93,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
### Code quality / dedup (from `/simplify` passes)
-- [ ] **Promote `resolveGalleryImage` to `server/lib/fileUtils.js`.** Basename + `resolvePath` + `startsWith(imagesRoot)` security check reimplemented in 5 places (videoGen, imageGen, visualStages, sceneRunner, imageGen/local). Pick up the `isFile()` symlink-following defense the four non-videoGen sites are missing.
- [ ] **Route-level tests for proof/final `target` + `useProofAsBase`.** Three test cases on `comicPageRenderSchema` + `comicCoverRenderSchema`.
- [ ] **Extract `useSwipeNav` hook + `lib/clipboard.js`.** `MediaLightbox` swipe nav; clipboard inlined across 8+ call sites. Clipboard can move now.
- [ ] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`.** Reconcile `Drawer`'s flat Esc handler with the lightbox's layered Escape cascade.
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index dcb9c103e3..4fd9bfa52f 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -5,11 +5,11 @@
*/
import { mkdir, readFile, writeFile, rename, unlink } from 'fs/promises';
-import { existsSync } from 'fs';
+import { existsSync, statSync } from 'fs';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { randomUUID } from 'crypto';
-import { join, dirname, basename } from 'path';
+import { join, dirname, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';
import { fileURLToPath } from 'url';
import { homedir } from 'os';
import { ServerError } from './errorHandler.js';
@@ -595,6 +595,52 @@ export function assertSafeFilename(filename, { extensions, subject = 'filename',
}
}
+/**
+ * Resolve a user-supplied gallery image filename to an absolute path under
+ * `PATHS.images`. Returns `null` on any failure so callers can decide whether
+ * to throw, log-and-skip, or substitute a fallback.
+ *
+ * Defense in depth:
+ * 1. `basename()` strips dirs (so `../../etc/passwd` → `passwd`).
+ * 2. Reject `.`/`..`/empty basenames outright.
+ * 3. `resolve` + `startsWith(imagesRoot)` so unicode tricks can't escape.
+ * 4. When `mustExist`, `statSync({ throwIfNoEntry: false }).isFile()` rejects
+ * directories (the images root itself would otherwise pass an existsSync
+ * check and flow into ffmpeg as an "image path" where it'd fail in
+ * confusing ways). Note: `statSync` follows symlinks, so a symlink inside
+ * `data/images/` pointing to a regular file outside the gallery still
+ * passes. PortOS is single-user (see CLAUDE.md "Security Model") so we
+ * accept that — if you need to reject symlinks too, use `lstatSync`.
+ *
+ * Pass `{ mustExist: false }` for code paths that intentionally skip the
+ * existence check (e.g. when the path is resolved at request time but read
+ * later — TOCTOU between resolve and use isn't worth the extra syscall, and
+ * the downstream renderer surfaces a clear error if the file vanished).
+ *
+ * @param {string} name - Filename to resolve (basenamed internally)
+ * @param {object} [opts]
+ * @param {boolean} [opts.mustExist=true] - Require the resolved path to be an existing regular file
+ * @returns {string|null} Absolute path inside PATHS.images, or null
+ */
+export function resolveGalleryImage(name, { mustExist = true } = {}) {
+ if (typeof name !== 'string' || !name) return null;
+ const safe = basename(name);
+ if (!safe || safe === '.' || safe === '..') return null;
+ const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;
+ const localPath = resolvePath(join(PATHS.images, safe));
+ if (!localPath.startsWith(imagesRoot)) return null;
+ if (!mustExist) return localPath;
+ // throwIfNoEntry:false swallows ENOENT but not EACCES / transient I/O —
+ // treat those as "not a valid gallery reference" too rather than bubbling
+ // a 500 out of the route layer.
+ try {
+ const stat = statSync(localPath, { throwIfNoEntry: false });
+ return stat?.isFile() ? localPath : null;
+ } catch {
+ return null;
+ }
+}
+
// Size in bytes of every file under `path`. Shells out to `du -sk` (or
// PowerShell on Windows) — orders of magnitude faster than walking with
// node's recursive readdir on large trees (hundreds of GB / 200k+ files).
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 734ec7f94b..5e999d8362 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -11,7 +11,6 @@
import { Router } from 'express';
import { z } from 'zod';
-import { existsSync } from 'fs';
import { copyFile, unlink } from 'fs/promises';
import { randomUUID } from 'crypto';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
@@ -30,8 +29,8 @@ import {
isExternallyManaged, createVenv, isAllowedPython, pipNameFor,
resolveFlux2Python, FLUX2_VENV_DEFAULT, installFlux2Venv, isFlux2VenvHealthy,
} from '../lib/pythonSetup.js';
-import { PATHS, ensureDir } from '../lib/fileUtils.js';
-import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'node:path';
+import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';
+import { join } from 'node:path';
import { readFile, writeFile } from 'fs/promises';
import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
import { cleanImageBuffer, CLEAN_LEVELS } from './imageClean.js';
@@ -146,10 +145,8 @@ router.post('/generate', initImageUpload, asyncHandler(async (req, res) => {
await copyFile(req.file.path, initImagePath);
uploadedInitTempPath = req.file.path;
} else if (data.initImageFile) {
- const candidate = join(PATHS.images, basename(data.initImageFile));
- const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;
- const resolved = resolvePath(candidate);
- if (!resolved.startsWith(imagesRoot) || !existsSync(resolved)) {
+ const resolved = resolveGalleryImage(data.initImageFile);
+ if (!resolved) {
throw new ServerError('Init image not found in gallery', { status: 400, code: 'INIT_IMAGE_NOT_FOUND' });
}
initImagePath = resolved;
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 36fb14ac9d..9bb7e51715 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -7,14 +7,14 @@
*/
import { Router } from 'express';
-import { existsSync, statSync } from 'fs';
+import { existsSync } from 'fs';
import { copyFile, unlink } from 'fs/promises';
import { randomUUID } from 'crypto';
-import { join, basename, resolve as resolvePath, sep as PATH_SEP, extname } from 'path';
+import { join, extname } from 'path';
import { z } from 'zod';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
import { uploadFields } from '../lib/multipart.js';
-import { PATHS, ensureDir } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';
import { safeUnder } from '../lib/ffmpeg.js';
import { getSettings } from '../services/settings.js';
import {
@@ -155,31 +155,6 @@ router.get('/models', (_req, res) => {
res.json(listVideoModels());
});
-// Path-traversal guard: basename() strips dirs, then resolve+prefix-check
-// against PATHS.images so a unicode trick can't escape data/images. Also
-// reject `.`/`..`/empty basenames and require the resolved entry to be a
-// regular file — otherwise the images-root directory itself would resolve
-// (existsSync is true for dirs) and flow into ffmpeg as an "image path"
-// where it'd fail in confusing ways.
-//
-// Wrap statSync in try/catch (one of the few "strictly necessary" uses):
-// throwIfNoEntry: false silences ENOENT but not EACCES/permissions or
-// transient I/O errors — those should be treated as "not a valid gallery
-// reference" and produce a clean validation null, not bubble up as a 500.
-const resolveGalleryImage = (name) => {
- const safe = basename(name);
- if (!safe || safe === '.' || safe === '..') return null;
- const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;
- const localPath = resolvePath(join(PATHS.images, safe));
- if (!localPath.startsWith(imagesRoot) || !existsSync(localPath)) return null;
- try {
- const stat = statSync(localPath, { throwIfNoEntry: false });
- return stat?.isFile() ? localPath : null;
- } catch {
- return null;
- }
-};
-
router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
// Pre-enqueue cleanup hook: every throw path below MUST drop ALL multipart
// temp uploads (the parser wrote them before this handler ran). Without
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 36a69bd55b..3dc4e9c503 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -62,14 +62,21 @@ vi.mock('../lib/fileUtils.js', () => ({
// Route awaits ensureDir before staging the upload; no-op for tests since
// we mock copyFile too.
ensureDir: vi.fn(async () => {}),
+ // The route resolves user-supplied basenames through this helper before
+ // handing them to the renderer. Mirror the real helper's basename-strip
+ // + dot-segment rejection so the "strips path-traversal" test below
+ // genuinely exercises the documented behavior (otherwise the mock would
+ // happily forward `../../etc/passwd` through unchanged).
+ resolveGalleryImage: vi.fn((name) => {
+ if (typeof name !== 'string' || !name) return null;
+ const safe = name.split(/[/\\]/).pop();
+ if (!safe || safe === '.' || safe === '..') return null;
+ return `/mock/images/${safe}`;
+ }),
}));
vi.mock('fs', () => ({
existsSync: vi.fn(() => true),
- // statSync gates resolveGalleryImage onto regular-file checks — the route
- // rejects directories, so the mock has to look like a file for the
- // gallery-image plumbing tests to pass.
- statSync: vi.fn(() => ({ isFile: () => true })),
}));
vi.mock('fs/promises', () => ({
unlink: vi.fn(async () => {}),
@@ -210,12 +217,13 @@ describe('videoGen routes', () => {
// Documented-safe behavior: `basename()` strips dirs so the resolved
// path is `/mock/images/passwd` (under PATHS.images). The route does
// NOT 400 — it just consumes whatever's safely under the images root.
- // What this test really locks in: the request succeeds + the route
- // never enqueues a job that points outside PATHS.images.
expect(r.status).toBe(200);
expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
kind: 'video',
- params: expect.objectContaining({ prompt: 'a cat' }),
+ params: expect.objectContaining({
+ prompt: 'a cat',
+ sourceImagePath: '/mock/images/passwd',
+ }),
}));
});
diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.js
index 99e8da97c9..e4a6e9f4b4 100644
--- a/server/services/creativeDirector/sceneRunner.js
+++ b/server/services/creativeDirector/sceneRunner.js
@@ -28,9 +28,8 @@
* isolated anyway.
*/
-import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';
-import { existsSync } from 'fs';
-import { PATHS } from '../../lib/fileUtils.js';
+import { join } from 'path';
+import { PATHS, resolveGalleryImage } from '../../lib/fileUtils.js';
import { verifyVideoPlayable } from '../../lib/ffmpeg.js';
import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';
import { extractLastFrame, sampleEvaluationFrames } from '../videoGen/local.js';
@@ -135,29 +134,9 @@ export async function runSceneRender(project, scene) {
}
}
- // Resolve sourceImageFile to an absolute path if it's a basename in the
- // gallery. Two-layer guard:
- // 1. basename() strips any path segments (so `../../etc/passwd` →
- // `passwd`); reject `.`/`..` outright.
- // 2. resolve + prefix-check against the images root so a unicode trick
- // can't escape PATHS.images.
- // Without these, `sourceImageFile: '..'` from a malicious / mistaken
- // payload could resolve to PATHS.images's parent and feed an arbitrary
- // local path into the renderer.
- let sourceImagePath = null;
- if (sourceImageFile) {
- const safe = basename(sourceImageFile);
- if (!safe || safe === '.' || safe === '..') {
- console.log(`⚠️ CD scene ${scene.sceneId} sourceImageFile rejected (dot segment): ${sourceImageFile}`);
- } else {
- const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;
- const localPath = resolvePath(join(PATHS.images, safe));
- if (localPath.startsWith(imagesRoot) && existsSync(localPath)) {
- sourceImagePath = localPath;
- } else {
- console.log(`⚠️ CD scene ${scene.sceneId} sourceImageFile not found on disk: ${sourceImageFile}`);
- }
- }
+ const sourceImagePath = sourceImageFile ? resolveGalleryImage(sourceImageFile) : null;
+ if (sourceImageFile && !sourceImagePath) {
+ console.log(`⚠️ CD scene ${scene.sceneId} sourceImageFile rejected or missing on disk: ${sourceImageFile}`);
}
// If the continuation branch above produced a sourceImageFile but the
// path-resolution step just dropped it (file missing, dot-segment, or
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index b5661a0a81..e520bf88f0 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -18,7 +18,7 @@ import { existsSync, watch as fsWatch } from 'fs';
import { join, dirname, resolve as resolvePath, sep as PATH_SEP, basename } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
-import { assertSafeFilename, ensureDir, PATHS, safeJSONParse } from '../../lib/fileUtils.js';
+import { assertSafeFilename, ensureDir, PATHS, safeJSONParse, resolveGalleryImage } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
@@ -267,17 +267,12 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
// what the new client API uses for remix. Keep `loraPaths` populated too
// so older code paths reading the sidecar don't break.
const validLoraFilenames = validLoras.map((p) => basename(p));
- // i2i: validate the init image path stays under PATHS.images so a malicious
- // payload (or a stale absolute path from an old sidecar) can't make mflux
- // read arbitrary files. If the caller passes a basename, the route layer
- // already resolved it to PATHS.images/<basename>; this is a defense-in-depth
- // check here too.
- let validInitImagePath = null;
- if (initImagePath && typeof initImagePath === 'string') {
- const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;
- const resolved = resolvePath(initImagePath);
- if (resolved.startsWith(imagesRoot) && existsSync(resolved)) validInitImagePath = resolved;
- }
+ // i2i: defense in depth — the route already validated a fresh request,
+ // but an old sidecar replay can carry a stale absolute path outside the
+ // gallery. Re-anchor through resolveGalleryImage before handing to mflux.
+ const validInitImagePath = (initImagePath && typeof initImagePath === 'string')
+ ? resolveGalleryImage(initImagePath)
+ : null;
const validInitImageStrength = validInitImagePath && initImageStrength != null
? Math.max(0, Math.min(1, Number(initImageStrength)))
: null;
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
index 362dfd4999..faa85f6783 100644
--- a/server/services/pipeline/visualStages.js
+++ b/server/services/pipeline/visualStages.js
@@ -23,12 +23,11 @@
* path drives the Creative Director scene runner end-to-end.
*/
-import { basename, join, resolve as resolvePath, sep as PATH_SEP } from 'node:path';
import { enqueueJob } from '../mediaJobQueue/index.js';
import { getSettings } from '../settings.js';
import { getSeries } from './series.js';
import { getIssue, updateStage, VISUAL_STAGE_IDS } from './issues.js';
-import { PATHS } from '../../lib/fileUtils.js';
+import { resolveGalleryImage } from '../../lib/fileUtils.js';
import { buildComicPagesOwner, buildSeasonCoverOwner, buildStoryboardsShotOwner } from './owners.js';
import { getUniverse, joinInfluenceList } from '../universeBuilder.js';
import { ServerError } from '../../lib/errorHandler.js';
@@ -113,10 +112,10 @@ export { buildRenderSlot } from '../../lib/renderSlot.js';
const PROOF_AS_BASE_DEFAULT_STRENGTH = 0.25;
// Resolve a stored proof filename (e.g. "abc123.png") to an absolute path
-// under PATHS.images, enforcing the gallery prefix. Skips existsSync — the
-// downstream image-gen runner reads the path and will surface a clear error
-// if the file vanished between enqueue and exec; an existsSync here would
-// add a TOCTOU race for no real benefit.
+// under PATHS.images, enforcing the gallery prefix. `mustExist:false` skips
+// the existsSync check — the downstream image-gen runner reads the path and
+// will surface a clear error if the file vanished between enqueue and exec;
+// an existsSync here would add a TOCTOU race for no real benefit.
const resolveProofInitImage = (proofImage, label) => {
const name = proofImage?.filename;
if (typeof name !== 'string' || !name) {
@@ -125,10 +124,8 @@ const resolveProofInitImage = (proofImage, label) => {
{ status: 400, code: 'PIPELINE_COMIC_PROOF_MISSING' },
);
}
- const candidate = join(PATHS.images, basename(name));
- const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;
- const resolved = resolvePath(candidate);
- if (!resolved.startsWith(imagesRoot)) {
+ const resolved = resolveGalleryImage(name, { mustExist: false });
+ if (!resolved) {
throw new ServerError(
`Proof image path escaped the gallery for ${label}: ${name}`,
{ status: 400, code: 'PIPELINE_COMIC_PROOF_NOT_FOUND' },