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
feat: bind standalone database transfers to explicit endpoints (#8816)
[._.]/ Adam Eivy180aca5673f4
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex dd8f6714e8..a5978093bf 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -30,6 +30,29 @@ target; overwriting or deleting it can destroy that recovery copy. Compare andrecover the missing records before choosing an authoritative backend.See [storage mode guidance](STORAGE.md#moving-between-docker-and-native).+### Explicit database endpoints for standalone transfers++Standalone exports and imports can bind all connection fields explicitly:++```bash+scripts/db.sh export --endpoint localhost 5432 example_user example_db recovery-copy+scripts/db.sh import --endpoint localhost 5561 example_user example_db data/db-dumps/portos-recovery-copy.sql+```++These commands require host `pg_dump` / `psql` and never fall back to a Docker+container or select a backend from saved mode. Use a `pg_dump` version compatible+with the source PostgreSQL server. The four endpoint arguments are host, port,+user, and database name; connection strings are not accepted as database names.+Supply credentials through `PGPASSWORD`, never as command arguments.+A failed export does not replace an existing dump.+Import retains the dump and uses one transaction with `ON_ERROR_STOP`.++An explicit endpoint only selects where a standalone transfer runs. Import+replaces database objects present in the dump: keep recovery copies and stop+the target's writers before restoring. These commands do not stop PortOS,+change saved mode, verify a restarted pool, or authorize a backend cutover.+The complete offline migration lifecycle remains unavailable under #8816.+## What gets backed upA backup run (`runBackup` in `server/services/backup.js`) writes to:diff --git a/scripts/db-migrate.test.js b/scripts/db-migrate.test.jsindex c7131eea81..32995fd625 100644--- a/scripts/db-migrate.test.js+++ b/scripts/db-migrate.test.js@@ -5,7 +5,7 @@// is a stub placed ahead of the system directories on PATH.import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { spawnSync } from 'node:child_process';-import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';@@ -40,10 +40,20 @@ exit 0const PSQL_STUB = `#!/bin/shecho "psql $*" >> "$STUB_LOG"+case "$*" in *--single-transaction*) cat >> "$IMPORT_LOG"; exit "\${IMPORT_EXIT:-0}" ;; esaccase "$*" in *count*) echo 3 ;; esacexit 0`;+const PG_DUMP_STUB = `#!/bin/sh+echo "pg_dump $*" >> "$STUB_LOG"+case "$DUMP_MODE" in+ partial) printf 'DROP TABLE example_record;\\n'; exit 1 ;;+ empty) exit 1 ;;+ *) printf '%s' "$FULL_DUMP" ;;+esac+`;+function writeStub(binDir, name, body) {const path = join(binDir, name);writeFileSync(path, body);@@ -65,6 +75,7 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',mkdirSync(binDir);writeStub(binDir, 'docker', DOCKER_STUB);writeStub(binDir, 'psql', PSQL_STUB);+ writeStub(binDir, 'pg_dump', PG_DUMP_STUB);writeStub(binDir, 'pg_isready', '#!/bin/sh\nexit 0\n');// Not Darwin, so db.sh skips prepending Homebrew's real Postgres to PATH.writeStub(binDir, 'uname', '#!/bin/sh\necho Linux\n');@@ -81,7 +92,7 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',rmSync(root, { recursive: true, force: true });});- const run = (args, dumpMode) => spawnSync('bash', [join(root, 'scripts', 'db.sh'), ...args], {+ const run = (args, dumpMode, overrides = {}) => spawnSync('bash', [join(root, 'scripts', 'db.sh'), ...args], {cwd: root,encoding: 'utf8',env: {@@ -92,7 +103,8 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',DUMP_MODE: dumpMode,FULL_DUMP,PGPASSWORD: 'test-only',- PGHOST: '127.0.0.1'+ PGHOST: '127.0.0.1',+ ...overrides,}});@@ -134,6 +146,83 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',expect(tempArtifacts()).toEqual([]);});+ // Regression: saved Docker mode formerly overrode a caller's explicit host+ // port, so a coordinator could silently snapshot the wrong database.+ it.each(['docker', 'native'])('binds export and transactional import to explicit endpoints in saved %s mode', (mode) => {+ writeFileSync(envFile, `PGMODE=${mode}\n`);+ const source = ['--endpoint', 'source.example.invalid', '6543', 'example_user', 'example source'];+ const target = ['--endpoint', 'target.example.invalid', '6544', 'example_user', 'example target'];+ const exported = run(['export', ...source, 'explicit'], 'ok', { PGPORT: '9999' });+ expect(exported.status, exported.stderr).toBe(0);+ const dump = join(dumpDir, 'portos-explicit.sql');+ expect(exported.stdout.trim()).toBe(dump);+ expect(readFileSync(dump, 'utf8')).toBe(FULL_DUMP);+ writeFileSync(dump, `\\restrict example\nSET transaction_timeout = 0;\n${FULL_DUMP}\\unrestrict example\n`);+ const imported = run(['import', ...target, dump], 'ok');+ expect(imported.status, imported.stderr).toBe(0);+ expect(readFileSync(importLog, 'utf8')).toBe(FULL_DUMP);+ const log = readFileSync(stubLog, 'utf8');+ expect(log).toContain('pg_dump -h source.example.invalid -p 6543 -U example_user -d example source');+ expect(log).toContain('psql -h target.example.invalid -p 6544 -U example_user -d example target -v ON_ERROR_STOP=1 --single-transaction');+ expect(log).not.toMatch(/docker|SOURCE_STOP|test-only/);+ expect(readFileSync(envFile, 'utf8')).toBe(`PGMODE=${mode}\n`);+ });++ it('preserves the recovery dump and propagates explicit dump/import failures', () => {+ const endpoint = ['--endpoint', 'example.invalid', '6543', 'example', 'example_db'];+ mkdirSync(dumpDir, { recursive: true });+ const dump = join(dumpDir, 'portos-recovery.sql');+ writeFileSync(dump, FULL_DUMP);+ const exported = run(['export', ...endpoint, 'recovery'], 'partial');+ expect(exported.status).not.toBe(0);+ expect(exported.stdout).toBe('');+ expect(tempArtifacts()).toEqual([]);+ const imported = run(['import', ...endpoint, dump], 'ok', { IMPORT_EXIT: '7' });+ expect(imported.status).not.toBe(0);+ expect(imported.stdout).not.toContain('Import complete');+ expect(readFileSync(dump, 'utf8')).toBe(FULL_DUMP);+ expect(readFileSync(stubLog, 'utf8')).not.toMatch(/docker|SOURCE_STOP/);+ });++ it('fails closed when explicit host tools are missing instead of using Docker', () => {+ rmSync(join(root, 'bin', 'psql'));+ rmSync(join(root, 'bin', 'pg_dump'));+ // Isolate PATH completely so installed PostgreSQL cannot be reached.+ const commands = ['dirname', 'mkdir', 'mktemp', 'rm', 'sed', 'grep', 'cut', 'tr'];+ const isolated = join(root, 'isolated');+ mkdirSync(isolated);+ writeStub(isolated, 'uname', '#!/bin/sh\necho Linux\n');+ for (const name of commands) {+ const binary = ['/usr/bin', '/bin'].map(dir => join(dir, name)).find(existsSync);+ symlinkSync(binary, join(isolated, name));+ }+ const endpoint = ['--endpoint', 'example.invalid', '6543', 'example', 'example_db'];+ const invoke = args => spawnSync('/bin/bash', [join(root, 'scripts', 'db.sh'), ...args], {+ encoding: 'utf8', env: { PATH: isolated, STUB_LOG: stubLog, PGPASSWORD: 'test-only' },+ });+ expect(invoke(['export', ...endpoint, 'missing']).status).not.toBe(0);+ const dump = join(root, 'example.sql');+ writeFileSync(dump, FULL_DUMP);+ expect(invoke(['import', ...endpoint, dump]).status).not.toBe(0);+ expect(readFileSync(stubLog, 'utf8')).toBe('');+ expect(dumps()).toEqual([]);+ });++ it('rejects incomplete endpoints and connection-string database overrides before any database command', () => {+ for (const args of [+ ['--endpoint', 'example.invalid', '6543'],+ ['--endpoint', 'example.invalid', '0', 'example', 'example_db'],+ ['--endpoint', 'example.invalid', '65536', 'example', 'example_db'],+ ['--endpoint', 'example.invalid', '6543', 'example', 'host=other.invalid'],+ ['--endpoint', 'example.invalid', '6543', 'example', 'postgresql://other.invalid/db'],+ ['--endpoint', 'first.invalid,second.invalid', '6543', 'example', 'example_db'],+ ]) {+ expect(run(['export', ...args], 'ok').status).not.toBe(0);+ }+ expect(readFileSync(stubLog, 'utf8')).toBe('');+ expect(existsSync(dumpDir)).toBe(false);+ });+it.each(['docker', 'native'])('refuses all cutover commands in %s mode before any database command', (mode) => {writeFileSync(envFile, `PGMODE=${mode}\n`);for (let attempt = 0; attempt < 2; attempt++) {diff --git a/scripts/db.sh b/scripts/db.shindex cf0ce00729..c3b42c3dda 100755--- a/scripts/db.sh+++ b/scripts/db.sh@@ -68,6 +68,45 @@ get_port() {}PGPORT=$(get_port)+EXPLICIT_ENDPOINT=false++# A coordinator must bind each transfer to its recorded endpoint, not saved+# mode, inherited PGPORT, or whichever Docker container happens to be running.+# Passwords remain in the environment, never command arguments.+set_explicit_endpoint() {+ if [ "$#" -ne 4 ] || [ -z "$1" ] || [ "${#1}" -gt 255 ] ||+ [[ "$1" =~ [[:space:],=] ]] || [[ ! "$2" =~ ^[0-9]{1,5}$ ]] ||+ [ "$((10#$2))" -lt 1 ] || [ "$((10#$2))" -gt 65535 ] ||+ [ -z "$3" ] || [ "${#3}" -gt 63 ] ||+ [ -z "$4" ] || [ "${#4}" -gt 63 ] || [[ "$4" == *"="* ]] ||+ [[ "$4" == postgres://* ]] || [[ "$4" == postgresql://* ]]; then+ err "Invalid explicit endpoint: expected host, port (1-65535), user, and database name" >&2+ return 1+ fi+ PGHOST="$1"+ PGPORT="$2"+ PGUSER="$3"+ PGDATABASE="$4"+ EXPLICIT_ENDPOINT=true+}++cmd_transfer() {+ local action="$1"+ shift+ if [ "${1:-}" = "--endpoint" ]; then+ if [ "$#" -lt 5 ]; then+ err "Usage: $action --endpoint <host> <port> <user> <database> [label|file]" >&2+ return 1+ fi+ set_explicit_endpoint "$2" "$3" "$4" "$5" || return 1+ shift 5+ fi+ if [ "$#" -gt 1 ] || { [ "$action" = "import" ] && [ "$#" -ne 1 ]; }; then+ err "Expected one import file or an optional export label" >&2+ return 1+ fi+ "cmd_$action" "${1:-}"+}# Check if Docker PostgreSQL is runningdocker_running() {@@ -487,6 +526,11 @@ cmd_setup_native() {# Run psql command, using Docker exec in Docker mode if host psql is unavailablerun_psql() {+ if [ "$EXPLICIT_ENDPOINT" = true ]; then+ # Never fall back to container-local psql: that is a different endpoint.+ PGPASSWORD="$PGPASSWORD" psql -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDATABASE" "$@"+ return $?+ filocal modemode=$(get_mode)if command -v psql >/dev/null 2>&1; then@@ -501,6 +545,10 @@ run_psql() {# Run pg_dump, preferring Docker exec in Docker mode to avoid version mismatchrun_pg_dump() {+ if [ "$EXPLICIT_ENDPOINT" = true ]; then+ PGPASSWORD="$PGPASSWORD" pg_dump -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDATABASE" "$@"+ return $?+ filocal modemode=$(get_mode)if [ "$mode" = "docker" ] && docker_running; then@@ -629,6 +677,9 @@ Commands:migrate Unavailable pending coordinated offline cutoverexport [label] Export database to data/db-dumps/import <file> Import a SQL dump file+ export --endpoint <host> <port> <user> <database> [label]+ import --endpoint <host> <port> <user> <database> <file>+ Use host PostgreSQL tools at this exact endpoint (no Docker fallback)Environment:PGMODE=docker|native Set in .env to control default mode@@ -647,8 +698,7 @@ case "${1:-help}" inuse-docker) cmd_migrate ;;use-native) cmd_migrate ;;migrate) cmd_migrate ;;- export) cmd_export "${2:-}" ;;- import) cmd_import "${2:?Usage: scripts/db.sh import <file>}" ;;+ export|import) action="$1"; shift; cmd_transfer "$action" "$@" ;;logs) cmd_logs ;;help|--help|-h) cmd_help ;;*) err "Unknown command: $1"; cmd_help; exit 1 ;;