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: verify snapshot files before restore (#7167)

[._.]/ Adam Eivy0e2a27bd5ca0
diff --git a/client/src/components/BackupWidget.jsx b/client/src/components/BackupWidget.jsx
index 1f4eae1f01..e0f30cfca6 100644
--- a/client/src/components/BackupWidget.jsx
+++ b/client/src/components/BackupWidget.jsx
@@ -178,6 +178,18 @@ function RestorePanel({ snapshot, onClose, restoring, onRestoreStateChange }) {
{/* Dry-run results */}
{preview && (
<div>
+ {preview.verification?.status === 'verified' && (
+ <p className="mb-2 flex items-center gap-1.5 text-xs text-port-success" role="status">
+ <CheckCircle size={13} />
+ Snapshot integrity verified ({preview.verification.checkedFiles} selected file(s)).
+ </p>
+ )}
+ {preview.verification?.status === 'unverified' && (
+ <p className="mb-2 flex items-start gap-1.5 rounded border border-port-warning/40 bg-port-warning/10 p-2 text-xs text-port-warning" role="alert">
+ <AlertTriangle size={13} className="mt-0.5 shrink-0" />
+ Legacy snapshot: no integrity manifest is available. PortOS cannot verify these backup bytes before restore.
+ </p>
+ )}
<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.jsx
index 771657fb18..6890fc2a5b 100644
--- a/client/src/components/BackupWidget.test.jsx
+++ b/client/src/components/BackupWidget.test.jsx
@@ -130,6 +130,7 @@ describe('BackupWidget snapshots', () => {
snapshotId: '2026-08-25T11-00-00',
subdirFilter: 'brain',
changedFiles: ['brain/example.json'],
+ verification: { status: 'verified', checkedFiles: 1 },
})
.mockReturnValueOnce(new Promise(resolve => { finishRestore = resolve; }));
renderWidget();
@@ -139,6 +140,7 @@ describe('BackupWidget snapshots', () => {
fireEvent.click(screen.getByRole('button', { name: 'Preview changes' }));
expect(await screen.findByText('brain/example.json')).toBeInTheDocument();
+ expect(screen.getByRole('status')).toHaveTextContent('Snapshot integrity verified (1 selected file(s)).');
expect(mockRestoreBackup).toHaveBeenNthCalledWith(1, {
snapshotId: '2026-08-25T11-00-00',
subdirFilter: 'brain',
@@ -163,6 +165,23 @@ describe('BackupWidget snapshots', () => {
expect(mockToast.success).toHaveBeenCalledWith('Restore complete — 1 file(s) restored');
});
+ it('warns before confirming a legacy snapshot without an integrity manifest', async () => {
+ mockRestoreBackup.mockResolvedValueOnce({
+ dryRun: true,
+ changedFiles: ['settings.json'],
+ verification: { status: 'unverified', reason: 'manifest_absent', checkedFiles: 0 },
+ });
+ renderWidget();
+
+ await openRestorePanel();
+ fireEvent.click(screen.getByRole('button', { name: 'Preview changes' }));
+
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'Legacy snapshot: no integrity manifest is available. PortOS cannot verify these backup bytes before restore.',
+ );
+ expect(screen.getByRole('button', { name: 'Restore 1 file(s)' })).toBeEnabled();
+ });
+
it('invalidates a selective preview when the filter is cleared', async () => {
mockRestoreBackup
.mockResolvedValueOnce({ changedFiles: ['brain/example.json'] })
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 52f85d169c..69f3360179 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -67,7 +67,11 @@ A backup run that fails after creating its snapshot directory records a durable
### Files — `restoreSnapshot()`
-rsyncs `<snapshot>/data/` back to `./data/`. `dryRun: true` (the default) reports what would change without writing; an optional `subdirFilter` limits the restore to one subdirectory.
+Before rsync can read or overwrite live data, PortOS strictly reads `manifest.json`, validates every manifest path and SHA-256 value, and hashes every recorded regular file in the selected restore scope. A missing, unreadable, or mismatching selected file refuses both preview and execution before rsync starts. Selective restore verifies only its literal selected subtree and ignores the separately handled `../portos-db.sql` entry. The same preflight runs again for execution, so changing snapshot bytes after a successful preview cannot bypass verification. Readable symlinks retain the hash behavior used when the manifest was created; dangling symlinks remain outside the regular-file manifest and retain rsync's archive compatibility.
+
+Snapshots from PortOS versions that predate `manifest.json` remain restorable as an explicit compatibility case. Restore responses report `verification.status` as `verified` (with `checkedFiles`) or `unverified` with reason `manifest_absent`; the confirmation panel warns when a legacy restore cannot be verified. An existing manifest that is malformed or unreadable fails closed and is never treated as legacy absence.
+
+After the preflight, rsync copies `<snapshot>/data/` back to `./data/`. `dryRun: true` (the default) reports what would change without writing; an optional `subdirFilter` limits the restore to one subdirectory.
### Database — `restorePostgres()`
diff --git a/server/routes/backup.test.js b/server/routes/backup.test.js
index 8bcd3127a1..ee06f31ecc 100644
--- a/server/routes/backup.test.js
+++ b/server/routes/backup.test.js
@@ -171,12 +171,20 @@ describe('backup routes', () => {
it('forwards a valid restore request to the service', async () => {
getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
- backup.restoreSnapshot.mockResolvedValue({ success: true, restored: 42 });
+ backup.restoreSnapshot.mockResolvedValue({
+ success: true,
+ restored: 42,
+ verification: { status: 'verified', checkedFiles: 42 },
+ });
const res = await request(buildApp())
.post('/api/backup/restore')
.send({ snapshotId: 'snap-1', subdirFilter: 'data', dryRun: false });
expect(res.status).toBe(200);
- expect(res.body).toEqual({ success: true, restored: 42 });
+ expect(res.body).toEqual({
+ success: true,
+ restored: 42,
+ verification: { status: 'verified', checkedFiles: 42 },
+ });
expect(backup.restoreSnapshot).toHaveBeenCalledWith(
'/dest',
'snap-1',
diff --git a/server/services/backup.js b/server/services/backup.js
index e5b88ae7a3..a98d6a2d9f 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -793,6 +793,8 @@ export async function listSnapshots(destPath) {
}
const SNAPSHOT_ID_PATTERN = /^[\w\-.:T]+$/;
+const SHA256_PATTERN = /^[0-9a-f]{64}$/;
+const MANIFEST_ABSENT = Symbol('manifest-absent');
function resolveSnapshotPath(destPath, snapshotId) {
if (!snapshotId || !SNAPSHOT_ID_PATTERN.test(snapshotId)) {
@@ -900,6 +902,89 @@ async function reconcileLiveFileRestore(subdirFilter) {
}
}
+function manifestDataEntries(manifest, srcDir, subdirFilter) {
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)
+ || !manifest.files || typeof manifest.files !== 'object' || Array.isArray(manifest.files)
+ || !Number.isInteger(manifest.fileCount) || manifest.fileCount < 0
+ || typeof manifest.generatedAt !== 'string' || Number.isNaN(Date.parse(manifest.generatedAt))) {
+ return null;
+ }
+
+ const entries = Object.entries(manifest.files);
+ if (manifest.fileCount !== entries.length) return null;
+
+ const selected = [];
+ for (const [entry, expectedHash] of entries) {
+ if (typeof expectedHash !== 'string' || !SHA256_PATTERN.test(expectedHash)) return null;
+ if (entry === '../portos-db.sql') continue;
+
+ // Manifests are portable across supported platforms, so normalize both
+ // separator forms before validating or comparing a literal filter. Validate
+ // before resolving: resolve() would otherwise erase evidence of `..`.
+ const normalized = entry.replaceAll('\\', '/');
+ const segments = normalized.split('/');
+ if (!normalized || normalized.startsWith('/') || /^[A-Za-z]:\//.test(normalized)
+ || segments.some(segment => !segment || segment === '.' || segment === '..')) {
+ return null;
+ }
+
+ const filePath = resolve(srcDir, ...segments);
+ const rel = relative(resolve(srcDir), filePath);
+ if (!rel || rel.startsWith('..') || isAbsolute(rel)) return null;
+
+ if (!subdirFilter || normalized === subdirFilter || normalized.startsWith(`${subdirFilter}/`)) {
+ selected.push({ filePath, expectedHash });
+ }
+ }
+
+ return selected;
+}
+
+const snapshotFileIntegrityError = (snapshotId) => new ServerError(
+ `Snapshot file integrity check failed: ${snapshotId}`,
+ { status: 409, code: 'BACKUP_FILE_INTEGRITY_FAILED' },
+);
+
+async function verifySnapshotFiles(snapshotDir, srcDir, snapshotId, subdirFilter) {
+ // A unique fallback distinguishes a genuinely absent legacy manifest from an
+ // existing file whose parsed value is JSON null.
+ const manifestRead = await readJSONFileStrict(
+ join(snapshotDir, 'manifest.json'),
+ MANIFEST_ABSENT,
+ { logError: false },
+ );
+ if (!manifestRead.ok) {
+ throw new ServerError(`Snapshot integrity manifest is unreadable: ${snapshotId}`, {
+ status: 409,
+ code: 'BACKUP_MANIFEST_UNREADABLE',
+ });
+ }
+ if (manifestRead.value === MANIFEST_ABSENT) {
+ return { status: 'unverified', reason: 'manifest_absent', checkedFiles: 0 };
+ }
+
+ const selected = manifestDataEntries(manifestRead.value, srcDir, subdirFilter);
+ if (!selected) {
+ throw new ServerError(`Snapshot integrity manifest is invalid: ${snapshotId}`, {
+ status: 409,
+ code: 'BACKUP_MANIFEST_INVALID',
+ });
+ }
+
+ for (const { filePath, expectedHash } of selected) {
+ const info = await lstat(filePath).catch(() => null);
+ if (!info || (!info.isFile() && !info.isSymbolicLink())) {
+ throw snapshotFileIntegrityError(snapshotId);
+ }
+ const actualHash = await sha256File(filePath).catch(() => null);
+ if (!actualHash || actualHash !== expectedHash) {
+ throw snapshotFileIntegrityError(snapshotId);
+ }
+ }
+
+ return { status: 'verified', checkedFiles: selected.length };
+}
+
/**
* Restore a snapshot back to PATHS.data using rsync.
* @param {string} destPath - Path to external drive backup root
@@ -922,6 +1007,11 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
throw new Error(`Invalid subdirFilter: ${subdirFilter}`);
}
+ // Run the preflight independently for preview and execution. A preview is an
+ // aid to confirmation, not an integrity lease: snapshot bytes may change
+ // between requests, especially on removable or network-backed destinations.
+ const verification = await verifySnapshotFiles(snapshotDir, srcDir, snapshotId, subdirFilter);
+
const flags = ['--itemize-changes'];
if (dryRun) flags.push('--dry-run');
if (subdirFilter) {
@@ -951,7 +1041,7 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
}
if (reconciliationError) throw reconciliationError;
- return { dryRun, snapshotId, subdirFilter, changedFiles: transfer.value };
+ return { dryRun, snapshotId, subdirFilter, changedFiles: transfer.value, verification };
}
/**
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index c5293d8d60..10019e3cc3 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -1132,6 +1132,142 @@ describe('generateManifest', () => {
});
});
+describe('restoreSnapshot manifest verification', () => {
+ let tmpRoot;
+ let snapshotDir;
+ let snapshotDataDir;
+ let realFs;
+
+ beforeEach(async () => {
+ 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);
+ spawn.mockReset();
+ tmpRoot = await realFs.mkdtemp(joinPath(tmpdir(), 'portos-restore-integrity-'));
+ snapshotDir = joinPath(tmpRoot, 'snapshots', machineHost, 'snap-1');
+ snapshotDataDir = joinPath(snapshotDir, 'data');
+ await realFs.mkdir(snapshotDataDir, { recursive: true });
+ });
+
+ afterEach(async () => {
+ await realFs?.rm(tmpRoot, { recursive: true, force: true });
+ await realFs?.rm(joinPath(PATHS.data, 'restore-integrity'), { recursive: true, force: true });
+ });
+
+ async function writeSnapshotFile(relativePath, content) {
+ const path = joinPath(snapshotDataDir, relativePath);
+ await realFs.mkdir(joinPath(path, '..'), { recursive: true });
+ await realFs.writeFile(path, content);
+ return createHash('sha256').update(Buffer.from(content)).digest('hex');
+ }
+
+ async function writeManifest(files) {
+ await realFs.writeFile(joinPath(snapshotDir, 'manifest.json'), JSON.stringify({
+ generatedAt: '2026-09-12T00:00:00.000Z',
+ fileCount: Object.keys(files).length,
+ files,
+ }));
+ }
+
+ async function finishRestore(options = {}) {
+ const proc = fakeProc();
+ spawn.mockReturnValueOnce(proc);
+ const pending = restoreSnapshot(tmpRoot, 'snap-1', options);
+ await vi.waitFor(() => expect(spawn).toHaveBeenCalled());
+ proc.emit('close', 0);
+ return pending;
+ }
+
+ it('rechecks snapshot bytes on execution and refuses a post-preview change before rsync', async () => {
+ const relativePath = 'restore-integrity/example.json';
+ const originalHash = await writeSnapshotFile(relativePath, 'trusted backup');
+ await writeManifest({ [relativePath]: originalHash });
+ const livePath = joinPath(PATHS.data, relativePath);
+ await realFs.mkdir(joinPath(livePath, '..'), { recursive: true });
+ await realFs.writeFile(livePath, 'healthy live data');
+
+ await expect(finishRestore({ dryRun: true })).resolves.toMatchObject({
+ verification: { status: 'verified', checkedFiles: 1 },
+ });
+
+ await realFs.writeFile(joinPath(snapshotDataDir, relativePath), 'changed after preview');
+ spawn.mockReset();
+ await expect(restoreSnapshot(tmpRoot, 'snap-1', { dryRun: false }))
+ .rejects.toMatchObject({ code: 'BACKUP_FILE_INTEGRITY_FAILED' });
+ expect(spawn).not.toHaveBeenCalled();
+ expect(await realFs.readFile(livePath, 'utf8')).toBe('healthy live data');
+ });
+
+ it.each([
+ ['missing', async (path) => realFs.unlink(path)],
+ ['unreadable', async (path) => {
+ fs.readFile.mockImplementation(async (candidate, ...args) => {
+ if (String(candidate) === path) throw Object.assign(new Error('unreadable'), { code: 'EACCES' });
+ return realFs.readFile(candidate, ...args);
+ });
+ }],
+ ])('refuses a %s selected file before rsync', async (_case, breakFile) => {
+ const relativePath = 'brain/example.json';
+ const filePath = joinPath(snapshotDataDir, relativePath);
+ const hash = await writeSnapshotFile(relativePath, 'snapshot data');
+ await writeManifest({ [relativePath]: hash });
+ await breakFile(filePath);
+
+ await expect(restoreSnapshot(tmpRoot, 'snap-1', { subdirFilter: 'brain' }))
+ .rejects.toMatchObject({ code: 'BACKUP_FILE_INTEGRITY_FAILED' });
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it('validates the whole manifest but hashes only the literal selective scope', async () => {
+ const brainHash = await writeSnapshotFile('brain/example.json', 'brain');
+ await writeSnapshotFile('media/example.json', 'media');
+ await writeManifest({
+ 'brain/example.json': brainHash,
+ 'media/example.json': '0'.repeat(64),
+ '../portos-db.sql': '1'.repeat(64),
+ });
+
+ await expect(finishRestore({ dryRun: true, subdirFilter: 'brain' })).resolves.toMatchObject({
+ verification: { status: 'verified', checkedFiles: 1 },
+ });
+ });
+
+ it.each([
+ ['malformed JSON', '{"files":'],
+ ['a null root', 'null'],
+ ['an invalid shape', JSON.stringify({ fileCount: 1, files: [] })],
+ ['an unsafe data path', JSON.stringify({ fileCount: 1, files: { '../outside.json': '0'.repeat(64) } })],
+ ])('fails closed when an existing manifest has %s', async (_case, manifestBytes) => {
+ await realFs.writeFile(joinPath(snapshotDir, 'manifest.json'), manifestBytes);
+
+ await expect(restoreSnapshot(tmpRoot, 'snap-1'))
+ .rejects.toMatchObject({ code: expect.stringMatching(/^BACKUP_MANIFEST_(UNREADABLE|INVALID)$/) });
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it('keeps legacy snapshots explicit and preserves manifest-compatible symlinks', async () => {
+ await expect(finishRestore({ dryRun: true })).resolves.toMatchObject({
+ verification: { status: 'unverified', reason: 'manifest_absent', checkedFiles: 0 },
+ });
+
+ const targetHash = await writeSnapshotFile('example.txt', 'example');
+ await realFs.symlink('example.txt', joinPath(snapshotDataDir, 'readable-link'));
+ await realFs.symlink('missing.txt', joinPath(snapshotDataDir, 'dangling-link'));
+ await writeManifest({
+ 'example.txt': targetHash,
+ 'readable-link': targetHash,
+ });
+ spawn.mockReset();
+
+ await expect(finishRestore({ dryRun: true })).resolves.toMatchObject({
+ verification: { status: 'verified', checkedFiles: 2 },
+ });
+ });
+});
+
// 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.