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
fix: harden subdirFilter and deleteBackup path validation (#1822)
[._.]/ Adam Eivy0eea069ad21b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5ca9cda125..7b08fcdecf 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,6 @@## Security+- **Backup restore/delete path validation hardened** — `subdirFilter` on `POST /api/backup/restore` was an unconstrained string interpolated into an rsync `--include=${subdirFilter}/***` arg, so `*` could override the filter chain (restoring everything over live data) and `../foo` could traverse out of the snapshot subdir; it now validates against a relative path pattern that rejects wildcard, `..`, and absolute-path segments, with a mirrored defense-in-depth guard in `restoreSnapshot` for non-route callers. `deleteBackup` previously validated `filename.replace(/[.]/g,'')` (so the real dotted filename was never checked, leaving only the `startsWith(backupDir)` guard) — it now validates the raw filename directly and explicitly rejects `..`. (#1822)- **Settings API no longer leaks third-party API tokens** — `GET` and `PUT /api/settings` redacted only the top-level `secrets` key, so `imageGen.hfToken` (HuggingFace) and `civitai.apiKey` were returned in full on both initial load and after any save. Both responses now run through a single sanitizer that strips those tokens (sibling config preserved), matching how the Settings UI already reads only token *presence* from the dedicated `/image-gen/setup/hf-token-status` and `/loras/auth/civitai` status routes. On-disk values are untouched. (#1821)- **Vision-test endpoint no longer reads arbitrary files** — `POST /api/providers/:id/test-vision` took `imagePath` straight from the request body, so a `../` traversal or absolute path could have any readable file base64-encoded and forwarded to the configured external vision provider. The image loader now allowlists `imagePath` to a real image basename under `data/screenshots` (via the canonical `resolveScreenshot` path resolver), rejecting traversal and absolute-path escapes before any file is read or forwarded. (#1820)diff --git a/server/lib/validation.js b/server/lib/validation.jsindex c707bbd3ec..8abb4d78d2 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -824,9 +824,20 @@ export const apiAccessSettingsSchema = z.object({sdapi: apiAccessEntrySchema.optional(),}).strict();+// subdirFilter is interpolated into an rsync `--include=${subdirFilter}/***` arg+// (rsync runs shell:false, so this is not shell injection — but `*` would expand+// to `--include=*/***` and defeat the filter chain, and `../foo` would traverse+// out of the snapshot subdir). Restrict to a relative path of safe characters+// with no traversal or wildcard segments. Mirrored by a service-side guard in+// restoreSnapshot for non-route callers — see issue #1822.+export const subdirFilterSchema = z.string()+ .regex(/^[a-z0-9._/-]+$/i, 'subdirFilter contains invalid characters')+ .refine((v) => !v.split('/').includes('..'), 'subdirFilter may not contain ".." segments')+ .refine((v) => !v.startsWith('/'), 'subdirFilter must be a relative path');+export const restoreRequestSchema = z.object({snapshotId: z.string().min(1),- subdirFilter: z.string().optional().nullable(),+ subdirFilter: subdirFilterSchema.optional().nullable(),dryRun: z.boolean().optional().default(true)});diff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex a472cfdc06..597a6e8a71 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -21,7 +21,9 @@ import {editorialCustomCheckUpdateSchema,pipelineEditorialChecksSettingsSchema,storyboardShotSchema,- storyboardSceneSchema+ storyboardSceneSchema,+ restoreRequestSchema,+ subdirFilterSchema} from './validation.js';describe('validation.js', () => {@@ -951,4 +953,29 @@ describe('validation.js', () => {expect(storyboardSceneSchema.safeParse({ shots: [{ id: 's', shotType: 'nope' }] }).success).toBe(false);});});++ describe('subdirFilter validation (#1822)', () => {+ it('accepts a plain relative subdir', () => {+ expect(subdirFilterSchema.safeParse('data').success).toBe(true);+ expect(subdirFilterSchema.safeParse('brain/notes').success).toBe(true);+ expect(subdirFilterSchema.safeParse('cos.worktrees').success).toBe(true);+ });++ it('rejects wildcard characters that would override the rsync filter chain', () => {+ expect(subdirFilterSchema.safeParse('*').success).toBe(false);+ expect(subdirFilterSchema.safeParse('data/*').success).toBe(false);+ });++ it('rejects ".." traversal segments and absolute paths', () => {+ expect(subdirFilterSchema.safeParse('../other-dir').success).toBe(false);+ expect(subdirFilterSchema.safeParse('data/../../etc').success).toBe(false);+ expect(subdirFilterSchema.safeParse('/etc/passwd').success).toBe(false);+ });++ it('allows the field to be omitted or null on the restore request', () => {+ expect(restoreRequestSchema.safeParse({ snapshotId: 's1' }).success).toBe(true);+ expect(restoreRequestSchema.safeParse({ snapshotId: 's1', subdirFilter: null }).success).toBe(true);+ expect(restoreRequestSchema.safeParse({ snapshotId: 's1', subdirFilter: '*' }).success).toBe(false);+ });+ });});diff --git a/server/services/backup.js b/server/services/backup.jsindex 224b276028..9ef89c0fd2 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -465,6 +465,16 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, subthrow new Error(`Path traversal detected for snapshotId: ${snapshotId}`);}+ // Defense-in-depth for non-route callers (the route already validates via+ // subdirFilterSchema). subdirFilter is interpolated into an rsync include arg,+ // so a `*` would override the filter chain (restoring everything) and `..`+ // would traverse out of the snapshot subdir — see issue #1822.+ if (subdirFilter != null && (!/^[a-z0-9._/-]+$/i.test(subdirFilter)+ || subdirFilter.split('/').includes('..')+ || subdirFilter.startsWith('/'))) {+ throw new Error(`Invalid subdirFilter: ${subdirFilter}`);+ }+const flags = ['--itemize-changes'];if (dryRun) flags.push('--dry-run');if (subdirFilter) {diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex 32ca667502..1b9d4fc4cd 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -48,7 +48,7 @@ vi.mock('fs/promises', async (importOriginal) => {import { checkHealth, getServerMajorVersion } from '../lib/db.js';import { getBackendName } from './memoryBackend.js';import * as fs from 'fs/promises';-import { DEFAULT_EXCLUDES, computeEffectiveExcludes, listSnapshots } from './backup.js';+import { DEFAULT_EXCLUDES, computeEffectiveExcludes, listSnapshots, restoreSnapshot } from './backup.js';// Helper: build a fake child process whose close/error we can drive.function fakeProc() {@@ -655,3 +655,30 @@ describe('generateManifest', () => {expect(manifest.files['../portos-db.sql']).toMatch(/^[0-9a-f]{64}$/);});});++// restoreSnapshot's service-side subdirFilter guard (issue #1822). These reject+// BEFORE runRsync/spawn is reached, so no fake child process is needed — an+// invalid filter must never make it into an `--include=` rsync arg.+describe('restoreSnapshot subdirFilter guard', () => {+ beforeEach(() => {+ spawn.mockReset();+ });++ it('rejects a wildcard filter before spawning rsync', async () => {+ await expect(restoreSnapshot('/dest', 'snap-1', { subdirFilter: '*' }))+ .rejects.toThrow(/Invalid subdirFilter/);+ expect(spawn).not.toHaveBeenCalled();+ });++ it('rejects a traversal filter before spawning rsync', async () => {+ await expect(restoreSnapshot('/dest', 'snap-1', { subdirFilter: '../escape' }))+ .rejects.toThrow(/Invalid subdirFilter/);+ expect(spawn).not.toHaveBeenCalled();+ });++ it('rejects an absolute-path filter before spawning rsync', async () => {+ await expect(restoreSnapshot('/dest', 'snap-1', { subdirFilter: '/etc' }))+ .rejects.toThrow(/Invalid subdirFilter/);+ expect(spawn).not.toHaveBeenCalled();+ });+});diff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex 34f0f10e7a..858d639a48 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -208,8 +208,14 @@ export async function getBackups() {return backups;}+// Backup archives are named like `agents-2026-06-30T12-34-56.tar.gz`, so the raw+// filename legitimately contains dots. Validate the dotted value directly — the+// old `filename.replace(/[.]/g,'')` double-pass never checked the real filename,+// leaving only the startsWith(backupDir) guard against traversal (issue #1822).+const SAFE_FILENAME = /^[a-z0-9._-]+$/i;+export async function deleteBackup(filename) {- if (!SAFE_NAME.test(filename.replace(/[.]/g, ''))) throw new Error('Invalid filename');+ if (!SAFE_FILENAME.test(filename) || filename.includes('..')) throw new Error('Invalid filename');const backupDir = join(DATA_DIR, 'backup');const fullPath = join(backupDir, filename);if (!fullPath.startsWith(backupDir)) throw new Error('Path traversal not allowed');diff --git a/server/services/dataManager.test.js b/server/services/dataManager.test.jsnew file mode 100644index 0000000000..cbaa29c971--- /dev/null+++ b/server/services/dataManager.test.js@@ -0,0 +1,46 @@+/**+ * Unit tests for deleteBackup filename validation (issue #1822).+ *+ * Backup archives are named like `agents-2026-06-30T12-34-56.tar.gz`, so the+ * raw filename legitimately contains dots. The validation must accept that+ * shape while rejecting traversal/wildcard names — the old dot-stripping+ * double-pass never validated the real dotted filename, leaving only the+ * startsWith(backupDir) guard against traversal.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock fs/promises so deleteBackup's rm is a no-op spy — the accept path must+// not touch the real filesystem, and reject paths throw before rm is reached.+vi.mock('fs/promises', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, rm: vi.fn().mockResolvedValue(undefined) };+});++import { rm } from 'fs/promises';+import { deleteBackup } from './dataManager.js';++describe('deleteBackup filename validation (#1822)', () => {+ beforeEach(() => {+ rm.mockClear();+ });++ it('accepts a real dotted backup archive name', async () => {+ const result = await deleteBackup('agents-2026-06-30T12-34-56.tar.gz');+ expect(result).toEqual({ deleted: 'agents-2026-06-30T12-34-56.tar.gz' });+ expect(rm).toHaveBeenCalledTimes(1);+ });++ it('rejects ".." traversal without touching the filesystem', async () => {+ await expect(deleteBackup('../secrets.json')).rejects.toThrow('Invalid filename');+ await expect(deleteBackup('a/../../etc/passwd')).rejects.toThrow('Invalid filename');+ expect(rm).not.toHaveBeenCalled();+ });++ it('rejects path separators and other unsafe characters', async () => {+ await expect(deleteBackup('sub/dir.tar.gz')).rejects.toThrow('Invalid filename');+ await expect(deleteBackup('name with spaces.tar.gz')).rejects.toThrow('Invalid filename');+ await expect(deleteBackup('weird$name.tar.gz')).rejects.toThrow('Invalid filename');+ expect(rm).not.toHaveBeenCalled();+ });+});