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

feat(backup): add restorePostgres with dry-run default and traversal guard

Adam Eivyaaeaf962bef7
diff --git a/server/services/backup.js b/server/services/backup.js
index f39b8ba371..9f1177953d 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -399,6 +399,76 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
return { dryRun, snapshotId, subdirFilter, changedFiles };
}
+/**
+ * Restore the PostgreSQL dump from a snapshot. Dry-run by default — mirrors
+ * restoreSnapshot's safety default. A real restore pipes the snapshot's
+ * portos-db.sql into psql; the dump was written with --no-owner --no-acl so
+ * it replays cleanly.
+ * { status: 'ok', dryRun, sizeBytes, tableCount } (dry-run or applied)
+ * { status: 'skipped', reason: 'no_dump' } (no sql file in snapshot)
+ * { status: 'skipped', reason: 'not_configured' } (real restore, PG unreachable)
+ * { status: 'failed', reason: 'restore_error', error }
+ * @param {string} destPath - Backup destination root
+ * @param {string} snapshotId
+ * @param {{dryRun?: boolean}} [options]
+ */
+export async function restorePostgres(destPath, snapshotId, { dryRun = true } = {}) {
+ if (!snapshotId || !/^[\w\-.:T]+$/.test(snapshotId)) {
+ throw new Error(`Invalid snapshotId: ${snapshotId}`);
+ }
+ const snapshotsRoot = resolve(join(destPath, 'snapshots', MACHINE_HOST));
+ const sqlPath = join(snapshotsRoot, snapshotId, 'portos-db.sql');
+ const rel = relative(snapshotsRoot, resolve(sqlPath));
+ if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
+ throw new Error(`Path traversal detected for snapshotId: ${snapshotId}`);
+ }
+
+ const info = await stat(sqlPath).catch(() => null);
+ if (!info || !info.isFile?.()) {
+ return { status: 'skipped', reason: 'no_dump' };
+ }
+ const sql = await readFile(sqlPath, 'utf-8').catch(() => '');
+ const tableCount = (sql.match(/^CREATE TABLE /gm) || []).length;
+
+ if (dryRun) {
+ return { status: 'ok', dryRun: true, sizeBytes: info.size, tableCount };
+ }
+
+ // Never half-restore: require a reachable DB before replaying.
+ const health = await checkHealth();
+ if (!health.connected) {
+ return { status: 'skipped', reason: 'not_configured' };
+ }
+
+ const pgHost = process.env.PGHOST || 'localhost';
+ const pgPort = process.env.PGPORT || '5432';
+ const pgDb = process.env.PGDATABASE || 'portos';
+ const pgUser = process.env.PGUSER || 'portos';
+
+ return new Promise((resolveP) => {
+ const proc = spawn('psql', [
+ '-h', pgHost, '-p', pgPort, '-U', pgUser, '-d', pgDb, '-f', sqlPath
+ ], { shell: false, env: { ...process.env, PGPASSWORD: process.env.PGPASSWORD || 'portos' } });
+
+ let stderr = '';
+ proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
+
+ proc.on('close', (code) => {
+ if (code === 0) {
+ console.log(`💾 psql restore complete from snapshot ${snapshotId}: ${tableCount} tables`);
+ resolveP({ status: 'ok', dryRun: false, sizeBytes: info.size, tableCount });
+ } else {
+ console.warn(`⚠️ psql restore failed (code ${code}): ${stderr.trim()}`);
+ resolveP({ status: 'failed', reason: 'restore_error', error: stderr.trim() });
+ }
+ });
+ proc.on('error', (err) => {
+ console.warn(`⚠️ psql not available: ${err.message}`);
+ resolveP({ status: 'failed', reason: 'restore_error', error: err.message });
+ });
+ });
+}
+
/**
* Get current backup state from disk.
*/
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index a5a8fb9168..5f01498b97 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -225,6 +225,45 @@ describe('dumpPostgres status classification', () => {
});
});
+describe('restorePostgres', () => {
+ let restorePostgres;
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ ({ restorePostgres } = await import('./backup.js'));
+ });
+
+ it('rejects a path-traversal snapshotId', async () => {
+ await expect(restorePostgres('/dest', '../../etc', { dryRun: true }))
+ .rejects.toThrow(/Invalid snapshotId/);
+ });
+
+ it('returns skipped/no_dump when the sql file is absent', async () => {
+ vi.spyOn(fs, 'stat').mockRejectedValue(new Error('ENOENT'));
+ const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: true });
+ expect(result).toEqual({ status: 'skipped', reason: 'no_dump' });
+ });
+
+ it('dry-run reports size/tableCount without spawning psql', async () => {
+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
+ vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE a (...);\n');
+ const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: true });
+ expect(result.status).toBe('ok');
+ expect(result.dryRun).toBe(true);
+ expect(result.sizeBytes).toBe(4096);
+ expect(result.tableCount).toBe(1);
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it('refuses a real restore when PG is not connected', async () => {
+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
+ vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE a (...);\n');
+ checkHealth.mockResolvedValue({ connected: false, hasSchema: false });
+ const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: false });
+ expect(result).toEqual({ status: 'skipped', reason: 'not_configured' });
+ expect(spawn).not.toHaveBeenCalled();
+ });
+});
+
describe('runBackup pg status propagation', () => {
let backup;
beforeEach(async () => {