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
test: cover restoreSnapshot snapshotId guards, subdirFilter rsync flags, and settings re-sync (#3917)
[._.]/ Adam Eivyc07b06ac5666
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fc8f494a8e..a82a986ff5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -39,6 +39,8 @@## Changed+- `restoreSnapshot` in the backup service now has tests for the three things a restore gets exactly one chance to get right. A restore rsyncs a snapshot over the user's live `data/`, and the suite previously only covered the `subdirFilter` rejection cases and which rsync binary gets spawned. It now asserts the `snapshotId` allow-list rejects separators and shell metacharacters before anything spawns; that a bare `..` — which passes the character allow-list — is still stopped by the `resolve()`/`relative()` traversal check; that a valid `subdirFilter` produces the exact ordered rsync argument array (`--include=<dir>/***`, `--include=*/`, `--exclude=*`, in that order, since a reordered chain silently widens a targeted restore into a full-tree one), and that no include/exclude flags appear when no filter is given; and that `reloadSettings()` runs after a live restore but not after a dry run or a failed one, so a restored `settings.json` can't sit behind a stale in-memory cache.+- A failed "Continue a story" fetch on the Story Builder index no longer looks like your saved stories were deleted. The list swallowed its own error and fell back to an empty array, and an empty array renders nothing — so a dropped connection or a restarting server left the sidebar section silently gone, with no indication anything had failed and no way to try again short of a reload. The section now reserves itself while the fetch is in flight with three pulsing placeholder rows, and on failure renders an error banner naming the error with a Retry button that re-runs the fetch and restores the list. Only a successful, genuinely empty list still hides the section.- `restorePostgres` now has tests for the three paths a PostgreSQL restore can go wrong on. A missing `psql` binary surfaces as a spawn `'error'` event rather than a `'close'`, so without its listener the restore promise would never settle and the UI would hang — the suite now drives that emit and pins the `{ status: 'failed', reason: 'restore_error' }` result. The `--single-transaction` / `ON_ERROR_STOP=1` pair is what makes a failed replay roll back instead of leaving the live database half-dropped, so both flags (and the `-v` flag's actual value, not just its presence) are asserted, along with the `portos` PGPASSWORD default and an explicit `PGPASSWORD` overriding it. A `manifest.json` that exists but is unparseable reads as absent — `readJSONFile` returns its `null` default, so hash verification is skipped and the restore proceeds; that is now pinned in both the dry-run and real-restore directions, so changing it to a hard failure has to be a deliberate decision.diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex a7f11da276..e129b65b3b 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -13,6 +13,11 @@* default-state recovery when state.json is missing or corrupted, patch* merging, and the createFileWriteQueue serialization that keeps two* concurrent saveState() callers from clobbering each other's fields.+ * - restoreSnapshot — the input guards (snapshotId allow-list + traversal+ * check, subdirFilter allow-list) and the exact rsync argument array a+ * subdirFilter produces, plus the live-restore-only settings cache re-sync.+ * A restore overwrites the user's live data/, so a broken filter chain or a+ * skipped reloadSettings() is a data/consistency bug, not cosmetics.*/import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';@@ -971,3 +976,121 @@ describe('getState and saveState', () => {expect(await readStateFile()).toEqual(after);});});++// snapshotId validation + rsync filter construction + settings cache re-sync.+// restoreSnapshot writes over the user's live data/ directory, so each of these+// is a data-loss-adjacent contract, not a style nit (issue #3917).+describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () => {+ // Mirrors backup.js's MACHINE_HOST derivation so the expected src path can be+ // built without hardcoding this machine's hostname.+ const machineHost = hostname().toLowerCase().replace(/[^\w.\-]/g, '_') || 'unknown';++ beforeEach(() => {+ spawn.mockReset();+ reloadSettings.mockClear();+ });++ // Drive a mocked rsync to a clean exit so restoreSnapshot resolves.+ async function runRestore(...args) {+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const pending = restoreSnapshot(...args);+ await flush();+ proc.emit('close', 0);+ return pending;+ }++ describe('snapshotId validation', () => {+ // Ids containing a separator fail the character allow-list outright...+ for (const bad of ['../../etc', '../escape', 'a/b', 'snap 1', 'snap;rm -rf', '']) {+ it(`rejects ${JSON.stringify(bad)} before spawning rsync`, async () => {+ await expect(restoreSnapshot('/dest', bad)).rejects.toThrow(/Invalid snapshotId/);+ expect(spawn).not.toHaveBeenCalled();+ });+ }++ // ...but `..` is made only of allow-listed characters, so it slips past the+ // regex and must be caught by the resolve()/relative() traversal check. This+ // is the bypass probe: delete that second guard and only this case fails.+ it('rejects a bare `..` that passes the character allow-list, via the traversal check', async () => {+ await expect(restoreSnapshot('/dest', '..')).rejects.toThrow(/Path traversal detected/);+ expect(spawn).not.toHaveBeenCalled();+ });++ it('accepts a timestamp-shaped id', async () => {+ await expect(runRestore('/dest', '2026-01-02T03:04:05.678Z')).resolves.toMatchObject({+ snapshotId: '2026-01-02T03:04:05.678Z',+ });+ expect(spawn).toHaveBeenCalledTimes(1);+ });+ });++ describe('subdirFilter rsync flags', () => {+ it('builds the exact include/exclude chain for a valid subdirFilter', async () => {+ await runRestore('/dest', 'snap-1', { dryRun: true, subdirFilter: 'brain' });++ const srcDir = join('/dest', 'snapshots', machineHost, 'snap-1', 'data');+ // Asserted as an exact array (not arrayContaining): the ORDER matters to+ // rsync — `--exclude=*` must come last, after both includes, or the+ // targeted restore silently degrades into a full-tree restore.+ expect(spawn.mock.calls[0][1]).toEqual([+ '--archive',+ '--itemize-changes',+ '--itemize-changes',+ '--dry-run',+ '--include=brain/***',+ '--include=*/',+ '--exclude=*',+ `${srcDir}/`,+ PATHS.data,+ ]);+ });++ it('emits no include/exclude flags when no subdirFilter is given', async () => {+ await runRestore('/dest', 'snap-1', { dryRun: true });++ const args = spawn.mock.calls[0][1];+ expect(args.filter(a => a.startsWith('--include=') || a.startsWith('--exclude='))).toEqual([]);+ });++ it('echoes the subdirFilter back in the result', async () => {+ await expect(runRestore('/dest', 'snap-1', { subdirFilter: 'brain' }))+ .resolves.toMatchObject({ subdirFilter: 'brain' });+ });+ });++ describe('settings cache re-sync', () => {+ it('reloads settings after a live restore', async () => {+ await runRestore('/dest', 'snap-1', { dryRun: false });++ expect(reloadSettings).toHaveBeenCalledTimes(1);+ // A live restore must not pass --dry-run to rsync.+ expect(spawn.mock.calls[0][1]).not.toContain('--dry-run');+ });++ it('does not reload settings for a dry run', async () => {+ await runRestore('/dest', 'snap-1', { dryRun: true });++ expect(reloadSettings).not.toHaveBeenCalled();+ expect(spawn.mock.calls[0][1]).toContain('--dry-run');+ });++ it('defaults to a dry run (no settings reload) when no options are given', async () => {+ await expect(runRestore('/dest', 'snap-1')).resolves.toMatchObject({ dryRun: true });++ expect(reloadSettings).not.toHaveBeenCalled();+ });++ it('does not reload settings when rsync fails a live restore', async () => {+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const pending = restoreSnapshot('/dest', 'snap-1', { dryRun: false });+ await flush();+ proc.stderr.emit('data', Buffer.from('boom'));+ proc.emit('close', 1);++ await expect(pending).rejects.toThrow(/rsync exited with code 1/);+ expect(reloadSettings).not.toHaveBeenCalled();+ });+ });+});