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: publish screenshot uploads via stage+rename and unique names so a failed upload never truncates a stored image (#9721)

[._.]/ Adam Eivy569d1dbfdfb0
diff --git a/server/lib/README.md b/server/lib/README.md
index 6d0732ad38..224d6b2993 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -346,7 +346,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `scaffoldSnippets.js` | Shared generated-project source snippets: `CORS_SNIPPET` provides dependency-free Express CORS middleware for the Express, PortOS, and Vite scaffold generators. |
| `failureLogging.js` | `logFailureWithStack(prefix, error, logger = console.error)` — logs `${prefix}: ${message}` plus `error.stack` as a second argument, so a fire-and-forget failure (boot init, a scheduled event handler) keeps its source location instead of collapsing to one message-only line (#6934, #7549). |
| `faultIsolatedEmitter.js` | `makeEmitterFaultIsolating(emitter)` overrides an `EventEmitter`'s `emit()` so each listener for a given event runs in its own try/catch — a throw in one listener no longer aborts dispatch to later listeners for that same call. Preserves emit order, `once` semantics (invokes `rawListeners()`, whose self-removing wrapper runs before the real listener), and the `true`/`false` had-listeners return value; leaves `'error'` events on Node's default semantics. Applied to `imageGenEvents`/`videoGenEvents` (#8931), whose multiple independent listeners (socket relay, quota accounting, waiter resolution, asset indexing) must not suppress each other. |
-| `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, `writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`, directory helpers, `parseFilesystemStats(stats)` → canonical/byte-alias metrics or `null`, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. |
+| `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, `writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `renameGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`, directory helpers, `parseFilesystemStats(stats)` → canonical/byte-alias metrics or `null`, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. |
| `familySettingsMap.js` | The merge rule every per-provider-family map in `data/settings.json` shares (plan prices, plan tiers) — `normalizeFamilyMap(raw, normalizeValue)` and `mergeFamilyMap(stored, patch, normalizeValue)`, which hold the absent-vs-present-but-empty contract in ONE place: an omitted family keeps its stored value, one sent empty is an intentional clear and is deleted. Each store supplies only its value normalizer. Pure. |
| `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |
| `portosEnv.js` | Single server-side helper for PortOS's own `.env` (`PORTOS_ENV_PATH` anchored to `installRoot` per #1947, `parseEnvContents`, `readPortosEnvValue`, `upsertPortosEnvLine` + `upsertEnvLine`), with replacer-function guard for `$`-patterns and `process.env` wins precedence; `scripts/lib/envFile.js` stays as the zero-dependency boundary copy. |
diff --git a/server/lib/fileCore.js b/server/lib/fileCore.js
index 190130a55a..b53a673dfa 100644
--- a/server/lib/fileCore.js
+++ b/server/lib/fileCore.js
@@ -308,6 +308,12 @@ export async function copyFileGuarded(src, dest, mode) {
return copyFile(src, dest, mode);
}
+/** Guarded `fs/promises.rename` — the DESTINATION is what gets replaced. */
+export async function renameGuarded(from, to) {
+ if (isVitestRunner()) (await loadGuard()).assertNotRealDataWrite(to, 'rename');
+ return rename(from, to);
+}
+
/** Guarded `fs/promises.rm`. Same signature. */
export async function rmGuarded(target, options) {
if (isVitestRunner()) (await loadGuard()).assertNotRealDataWrite(target, 'rm');
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index 73afbc2a79..0e6840939d 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -22,6 +22,7 @@ vi.mock('fs/promises', async (importOriginal) => {
mkdir: vi.fn((...args) => actual.mkdir(...args)),
readFile: vi.fn((...args) => actual.readFile(...args)),
rename: vi.fn((...args) => actual.rename(...args)),
+ writeFile: vi.fn((...args) => actual.writeFile(...args)),
readdir: vi.fn((...args) => actual.readdir(...args)),
stat: vi.fn((...args) => actual.stat(...args)),
};
@@ -1926,6 +1927,61 @@ describe('saveImageUpload (shared image upload pipeline)', () => {
expect(existsSync(saved.filePath)).toBe(true);
});
+ // #9721: the shared bucket's earlier images are referenced by task records, so
+ // a failed replacement must leave the prior bytes intact and no stage behind.
+ describe('publication failures (#9721)', () => {
+ const OLD = Buffer.concat([PNG, Buffer.from('previously stored image bytes')]);
+ const NEW = Buffer.concat([PNG, Buffer.from('replacement')]);
+
+ it('keeps the previous image intact when the write fails mid-way, then a retry succeeds', async () => {
+ writeFileSync(join(dir, 'diagram.png'), OLD);
+ const enospc = Object.assign(new Error('no space left on device'), { code: 'ENOSPC' });
+ fsPromises.writeFile.mockImplementationOnce(async (path) => {
+ await fsPromises.appendFile(path, NEW.subarray(0, 5)); // partial bytes land, then the write rejects
+ throw enospc;
+ });
+ await expect(saveImageUpload(dir, { filename: 'diagram.png', data: b64(NEW) }, { maxBytes: 4096 }))
+ .rejects.toBe(enospc);
+ expect(readFileSync(join(dir, 'diagram.png'))).toEqual(OLD);
+ expect(readdirSync(dir)).toEqual(['diagram.png']);
+
+ const saved = await saveImageUpload(dir, { filename: 'diagram.png', data: b64(NEW) }, { maxBytes: 4096 });
+ expect(readFileSync(saved.filePath)).toEqual(NEW);
+ expect(readdirSync(dir)).toEqual(['diagram.png']);
+ });
+
+ it('keeps the previous image and removes the stage when the rename fails', async () => {
+ writeFileSync(join(dir, 'diagram.png'), OLD);
+ const eio = Object.assign(new Error('io error'), { code: 'EIO' });
+ fsPromises.rename.mockImplementationOnce(async () => { throw eio; });
+ await expect(saveImageUpload(dir, { filename: 'diagram.png', data: b64(NEW) }, { maxBytes: 4096 }))
+ .rejects.toBe(eio);
+ expect(readFileSync(join(dir, 'diagram.png'))).toEqual(OLD);
+ expect(readdirSync(dir)).toEqual(['diagram.png']);
+ });
+
+ it('leaves a stage that carries the owner prefix and image extension when cleanup also fails', async () => {
+ const prefix = 'mind-11111111-2222-3333-4444-555555555555-';
+ const eio = Object.assign(new Error('io error'), { code: 'EIO' });
+ fsPromises.rename.mockImplementationOnce(async () => { throw eio; });
+ const unlinkSpy = vi.spyOn(fsPromises, 'unlink').mockRejectedValueOnce(new Error('unlink denied'));
+ await expect(saveImageUpload(dir, { filename: `${prefix}a.png`, data: b64(NEW) }, { maxBytes: 4096, stagePrefix: prefix }))
+ .rejects.toBe(eio);
+ unlinkSpy.mockRestore();
+ const [left, ...rest] = readdirSync(dir);
+ expect(rest).toEqual([]);
+ expect(left.startsWith(prefix)).toBe(true);
+ expect(left.endsWith('.png')).toBe(true);
+ });
+
+ it('stages with a bounded name so a NAME_MAX-length final name still publishes', async () => {
+ const saved = await saveImageUpload(dir, { filename: `${'a'.repeat(300)}.png`, data: b64(NEW) }, { maxBytes: 4096 });
+ expect(saved.filename.length).toBe(255);
+ expect(readFileSync(saved.filePath)).toEqual(NEW);
+ expect(readdirSync(dir)).toEqual([saved.filename]);
+ });
+ });
+
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');
diff --git a/server/lib/uploads.js b/server/lib/uploads.js
index f2f386609f..35a28dffa9 100644
--- a/server/lib/uploads.js
+++ b/server/lib/uploads.js
@@ -4,7 +4,7 @@ import { randomUUID } from 'crypto';
import { join, resolve as resolvePath } from 'path';
import { MIRRORED_MIME_TYPES } from './beeperAttachmentPaths.js';
import { ServerError } from './errorHandler.js';
-import { copyFileGuarded, ensureDir, pathExists, writeFileGuarded } from './fileCore.js';
+import { copyFileGuarded, ensureDir, pathExists, renameGuarded, unlinkGuarded, writeFileGuarded } from './fileCore.js';
import { detectImageFormat, getFileExtension, getMimeType, RISKY_MIME_TYPES, sanitizeFilename } from './mimeTypes.js';
import { PATHS } from './paths.js';
import { assertSafeFilename, isPathInsideDir } from './pathSafety.js';
@@ -62,7 +62,11 @@ const MAX_FILENAME_BYTES = 255;
* they wrote an image (they hand the file to an image-gen backend or to an agent
* that will read it), so an extension allowlist isn't enough. Naming is the
* CALLER's call — pass a name that is already unique if later uploads must not
- * overwrite this one, since `dir` is a shared bucket.
+ * overwrite this one, since `dir` is a shared bucket. The bytes are staged in a
+ * short-named sibling file and renamed into place, so a write that fails midway
+ * (ENOSPC, …) never truncates an image already stored under the final name.
+ * `stagePrefix` lets an owner keep its recovery prefix on the stage name (the
+ * Persistent Mind sweeps `mind-<attachmentId>-*` images when a cleanup fails).
*
* Throws ServerError with the status/code/message contract `routes/screenshots.js`
* established (`FILE_TOO_LARGE`, `INVALID_FILE_TYPE`, `INVALID_FILENAME` — all
@@ -71,11 +75,11 @@ const MAX_FILENAME_BYTES = 255;
* @param {string} dir - Destination directory (created if missing).
* @param {{ filename: string, data: string }} upload - Desired base name (the
* extension is replaced with the detected one) + base64 payload.
- * @param {{ maxBytes: number }} opts
+ * @param {{ maxBytes: number, stagePrefix?: string }} opts
* @returns {Promise<{ filename: string, filePath: string, size: number,
* format: string, mime: string }>}
*/
-export async function saveImageUpload(dir, { filename, data }, { maxBytes }) {
+export async function saveImageUpload(dir, { filename, data }, { maxBytes, stagePrefix = '' }) {
const buffer = Buffer.from(data, 'base64');
if (buffer.length > maxBytes) {
throw new ServerError(`File exceeds maximum size of ${maxBytes / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });
@@ -113,10 +117,22 @@ export async function saveImageUpload(dir, { filename, data }, { maxBytes }) {
}
await ensureDir(dir);
- // writeFileGuarded, not atomicWrite: the stored name is clamped to NAME_MAX
- // just above, and atomicWrite's `.<pid>.<ts>.<uuid>.tmp` suffix would push the
- // temp file past it (#6176).
- await writeFileGuarded(filePath, buffer);
+ // Stage + rename rather than atomicWrite: the stored name is clamped to
+ // NAME_MAX just above, and atomicWrite's `.<pid>.<ts>.<uuid>.tmp` suffix would
+ // push the temp file past it (#6176). The stage name is short and fixed-size
+ // whatever the final name is. Both paths are in `dir`, so rename is atomic.
+ const stagePath = join(dir, `${stagePrefix}.stage-${randomUUID().slice(0, 8)}${detected.ext}`);
+ if (!isPathInsideDir(dir, stagePath)) {
+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });
+ }
+ const published = await writeFileGuarded(stagePath, buffer)
+ .then(() => renameGuarded(stagePath, filePath))
+ .then(() => null, (error) => error);
+ if (published) {
+ // Best-effort: a stage that survives keeps its owner prefix for sweeps.
+ await unlinkGuarded(stagePath).catch(() => {});
+ throw published;
+ }
return { filename: fname, filePath, size: buffer.length, format: detected.format, mime: detected.mime };
}
diff --git a/server/routes/screenshots.js b/server/routes/screenshots.js
index 5ad00bf374..c1f9d54e95 100644
--- a/server/routes/screenshots.js
+++ b/server/routes/screenshots.js
@@ -22,11 +22,16 @@ router.post('/', asyncHandler(async (req, res) => {
}
const id = uuidv4();
+ // The server UUID always prefixes the stored name: clients (camera roll,
+ // screenshot tools) reuse names, and `SCREENSHOTS_DIR` is a shared bucket whose
+ // files are referenced by task records, so a repeat must never replace an
+ // earlier image. Sanitize BEFORE prefixing so a traversal-shaped name can't
+ // swallow the prefix.
// Shared pipeline: decode → size cap → magic-byte sniff → detected extension →
// containment guard → write. The client-supplied mimeType is deliberately
// ignored; the bytes decide the type.
const saved = await saveImageUpload(SCREENSHOTS_DIR, {
- filename: filename || `screenshot-${id}`,
+ filename: `${id}-${sanitizeFilename(filename || 'screenshot')}`,
data,
}, { maxBytes: MAX_FILE_SIZE });
diff --git a/server/routes/screenshots.test.js b/server/routes/screenshots.test.js
index 1e3ec3e678..59640d6d4e 100644
--- a/server/routes/screenshots.test.js
+++ b/server/routes/screenshots.test.js
@@ -17,6 +17,13 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {
return { ...actual, PATHS: { ...actual.PATHS, screenshots: join(root, 'screenshots') } };
});
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, writeFile: vi.fn((...args) => actual.writeFile(...args)) };
+});
+
+import { readFileSync, readdirSync } from 'fs';
+import * as fsPromises from 'fs/promises';
import { PATHS } from '../lib/fileUtils.js';
import screenshotRoutes from './screenshots.js';
@@ -46,6 +53,38 @@ describe('screenshots routes (#2518)', () => {
expect(res.body.path).toBe(`/api/screenshots/${encodeURIComponent(res.body.filename)}`);
});
+ it('stores repeated client filenames as distinct files, keeping both images', async () => {
+ const other = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0e]);
+ const first = await request(buildApp()).post('/api/screenshots').send({ data: pngBase64, filename: 'dup.png' });
+ const second = await request(buildApp()).post('/api/screenshots').send({ data: other.toString('base64'), filename: 'dup.png' });
+ expect(first.status).toBe(200);
+ expect(second.status).toBe(200);
+ expect(first.body.filename).not.toBe(second.body.filename);
+ expect(first.body.filename).toBe(`${first.body.id}-dup.png`);
+ expect(readFileSync(`${PATHS.screenshots}/${first.body.filename}`)).toEqual(Buffer.from(pngBase64, 'base64'));
+ expect(readFileSync(`${PATHS.screenshots}/${second.body.filename}`)).toEqual(other);
+ });
+
+ it('keeps a traversal-shaped name inside the bucket and prefixed with the server id', async () => {
+ const res = await request(buildApp()).post('/api/screenshots').send({ data: pngBase64, filename: '../../x.png' });
+ expect(res.status).toBe(200);
+ expect(res.body.filename).toBe(`${res.body.id}-x.png`);
+ });
+
+ it('a failed write leaves earlier uploads untouched and a retry succeeds', async () => {
+ const ok = await request(buildApp()).post('/api/screenshots').send({ data: pngBase64, filename: 'keep.png' });
+ const before = readdirSync(PATHS.screenshots).sort();
+ fsPromises.writeFile.mockImplementationOnce(async () => {
+ throw Object.assign(new Error('no space left on device'), { code: 'ENOSPC' });
+ });
+ const failed = await request(buildApp()).post('/api/screenshots').send({ data: pngBase64, filename: 'keep.png' });
+ expect(failed.status).toBe(500);
+ expect(readdirSync(PATHS.screenshots).sort()).toEqual(before);
+ expect(readFileSync(`${PATHS.screenshots}/${ok.body.filename}`)).toEqual(Buffer.from(pngBase64, 'base64'));
+ const retry = await request(buildApp()).post('/api/screenshots').send({ data: pngBase64, filename: 'keep.png' });
+ expect(retry.status).toBe(200);
+ });
+
it('rejects non-image content (magic-byte guard)', async () => {
const res = await request(buildApp())
.post('/api/screenshots')
diff --git a/server/services/persistentMindAttachments.js b/server/services/persistentMindAttachments.js
index b95d58b07e..c392e06e20 100644
--- a/server/services/persistentMindAttachments.js
+++ b/server/services/persistentMindAttachments.js
@@ -256,7 +256,7 @@ export async function createPersistentMindAttachment({ filename, data } = {}) {
const saved = await saveImageUpload(PATHS.screenshots, {
filename: `mind-${attachmentId}-${originalName}`,
data,
- }, { maxBytes: PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_BYTES }).then(
+ }, { maxBytes: PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_BYTES, stagePrefix: `mind-${attachmentId}-` }).then(
(value) => value,
async (error) => {
await removeRejectedUpload(attachmentId);