'use strict'; const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); const {spawnSync} = require('node:child_process'); const {DatabaseSync} = require('node:sqlite'); const {openStore} = require('../server/store.cjs'); const {createAuth} = require('../server/auth.cjs'); const {createService} = require('../server/service.cjs'); const {createRehearsals, verifyStoredRehearsal} = require('../server/rehearsal.cjs'); const U = require('../server/util.cjs'); const NOW = '2026-10-22T12:00:00.000Z'; const PASSWORD = 'Fictional rehearsal recovery password 2026!'; const MANAGE = path.resolve(__dirname, '../scripts/manage.cjs'); let encodedPassword; const missing = e => e.code === 'missing' && e.status === 404; async function fixture(t) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'glemo-rehearsal-recovery-')); let store, auth, service, rehearsals; const now = () => NOW; function reopen() { store = openStore(dir); auth = createAuth(store, {now}); service = createService(store, auth, {now}); rehearsals = createRehearsals(store, {now}); } function close() { if (store) { store.close(); store = null; } } t.after(() => { try { close(); } finally { fs.rmSync(dir, {recursive: true, force: true}); } }); reopen(); encodedPassword ||= U.passwordHash(PASSWORD); const passwordHash = await encodedPassword; function person(role) { const id = U.id(), orgId = U.id(), alias = 'rehearsal-recovery-' + role; store.run('INSERT INTO organizations VALUES (?,?,?)', orgId, 'DEMO recovery ' + role, NOW); store.run('INSERT INTO users VALUES (?,?,?,?,?,?,?)', id, alias, role, orgId, passwordHash, 1, NOW); store.run('INSERT INTO profiles VALUES (?,?,?,?)', id, JSON.stringify({completed: true, preferences: {inApp: true}}), 1, NOW); return auth.publicUser(store.get('SELECT * FROM users WHERE id=?', id)); } const admin = person('admin'), owner = person('buyer'), other = person('holder'); function start(user = owner, role = 'buyer', scenario = 'standard') { return rehearsals.start(user, {offerId: 'DEMO-OFFER-001', role, scenario}); } function step(user, id, action, payload) { const view = rehearsals.get(user, id); const body = {action, payload, expectedRevision: view.revision, idempotencyKey: U.id()}; return {body, view: rehearsals.commands(user, id, body)}; } function feedback(user, id, body) { const view = rehearsals.get(user, id); return rehearsals.feedback(user, id, {score: 4, body, expectedRevision: view.revision}); } return {dir, admin, owner, other, close, reopen, start, step, feedback, get store() { return store; }, get auth() { return auth; }, get service() { return service; }, get rehearsals() { return rehearsals; }}; } function cli(dir, args) { const result = spawnSync(process.execPath, args, { env: {...process.env, PILOT_DATA_DIR: dir, PUBLIC_ORIGIN: 'http://127.0.0.1:8816'}, encoding: 'utf8', timeout: 15000 }); assert.equal(result.error, undefined, result.error?.message); assert.equal(result.signal, null); return result; } const manage = (dir, action, ...args) => cli(dir, [MANAGE, action, ...args]); const rows = f => f.store.all('SELECT * FROM rehearsals ORDER BY id'); const credentials = f => f.store.all('SELECT id,role,password_hash FROM users ORDER BY id') .map(({password_hash, ...user}) => ({...user, passwordDigest: U.hash(password_hash)})); const databaseDigest = dir => U.hash(fs.readFileSync(path.join(dir, 'pilot.sqlite'))); function assertNoRestoreDebris(dir) { assert.equal(fs.existsSync(path.join(dir, 'maintenance.lock')), false); assert.deepEqual(fs.readdirSync(dir).filter(name => name.startsWith('restore-')), []); } function assertPrivate(f, owner, other, admin, completedId, partialId) { assert.deepEqual(f.rehearsals.list(owner).sessions.map(s => s.id), [completedId]); assert.deepEqual(f.rehearsals.list(other).sessions.map(s => s.id), [partialId]); assert.deepEqual(f.rehearsals.list(admin).sessions, []); for (const [user, id] of [[other, completedId], [owner, partialId], [admin, completedId], [admin, partialId]]) { assert.throws(() => f.rehearsals.get(user, id), missing); assert.throws(() => f.rehearsals.report(user, id), missing); } } function seedJourneys(f) { const completed = f.start(); let first; for (const [action, payload] of [['propose', {price: completed.suggested.price}], ['acknowledge', {acknowledged: true}], ['settle', {acknowledged: true}], ['reconcile', {acknowledged: true}]]) { const result = f.step(f.owner, completed.id, action, payload); assert.equal(result.view.commandError, null); first ||= result.body; } f.feedback(f.owner, completed.id, 'DEMO private completed recovery feedback'); const partial = f.start(f.other, 'holder', 'missing_documents'); f.step(f.other, partial.id, 'offer', {quantity: partial.suggested.quantity, price: partial.suggested.price, agent: true, acknowledged: true}); const blocked = f.step(f.other, partial.id, 'propose', {price: partial.suggested.price}); assert.equal(blocked.view.commandError, 'checklistRequired'); f.feedback(f.other, partial.id, 'DEMO private partial recovery feedback'); return {completedId: completed.id, partialId: partial.id, first, blocked: blocked.body}; } function backup(f) { f.close(); const result = manage(f.dir, 'backup'); assert.equal(result.status, 0, result.stderr); const info = JSON.parse(result.stdout), filename = path.join(f.dir, 'backups', info.name); assert.equal(info.sha256, U.hash(fs.readFileSync(filename))); assert.equal(info.bytes, fs.statSync(filename).size); assert.equal(fs.statSync(filename).mode & 0o777, 0o600); f.reopen(); return filename; } function editBackup(filename, id, change) { const db = new DatabaseSync(filename); try { const original = db.prepare('SELECT * FROM rehearsals WHERE id=?').get(id); const next = change(JSON.parse(original.data), original); const data = typeof next === 'string' ? next : JSON.stringify(next); db.prepare('UPDATE rehearsals SET data=?,data_hash=? WHERE id=?').run(data, U.hash(data), id); const row = db.prepare('SELECT * FROM rehearsals WHERE id=?').get(id); assert.equal(row.data_hash, U.hash(row.data)); assert.equal(db.prepare('PRAGMA integrity_check').get().integrity_check, 'ok'); assert.deepEqual(db.prepare('PRAGMA foreign_key_check').all(), []); } finally { db.close(); } } test('rehearsal recovery: restart preserves private completed and partial sessions, feedback and retry journals', async t => { const f = await fixture(t), journeys = seedJourneys(f); const expected = rows(f), accounts = credentials(f); const reports = [f.rehearsals.report(f.owner, journeys.completedId), f.rehearsals.report(f.other, journeys.partialId)]; const audit = f.store.all('SELECT * FROM security_audit ORDER BY sequence'); f.close(); f.reopen(); assert.deepEqual(rows(f), expected); assert.deepEqual(credentials(f), accounts); for (const row of rows(f)) assert.equal(verifyStoredRehearsal(row).revision, row.revision); assert.deepEqual(f.rehearsals.report(f.owner, journeys.completedId), reports[0]); assert.deepEqual(f.rehearsals.report(f.other, journeys.partialId), reports[1]); assert.equal(reports[0].complete, true); assert.equal(reports[0].outputs.reconciled, true); assert.equal(reports[1].phase, 'documents'); assert.equal(reports[1].complete, false); assert.equal(reports[1].outputs.cashRecorded, false); assert.equal(reports[1].attempts.at(-1).code, 'checklistRequired'); assertPrivate(f, f.owner, f.other, f.admin, journeys.completedId, journeys.partialId); const replay = f.rehearsals.commands(f.owner, journeys.completedId, journeys.first); assert.equal(replay.replayed, true); assert.equal(replay.complete, true); const blocked = f.rehearsals.commands(f.other, journeys.partialId, journeys.blocked); assert.equal(blocked.replayed, true); assert.equal(blocked.commandError, 'checklistRequired'); assert.deepEqual(rows(f), expected); assert.deepEqual(f.store.all('SELECT * FROM security_audit ORDER BY sequence'), audit); }); test('rehearsal recovery: CLI backup and restore recover snapshot state and private feedback for each owner', async t => { const source = await fixture(t), destination = await fixture(t), journeys = seedJourneys(source); const session = await source.auth.login({alias: source.owner.alias, password: PASSWORD}, 'fictional-local'); const expected = rows(source), accounts = credentials(source), metrics = source.service.metrics(source.admin); const filename = backup(source), sourceDigest = U.hash(fs.readFileSync(filename)); const copy = new DatabaseSync(filename, {readOnly: true}); try { assert.deepEqual(copy.prepare('SELECT * FROM rehearsals ORDER BY id').all(), expected); } finally { copy.close(); } source.feedback(source.owner, journeys.completedId, 'DEMO newer feedback excluded from snapshot'); source.step(source.other, journeys.partialId, 'restore_documents', {acknowledged: true}); const marker = destination.start(); const previous = rows(destination); source.close(); destination.close(); const result = manage(destination.dir, 'restore', filename); assert.equal(result.status, 0, result.stderr); assert.deepEqual(JSON.parse(result.stdout), {restored: true, credentialsPreserved: true, sessionsRevoked: true, unusedInvitesRevoked: true}); assertNoRestoreDebris(destination.dir); destination.reopen(); assert.deepEqual(rows(destination), expected); assert.deepEqual(credentials(destination), accounts); assert.equal(destination.rehearsals.get(source.owner, journeys.completedId).feedback.body, 'DEMO private completed recovery feedback'); assert.equal(destination.rehearsals.get(source.other, journeys.partialId).feedback.body, 'DEMO private partial recovery feedback'); assert.equal(destination.rehearsals.get(source.other, journeys.partialId).phase, 'documents'); assertPrivate(destination, source.owner, source.other, source.admin, journeys.completedId, journeys.partialId); assert.equal(destination.store.get('SELECT id FROM rehearsals WHERE id=?', marker.id), undefined); assert.equal(destination.auth.session(session.raw), null); assert.equal(destination.store.get('SELECT count(*) AS n FROM sessions').n, 0); assert.deepEqual(destination.service.metrics(source.admin), metrics); assert.equal(destination.store.get('SELECT count(*) AS n FROM external_evidence').n, 0); assert.equal(U.hash(fs.readFileSync(filename)), sourceDigest, 'restore must not edit its source backup'); assert.equal(destination.store.get('SELECT action FROM security_audit ORDER BY sequence DESC LIMIT 1').action, 'backup_restored'); const retained = fs.readdirSync(path.join(destination.dir, 'backups')).filter(name => name.endsWith('.sqlite')); assert.equal(retained.length, 1); const old = new DatabaseSync(path.join(destination.dir, 'backups', retained[0]), {readOnly: true}); try { assert.deepEqual(old.prepare('SELECT * FROM rehearsals ORDER BY id').all(), previous); } finally { old.close(); } const audit = destination.store.get('SELECT count(*) AS n FROM security_audit').n; assert.equal(destination.rehearsals.commands(source.other, journeys.partialId, journeys.blocked).replayed, true); assert.equal(destination.store.get('SELECT count(*) AS n FROM security_audit').n, audit); assert.equal(destination.step(source.other, journeys.partialId, 'restore_documents', {acknowledged: true}).view.phase, 'negotiation'); assert.equal(destination.rehearsals.get(source.owner, journeys.completedId).outputs.feeCollected, false); }); async function rejectCorruptBackup(t, change) { const source = await fixture(t), destination = await fixture(t), view = source.start(); const filename = backup(source); editBackup(filename, view.id, change); const marker = destination.start(); destination.feedback(destination.owner, marker.id, 'DEMO valid destination must survive rejected restore'); const expected = rows(destination), accounts = credentials(destination); destination.close(); source.close(); const before = databaseDigest(destination.dir), sourceDigest = U.hash(fs.readFileSync(filename)); const result = manage(destination.dir, 'restore', filename); assertNoRestoreDebris(destination.dir); assert.equal(U.hash(fs.readFileSync(filename)), sourceDigest); assert.equal(result.status, 1, 'a logically corrupt rehearsal backup must be rejected'); assert.match(result.stderr, /corrupt|Invalid backup/); assert.equal(databaseDigest(destination.dir), before, 'rejection must preserve destination bytes'); destination.reopen(); assert.deepEqual(rows(destination), expected); assert.deepEqual(credentials(destination), accounts); assert.equal(destination.rehearsals.get(destination.owner, marker.id).feedback.body, 'DEMO valid destination must survive rejected restore'); } test('rehearsal recovery: matching digests cannot hide corrupt JSON, domain state or row identity', async t => { for (const [name, change] of Object.entries({ 'invalid JSON': () => '{', 'simulation disabled': s => ({...s, simulation: false}), 'invalid financial state': s => { s.state.core.positions[0].quantity = '-1'; return s; }, 'row identity mismatch': s => ({...s, id: 'REHEARSAL-DEMO-DIFFERENT'}), 'row revision mismatch': s => ({...s, revision: s.revision + 1}) })) await t.test(name, sub => rejectCorruptBackup(sub, change)); }); test('rehearsal recovery: matching digests cannot hide unusable rehearsal wrapper fields', async t => { for (const [name, change] of Object.entries({ 'invalid synthetic clock': s => ({...s, clock: 'invalid'}), 'missing recovery flags': s => ({...s, flags: null}), 'malformed retry journal': s => ({...s, commands: [null]}), 'missing offer context': s => ({...s, offer: null}) })) await t.test(name, sub => rejectCorruptBackup(sub, change)); }); test('rehearsal recovery: staged-copy validation rejects corruption introduced after source validation', async t => { const source = await fixture(t), destination = await fixture(t), view = source.start(); const filename = backup(source), sourceDigest = U.hash(fs.readFileSync(filename)); const marker = destination.start(), expected = rows(destination); source.close(); destination.close(); const before = databaseDigest(destination.dir); // Damage only the fixture's staged copy, leaving the validated source file intact. const script = ` const fs = require('node:fs'), path = require('node:path'); const {DatabaseSync} = require('node:sqlite'), U = require(${JSON.stringify(path.resolve(__dirname, '../server/util.cjs'))}); const [manage, source, id] = process.argv.slice(1), copy = fs.copyFileSync; fs.copyFileSync = function(from, to, ...args) { const result = Reflect.apply(copy, this, [from, to, ...args]); if (path.basename(to).startsWith('restore-')) { const db = new DatabaseSync(to); try { const s = JSON.parse(db.prepare('SELECT data FROM rehearsals WHERE id=?').get(id).data); s.simulation = false; const data = JSON.stringify(s); db.prepare('UPDATE rehearsals SET data=?,data_hash=? WHERE id=?').run(data, U.hash(data), id); } finally { db.close(); } } return result; }; process.argv = [process.execPath, manage, 'restore', source]; require(manage).main().catch(e => { console.error(e.code || e.message); process.exitCode = 1; }); `; const result = cli(destination.dir, ['--eval', script, MANAGE, filename, view.id]); assert.equal(result.status, 1); assert.match(result.stderr, /corrupt/); assert.equal(databaseDigest(destination.dir), before); assert.equal(U.hash(fs.readFileSync(filename)), sourceDigest); assertNoRestoreDebris(destination.dir); destination.reopen(); assert.deepEqual(rows(destination), expected); assert.equal(destination.rehearsals.get(destination.owner, marker.id).revision, 0); }); test('rehearsal recovery: legacy backups without a rehearsals table restore and migrate to an empty table', async t => { const source = await fixture(t), destination = await fixture(t), legacySession = source.start(); const filename = backup(source), accounts = credentials(source); const legacy = new DatabaseSync(filename); try { legacy.exec('DROP TABLE rehearsals'); assert.equal(legacy.prepare("SELECT name FROM sqlite_schema WHERE type='table' AND name='rehearsals'").get(), undefined); assert.equal(legacy.prepare('PRAGMA integrity_check').get().integrity_check, 'ok'); assert.deepEqual(legacy.prepare('PRAGMA foreign_key_check').all(), []); } finally { legacy.close(); } const marker = destination.start(), sourceDigest = U.hash(fs.readFileSync(filename)); source.close(); destination.close(); const result = manage(destination.dir, 'restore', filename); assert.equal(result.status, 0, result.stderr); assertNoRestoreDebris(destination.dir); const restored = new DatabaseSync(path.join(destination.dir, 'pilot.sqlite'), {readOnly: true}); try { assert.equal(restored.prepare("SELECT name FROM sqlite_schema WHERE type='table' AND name='rehearsals'").get(), undefined); } finally { restored.close(); } destination.reopen(); assert.deepEqual(rows(destination), []); assert.deepEqual(credentials(destination), accounts); assert.deepEqual(destination.rehearsals.list(source.owner).sessions, []); assert.throws(() => destination.rehearsals.get(source.owner, legacySession.id), missing); assert.throws(() => destination.rehearsals.get(source.owner, marker.id), missing); assert.equal(destination.service.metrics(source.admin).realRevenueCents, 0); const fresh = destination.start(source.owner); assert.equal(fresh.revision, 0); assert.equal(verifyStoredRehearsal(destination.store.get('SELECT * FROM rehearsals WHERE id=?', fresh.id)).id, fresh.id); assert.equal(U.hash(fs.readFileSync(filename)), sourceDigest); });