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: keep the per-item purge to one listed file, never a directory or a nested path (#3327)

[._.]/ Adam Eivy3d6ada089638
diff --git a/client/src/pages/DataManager.jsx b/client/src/pages/DataManager.jsx
index e54488a380..62197a8bcb 100644
--- a/client/src/pages/DataManager.jsx
+++ b/client/src/pages/DataManager.jsx
@@ -238,7 +238,13 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu
<td className="p-2 pr-3 text-right text-gray-500">{item.type === 'directory' ? item.fileCount?.toLocaleString() : '—'}</td>
{itemScoped && (
<td className="p-2 pr-3 text-right">
- {isConfirming(item.name) ? (
+ {item.type === 'directory' ? (
+ // Subdirectories of these categories are another
+ // feature's working state (in-flight render
+ // control dirs, scratch), not user assets — the
+ // server refuses them too.
+ <span className="text-gray-600" title="Directories here hold working files for other features and are not deletable from this page">—</span>
+ ) : isConfirming(item.name) ? (
<ConfirmButtonPair
className="justify-end"
prompt="Delete?"
diff --git a/client/src/pages/DataManager.test.jsx b/client/src/pages/DataManager.test.jsx
index a6b39f4cce..0d7c617c20 100644
--- a/client/src/pages/DataManager.test.jsx
+++ b/client/src/pages/DataManager.test.jsx
@@ -110,6 +110,22 @@ describe('DataManager per-item purge (#3327)', () => {
await waitFor(() => expect(screen.queryByText('render-0001.png')).not.toBeInTheDocument());
});
+ it('offers no delete for a directory entry — the server refuses those too', async () => {
+ getDataCategory.mockResolvedValue({
+ key: 'images',
+ items: [
+ { name: 'render-0001.png', type: 'file', size: 1200 },
+ { name: '.scratch', type: 'directory', size: 800, fileCount: 3 },
+ ],
+ });
+ render(<DataManager />);
+ await waitFor(() => expect(screen.getAllByText('Images').length).toBeGreaterThan(0));
+
+ expandRow('Images');
+ await screen.findByRole('button', { name: 'Delete render-0001.png from Images' });
+ expect(screen.queryByRole('button', { name: 'Delete .scratch from Images' })).not.toBeInTheDocument();
+ });
+
it('keeps the category-wide Purge button for category-scoped and legacy rows', async () => {
render(<DataManager />);
await waitFor(() => expect(screen.getByText('Messages')).toBeInTheDocument());
diff --git a/server/lib/README.md b/server/lib/README.md
index 4b1289c957..2fc9128eb6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -134,7 +134,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |
-| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), `assertSafeFilename(name, {extensions, subject})` (throwing basename/traversal/extension gate) plus its non-throwing twin `isSafeFilename(name, extensions)` for read-only callers that must report a bad stored name as data rather than 400 the request — both share one implementation so the gate and the verdict can't drift, JSONL append/read/write helpers, dir scans, hashes (`sha256File` streams above 512 KB; `sha256Text` is its in-memory twin for strings/Buffers), JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. Most paths/file work goes through here. The slashdo command/lib loaders live in `slashdoLoader.js`. |
+| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), `assertSafeFilename(name, {extensions, subject})` (throwing basename/traversal/extension gate) plus its non-throwing twin `isSafeFilename(name, extensions)` for read-only callers that must report a bad stored name as data rather than 400 the request — both share one implementation so the gate and the verdict can't drift, and `isTopLevelEntryName(name)` is that shared traversal half on its own, for callers that can't allowlist extensions (arbitrary user assets, directory entries) but still must refuse separators so no intermediate component is left for a symlink to redirect, JSONL append/read/write helpers, dir scans, hashes (`sha256File` streams above 512 KB; `sha256Text` is its in-memory twin for strings/Buffers), JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. Most paths/file work goes through here. The slashdo command/lib loaders live in `slashdoLoader.js`. |
| `boundedStateMap.js` | `createBoundedStateMap({ maxSize, ttlMs })` — a `Map` that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on `get`/`set` (no timers); `get` doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state. |
| `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. |
| `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index cd926bf7c6..a487156687 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -1308,15 +1308,34 @@ export function assertSafeFilename(filename, { extensions, subject = 'filename',
* `not-an-imagepng`. Pass a module constant, never a caller-supplied list.
*/
export function isSafeFilename(filename, extensions) {
- if (!filename || typeof filename !== 'string') return false;
- if (filename.includes('\0')) return false;
- if (filename === '.' || filename === '..') return false;
- if (filename.includes('/') || filename.includes('\\')) return false;
- if (basename(filename) !== filename) return false;
+ if (!isTopLevelEntryName(filename)) return false;
const lower = filename.toLowerCase();
return extensions.some((ext) => lower.endsWith(String(ext).toLowerCase()));
}
+/**
+ * `isSafeFilename`'s traversal half, without the extension gate: true when
+ * `name` addresses exactly one entry directly inside some directory.
+ *
+ * For callers that legitimately cannot allowlist extensions — an arbitrary
+ * user asset, or a directory entry — but must still refuse traversal. Naming
+ * a single entry is what makes a subsequent `join(dir, name)` safe *in the
+ * filesystem sense* and not just lexically: with no separator there is no
+ * intermediate component left for a symlink to redirect, which a
+ * `resolve`/`relative` containment check cannot see. The Data Manager's
+ * per-item purge (`purgeCategory`) is the reference caller.
+ *
+ * `isSafeFilename` is layered on top of this, so the two can never disagree
+ * about what "a single entry" means.
+ */
+export function isTopLevelEntryName(name) {
+ if (!name || typeof name !== 'string') return false;
+ if (name.includes('\0')) return false;
+ if (name === '.' || name === '..') return false;
+ if (name.includes('/') || name.includes('\\')) return false;
+ return basename(name) === name;
+}
+
/**
* True when `candidatePath` resolves to a location strictly inside `dir`.
*
diff --git a/server/lib/validation.js b/server/lib/validation.js
index b673e7afbd..f2962a6522 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -827,11 +827,19 @@ export const portsAllocateSchema = z.object({
// DELETE /api/data/:category — purge a category, or one entry inside it.
// `subPath` names a single top-level entry of the category directory; omitting
// it asks for the whole-directory wipe, which `purgeCategory` only honors for
-// `purgeScope: 'category'` entries (#3327). Traversal is still rejected in the
-// service by a path.relative containment check — this schema just refuses the
-// obviously-wrong shapes (non-string, empty, absurdly long) before that.
+// `purgeScope: 'category'` entries (#3327). `isTopLevelEntryName` in
+// `fileUtils.js` is the authoritative gate — it runs in `purgeCategory`, which
+// is the boundary a non-HTTP caller crosses too. The separator check is spelled
+// out here rather than imported so this module keeps its narrow import surface
+// (a partial mock of fileUtils in an unrelated suite would break schema
+// construction at module load).
export const dataPurgeSchema = z.object({
- subPath: z.string().min(1).max(1024).optional()
+ subPath: z.string().min(1).max(255)
+ .refine(
+ (v) => !v.includes('/') && !v.includes('\\') && v !== '.' && v !== '..',
+ 'subPath must name a single entry in the category'
+ )
+ .optional()
});
// =============================================================================
diff --git a/server/routes/dataManager.test.js b/server/routes/dataManager.test.js
index d924dd85e2..3702cdd837 100644
--- a/server/routes/dataManager.test.js
+++ b/server/routes/dataManager.test.js
@@ -48,6 +48,15 @@ describe('DELETE /api/data/:category', () => {
expect(purgeCategory).not.toHaveBeenCalled();
});
+ it.each(['sub/child.png', 'sub\\child.png', '../images/render.png', '..', '.'])(
+ 'rejects a subPath that is not a single entry: %s',
+ async (subPath) => {
+ const res = await request(makeApp()).delete('/api/data/images').send({ subPath });
+ expect(res.status).toBe(400);
+ expect(purgeCategory).not.toHaveBeenCalled();
+ }
+ );
+
// The endpoint stays reachable even when the UI hides the button, so the
// service's refusal has to surface as a 4xx rather than an opaque 500.
it('surfaces the service refusal of a category-wide purge on an item-scoped category', async () => {
diff --git a/server/services/dataManager.itemPurge.test.js b/server/services/dataManager.itemPurge.test.js
new file mode 100644
index 0000000000..7f7d846c29
--- /dev/null
+++ b/server/services/dataManager.itemPurge.test.js
@@ -0,0 +1,110 @@
+/**
+ * Behavioral cover for the Data Manager's per-item purge (issue #3327).
+ *
+ * Every case here runs against a throwaway temp root — `PATHS.data` is
+ * redirected before `dataManager.js` captures it, so nothing in this file can
+ * reach the install's real `data/` directory, which holds the only copy of the
+ * media these categories hold.
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, existsSync, symlinkSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'datamanager-purge-test-'));
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, { dataRoot: TEST_DATA_ROOT });
+});
+
+const { purgeCategory } = await import('./dataManager.js');
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+const dataPath = (...parts) => join(TEST_DATA_ROOT, ...parts);
+
+beforeEach(() => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ // `images` is item-scoped: a flat directory of assets plus one scratch dir.
+ mkdirSync(dataPath('images', '.scratch'), { recursive: true });
+ writeFileSync(dataPath('images', 'render-0001.png'), 'png');
+ writeFileSync(dataPath('images', 'render-0002.png'), 'png');
+ writeFileSync(dataPath('images', '.scratch', 'work.tmp'), 'tmp');
+ // `messages` stays category-scoped.
+ mkdirSync(dataPath('messages', 'account'), { recursive: true });
+ writeFileSync(dataPath('messages', 'index.json'), '{}');
+});
+
+describe('purgeCategory — item-scoped categories (#3327)', () => {
+ it('removes exactly the named file and leaves the rest of the category', async () => {
+ const result = await purgeCategory('images', { subPath: 'render-0001.png' });
+ expect(result).toEqual({ category: 'images', subPath: 'render-0001.png' });
+ expect(existsSync(dataPath('images', 'render-0001.png'))).toBe(false);
+ expect(existsSync(dataPath('images', 'render-0002.png'))).toBe(true);
+ });
+
+ it('refuses a directory entry — those hold other features working state', async () => {
+ await expect(purgeCategory('images', { subPath: '.scratch' })).rejects.toThrow(/only removes files/);
+ expect(existsSync(dataPath('images', '.scratch', 'work.tmp'))).toBe(true);
+ });
+
+ it('404s a subPath that does not exist instead of silently reporting success', async () => {
+ await expect(purgeCategory('images', { subPath: 'never-existed.png' })).rejects.toThrow(/Item not found/);
+ });
+
+ it('refuses a nested subPath, so only listed entries are reachable', async () => {
+ await expect(purgeCategory('images', { subPath: '.scratch/work.tmp' })).rejects.toThrow(/single entry/);
+ expect(existsSync(dataPath('images', '.scratch', 'work.tmp'))).toBe(true);
+ });
+
+ it('cannot follow an intermediate symlink out of the category', async () => {
+ mkdirSync(dataPath('elsewhere'), { recursive: true });
+ writeFileSync(dataPath('elsewhere', 'keepsake.png'), 'png');
+ symlinkSync(dataPath('elsewhere'), dataPath('images', 'link'));
+
+ // The lexical resolve/relative containment check alone would pass this —
+ // it never touches the filesystem, so it cannot see the symlink hop.
+ await expect(purgeCategory('images', { subPath: 'link/keepsake.png' })).rejects.toThrow(/single entry/);
+ expect(existsSync(dataPath('elsewhere', 'keepsake.png'))).toBe(true);
+ });
+
+ it('unlinks a symlinked entry itself without touching what it points at', async () => {
+ mkdirSync(dataPath('elsewhere'), { recursive: true });
+ writeFileSync(dataPath('elsewhere', 'keepsake.png'), 'png');
+ symlinkSync(dataPath('elsewhere', 'keepsake.png'), dataPath('images', 'alias.png'));
+
+ await purgeCategory('images', { subPath: 'alias.png' });
+ expect(existsSync(dataPath('images', 'alias.png'))).toBe(false);
+ expect(existsSync(dataPath('elsewhere', 'keepsake.png'))).toBe(true);
+ });
+
+ it('still refuses the whole-category form even though the directory exists', async () => {
+ await expect(purgeCategory('images')).rejects.toThrow(/only supports per-item purge/);
+ expect(existsSync(dataPath('images', 'render-0001.png'))).toBe(true);
+ });
+});
+
+describe('purgeCategory — category-scoped categories keep their behavior', () => {
+ it('empties the directory when no subPath is given', async () => {
+ const result = await purgeCategory('messages');
+ expect(result).toEqual({ category: 'messages', subPath: null });
+ expect(existsSync(dataPath('messages', 'index.json'))).toBe(false);
+ expect(existsSync(dataPath('messages', 'account'))).toBe(false);
+ expect(existsSync(dataPath('messages'))).toBe(true);
+ });
+
+ it('removes a named subdirectory recursively', async () => {
+ writeFileSync(dataPath('messages', 'account', 'inbox.json'), '{}');
+ await purgeCategory('messages', { subPath: 'account' });
+ expect(existsSync(dataPath('messages', 'account'))).toBe(false);
+ expect(existsSync(dataPath('messages', 'index.json'))).toBe(true);
+ });
+
+ it('still refuses a nested subPath', async () => {
+ await expect(purgeCategory('messages', { subPath: '../images/render-0001.png' })).rejects.toThrow(/single entry/);
+ expect(existsSync(dataPath('images', 'render-0001.png'))).toBe(true);
+ });
+});
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index d4c2c0a011..c1016ca35b 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -1,9 +1,9 @@
-import { readdir, stat, rm, writeFile as fsWriteFile } from 'fs/promises';
+import { readdir, stat, lstat, rm, writeFile as fsWriteFile } from 'fs/promises';
import { join, relative, resolve, isAbsolute } from 'path';
import { existsSync } from 'fs';
import { execFile } from 'child_process';
import { promisify } from 'util';
-import { PATHS, ensureDir } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, isTopLevelEntryName } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
const execFileAsync = promisify(execFile);
@@ -282,6 +282,14 @@ export async function purgeCategory(categoryKey, options = {}) {
}
if (options.subPath) {
+ // `subPath` names ONE top-level entry — exactly what the detail table
+ // lists. Refusing separators outright means no traversal segment can form
+ // and, more importantly, no *intermediate* component can be a symlink for
+ // `rm` to follow out of the category (the lexical containment check below
+ // is blind to that, since it never touches the filesystem).
+ if (!isTopLevelEntryName(options.subPath)) {
+ throw new ServerError('subPath must name a single entry in the category', { status: 400, code: 'VALIDATION_ERROR' });
+ }
const resolvedRoot = resolve(dirPath);
const resolvedTarget = resolve(join(dirPath, options.subPath));
// Boundary-aware containment check: use path.relative so a prefix like
@@ -290,7 +298,26 @@ export async function purgeCategory(categoryKey, options = {}) {
if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
throw new ServerError('Invalid subPath', { status: 400, code: 'VALIDATION_ERROR' });
}
- await rm(resolvedTarget, { recursive: true, force: true });
+ // Item-scoped categories are flat directories of assets; their only
+ // subdirectories are working state for other features (`data/videos/.detached`
+ // holds the control files of in-flight renders). A one-click recursive
+ // delete next to those on a cleanup page is a foot-gun, so an item purge
+ // removes a single file and never recurses. `lstat`, not `stat`, so a
+ // symlinked entry is judged as the link it is and simply unlinked.
+ const itemScoped = meta.purgeScope === 'items';
+ if (itemScoped) {
+ const entryStat = await lstat(resolvedTarget).catch(() => null);
+ if (!entryStat) {
+ throw new ServerError(`Item not found in "${categoryKey}"`, { status: 404, code: 'NOT_FOUND' });
+ }
+ if (entryStat.isDirectory()) {
+ throw new ServerError(
+ `"${options.subPath}" is a directory — per-item purge in "${categoryKey}" only removes files`,
+ { status: 400, code: 'ITEM_PURGE_FILE_ONLY' }
+ );
+ }
+ }
+ await rm(resolvedTarget, { recursive: !itemScoped, force: true });
console.log(`🗑️ Purged item from data/${categoryKey}`);
} else {
const entries = await readdir(dirPath).catch(() => []);