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: canonicalize backup restore scope so brain/ or ./brain restores brain (#11865)
Adam Eivy0e7d41436458
diff --git a/server/lib/sharedSchemas.js b/server/lib/sharedSchemas.jsindex 46048a3fe6..a7fdbd5a75 100644--- a/server/lib/sharedSchemas.js+++ b/server/lib/sharedSchemas.js@@ -91,15 +91,16 @@ export const csvIdsParam = ({ max, maxIdLength = 64, truncate = false } = {}) =>// 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 wildcard, traversal, or absolute segments. Exported as a+// characters with no wildcard, traversal, or absolute segments, and no empty+// or `.` segment (`brain/`, `./brain`, `a//b`) — those spell the same path+// differently at each restore call site. Exported as a// predicate so the restoreSnapshot service guard and the sprite run-id schemas// reuse the exact same rule (mirrors isSafeRecordId in validation.js) — see// issue #1822.export const isSafeSubdirFilter = (v) =>typeof v === 'string'&& /^[a-z0-9._/-]+$/i.test(v)- && !v.split('/').includes('..')- && !v.startsWith('/');+ && !v.split('/').some(part => part === '' || part === '.' || part === '..');// Backup sources are directory names under snapshots/. `@legacy` is reserved// for the pre-namespace snapshots root; `@` cannot occur in the sanitizeddiff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex 4dc139e2da..5b946779b5 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -2186,6 +2186,9 @@ describe('validation.js', () => {it('rejects ".." traversal segments and absolute paths', () => {expect(subdirFilterSchema.safeParse('../other-dir').success).toBe(false);expect(subdirFilterSchema.safeParse('data/../../etc').success).toBe(false);+ for (const v of ['brain/', './brain', 'brain/./x', 'brain//x']) {+ expect(subdirFilterSchema.safeParse(v).success).toBe(false);+ }expect(subdirFilterSchema.safeParse('/etc/passwd').success).toBe(false);});diff --git a/server/services/backup.js b/server/services/backup.jsindex 2aad7e36a6..35e090c493 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -1647,7 +1647,13 @@ function restoreIdleTimeoutMs(largestFileBytes = 0) {* @param {boolean} [options.dryRun=true] - If true, do not write any files* @param {string|null} [options.subdirFilter=null] - Limit restore to a subdirectory*/-export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, subdirFilter = null, source } = {}) {+export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, subdirFilter: requestedFilter = null, source } = {}) {+ // Canonicalize once: manifest selection, the inventory and the rsync include+ // chain each spell the filter differently, so `brain/` or `./brain` would+ // select nothing yet verify clean. An all-dot/empty filter means no filter.+ const subdirFilter = typeof requestedFilter === 'string'+ ? requestedFilter.split('/').filter(part => part && part !== '.').join('/') || null+ : requestedFilter;const resolved = resolveSnapshotPath(destPath, snapshotId, source);await assertExplicitSnapshotSourceSafe(resolved, snapshotId);@@ -1656,8 +1662,8 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub// so a `*` would override the filter chain (restoring everything) and `..`// would traverse out of the snapshot subdir. Reuse the same predicate the// schema does so the two can't drift — see issue #1822.- if (subdirFilter != null && !isSafeSubdirFilter(subdirFilter)) {- throw new Error(`Invalid subdirFilter: ${subdirFilter}`);+ if (requestedFilter != null && (String(requestedFilter).startsWith('/') || (subdirFilter != null && !isSafeSubdirFilter(subdirFilter)))) {+ throw new Error(`Invalid subdirFilter: ${requestedFilter}`);}// Refused for previews too, before any verification or transfer, so a preview// never promises a restore that execution would silently skip.@@ -1739,8 +1745,7 @@ async function restoreHeldSnapshot({ snapshotDir, currentSource }, snapshotId, {return { dryRun, snapshotId, subdirFilter, changedFiles, verification };}- // Applicability uses the normalized scope; reconciliation keeps the raw filter.- const scope = subdirFilter?.split('/').filter(part => part && part !== '.').join('/');+ const scope = subdirFilter;const changedFiles = await withLiveFileRestoreOwners(scope, () => transferAndReconcileLiveFiles({subdirFilter,transfer: () => transferWithIdentityFence({ scope, srcDir, transferFiles }),diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex 520372923d..da4a5d5b06 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -2309,6 +2309,20 @@ describe('restoreSnapshot manifest verification', () => {]));});+ it.each(['brain/', './brain', 'brain/.', 'brain//'])(+ 'selects and verifies the same files for the equivalent scope %s',+ async (spelling) => {+ const relativePath = 'brain/example.json';+ await writeManifest({ [relativePath]: await writeSnapshotFile(relativePath, 'snapshot data') });++ await expect(finishRestore({ dryRun: true, subdirFilter: spelling })).resolves.toMatchObject({+ subdirFilter: 'brain',+ verification: { status: 'verified', checkedFiles: 1 },+ });+ expect(spawn.mock.calls[0][1]).toEqual(expect.arrayContaining(['--include=/brain', '--include=/brain/***']));+ },+ );+it.each([['missing', async (path) => realFs.unlink(path)],['unreadable', async (path) => {