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: remove shell interpolation from database dump import (#2516)
Adam Eivy056e84783571
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8ea0db9e43..9b3587f7b1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,3 +3,4 @@## Fixed- **[issue-2510] MidiPianoRoll: clear the stale hover overlay when the transcription data changes.** The piano-roll kept its hovered note/chord identity (objects from the previous parse) when the `data`/`chords` props swapped on a mounted instance, so a re-transcription or Retry while a hover was active and the pointer sat still would keep stroking the old note at coordinates mapped into the new file until the next pointer move or Escape. A `useEffect` now drops the hover identity whenever `data`/`chords` change.+- **[issue-2516] Database sync: remove shell interpolation from the dump import.** The active→inactive backend sync built a `bash -c "sed … \"${dumpFile}\" | psql … -U ${pgUser} -d ${pgDb}"` string that interpolated the dump path, port, user, and database name into a shell command — any shell metacharacter in those values (env-derived or surfacing from the export pipeline) was injectable into `psql`. The import now streams the dump through `spawn('psql', argv)` with no shell: the dump is read and piped to psql's stdin, and the pg17-only directives (`\restrict`/`\unrestrict`/`SET transaction_timeout`) the old `sed` stage stripped are filtered in-process. No user- or env-derived value ever reaches a shell string.diff --git a/server/routes/database.js b/server/routes/database.jsindex 6f4d367578..d3edb317fb 100644--- a/server/routes/database.js+++ b/server/routes/database.js@@ -1,6 +1,7 @@import { Router } from 'express';-import { execFile } from 'child_process';-import { existsSync, mkdirSync } from 'fs';+import { execFile, spawn } from 'child_process';+import { existsSync, mkdirSync, createReadStream } from 'fs';+import { createInterface } from 'readline';import { join } from 'path';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { checkHealth, query } from '../lib/db.js';@@ -301,6 +302,80 @@ 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));++/**+ * Import a pg_dump SQL file into the target database WITHOUT invoking a shell.+ *+ * The legacy path built a `bash -c "sed … \"${dumpFile}\" | psql … -U ${pgUser}+ * -d ${pgDb}"` string, interpolating the dump path, port, user, and db name+ * 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.+ *+ * Runs outside the Express request lifecycle (spawn/stream callbacks), so every+ * async boundary resolves rather than throws — an uncaught throw here would+ * crash the Node process (there is no next(err) to bubble to). Returns the same+ * { stdout, stderr, exitCode } shape as runCmd().+ */+export function importDumpFile(dumpFile, port, env, timeout = 120_000) {+ return new Promise((resolve) => {+ const psql = spawn('psql', [+ '-h', 'localhost', '-p', String(port), '-U', pgUser, '-d', pgDb,+ '-v', 'ON_ERROR_STOP=1', '--single-transaction'+ ], { cwd: rootDir, env });++ let stdout = '';+ let stderr = '';+ let finished = false;+ const finish = (exitCode, extraDetail) => {+ if (finished) return;+ finished = true;+ clearTimeout(timer);+ if (exitCode !== 0) {+ const detail = stripAnsi(stderr || stdout || extraDetail || '').replace(/\s+/g, ' ').trim();+ console.error(`🗄️ psql import exited ${exitCode}: ${detail}`);+ }+ resolve({ stdout: stripAnsi(stdout), stderr: stripAnsi(stderr), exitCode });+ };++ const timer = setTimeout(() => {+ psql.kill('SIGKILL');+ finish(1, `import timed out after ${timeout}ms`);+ }, timeout);++ psql.stdout.on('data', (d) => { stdout += d.toString(); });+ psql.stderr.on('data', (d) => { stderr += d.toString(); });+ psql.on('error', (err) => finish(1, err.message));+ psql.on('close', (code) => finish(typeof code === 'number' ? code : 1));+ // psql may exit early (e.g. ON_ERROR_STOP) while we're still writing — the+ // resulting EPIPE would otherwise crash the process.+ psql.stdin.on('error', () => {});++ const rl = createInterface({ input: createReadStream(dumpFile), crlfDelay: Infinity });+ rl.on('error', (err) => {+ if (psql.stdin.writable) psql.stdin.end();+ finish(1, err.message);+ });+ rl.on('line', (line) => {+ if (isPg17OnlyDirective(line) || !psql.stdin.writable) return;+ // Honor backpressure so a large dump doesn't buffer unboundedly in memory.+ if (!psql.stdin.write(line + '\n')) {+ rl.pause();+ psql.stdin.once('drain', () => rl.resume());+ }+ });+ rl.on('close', () => { if (psql.stdin.writable) psql.stdin.end(); });+ });+}+/*** Read a specific backend's PostgreSQL major version by probing it on its own* port (native 5432 / Docker 5561 can run different majors, so the connection@@ -375,12 +450,11 @@ router.post('/sync', asyncHandler(async (req, res) => {], 10_000, sysEnv);}- // Step 3: Import into target (active backend untouched — different port)- // Strip pg17-only features for compat with older psql: \restrict/\unrestrict, transaction_timeout+ // Step 3: Import into target (active backend untouched — different port).+ // Streamed via spawn (no shell) with pg17-only directives stripped in-process,+ // so no user/env value is ever interpolated into a shell string.emit('start', { message: `Importing into ${targetMode} (port ${targetPort})...` });- const importResult = await runCmd(bashBinary, ['-c',- `sed -e '/^\\\\restrict /d' -e '/^\\\\unrestrict /d' -e '/^SET transaction_timeout/d' "${dumpFile}" | psql -h localhost -p ${targetPort} -U ${pgUser} -d ${pgDb} -v ON_ERROR_STOP=1 --single-transaction`- ], 120_000, pgEnv(targetPort));+ const importResult = await importDumpFile(dumpFile, targetPort, pgEnv(targetPort));if (importResult.exitCode !== 0) {emit('error', { message: `Import into ${targetMode} failed` });diff --git a/server/routes/database.test.js b/server/routes/database.test.jsindex 264d38f287..8f0e6fc5f5 100644--- a/server/routes/database.test.js+++ b/server/routes/database.test.js@@ -32,17 +32,23 @@ vi.mock('../lib/db.js', () => ({query: vi.fn(async () => ({ rows: [] })),}));-// Mock child_process.execFile at the module level.+// Mock child_process.execFile + spawn at the module level.vi.mock('child_process', async (importOriginal) => {const actual = await importOriginal();return {...actual,execFile: vi.fn(),+ spawn: vi.fn(),};});-import { execFile } from 'child_process';-import databaseRoutes from './database.js';+import { execFile, spawn } from 'child_process';+import { EventEmitter } from 'events';+import { PassThrough } from 'stream';+import { writeFileSync, mkdtempSync } from 'fs';+import { tmpdir } from 'os';+import { join as pathJoin } from 'path';+import databaseRoutes, { isPg17OnlyDirective, importDumpFile } from './database.js';// Helper: make execFile call the callback with controlled outputfunction mockExecFile(responses) {@@ -72,6 +78,90 @@ function makeApp() {return app;}+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)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ // Build a fake psql child process backed by real streams.+ function makeFakePsql() {+ const child = new EventEmitter();+ child.stdout = new PassThrough();+ child.stderr = new PassThrough();+ const writes = [];+ child.stdin = new PassThrough();+ child.stdin.on('data', (chunk) => writes.push(chunk.toString()));+ child.stdin.on('finish', () => {+ // Emulate psql exiting cleanly once stdin closes.+ child.emit('close', 0);+ });+ child.kill = vi.fn();+ child.__writes = writes;+ return child;+ }++ it('spawns psql via argv without a shell and pipes filtered dump to stdin', async () => {+ const child = makeFakePsql();+ spawn.mockReturnValue(child);++ const dir = mkdtempSync(pathJoin(tmpdir(), 'portos-dump-'));+ const dumpPath = pathJoin(dir, 'dump.sql');+ writeFileSync(dumpPath,+ '\\restrict token\n' ++ 'SET transaction_timeout = 0;\n' ++ 'CREATE TABLE foo (id int);\n' ++ '\\unrestrict token\n' ++ "INSERT INTO foo VALUES (1);\n"+ );++ const result = await importDumpFile(dumpPath, '5561', { PGPASSWORD: 'x' });++ expect(result.exitCode).toBe(0);+ // spawn called with the psql binary and an argv array (no shell / no bash -c).+ expect(spawn).toHaveBeenCalledTimes(1);+ const [cmd, args, opts] = spawn.mock.calls[0];+ expect(cmd).toBe('psql');+ expect(Array.isArray(args)).toBe(true);+ expect(args).toContain('--single-transaction');+ expect(args).toContain('ON_ERROR_STOP=1');+ // No shell option and no interpolated command string.+ expect(opts.shell).toBeFalsy();+ expect(args.join(' ')).not.toMatch(/sed|\|/);++ // The pg17-only directives were stripped; real SQL survived.+ const piped = child.__writes.join('');+ expect(piped).not.toMatch(/\\restrict/);+ expect(piped).not.toMatch(/\\unrestrict/);+ expect(piped).not.toMatch(/SET transaction_timeout/);+ expect(piped).toMatch(/CREATE TABLE foo/);+ expect(piped).toMatch(/INSERT INTO foo VALUES \(1\);/);+ });++ it('resolves with a non-zero exitCode when the dump file cannot be read (no throw)', async () => {+ const child = makeFakePsql();+ spawn.mockReturnValue(child);++ const result = await importDumpFile('/nonexistent/dump.sql', '5432', {});+ expect(result.exitCode).not.toBe(0);+ });+});+describe('POST /api/database/destroy', () => {beforeEach(() => {vi.clearAllMocks();