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: verify snapshot manifest hashes before file restore (#7167)
Louis Deconincka7bb74099042
diff --git a/client/src/components/BackupWidget.jsx b/client/src/components/BackupWidget.jsxindex 1f4eae1f01..a9d30d5062 100644--- a/client/src/components/BackupWidget.jsx+++ b/client/src/components/BackupWidget.jsx@@ -120,7 +120,10 @@ function RestorePanel({ snapshot, onClose, restoring, onRestoreStateChange }) {});onRestoreStateChange(null);if (result) {- toast.success(`Restore complete — ${result.changedFiles?.length ?? 0} file(s) restored`);+ // A legacy snapshot has no manifest to verify against — say so plainly+ // rather than letting "complete" read as "integrity-checked".+ const suffix = result.verification?.status === 'unverified' ? ' (unverified legacy snapshot)' : '';+ toast.success(`Restore complete — ${result.changedFiles?.length ?? 0} file(s) restored${suffix}`);onClose();}}, [acceptedPreview, onClose, onRestoreStateChange, previewMatchesCurrentRequest, restoring, snapshot.id]);@@ -178,6 +181,21 @@ function RestorePanel({ snapshot, onClose, restoring, onRestoreStateChange }) {{/* Dry-run results */}{preview && (<div>+ {/* Verification state is part of the confirmation: a verified snapshot+ is labeled as such, and a manifest-less legacy snapshot is flagged+ so its restore is never mistaken for an integrity-checked one. */}+ {preview.verification?.status === 'unverified' ? (+ <div className="mb-1 flex items-start gap-2 rounded bg-port-warning/10 border border-port-warning/20 p-2">+ <AlertTriangle size={14} className="text-port-warning shrink-0 mt-0.5" />+ <p className="text-xs text-port-warning">+ Legacy snapshot with no integrity manifest — its contents cannot be verified and will be restored unverified.+ </p>+ </div>+ ) : preview.verification?.status === 'verified' ? (+ <p className="text-xs text-gray-600 mb-1">+ Snapshot integrity verified against manifest ({preview.verification.checkedFiles} file(s) checked).+ </p>+ ) : null}<p className="text-xs text-gray-500 mb-1">{preview.changedFiles?.length ?? 0} file(s) would change:</p>diff --git a/client/src/components/BackupWidget.test.jsx b/client/src/components/BackupWidget.test.jsxindex 771657fb18..97c3a01c9f 100644--- a/client/src/components/BackupWidget.test.jsx+++ b/client/src/components/BackupWidget.test.jsx@@ -213,6 +213,43 @@ describe('BackupWidget snapshots', () => {expect(screen.getByRole('button', { name: 'Preview changes' })).toBeEnabled();});+ // #7167: the server reports manifest verification state on restore results.+ // A manifest-less legacy snapshot must be flagged in the confirmation flow,+ // and a verified one labeled, so neither reads as the other.+ it('flags a manifest-less legacy snapshot as unverified through the restore flow', async () => {+ const legacy = { status: 'unverified', reason: 'no_manifest' };+ mockRestoreBackup+ .mockResolvedValueOnce({ dryRun: true, changedFiles: ['a.json'], verification: legacy })+ .mockResolvedValueOnce({ dryRun: false, changedFiles: ['a.json'], verification: legacy });+ renderWidget();++ await openRestorePanel();+ fireEvent.click(screen.getByRole('button', { name: 'Preview changes' }));++ expect(await screen.findByText(/cannot be verified/)).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Restore 1 file(s)' }));+ await waitFor(() => expect(mockToast.success).toHaveBeenCalledWith(+ 'Restore complete — 1 file(s) restored (unverified legacy snapshot)',+ ));+ });++ it('labels a manifest-verified preview instead of the unverified warning', async () => {+ mockRestoreBackup.mockResolvedValueOnce({+ dryRun: true,+ changedFiles: [],+ verification: { status: 'verified', checkedFiles: 2 },+ });+ renderWidget();++ await openRestorePanel();+ fireEvent.click(screen.getByRole('button', { name: 'Preview changes' }));++ expect(await screen.findByText(/integrity verified against manifest/)).toBeInTheDocument();+ expect(screen.queryByText(/cannot be verified/)).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Nothing to restore' })).toBeDisabled();+ });+it('reports a current preview failure and re-enables previewing', async () => {mockRestoreBackup.mockRejectedValueOnce(new Error('disk offline'));renderWidget();diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 52f85d169c..02efc7f68c 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -69,6 +69,10 @@ A backup run that fails after creating its snapshot directory records a durablersyncs `<snapshot>/data/` back to `./data/`. `dryRun: true` (the default) reports what would change without writing; an optional `subdirFilter` limits the restore to one subdirectory.+**Manifest verification runs before every file restore — preview and execution alike.** When the snapshot carries a `manifest.json`, its structure is strictly validated and every recorded file the restore would write (all data files on a full restore, only the selected `subdirFilter` entries on a selective one) is re-hashed and compared before rsync is spawned. A missing, unreadable, or hash-mismatched file rejects the restore with `SNAPSHOT_MANIFEST_MISMATCH`, leaving live data untouched; an existing manifest that is corrupt, unreadable, or malformed rejects with `SNAPSHOT_MANIFEST_UNREADABLE` — fail closed, never restore on a manifest that can't be trusted. The parent-relative `../portos-db.sql` manifest entry is skipped here: it names the DB dump, not a data-file path, and `restorePostgres()` verifies it separately. The actual restore re-verifies rather than trusting a prior preview, so bytes changed between preview and execution are still caught.++Snapshots written before manifests existed have no `manifest.json` at all and remain restorable as an explicit **unverified** compatibility case — the restore result reports `verification: { status: 'unverified', reason: 'no_manifest' }` (vs `{ status: 'verified', checkedFiles }`), which the restore confirmation flow surfaces so a legacy restore is never mistaken for a verified one. Manifest keys are validated as safe relative paths before they are resolved, and symlinked files keep their documented behavior (`stat` follows links exactly as `generateManifest` does, so a link to a regular file verifies against its target's hash and dangling links stay out of scope).+### Database — `restorePostgres()`Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ERROR_STOP=1 --single-transaction`, so the restore is **atomic**: it either fully applies or rolls back, never leaving a mixed snapshot/current state.diff --git a/server/routes/backup.test.js b/server/routes/backup.test.jsindex 8bcd3127a1..980b8d08ff 100644--- a/server/routes/backup.test.js+++ b/server/routes/backup.test.js@@ -196,6 +196,44 @@ describe('backup routes', () => {expect.objectContaining({ dryRun: true }));});++ // #7167: the service reports manifest verification state on the result —+ // the client confirmation flow reads it to distinguish a verified restore+ // from a legacy unverified one, so it must survive the response verbatim.+ it.each([+ ['verified', { status: 'verified', checkedFiles: 3 }],+ ['unverified (legacy)', { status: 'unverified', reason: 'no_manifest' }],+ ])('forwards the %s verification descriptor verbatim', async (_label, verification) => {+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });+ const serviceResult = {+ dryRun: true, snapshotId: 'snap-1', subdirFilter: null, changedFiles: [], verification,+ };+ backup.restoreSnapshot.mockResolvedValue(serviceResult);+ const res = await request(buildApp())+ .post('/api/backup/restore')+ .send({ snapshotId: 'snap-1' });+ expect(res.status).toBe(200);+ expect(res.body).toEqual(serviceResult);+ });++ // A manifest verification failure rejects before rsync; the route must+ // surface the structured error envelope so the client can show why the+ // restore was refused.+ it.each([+ ['SNAPSHOT_MANIFEST_MISMATCH', 'hash mismatch for file: a.json'],+ ['SNAPSHOT_MANIFEST_UNREADABLE', 'Snapshot manifest is malformed'],+ ])('returns 409 with code %s when verification rejects the restore', async (code, detail) => {+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });+ backup.restoreSnapshot.mockRejectedValue(+ Object.assign(new Error(detail), { status: 409, code }),+ );+ const res = await request(buildApp())+ .post('/api/backup/restore')+ .send({ snapshotId: 'snap-1', dryRun: false });+ expect(res.status).toBe(409);+ expect(res.body.code).toBe(code);+ expect(res.body.error).toContain(detail);+ });});describe('POST /api/backup/restore-db', () => {diff --git a/server/services/backup.js b/server/services/backup.jsindex a9af7f9089..7f9079e946 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -11,7 +11,7 @@ import { killWithEscalation } from '../lib/killWithEscalation.js';import { access, lstat, readdir, readFile, stat, unlink, writeFile } from 'fs/promises';import { PassThrough } from 'node:stream';import { hostname } from 'os';-import { join, resolve, relative, isAbsolute } from 'path';+import { join, resolve, relative, isAbsolute, posix } from 'path';import { PATHS, ensureDir, readJSONFile, readJSONFileStrict, atomicWrite, sha256File } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { createLineReader } from '../lib/streamLines.js';@@ -47,6 +47,10 @@ const STATE_PATH = join(PATHS.data, 'backup', 'state.json');// tree from both completed and legacy snapshots after a restart.const SNAPSHOT_IN_PROGRESS_MARKER = '.in-progress';const SNAPSHOT_FAILED_MARKER = '.failed';+// The pg_dump lives one level ABOVE the snapshot's data/ tree, so its manifest+// key is parent-relative. File restore must recognize and skip this key rather+// than resolving it as a data-file path — restorePostgres verifies it.+const SNAPSHOT_DUMP_MANIFEST_KEY = '../portos-db.sql';let activeSnapshotId = null;const markerPath = (snapshotDir) => join(snapshotDir, SNAPSHOT_IN_PROGRESS_MARKER);@@ -728,9 +732,9 @@ export async function generateManifest(snapshotDataDir, manifestPath, pgDumpPath}if (dumpInfo?.isFile()) {// Parent-relative key: the dump lives one level ABOVE snapshotDataDir- // (alongside it, not inside it). A future manifest-verify must not assume- // every key resolves under snapshotDataDir.- files['../portos-db.sql'] = await sha256File(pgDumpPath)+ // (alongside it, not inside it). A manifest-verify must not assume+ // every key resolves under snapshotDataDir — see verifySnapshotManifest.+ files[SNAPSHOT_DUMP_MANIFEST_KEY] = await sha256File(pgDumpPath).catch(err => { throw manifestReadFailure('dump hash', err); });}}@@ -878,6 +882,130 @@ export async function openSnapshotStream(destPath, snapshotId) {return archive;}+// A manifest key names a path RELATIVE to the snapshot's data/ dir. The+// manifest is data read off the backup medium — which may be a shared or+// damaged volume — so every key is validated before it is joined onto a real+// path: a corrupt or hostile manifest must not point the verifier outside the+// snapshot tree. `..` is detected by splitting on BOTH separators so a+// Windows-written manifest can't smuggle traversal through `..\`.+const SHA256_HEX = /^[0-9a-f]{64}$/;+function isSafeManifestKey(key) {+ if (typeof key !== 'string' || !key || key.includes('\0')) return false;+ if (isAbsolute(key) || key.startsWith('/') || key.startsWith('\\')) return false;+ if (/^[a-zA-Z]:($|[\\/])/.test(key)) return false; // drive-letter absolute+ if (key.split(/[\\/]/).includes('..')) return false;+ return true;+}++// Sentinel default for readJSONFileStrict so a confirmed-absent manifest (the+// legacy pre-manifest snapshot case) is distinguished from a manifest file that+// exists but parses to a falsy/non-object value — the former is an explicit+// unverified compatibility path, the latter must fail closed.+const MANIFEST_ABSENT = {};++const manifestVerificationError = (snapshotId, detail) => new ServerError(+ `Snapshot ${snapshotId} failed manifest verification: ${detail}. Choose another snapshot or repair the backup media before retrying.`,+ { status: 409, code: 'SNAPSHOT_MANIFEST_MISMATCH' },+);++/**+ * Verify a snapshot's manifest.json against its data/ bytes before restore.+ * Runs ahead of EVERY restore — preview and execution alike — so damaged or+ * mismatched snapshot bytes can never reach rsync and overwrite live data.+ *+ * Returns a verification descriptor the route/UI can surface:+ * { status: 'verified', checkedFiles: n } manifest present, all selected entries hashed clean+ * { status: 'unverified', reason: 'no_manifest' } legacy snapshot written before manifests existed+ * Throws ServerError (409) when the manifest exists but is unreadable,+ * malformed, or a selected file is missing/unreadable/hash-mismatched.+ *+ * @param {string} snapshotDir - Resolved snapshot directory+ * @param {string} snapshotId - For messages only+ * @param {string|null} subdirFilter - Already-validated selective restore scope+ */+async function verifySnapshotManifest(snapshotDir, snapshotId, subdirFilter) {+ const manifestPath = join(snapshotDir, 'manifest.json');+ const manifestRead = await readJSONFileStrict(manifestPath, MANIFEST_ABSENT);+ if (!manifestRead.ok) {+ throw new ServerError(`Snapshot manifest is unreadable: ${snapshotId}`, {+ status: 409,+ code: 'SNAPSHOT_MANIFEST_UNREADABLE',+ });+ }+ const manifest = manifestRead.value;+ if (manifest === MANIFEST_ABSENT) {+ return { status: 'unverified', reason: 'no_manifest' };+ }++ // Structural validation is strict on the security-relevant part: `files`+ // must be a map of safe relative keys to sha256 hex digests. Anything else —+ // a non-object manifest, an array, a garbage hash, an absolute/traversing+ // key — means the manifest cannot be trusted and the restore fails closed.+ const files = manifest?.files;+ const malformed = !manifest || typeof manifest !== 'object' || Array.isArray(manifest)+ || !files || typeof files !== 'object' || Array.isArray(files)+ || Object.entries(files).some(([key, hash]) =>+ key !== SNAPSHOT_DUMP_MANIFEST_KEY && (!isSafeManifestKey(key) || !SHA256_HEX.test(hash)));+ if (malformed) {+ throw new ServerError(`Snapshot manifest is malformed: ${snapshotId}`, {+ status: 409,+ code: 'SNAPSHOT_MANIFEST_UNREADABLE',+ });+ }++ // The dump key is verified by restorePostgres — it is not a data-file path+ // and must never be resolved under data/. Selection mirrors what the rsync+ // filter chain would restore: all recorded data files for a full restore, or+ // only entries at/under the literal subdirFilter for a selective one. Keys+ // are normalized to `/` (and `.`/duplicate separators collapsed) so a+ // manifest written on Windows still matches an `/`-separated filter.+ const filterNorm = subdirFilter+ ? posix.normalize(subdirFilter.replace(/\\/g, '/').replace(/\/+$/, ''))+ : null;+ const selectAll = !filterNorm || filterNorm === '.';+ const selected = Object.entries(files).filter(([key]) => {+ if (key === SNAPSHOT_DUMP_MANIFEST_KEY) return false;+ if (selectAll) return true;+ const normalized = posix.normalize(key.replace(/\\/g, '/'));+ return normalized === filterNorm || normalized.startsWith(`${filterNorm}/`);+ });++ const srcDir = join(snapshotDir, 'data');+ for (const [key, expectedHash] of selected) {+ const filePath = resolve(srcDir, key);+ const rel = relative(srcDir, filePath);+ if (!rel || rel.startsWith('..') || isAbsolute(rel)) {+ // Defense-in-depth: isSafeManifestKey already rejected traversal, so+ // reaching here means the two checks drifted — fail closed either way.+ throw new ServerError(`Snapshot manifest is malformed: ${snapshotId}`, {+ status: 409,+ code: 'SNAPSHOT_MANIFEST_UNREADABLE',+ });+ }+ const info = await stat(filePath).catch((err) => {+ throw manifestVerificationError(+ snapshotId,+ err?.code === 'ENOENT' || err?.code === 'ENOTDIR'+ ? `recorded file is missing: ${key}`+ : `recorded file is unreadable: ${key}`,+ );+ });+ // stat follows links, mirroring generateManifest (a symlink to a regular+ // file is hashed under the link's path — that documented compatibility is+ // retained). Anything that is no longer a regular file cannot match.+ if (!info.isFile()) {+ throw manifestVerificationError(snapshotId, `recorded file is not a regular file: ${key}`);+ }+ const actualHash = await sha256File(filePath).catch(() => {+ throw manifestVerificationError(snapshotId, `recorded file is unreadable: ${key}`);+ });+ if (actualHash !== expectedHash) {+ throw manifestVerificationError(snapshotId, `hash mismatch for file: ${key}`);+ }+ }+ return { status: 'verified', checkedFiles: selected.length };+}+/*** Restore a snapshot back to PATHS.data using rsync.* @param {string} destPath - Path to external drive backup root@@ -900,6 +1028,16 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, subthrow new Error(`Invalid subdirFilter: ${subdirFilter}`);}+ // Integrity preflight (#7167): when the snapshot carries a manifest, every+ // recorded file this restore would write must still match its SHA-256 before+ // rsync runs — otherwise a damaged backup overwrites healthy live data with+ // corrupt bytes. This re-verifies on the actual restore rather than trusting+ // a prior preview: bytes changed between the two calls are caught here.+ const verification = await verifySnapshotManifest(snapshotDir, snapshotId, subdirFilter);+ if (verification.status === 'unverified') {+ console.warn(`⚠️ restore: snapshot ${snapshotId} has no integrity manifest — restoring unverified (legacy snapshot)`);+ }+const flags = ['--itemize-changes'];if (dryRun) flags.push('--dry-run');if (subdirFilter) {@@ -933,7 +1071,7 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub}await reloadSettings();}- return { dryRun, snapshotId, subdirFilter, changedFiles };+ return { dryRun, snapshotId, subdirFilter, changedFiles, verification };}/**@@ -978,7 +1116,7 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true } =return { status: 'failed', reason: 'manifest_unreadable' };}const manifest = manifestRead.value;- const expectedHash = manifest?.files?.['../portos-db.sql'];+ const expectedHash = manifest?.files?.[SNAPSHOT_DUMP_MANIFEST_KEY];if (expectedHash) {const actualHash = await sha256File(sqlPath);if (actualHash !== expectedHash) {diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex 4931e71b3e..1161d9e653 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -103,7 +103,7 @@ vi.mock('./brainStorage.js', async (importOriginal) => ({}));import { reloadSettings } from './settings.js';import { invalidateAllCaches as invalidateBrainCaches } from './brainStorage.js';-import { DEFAULT_EXCLUDES, computeEffectiveExcludes, listSnapshots, openSnapshotStream, restoreSnapshot } from './backup.js';+import { DEFAULT_EXCLUDES, computeEffectiveExcludes, generateManifest, listSnapshots, openSnapshotStream, restoreSnapshot } from './backup.js';// fs.access is mocked file-wide because backup.js probes the .in-progress marker// with it. Restore the real implementation before EVERY test: vi.clearAllMocks()@@ -1557,6 +1557,209 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>});});+// Manifest hash verification for file restore (issue #7167). Every case runs+// against real temporary snapshot and destination trees — never the install's+// data/ — with rsync stubbed at the spawn boundary, so a verification failure+// is proven to reject BEFORE any byte could be written to the live tree.+describe('restoreSnapshot manifest verification', () => {+ const SNAPSHOT_ID = '2026-09-12T00-00-00';+ let realFs;+ let destRoot;+ let snapshotDir;+ let snapshotDataDir;++ const writeTree = async (files) => {+ for (const [rel, content] of Object.entries(files)) {+ const filePath = joinPath(snapshotDataDir, rel);+ await realFs.mkdir(joinPath(filePath, '..'), { recursive: true });+ await realFs.writeFile(filePath, content);+ }+ };++ // Build a real snapshot (files + manifest written by the real+ // generateManifest, optionally hashing a sibling dump) so verification runs+ // against production-format bytes, not a hand-shaped fixture.+ const makeSnapshot = async (files, { dumpSql = null } = {}) => {+ await writeTree(files);+ const dumpPath = dumpSql === null ? null : joinPath(snapshotDir, 'portos-db.sql');+ if (dumpPath) await realFs.writeFile(dumpPath, dumpSql);+ await generateManifest(snapshotDataDir, joinPath(snapshotDir, 'manifest.json'), dumpPath);+ };++ // Drive a mocked rsync to a clean exit so a restore that passes verification+ // resolves through the real code path.+ const driveRestore = async (options) => {+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const pending = restoreSnapshot(destRoot, SNAPSHOT_ID, options);+ await vi.waitFor(() => expect(spawn).toHaveBeenCalled());+ proc.emit('close', 0);+ return pending;+ };++ beforeEach(async () => {+ // Same spy hygiene as the generateManifest/getState suites: earlier suites+ // leave persistent fs spies and factory-level stat/readFile stubs, and+ // these tests need the real filesystem end to end.+ vi.restoreAllMocks();+ vi.clearAllMocks();+ realFs = await vi.importActual('fs/promises');+ fs.stat.mockImplementation(realFs.stat);+ fs.readFile.mockImplementation(realFs.readFile);+ fs.access.mockImplementation(realFs.access);+ fs.writeFile.mockImplementation(realFs.writeFile);+ spawn.mockReset();+ reloadSettings.mockClear();+ invalidateBrainCaches.mockClear();++ destRoot = await realFs.mkdtemp(joinPath(tmpdir(), 'portos-restore-dest-'));+ snapshotDir = joinPath(destRoot, 'snapshots', machineHost, SNAPSHOT_ID);+ snapshotDataDir = joinPath(snapshotDir, 'data');+ await realFs.mkdir(snapshotDataDir, { recursive: true });+ });++ afterEach(async () => {+ await realFs.rm(destRoot, { recursive: true, force: true });+ });++ it.each([true, false])(+ 'rejects a damaged snapshot file before rsync (dryRun=%s) and leaves live data untouched',+ async (dryRun) => {+ await makeSnapshot({ 'example.json': 'original snapshot bytes' });+ // Backup media damage: the snapshot bytes no longer match the manifest.+ await realFs.writeFile(joinPath(snapshotDataDir, 'example.json'), 'corrupted bytes');+ const liveFile = joinPath(PATHS.data, 'restore-verify-example.json');+ await realFs.writeFile(liveFile, 'HEALTHY LIVE DATA');+ try {+ await expect(restoreSnapshot(destRoot, SNAPSHOT_ID, { dryRun }))+ .rejects.toMatchObject({ status: 409, code: 'SNAPSHOT_MANIFEST_MISMATCH' });+ expect(spawn).not.toHaveBeenCalled();+ await expect(realFs.readFile(liveFile, 'utf-8')).resolves.toBe('HEALTHY LIVE DATA');+ } finally {+ await realFs.rm(liveFile, { force: true });+ }+ },+ );++ it('rejects when a manifest-recorded file is missing from the snapshot', async () => {+ await makeSnapshot({ 'a.json': 'A', 'b.json': 'B' });+ await realFs.rm(joinPath(snapshotDataDir, 'b.json'));++ await expect(restoreSnapshot(destRoot, SNAPSHOT_ID, { dryRun: true }))+ .rejects.toMatchObject({ code: 'SNAPSHOT_MANIFEST_MISMATCH' });+ await expect(restoreSnapshot(destRoot, SNAPSHOT_ID, { dryRun: true }))+ .rejects.toThrow(/missing: b\.json/);+ expect(spawn).not.toHaveBeenCalled();+ });++ it('rejects when a recorded file cannot be read from the backup media', async () => {+ await makeSnapshot({ 'example.json': 'bytes' });+ const target = joinPath(snapshotDataDir, 'example.json');+ fs.stat.mockImplementation((path, ...args) => path === target+ ? Promise.reject(Object.assign(new Error('media I/O failure'), { code: 'EIO' }))+ : realFs.stat(path, ...args));++ await expect(restoreSnapshot(destRoot, SNAPSHOT_ID, { dryRun: false }))+ .rejects.toMatchObject({ code: 'SNAPSHOT_MANIFEST_MISMATCH' });+ await expect(restoreSnapshot(destRoot, SNAPSHOT_ID, { dryRun: false }))+ .rejects.toThrow(/unreadable: example\.json/);+ expect(spawn).not.toHaveBeenCalled();+ });++ it('re-verifies on the actual restore instead of trusting the earlier preview', async () => {+ await makeSnapshot({ 'example.json': 'v1' });+ await expect(driveRestore({ dryRun: true })).resolves.toMatchObject({+ verification: { status: 'verified', checkedFiles: 1 },+ });+ expect(spawn).toHaveBeenCalledTimes(1);++ // The snapshot bytes change between preview and execution — the execution+ // must not inherit the preview's clean bill.+ await realFs.writeFile(joinPath(snapshotDataDir, 'example.json'), 'corrupted after preview');+ await expect(restoreSnapshot(destRoot, SNAPSHOT_ID, { dryRun: false }))+ .rejects.toMatchObject({ code: 'SNAPSHOT_MANIFEST_MISMATCH' });+ expect(spawn).toHaveBeenCalledTimes(1); // still only the preview's rsync+ });++ it('verifies only the selected scope and never treats the dump key as a data path', async () => {+ await makeSnapshot(+ { 'brain/ok.json': 'good', 'media/damaged.json': 'will corrupt' },+ { dumpSql: 'CREATE TABLE a;' },+ );+ // Damage lands OUTSIDE the selected brain/ scope and in the dump itself —+ // neither may block a selective brain/ restore.+ await realFs.writeFile(joinPath(snapshotDataDir, 'media', 'damaged.json'), 'CORRUPT');+ await realFs.writeFile(joinPath(snapshotDir, 'portos-db.sql'), 'CORRUPT DUMP');++ await expect(driveRestore({ dryRun: false, subdirFilter: 'brain' }))+ .resolves.toMatchObject({ verification: { status: 'verified', checkedFiles: 1 } });+ expect(spawn).toHaveBeenCalledTimes(1);+ });++ it('blocks a selective restore when a file INSIDE the selected scope is damaged', async () => {+ await makeSnapshot({ 'brain/ok.json': 'good', 'media/fine.json': 'fine' });+ await realFs.writeFile(joinPath(snapshotDataDir, 'brain', 'ok.json'), 'CORRUPT');++ await expect(restoreSnapshot(destRoot, SNAPSHOT_ID, { dryRun: false, subdirFilter: 'brain' }))+ .rejects.toMatchObject({ code: 'SNAPSHOT_MANIFEST_MISMATCH' });+ expect(spawn).not.toHaveBeenCalled();+ });++ it('restores a valid snapshot and reports verified status', async () => {+ await makeSnapshot(+ { 'a.json': 'A', 'sub/b.json': 'B' },+ { dumpSql: 'CREATE TABLE a;' },+ );++ await expect(driveRestore({ dryRun: false })).resolves.toMatchObject({+ verification: { status: 'verified', checkedFiles: 2 },+ });+ expect(reloadSettings).toHaveBeenCalledTimes(1);+ });++ it('retains symlink compatibility: links to regular files verify against their target', async () => {+ await realFs.writeFile(joinPath(snapshotDataDir, 'example.txt'), 'example');+ await realFs.symlink('example.txt', joinPath(snapshotDataDir, 'readable-link'));+ await realFs.symlink('excluded.txt', joinPath(snapshotDataDir, 'dangling-link'));+ // Real manifest: hashes example.txt and readable-link's target, records+ // nothing for the dangling link (generateManifest's documented behavior).+ await generateManifest(snapshotDataDir, joinPath(snapshotDir, 'manifest.json'));++ await expect(driveRestore({ dryRun: false })).resolves.toMatchObject({+ verification: { status: 'verified', checkedFiles: 2 },+ });+ });++ it('restores a legacy manifest-less snapshot as explicitly unverified', async () => {+ await writeTree({ 'a.json': 'A' }); // pre-manifest snapshot: no manifest.json++ await expect(driveRestore({ dryRun: false })).resolves.toMatchObject({+ verification: { status: 'unverified', reason: 'no_manifest' },+ });+ expect(spawn).toHaveBeenCalledTimes(1);+ });++ it.each([+ ['unparseable JSON', '{ "files": { '],+ ['a parsed non-object', 'null'],+ ['a non-object files map', JSON.stringify({ files: ['a.json'] })],+ ['a non-hash digest', JSON.stringify({ files: { 'a.json': 'not-a-hash' } })],+ // Valid hex on a traversing/absolute key — isolates the path check from+ // the digest check (a hostile manifest must not redirect verification).+ ['a traversal key', JSON.stringify({ files: { '../../outside.txt': 'a'.repeat(64) } })],+ ['an absolute key', JSON.stringify({ files: { '/etc/passwd': 'a'.repeat(64) } })],+ ])('fails closed when an existing manifest.json holds %s', async (_label, manifestText) => {+ await writeTree({ 'a.json': 'A' });+ await realFs.writeFile(joinPath(snapshotDir, 'manifest.json'), manifestText);++ await expect(restoreSnapshot(destRoot, SNAPSHOT_ID, { dryRun: true }))+ .rejects.toMatchObject({ status: 409, code: 'SNAPSHOT_MANIFEST_UNREADABLE' });+ await expect(restoreSnapshot(destRoot, SNAPSHOT_ID, { dryRun: false }))+ .rejects.toMatchObject({ code: 'SNAPSHOT_MANIFEST_UNREADABLE' });+ expect(spawn).not.toHaveBeenCalled();+ });+});+// =============================================================================// runBackup lifecycle (#3915)//