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: preserve provisioned extensions during database imports (#9901)
Adam Eivy7825cfe327e8
diff --git a/scripts/db-migrate.test.js b/scripts/db-migrate.test.jsindex 6abf6c006c..298a6b449f 100644--- a/scripts/db-migrate.test.js+++ b/scripts/db-migrate.test.js@@ -84,8 +84,14 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',root = mkdtempSync(join(tmpdir(), 'portos-db-sh-'));mkdirSync(join(root, 'scripts'));copyFileSync(join(here, 'db.sh'), join(root, 'scripts', 'db.sh'));+ copyFileSync(join(here, 'prepare-database-replay.mjs'), join(root, 'scripts', 'prepare-database-replay.mjs'));+ mkdirSync(join(root, 'server', 'services'), { recursive: true });+ copyFileSync(join(here, '../server/services/backupDatabaseDump.js'), join(root, 'server/services/backupDatabaseDump.js'));+ copyFileSync(join(here, '../server/services/databaseImport.js'), join(root, 'server/services/databaseImport.js'));+ writeFileSync(join(root, 'package.json'), '{"type":"module"}');const binDir = join(root, 'bin');mkdirSync(binDir);+ symlinkSync(process.execPath, join(binDir, 'node'));writeStub(binDir, 'docker', DOCKER_STUB);writeStub(binDir, 'psql', PSQL_STUB);writeStub(binDir, 'pg_dump', PG_DUMP_STUB);@@ -224,6 +230,24 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',expect(dumps()).toEqual([]);});+ it('imports legacy extension metadata through a private copy without changing stored data', async () => {+ const { databaseImportFixture } = await import('../server/test/fixtures/databaseImportDump.js');+ const { original, replay } = databaseImportFixture();+ const file = join(root, 'legacy.sql');+ writeFileSync(file, original);+ const result = run(['import', '--endpoint', 'example.invalid', '6543', 'example', 'example_test', file], 'ok');+ expect(result.status, result.stderr).toBe(0);+ expect(readFileSync(importLog)).toEqual(replay);+ expect(readFileSync(file)).toEqual(original);+ // A changed original identity must fail before the target sees any bytes.+ rmSync(importLog);+ const rejected = run(['import', '--endpoint', 'example.invalid', '6543', 'example', 'example_test', file], 'ok', {+ PORTOS_IMPORT_SHA256: '0'.repeat(64),+ });+ expect(rejected.status).not.toBe(0);+ expect(existsSync(importLog)).toBe(false);+ });+it('rejects incomplete endpoints and connection-string database overrides before any database command', () => {for (const args of [['--endpoint', 'example.invalid', '6543'],diff --git a/scripts/db.sh b/scripts/db.shindex c327a16f60..0f5bda6550 100755--- a/scripts/db.sh+++ b/scripts/db.sh@@ -649,7 +649,7 @@ cmd_export() {}# Import SQL dump into database-cmd_import() {+cmd_import() (local dumpfile="$1"if [ ! -f "$dumpfile" ]; then@@ -659,13 +659,18 @@ cmd_import() {info "Importing $dumpfile..."- # Strip pg17-only features for compatibility with older psql versions:- # - \restrict/\unrestrict (pg17 dump security tokens)- # - SET transaction_timeout (pg17 config parameter)- sed -e '/^\\restrict /d' -e '/^\\unrestrict /d' -e '/^SET transaction_timeout/d' "$dumpfile" | run_psql -v ON_ERROR_STOP=1 --single-transaction+ # Finish a private, byte-preserving replay copy before psql sees any SQL.+ # A failed source read must never become a successful end-of-script commit.+ local stage replay+ stage="$(mktemp -d "${TMPDIR:-/tmp}/portos-database-import.XXXXXX")" || return 1+ trap 'rm -rf "$stage"' EXIT+ if ! replay="$(node "$ROOT_DIR/scripts/prepare-database-replay.mjs" "$dumpfile" "$stage")"; then+ return 1+ fi+ run_psql -v ON_ERROR_STOP=1 --single-transaction < "$replay"log "Import complete"-}+)# Do not snapshot and change mode while PortOS can still accept writes.# A process-list probe is not a writer fence. The recoverable coordinator indiff --git a/scripts/prepare-database-replay.mjs b/scripts/prepare-database-replay.mjsnew file mode 100644index 0000000000..7dd1905578--- /dev/null+++ b/scripts/prepare-database-replay.mjs@@ -0,0 +1,10 @@+// This CLI stages only bytes; it never connects to a database.+import { stageDatabaseImport } from '../server/services/databaseImport.js';++try {+ const replay = await stageDatabaseImport(process.argv[2], process.argv[3], process.env.PORTOS_IMPORT_SHA256);+ process.stdout.write(replay + '\n');+} catch (err) {+ console.error(`❌ Could not stage database import: ${err.message}`);+ process.exitCode = 1;+}diff --git a/server/routes/database.test.js b/server/routes/database.test.jsindex d8265e113b..86057bf3bc 100644--- a/server/routes/database.test.js+++ b/server/routes/database.test.js@@ -65,7 +65,7 @@ vi.mock('../lib/childProcess.js', async (importOriginal) => {import { POOL_CONFIG, query, checkHealth } from '../lib/db.js';import { execFile, spawn } from '../lib/childProcess.js';import { EventEmitter } from 'events';-import { PassThrough, Readable } from 'stream';+import { PassThrough, Readable, Writable } from 'stream';import { writeFileSync, mkdtempSync, readFileSync, createReadStream, rmSync } from 'fs';import { tmpdir } from 'os';import { join as pathJoin } from 'path';@@ -76,7 +76,7 @@ import { cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';import { hostControlRouteGate } from '../services/authGate.js';afterAll(cleanupTempDataRoots);-import { isPg17OnlyDirective, importDumpFile } from '../services/dbAdmin.js';+import { importDumpFile, _importReplayFile } from '../services/dbAdmin.js';// Helper: make execFile call the callback with controlled outputfunction mockExecFile(responses) {@@ -224,22 +224,6 @@ describe('database maintenance status', () => {});});-describe('isPg17OnlyDirective (sed-replacement line filter)', () => {- it('matches the pg17-only directives the legacy sed stripped', () => {- expect(isPg17OnlyDirective('\\restrict abc123')).toBe(true);- expect(isPg17OnlyDirective('\\unrestrict abc123')).toBe(true);- expect(isPg17OnlyDirective('SET transaction_timeout = 0;')).toBe(true);- });-- it('leaves ordinary dump lines untouched', () => {- expect(isPg17OnlyDirective('CREATE TABLE foo (id int);')).toBe(false);- expect(isPg17OnlyDirective('SET statement_timeout = 0;')).toBe(false);- expect(isPg17OnlyDirective("INSERT INTO t VALUES ('\\restrict not-a-directive');")).toBe(false);- expect(isPg17OnlyDirective(' \\restrict indented')).toBe(false); // anchored at start, like sed /^…/- expect(isPg17OnlyDirective('')).toBe(false);- });-});-describe('importDumpFile (no-shell streaming import)', () => {const dumpDirs = [];@@ -372,6 +356,36 @@ describe('importDumpFile (no-shell streaming import)', () => {expect(child.__pipedBuffer().equals(expected)).toBe(true);});+ it('stages extension metadata, preserves stored bytes, and respects replay backpressure', async () => {+ const { databaseImportFixture } = await import('../test/fixtures/databaseImportDump.js');+ const { original, replay } = databaseImportFixture();+ const child = makeFakePsql();+ const piped = [];+ child.stdin = new Writable({ highWaterMark: 1, write(chunk, _encoding, done) {+ piped.push(Buffer.from(chunk));+ setImmediate(done);+ } });+ child.stdin.on('finish', () => child.emit('close', 0));+ spawn.mockReturnValue(child);+ const dir = mkdtempSync(pathJoin(tmpdir(), 'portos-dump-'));+ dumpDirs.push(dir);+ const file = pathJoin(dir, 'dump.sql');+ writeFileSync(file, original);+ expect((await importDumpFile(file, '5561', {})).exitCode).toBe(0);+ expect(Buffer.concat(piped)).toEqual(replay);+ expect(readFileSync(file)).toEqual(original);+ });++ it('does not spawn a target writer after a staging read failure', async () => {+ createReadStream.mockImplementationOnce(() => Readable.from((async function* () {+ yield Buffer.from('DROP TABLE example;\n');+ throw new Error('dump read failed mid-stream');+ })()));+ const result = await importDumpFile('/fake/dump.sql', '5561', {});+ expect(result).toMatchObject({ exitCode: 1, stderr: 'dump read failed mid-stream' });+ expect(spawn).not.toHaveBeenCalled();+ });+it('resolves with a non-zero exitCode when the dump file cannot be read (no throw)', async () => {const child = makeFakePsql();spawn.mockReturnValue(child);@@ -391,7 +405,7 @@ describe('importDumpFile (no-shell streaming import)', () => {));let settled = false;- const promise = importDumpFile('/fake/dump.sql', '5561', {})+ const promise = _importReplayFile('/fake/dump.sql', '5561', {}).then((r) => { settled = true; return r; });// The destructive prefix reached psql's stdin, the read failed, and the@@ -426,7 +440,7 @@ describe('importDumpFile (no-shell streaming import)', () => {'DROP TABLE memories;\n'));- const promise = importDumpFile('/fake/dump.sql', '5561', {});+ const promise = _importReplayFile('/fake/dump.sql', '5561', {});// Under fake timers the stream's internal setImmediate is faked too;// advancing the clock by 0 pumps it plus the generator microtasks, so// the yield→data→throw→error chain runs and abort() fires SIGTERM.@@ -466,7 +480,7 @@ describe('importDumpFile (no-shell streaming import)', () => {const stdinEnd = vi.spyOn(child.stdin, 'end');createReadStream.mockImplementationOnce(() => makeFailingSource('SELECT 1;\n'));- const promise = importDumpFile('/fake/dump.sql', '5561', {});+ const promise = _importReplayFile('/fake/dump.sql', '5561', {});await vi.advanceTimersByTimeAsync(10_000);const result = await promise;expect(child.kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGTERM', 'SIGKILL']);@@ -486,7 +500,7 @@ describe('importDumpFile (no-shell streaming import)', () => {'DROP TABLE memories;\n'));- const promise = importDumpFile('/fake/dump.sql', '5561', {});+ const promise = _importReplayFile('/fake/dump.sql', '5561', {});await vi.waitFor(() => expect(child.kill).toHaveBeenCalledWith('SIGTERM'));// A failed termination surfaces as 'error' — the child may still bediff --git a/server/services/backupDatabaseDump.js b/server/services/backupDatabaseDump.jsindex b5c664fe21..e50892bfe1 100644--- a/server/services/backupDatabaseDump.js+++ b/server/services/backupDatabaseDump.js@@ -40,10 +40,10 @@ const MAX_SCANNED_LINE = 64 * 1024;* (created exclusively, owner-only), so a restore can replay what it checked* even if the snapshot changes afterwards; a spool write failure rejects too.* @param {string} path- * @param {{ spoolTo?: string }} [options]+ * @param {{ spoolTo?: string, omitVersionDirectives?: boolean }} [options]* @returns {Promise<{ sizeBytes: number, sha256: string, tableCount: number, complete: boolean, missingTables: string[], extensionMetadata?: {start: number, end: number}[] }>}*/-export function inspectDatabaseDump(path, { spoolTo } = {}) {+export function inspectDatabaseDump(path, { spoolTo, omitVersionDirectives = false } = {}) {return new Promise((resolvePromise, reject) => {const hash = createHash('sha256');// Latin-1 preserves byte offsets and dumps in non-UTF-8 client encodings.@@ -73,7 +73,13 @@ export function inspectDatabaseDump(path, { spoolTo } = {}) {if (line.replace(/\r?\n$/, '') === '\\.') copyData = false;return;}- if (!statement && !quote && !dollarQuote && !blockDepth && line.startsWith('\\')) return;+ if (!statement && !quote && !dollarQuote && !blockDepth) {+ if (omitVersionDirectives && (/^\\(?:un)?restrict /.test(line) || /^SET transaction_timeout = 0;\r?\n?$/.test(line))) {+ extensionMetadata.push({ start: lineStart, end: scannedBytes });+ return;+ }+ if (line.startsWith('\\')) return;+ }for (let i = 0; i < line.length; i += 1) {const c = line[i];const next = line[i + 1];@@ -196,6 +202,7 @@ export function inspectDatabaseDump(path, { spoolTo } = {}) {&& !statement.trim() && COMPLETE_TRAILER.test(tail.toString('latin1')),missingTables: REQUIRED_DUMP_TABLES.filter(name => !tables.has(name)),...(spoolTo ? { extensionMetadata } : {}),+ ...(omitVersionDirectives ? { replayScanSafe: !unscannable } : {}),};spooled.then(() => { if (!failed) resolvePromise(result); });});diff --git a/server/services/databaseImport.js b/server/services/databaseImport.jsnew file mode 100644index 0000000000..e4ff04f0ec--- /dev/null+++ b/server/services/databaseImport.js@@ -0,0 +1,26 @@+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { inspectDatabaseDump, prepareDatabaseReplay } from './backupDatabaseDump.js';++/** Stage an import before any target writes, keeping its original identity. */+export async function stageDatabaseImport(dumpPath, directory, expectedSha256) {+ const spool = join(directory, 'original.sql');+ const inspected = await inspectDatabaseDump(dumpPath, { spoolTo: spool, omitVersionDirectives: true });+ if (!inspected.replayScanSafe) throw new Error('Database import contains oversized SQL that cannot be safely scanned');+ if (expectedSha256 && inspected.sha256 !== expectedSha256) {+ throw new Error('Database import no longer matches its recorded digest');+ }+ return prepareDatabaseReplay(spool, inspected.extensionMetadata);+}++/** Own the private copy until the consumer confirms replay has finished. */+export async function withDatabaseImport(dumpPath, consume) {+ const directory = await mkdtemp(join(tmpdir(), 'portos-database-import-'));+ try {+ const replay = await stageDatabaseImport(dumpPath, directory);+ return await consume(replay);+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+}diff --git a/server/services/databaseMaintenanceTransfer.js b/server/services/databaseMaintenanceTransfer.jsindex d418278cd1..5efddd0d78 100644--- a/server/services/databaseMaintenanceTransfer.js+++ b/server/services/databaseMaintenanceTransfer.js@@ -58,9 +58,10 @@ function hasCompletionMarker(path) {* prove none survive (assertPredecessorCoordinatorsStopped). Output is kept* internal: it can name hosts and paths.*/-function runDbScript(action, endpoint, argument, dumpDir) {+function runDbScript(action, endpoint, argument, dumpDir, expectedSha256) {const env = { PATH: process.env.PATH ?? '', HOME: process.env.HOME ?? PATHS.installRoot,- PGPASSWORD: process.env.PGPASSWORD || 'portos', PORTOS_DUMP_DIR: dumpDir, LC_ALL: 'C' };+ PGPASSWORD: process.env.PGPASSWORD || 'portos', PORTOS_DUMP_DIR: dumpDir, LC_ALL: 'C',+ ...(expectedSha256 ? { PORTOS_IMPORT_SHA256: expectedSha256 } : {}) };const args = [join(PATHS.root, 'scripts', 'db.sh'), action, '--endpoint',endpoint.host, String(endpoint.port), endpoint.user, endpoint.database, argument];return new Promise((resolve) => {@@ -149,7 +150,7 @@ export async function runDatabaseTransfer(id, token, options = {}) {if (!journal.readTransferImport(id)) {const path = await assertRecordedDump(journal, id, dump);journal.assertCoordinatorWorker(id, token);- const result = await runDbScript('import', operation.target, path, dirname(path));+ const result = await runDbScript('import', operation.target, path, dirname(path), dump.sha256);journal.assertCoordinatorWorker(id, token);if (result.code !== 0) throw refused(`the target import failed and was rolled back (exit ${result.code ?? 'spawn'})`);journal.recordTransferImport(id, token, { id, target: operation.target, sha256: dump.sha256 });diff --git a/server/services/databaseMaintenanceTransfer.test.js b/server/services/databaseMaintenanceTransfer.test.jsindex 8b712f04e3..8c180a442a 100644--- a/server/services/databaseMaintenanceTransfer.test.js+++ b/server/services/databaseMaintenanceTransfer.test.js@@ -161,6 +161,26 @@ describe.skipIf(process.platform === 'win32')('offline database transfer', () =>expect(stubs.invocations('psql')).toHaveLength(1);}, 30_000);+ it.each(['ok', 'fail'])('preserves original dump and receipt identity when extension metadata is normalized (%s)', async mode => {+ const legacy = "DROP EXTENSION IF EXISTS vector;\nCOMMENT ON EXTENSION vector IS 'legacy';\n" + STUB_DUMP_COMPLETE;+ writeFileSync(join(stubs.dir, 'dump.sql'), legacy);+ begin();+ stubs.setMode('import', mode);+ if (mode === 'fail') {+ await expect(transfer()).rejects.toThrow(/target import failed/);+ expect(journal.transferStatus(operation.id)).toEqual({ dump: 'recorded', import: 'pending' });+ successor();+ stubs.setMode('import', 'ok');+ }+ expect(await transfer()).toMatchObject({ importCommitted: true });+ expect(stubs.invocations('pg_dump')).toHaveLength(1);+ expect(stubs.imported()).toBe('\n\n' + STUB_DUMP_COMPLETE);+ expect(readFileSync(dumpPath(), 'utf8')).toBe(legacy);+ expect(journal.readTransferDump(operation.id)).toMatchObject({ sha256: sha256(legacy), bytes: Buffer.byteLength(legacy) });+ expect(journal.readTransferImport(operation.id)).toMatchObject({ id: operation.id, target: docker, sha256: sha256(legacy) });+ expect(() => journal.assertAdmission()).toThrow();+ }, 30_000);+it('refuses ordinary writes and spawns while export and import are paused', async () => {begin();stubs.setMode('dump', 'pause');diff --git a/server/services/dbAdmin.db.test.js b/server/services/dbAdmin.db.test.jsindex 32cb46507b..078b6a83a3 100644--- a/server/services/dbAdmin.db.test.js+++ b/server/services/dbAdmin.db.test.js@@ -13,7 +13,7 @@ import { afterAll, describe, expect, it, vi } from 'vitest';import { Readable } from 'stream';import { createReadStream } from 'fs';import { spawn, spawnSync } from '../lib/childProcess.js';-import { checkHealth, close, query } from '../lib/db.js';+import { checkHealth, close, query, POOL_CONFIG } from '../lib/db.js';import { requireDbOrSkip } from '../lib/dbTestGate.js';vi.mock('fs', async (importOriginal) => {@@ -26,7 +26,12 @@ vi.mock('../lib/childProcess.js', async (importOriginal) => {return { ...actual, spawn: vi.fn(actual.spawn) };});-import { importDumpFile } from './dbAdmin.js';+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { fileURLToPath } from 'node:url';+import { importDumpFile, _importReplayFile } from './dbAdmin.js';const TABLE = 'import_abort_probe';const PORT = process.env.PGPORT || '5432';@@ -55,6 +60,56 @@ afterAll(async () => {});describe.skipIf(!runDb)('importDumpFile abort rolls back the interrupted import (#7213)', () => {+ it('restores as an unprivileged role with a foreign-owned vector extension and rolls back invalid SQL', async () => {+ const authority = await query("SELECT rolsuper FROM pg_roles WHERE rolname = current_user");+ const provisionRole = authority.rows[0].rolsuper;+ const role = 'import_probe_' + randomUUID().replaceAll('-', '');+ const schema = role;+ const dir = mkdtempSync(join(tmpdir(), 'portos-import-db-'));+ try {+ await query('CREATE EXTENSION IF NOT EXISTS vector');+ if (provisionRole) await query(`CREATE ROLE ${role} NOLOGIN NOSUPERUSER`);+ await query(`CREATE SCHEMA ${schema}${provisionRole ? ' AUTHORIZATION ' + role : ''}`);+ const prefix = provisionRole ? `SET ROLE ${role};\n` : '';+ await query(`${prefix}CREATE TABLE ${schema}.probe (id int); INSERT INTO ${schema}.probe VALUES (1); RESET ROLE;`);+ const ownerSql = provisionRole+ ? "SELECT extowner <> (SELECT oid FROM pg_roles WHERE rolname = $1) AS foreign_owner FROM pg_extension WHERE extname = 'vector'"+ : "SELECT extowner <> (SELECT oid FROM pg_roles WHERE rolname = current_user) AS foreign_owner FROM pg_extension WHERE extname = 'vector'";+ const ownerArgs = provisionRole ? [role] : [];+ const foreignOwner = await query(ownerSql, ownerArgs);+ expect(foreignOwner.rows[0].foreign_owner).toBe(true);+ const clean = `DROP TABLE IF EXISTS ${schema}.probe;\nCREATE TABLE ${schema}.probe (id int);\nINSERT INTO ${schema}.probe VALUES (2);\n`;+ const file = join(dir, 'legacy.sql');+ // Raw replay reproduces the ownership failure under the application role.+ writeFileSync(file, prefix + 'DROP EXTENSION IF EXISTS vector;\n');+ const refused = await _importReplayFile(file, PORT, { ...process.env });+ expect(refused.exitCode).not.toBe(0);+ expect(refused.stderr).toContain('must be owner of extension vector');+ const imports = [file => importDumpFile(file, PORT, { ...process.env })];+ if (process.platform !== 'win32') imports.push(async file => {+ const child = spawnSync('bash', [fileURLToPath(new URL('../../scripts/db.sh', import.meta.url)),+ 'import', '--endpoint', POOL_CONFIG.host, String(POOL_CONFIG.port), POOL_CONFIG.user, POOL_CONFIG.database, file], {+ env: { ...process.env, PGPASSWORD: POOL_CONFIG.password }, encoding: 'utf8', timeout: 15_000,+ });+ return { exitCode: child.status, stderr: child.stderr };+ });+ for (const load of imports) {+ writeFileSync(file, prefix + "DROP EXTENSION IF EXISTS vector;\nCOMMENT ON EXTENSION vector IS 'legacy';\n" + clean);+ expect((await load(file)).exitCode).toBe(0);+ expect((await query(`SELECT id FROM ${schema}.probe`)).rows).toEqual([{ id: 2 }]);+ writeFileSync(file, prefix + clean.replace('VALUES (2)', 'VALUES (3)') + 'INVALID SQL;\n');+ expect((await load(file)).exitCode).not.toBe(0);+ expect((await query(`SELECT id FROM ${schema}.probe`)).rows).toEqual([{ id: 2 }]);+ }+ expect((await query(ownerSql, ownerArgs)).rows[0].foreign_owner).toBe(true);+ } finally {+ await query('RESET ROLE');+ await query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);+ if (provisionRole) await query(`DROP ROLE IF EXISTS ${role}`);+ rmSync(dir, { recursive: true, force: true });+ }+ });+it('preserves preexisting target rows when the dump read fails mid-import', async () => {// The target's pre-sync "recovery copy": a table with a row the dump would// destroy and repopulate.@@ -87,7 +142,7 @@ describe.skipIf(!runDb)('importDumpFile abort rolls back the interrupted importthrow new Error('simulated dump read failure');})(), { encoding: 'latin1' }));- const importing = importDumpFile('/unused/dump.sql', PORT, { ...process.env }, 15_000);+ const importing = _importReplayFile('/unused/dump.sql', PORT, { ...process.env }, 15_000);const child = spawn.mock.results.at(-1).value;let output = '';child.stdout.on('data', (chunk) => {diff --git a/server/services/dbAdmin.js b/server/services/dbAdmin.jsindex fadad80891..1932ffada9 100644--- a/server/services/dbAdmin.js+++ b/server/services/dbAdmin.js@@ -10,6 +10,8 @@ import { resolveBashBinary, toBashPath } from '../lib/bashResolver.js';import { resolvePostgresPort } from '../lib/ports.js';import { assertDatabaseAdmission, createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';+import { withDatabaseImport } from './databaseImport.js';+import { acceptDatabaseMaintenance } from './databasePreflight.js';import { createDatabaseAuthority } from '../lib/databaseAuthority.js';@@ -333,13 +335,6 @@ const pgEnv = (port) => ({PGDATABASE: pgDb});-// pg17-only directives that older psql chokes on. The legacy import piped the-// dump through `sed -e '/^\restrict /d' …` to strip them; we filter the same-// lines in-process instead (see importDumpFile) so no `sed`/`bash -c` shell is-// involved. Exported for unit testing.-const PG17_ONLY_DIRECTIVES = [/^\\restrict /, /^\\unrestrict /, /^SET transaction_timeout/];-export const isPg17OnlyDirective = (line) => PG17_ONLY_DIRECTIVES.some((re) => re.test(line));-// Abort escalation bounds for importDumpFile's read-failure path: after// SIGTERM, wait this long for the child's 'close' before escalating to// SIGKILL, then this much longer before reporting failure without a confirmed@@ -355,8 +350,8 @@ const ABORT_KILL_GRACE_MS = 2_000;* into the shell — any shell metacharacter in those values (or in a hostile* export line surfacing through the pipeline) was injectable. Here psql runs via* spawn with an argv array (no shell), the dump is streamed on stdin, and the- * pg17-only directives are stripped in-process by isPg17OnlyDirective(),- * replacing the `sed` stage entirely.+ * replay is staged privately before spawning; extension metadata and version+ * directives are omitted only outside stored SQL/COPY data.** Runs outside the Express request lifecycle (spawn/stream callbacks), so every* async boundary resolves rather than throws — an uncaught throw here would@@ -368,7 +363,16 @@ const ABORT_KILL_GRACE_MS = 2_000;* that psql would commit as a finished --single-transaction script, and the* promise waits for 'close' or the bounded abort deadline (see abort()).*/-export function importDumpFile(dumpFile, port, env, timeout = 120_000) {+export async function importDumpFile(dumpFile, port, env, timeout = 120_000) {+ try {+ return await withDatabaseImport(dumpFile, replay => _importReplayFile(replay, port, env, timeout));+ } catch (err) {+ return { stdout: '', stderr: err.message, exitCode: 1 };+ }+}++// Separate process boundary so read-error escalation can be exercised precisely.+export function _importReplayFile(dumpFile, port, env, timeout = 120_000) {return new Promise((resolve) => {const psql = spawn('psql', ['-h', 'localhost', '-p', String(port), '-U', pgUser, '-d', pgDb,@@ -478,13 +482,13 @@ export function importDumpFile(dumpFile, port, env, timeout = 120_000) {// resulting EPIPE would otherwise crash the process.psql.stdin.on('error', () => {});- // Byte-transparent line filter: buffer latin1 chars, split on '\n', drop the- // pg17-only directive lines, and forward every other line's original bytes+ // Byte-transparent replay pump: buffer latin1 chars, split on '\n',+ // and forward every staged line's original bytes// (its trailing '\n' re-appended) to psql's stdin. Backpressure pauses the// source; a drain resumes it and re-drains any buffered lines.let pending = '';const writeLine = (line) => {- if (isPg17OnlyDirective(line) || !psql.stdin.writable) return true;+ if (!psql.stdin.writable) return true;return psql.stdin.write(line + '\n', 'latin1');};const pump = () => {@@ -514,7 +518,7 @@ export function importDumpFile(dumpFile, port, env, timeout = 120_000) {if (finished || aborting) return; // the success EOF must never follow an abort// Flush a final line that lacked a trailing newline, then close stdin so// psql runs the script and emits 'close'.- if (pending.length) { writeLine(pending); pending = ''; }+ if (pending.length && psql.stdin.writable) { psql.stdin.write(pending, 'latin1'); pending = ''; }if (psql.stdin.writable) psql.stdin.end();});});diff --git a/server/test/fixtures/databaseImportDump.js b/server/test/fixtures/databaseImportDump.jsnew file mode 100644index 0000000000..4bba835b55--- /dev/null+++ b/server/test/fixtures/databaseImportDump.js@@ -0,0 +1,31 @@+// Synthetic SQL intentionally includes filter-shaped bytes in stored data.+export function databaseImportFixture() {+ const version = '\\restrict example\r\nSET transaction_timeout = 0;\r\n';+ const metadata = "DROP EXTENSION IF EXISTS vector;COMMENT ON EXTENSION vector IS 'legacy';";+ const preserved = `-- ordinary comment\r+DROP TABLE IF EXISTS example_record;\r+CREATE TABLE example_record (body text);\r+COPY example_record (body) FROM stdin;\r+DROP EXTENSION IF EXISTS vector;\r+COMMENT ON EXTENSION vector IS 'copy row';\r+SET transaction_timeout = 0;\r+\\restrict stored-data\r+${'x'.repeat(140000)}\r+\\.\r+SELECT 'multiline\r+DROP EXTENSION IF EXISTS vector;\r+SET transaction_timeout = 0;\r+';\r+CREATE FUNCTION example_sql() RETURNS text AS $body$\r+COMMENT ON EXTENSION vector IS 'function body';\r+$body$ LANGUAGE sql;\r+/* ordinary block comment: DROP EXTENSION IF EXISTS vector; */\r+DROP EXTENSION IF EXISTS other_extension CASCADE;\r+DROP EXTENSION another_extension;\r+SELECT `;+ const raw = Buffer.from([0xe9, 0x0d, 0x0a]);+ const trailer = Buffer.from('--\r\n-- PostgreSQL database dump complete\r\n--\r\n');+ const replay = Buffer.concat([Buffer.from(preserved, 'latin1'), raw, trailer]);+ const original = Buffer.concat([Buffer.from(version + metadata, 'latin1'), replay]);+ return { original, replay };+}diff --git a/server/test/fixtures/databaseTransferStubs.js b/server/test/fixtures/databaseTransferStubs.jsindex f0078a6188..bbb0047d65 100644--- a/server/test/fixtures/databaseTransferStubs.js+++ b/server/test/fixtures/databaseTransferStubs.js@@ -43,7 +43,7 @@ case "$mode" infail) printf 'DROP TABLE example_record;\\n'; exit 1 ;;incomplete) printf '%s' ${quote(STUB_DUMP_BODY)}; exit 0 ;;esac-printf '%s' ${quote(STUB_DUMP_COMPLETE)}+if [ -f "$R/dump.sql" ]; then cat "$R/dump.sql"; else printf '%s' ${quote(STUB_DUMP_COMPLETE)}; fi`);writeStub(join(bin, 'psql'), `#!/bin/shR=${R}