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(#980): verify pg dump against manifest SHA-256 before DB restore

Adam Eivybcdf11ef988b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index aa37deeda4..39c28d6e5c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -31,6 +31,8 @@
## Fixed
- **Sheet music: low notes no longer overlap their lyrics** — the lyric line was drawn at a fixed distance below the staff, so notes that dip below it (ledger-line pitches like A3) rendered their noteheads on top of the syllable. Lyrics now sit below the lowest note in each line.
+- **[issue-980] PostgreSQL restores now verify the backup against its manifest before replaying** — a snapshot's database dump is hashed into the snapshot's `manifest.json` when the backup is taken, but the restore path never checked that hash, so a corrupted or tampered dump would be fed straight into `psql`. Restores now recompute the dump's SHA-256 and compare it against the stored hash first; on a mismatch the restore refuses (no `psql` is run) rather than replaying a damaged dump over your live database. Older snapshots taken before manifests existed — or any manifest missing the dump's entry — still restore as before, since there's nothing recorded to verify against.
+
- **MortalLoom iCloud writes no longer fail when the data file has been offloaded** — under macOS "Optimize Mac Storage," iCloud can evict `MortalLoom.json` to the cloud (a dataless placeholder) hours after PortOS booted. A write would then fail to read the evicted file within the brief retry window and refuse to overwrite it ("MortalLoom store is unreadable; refusing to overwrite") rather than risk truncating your data — but that also blocked the write entirely. PortOS now pre-warms the file on demand: before refusing, it runs `brctl download` and waits for the file to materialize, then re-reads and proceeds. It also detects a legacy `.icloud` placeholder shadowing the real path so it won't seed a fresh (empty) store on top of evicted data. If the file is genuinely corrupt, or the device is offline and can't download it, PortOS still safely refuses rather than clobbering the iCloud copy. The fire-and-forget boot/settings-change pinning remains as the first line of defense.
- **[issue-978] Apps no longer get stuck reading "in review" after a no-op idle check** — when the Chief of Staff's idle review picked an app but had nothing to actually do (no claimable plan item, no new commits or PRs to watch), the app could stay marked as under review until a restart or cleanup pass cleared it. Idle checks that find no work now release the app right away while still spacing out how often it's rechecked.
diff --git a/server/services/backup.js b/server/services/backup.js
index f0c7adf026..f06719dc23 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -464,6 +464,24 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true } =
if (!info || !info.isFile?.() || info.size === 0) {
return { status: 'skipped', reason: 'no_dump' };
}
+ // Verify the dump against the manifest's stored SHA-256 before trusting it.
+ // The dump is hashed in generateManifest under the parent-relative key
+ // '../portos-db.sql' (it lives ALONGSIDE the snapshot data/ dir, not inside
+ // it). Backward-compat: snapshots taken before manifests existed — or missing
+ // the dump key — have nothing to verify against, so we SKIP verification and
+ // proceed rather than hard-failing. Only a manifest that IS present AND
+ // carries a mismatching hash refuses the restore.
+ const manifestPath = join(snapshotsRoot, snapshotId, 'manifest.json');
+ const manifest = await readJSONFile(manifestPath, null);
+ const expectedHash = manifest?.files?.['../portos-db.sql'];
+ if (expectedHash) {
+ const actualHash = await sha256File(sqlPath);
+ if (actualHash !== expectedHash) {
+ console.error(`❌ restore: manifest hash mismatch for snapshot ${snapshotId} (expected ${expectedHash}, got ${actualHash})`);
+ return { status: 'failed', reason: 'manifest_mismatch' };
+ }
+ }
+
const sql = await readFile(sqlPath, 'utf-8').catch(() => '');
const tableCount = (sql.match(/^CREATE TABLE /gm) || []).length;
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index a2e9f4d3ca..d070249e03 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -25,6 +25,7 @@ vi.mock('./memoryBackend.js', () => ({
}));
import { EventEmitter } from 'events';
+import { createHash } from 'crypto';
import { spawn } from 'child_process';
// Partial mock: only override spawn. Preserve execFile et al. because
// backup.js transitively imports fileUtils.js, which promisifies execFile.
@@ -397,6 +398,65 @@ describe('restorePostgres', () => {
expect(result.reason).toBe('restore_error');
expect(result.error).toContain('already exists');
});
+
+ // Manifest SHA-256 verification (#980). The dump is hashed in generateManifest
+ // under the parent-relative key '../portos-db.sql' — these tests assert the
+ // exact key, the mismatch refusal, and the backward-compat skip paths.
+ //
+ // sha256File reads the dump via fs.readFile (small-file path). We mock
+ // readFile path-aware: manifest.json returns the manifest JSON, the dump path
+ // returns the SQL bytes that sha256File hashes. The dump content here is the
+ // small string 'CREATE TABLE a;' — its real sha256 is the constant below.
+ const DUMP_SQL = 'CREATE TABLE a;';
+ // Compute the genuine hash so the "match" test verifies real bytes, not a
+ // hard-coded string that could drift from sha256File's implementation.
+ const REAL_DUMP_SHA256 = createHash('sha256').update(Buffer.from(DUMP_SQL)).digest('hex');
+
+ function mockDumpAndManifest(manifestObj) {
+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: DUMP_SQL.length, isFile: () => true });
+ vi.spyOn(fs, 'readFile').mockImplementation(async (p) => {
+ const path = String(p);
+ if (path.endsWith('manifest.json')) {
+ if (manifestObj === null) {
+ const err = new Error('ENOENT');
+ err.code = 'ENOENT';
+ throw err;
+ }
+ return JSON.stringify(manifestObj);
+ }
+ return DUMP_SQL;
+ });
+ }
+
+ it('proceeds when the dump hash matches the manifest (match)', async () => {
+ mockDumpAndManifest({ files: { '../portos-db.sql': REAL_DUMP_SHA256 } });
+ const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: true });
+ expect(result.status).toBe('ok');
+ expect(result.dryRun).toBe(true);
+ expect(result.tableCount).toBe(1);
+ });
+
+ it('refuses with manifest_mismatch when the dump hash differs (mismatch)', async () => {
+ mockDumpAndManifest({ files: { '../portos-db.sql': 'deadbeef'.repeat(8) } });
+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
+ const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: false });
+ expect(result).toEqual({ status: 'failed', reason: 'manifest_mismatch' });
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it('skips verification when manifest.json is absent (backward-compat)', async () => {
+ mockDumpAndManifest(null);
+ const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: true });
+ expect(result.status).toBe('ok');
+ expect(result.tableCount).toBe(1);
+ });
+
+ it('skips verification when the manifest lacks the dump key (pre-#976 manifest)', async () => {
+ mockDumpAndManifest({ files: { 'instances.json': 'abc123' } });
+ const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: true });
+ expect(result.status).toBe('ok');
+ expect(result.tableCount).toBe(1);
+ });
});
describe('runBackup pg status propagation', () => {