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: honor saved database endpoints in the administration CLI

Adam Eivyd494de4b433d
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 130fe577b9..5ad6c87bea 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -324,6 +324,17 @@ PortOS treats **PostgreSQL as a mandatory install/runtime dependency** for every
Provision either path with **`npm run setup:db`** (also run automatically by `npm run setup` and `npm start`). It follows `PGMODE` (shell environment → `.env` → `docker`), and provisions only that selected backend. An unavailable Docker installation fails setup without probing native PostgreSQL or changing the saved mode. See [Setup path](#setup-path-npm-run-setupdb) below.
+The standalone `scripts/db.sh` also reads the repository-root `.env` through the
+shared setup parser (Node is required), with nonempty shell settings taking
+precedence. Quoted mode and connection values are supported without evaluating
+shell syntax. Native commands use `PGPORT`; Docker commands use
+`PGPORT_DOCKER`, unless the caller explicitly exports an active `PGPORT`.
+`setup-native` uses `PORTOS_NATIVE_PGPORT` when inherited from PM2, then the
+configured native `PGPORT`, without changing the selected mode. Container-local
+dump/import tools are used only for the selected local Docker endpoint; a
+host/port override cannot silently fall back to the local container. Maintenance
+`--endpoint` transfers remain bound to their explicitly recorded endpoint.
+
### `MEMORY_BACKEND=file` is a development/test-only escape hatch — NOT a deployment mode
The file backend (`server/services/memory.js`, JSON under `./data/`) is **unsupported for production and for federated peers.** It exists only so the test suite (and ad-hoc local development) can boot without a database. It is **not** a fallback, a "lite" mode, or a way to run PortOS without Postgres:
diff --git a/scripts/db-migrate.test.js b/scripts/db-migrate.test.js
index 51b6e123b8..fa9f0d6b60 100644
--- a/scripts/db-migrate.test.js
+++ b/scripts/db-migrate.test.js
@@ -86,7 +86,8 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'portos-db-sh-'));
- mkdirSync(join(root, 'scripts'));
+ mkdirSync(join(root, 'scripts', 'lib'), { recursive: true });
+ copyFileSync(join(here, 'lib', 'envFile.cjs'), join(root, 'scripts', 'lib', 'envFile.cjs'));
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 });
@@ -169,6 +170,63 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',
expect(tempArtifacts()).toEqual([]);
});
+ // Regression: the standalone CLI used defaults or a stale Docker database
+ // while the application used the quoted native endpoint saved in .env.
+ it('exports and imports the saved quoted native endpoint without evaluating shell text', () => {
+ const password = "example $(touch SHOULD_NOT_EXIST) ' password";
+ writeFileSync(envFile, `PGMODE = "native"\nPGHOST=db.example.invalid\nPGPORT=6543\nPGUSER=example_user\nPGDATABASE=example_db\nPGPASSWORD="${password}"\n`);
+ const overrides = { PGHOST: undefined, PGPASSWORD: undefined };
+ const exported = run(['export', 'saved'], 'ok', overrides);
+ expect(exported.status, exported.stderr).toBe(0);
+ const dump = join(dumpDir, 'portos-saved.sql');
+ expect(run(['import', dump], 'ok', overrides).status).toBe(0);
+ const log = readFileSync(stubLog, 'utf8');
+ expect(log).toContain('pg_dump -h db.example.invalid -p 6543 -U example_user -d example_db');
+ expect(log).toContain('psql -h db.example.invalid -p 6543 -U example_user -d example_db');
+ expect(log).not.toContain('docker');
+ expect(existsSync(join(root, 'SHOULD_NOT_EXIST'))).toBe(false);
+ expect(readFileSync(importLog, 'utf8')).toBe(FULL_DUMP);
+ });
+
+ it('honors shell connection overrides without exporting the unrelated local Docker database', () => {
+ writeFileSync(envFile, 'PGMODE=docker\nPGHOST=localhost\nPGPORT_DOCKER=5599\n');
+ const exported = run(['export', 'override'], 'ok', {
+ PGHOST: 'other.example.invalid', PGPORT: '6544', PGUSER: 'override_user', PGDATABASE: 'override_db',
+ });
+ expect(exported.status, exported.stderr).toBe(0);
+ const log = readFileSync(stubLog, 'utf8');
+ expect(log).toContain('pg_dump -h other.example.invalid -p 6544 -U override_user -d override_db');
+ expect(log).not.toContain('docker');
+ });
+
+ it('fails before database commands when the configuration parser is missing', () => {
+ rmSync(join(root, 'scripts', 'lib', 'envFile.cjs'));
+ const result = run(['export', 'no-config'], 'ok');
+ expect(result.status).not.toBe(0);
+ expect(result.stderr).toContain('Could not load database configuration');
+ expect(readFileSync(stubLog, 'utf8')).toBe('');
+ expect(dumps()).toEqual([]);
+ });
+
+ it('provisions the saved native endpoint even when Docker is the selected runtime', () => {
+ writeFileSync(envFile, 'PGMODE=docker\nPGHOST=db.example.invalid\nPGPORT=5433\nPGPORT_DOCKER=5599\n');
+ const result = run(['setup-native'], 'ok', { PGHOST: undefined, READY_PORTS: '5433' });
+ expect(result.status, result.stderr).toBe(0);
+ expect(psqlCalls().length).toBeGreaterThanOrEqual(6);
+ expect(psqlCalls().every(call => call.includes('-h db.example.invalid -p 5433 '))).toBe(true);
+ });
+
+ it('uses the saved Docker port for host imports while retaining container-only exports', () => {
+ writeFileSync(envFile, 'PGMODE="docker"\nPGPORT=5433\nPGPORT_DOCKER=5599\n');
+ const exported = run(['export', 'docker-saved'], 'ok');
+ expect(exported.status, exported.stderr).toBe(0);
+ const dump = join(dumpDir, 'portos-docker-saved.sql');
+ expect(run(['import', dump], 'ok').status).toBe(0);
+ const log = readFileSync(stubLog, 'utf8');
+ expect(log).toContain('portos-db pg_dump');
+ expect(log).toContain('psql -h 127.0.0.1 -p 5599');
+ });
+
// 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) => {
@@ -217,6 +275,7 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',
const commands = ['dirname', 'mkdir', 'mktemp', 'rm', 'sed', 'grep', 'cut', 'tr'];
const isolated = join(root, 'isolated');
mkdirSync(isolated);
+ symlinkSync(process.execPath, join(isolated, 'node'));
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);
diff --git a/scripts/db.sh b/scripts/db.sh
index fc68daac77..ba90c197e0 100755
--- a/scripts/db.sh
+++ b/scripts/db.sh
@@ -27,11 +27,48 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
-PGUSER="${PGUSER:-portos}"
-PGDATABASE="${PGDATABASE:-portos}"
-PGPASSWORD="${PGPASSWORD:-portos}"
-SELECTED_PGHOST="${PGHOST:-}"
-PGHOST="${PGHOST:-localhost}"
+# Read the same .env grammar as setup/PM2, without sourcing or evaluating it.
+# NUL-delimited values preserve password whitespace and shell metacharacters.
+# The completion marker makes a missing Node/parser or truncated pipe fail closed
+# before any database command, instead of silently targeting the defaults.
+read_db_config() {
+ node --input-type=commonjs - "$ROOT_DIR" "$1" <<'NODE'
+const { join } = require('node:path');
+const { parseEnvFile } = require(join(process.argv[2], 'scripts/lib/envFile.cjs'));
+const saved = parseEnvFile(join(process.argv[2], '.env'));
+const value = (key, fallback = '') => process.env[key] || saved[key] || fallback;
+const mode = value('PGMODE', 'docker');
+const nativeSetup = process.argv[3] === 'setup-native';
+const selectedHost = value('PGHOST');
+const dockerPort = value('PGPORT_DOCKER', '5561');
+const selectedPort = nativeSetup
+ ? process.env.PORTOS_NATIVE_PGPORT || value('PGPORT')
+ : process.env.PGPORT || (mode === 'native' ? saved.PGPORT || '' : dockerPort);
+const settings = {
+ PGMODE: mode, PGUSER: value('PGUSER', 'portos'),
+ PGDATABASE: value('PGDATABASE', 'portos'), PGPASSWORD: value('PGPASSWORD', 'portos'),
+ PGHOST: selectedHost || 'localhost', SELECTED_PGHOST: selectedHost,
+ PGPORT: selectedPort || (mode === 'native' || nativeSetup ? '5432' : dockerPort),
+ SELECTED_PGPORT: selectedPort, PGPORT_DOCKER: dockerPort,
+};
+process.stdout.write(Object.entries({ ...settings, complete: '1' })
+ .flat().join('\0') + '\0');
+NODE
+}
+_DB_CONFIG_COMPLETE=false
+while IFS= read -r -d '' key && IFS= read -r -d '' value; do
+ case "$key" in
+ PGMODE|PGUSER|PGDATABASE|PGPASSWORD|PGHOST|PGPORT|PGPORT_DOCKER|SELECTED_PGHOST|SELECTED_PGPORT)
+ printf -v "$key" '%s' "$value" ;;
+ complete) _DB_CONFIG_COMPLETE=true ;;
+ esac
+done < <(read_db_config "${1:-}")
+
+if [ "$_DB_CONFIG_COMPLETE" != true ]; then
+ echo "❌ Could not load database configuration; no database command was run" >&2
+ exit 1
+fi
+unset key value _DB_CONFIG_COMPLETE
# The maintenance coordinator names its install's dump directory explicitly
# (its data root can differ from this checkout); otherwise use this checkout.
DUMP_DIR="${PORTOS_DUMP_DIR:-$ROOT_DIR/data/db-dumps}"
@@ -49,33 +86,17 @@ warn() { echo -e "${YELLOW}⚠️ $1${NC}"; }
err() { echo -e "${RED}❌ $1${NC}"; }
info() { echo -e "${BLUE}🗄️ $1${NC}"; }
-# Detect current mode from .env or default to docker
get_mode() {
- if [ -f "$ENV_FILE" ]; then
- local mode
- mode=$(grep -E '^PGMODE=' "$ENV_FILE" 2>/dev/null | cut -d= -f2 | tr -d '[:space:]' || true)
- echo "${mode:-docker}"
- else
- echo "docker"
- fi
+ printf '%s\n' "$PGMODE"
}
-# Derive port from mode: native=5432 (system pg), docker=5561 (container)
-get_port() {
- if [ -n "${PGPORT:-}" ]; then
- echo "$PGPORT"
- elif [ "$(get_mode)" = "native" ]; then
- echo "5432"
- else
- echo "5561"
- fi
+# Container-local tools are equivalent only for the configured local Docker
+# endpoint. A shell host/port override must not silently export another DB.
+uses_local_docker_endpoint() {
+ [ "$PGMODE" = docker ] && [ "$PGPORT" = "$PGPORT_DOCKER" ] || return 1
+ case "$PGHOST" in localhost|127.0.0.1|::1) return 0 ;; *) return 1 ;; esac
}
-# Whether the caller named a host or port. setup-native provisions exactly that
-# endpoint (an unnamed half keeps its default); only a fully unnamed endpoint
-# falls back to local service discovery.
-SELECTED_PGPORT="${PGPORT:-}"
-PGPORT=$(get_port)
EXPLICIT_ENDPOINT=false
# A coordinator must bind each transfer to its recorded endpoint, not saved
@@ -574,11 +595,9 @@ run_psql() {
run_explicit_pg psql "$@"
return $?
fi
- local mode
- mode=$(get_mode)
if command -v psql >/dev/null 2>&1; then
PGPASSWORD="$PGPASSWORD" psql -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDATABASE" "$@"
- elif [ "$mode" = "docker" ] && docker_running; then
+ elif uses_local_docker_endpoint && docker_running; then
docker exec -i -e PGPASSWORD="$PGPASSWORD" portos-db psql -U "$PGUSER" -d "$PGDATABASE" "$@"
else
err "psql not found on host and Docker DB is not running"
@@ -592,9 +611,7 @@ run_pg_dump() {
run_explicit_pg pg_dump "$@"
return $?
fi
- local mode
- mode=$(get_mode)
- if [ "$mode" = "docker" ] && docker_running; then
+ if uses_local_docker_endpoint && docker_running; then
docker exec -e PGPASSWORD="$PGPASSWORD" portos-db pg_dump -U "$PGUSER" -d "$PGDATABASE" "$@"
elif command -v pg_dump >/dev/null 2>&1; then
PGPASSWORD="$PGPASSWORD" pg_dump -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDATABASE" "$@"