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: bind backup and restore tools to the checked database (#9451)
[._.]/ Adam Eivy063b0281a7b7
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 258715c778..1e4885a944 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -11,6 +11,15 @@ The dump includes the machine-local `cos_pending_agent_feedback` reference indexImplementation: `server/services/backup.js` (snapshot/dump/restore), `server/services/backupScheduler.js` (cron), `server/routes/backup.js` (API), and `server/routes/database.js` (DB export/sync).+Snapshot dump and replay use the endpoint and credentials captured by the active+pool at server startup. Changing `PGHOST`, `PGPORT`, `PGDATABASE`, `PGUSER`, or+`PGPASSWORD` requires restarting PortOS. Inherited libpq overrides (including+`PGHOSTADDR`, service files and `PGOPTIONS`) are removed from these subprocesses.+TLS is captured at startup too: disabled TLS stays disabled, verified TLS uses+`verify-full` with system trust (requires libpq 17 or newer), and `no-verify` uses `require`. Inline TLS+certificate settings are refused rather than silently weakened. Executable+resolution (`PATH` and `PORTOS_PGDUMP`) is preserved.+## Database backend migrationSettings (Database tab) offers a coordinated offline cutover between Docker anddiff --git a/server/lib/README.md b/server/lib/README.mdindex 1266f93a58..59789c20d2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -625,7 +625,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `db.js` | PostgreSQL connection pool and `withDatabaseMaintenance(fn)` admission/drain gate for atomic restore and reconciliation. || `db/` | Boot DDL for the PostgreSQL schema, split per domain (#2832). `db/schema/index.js` re-exports each module's statement array and composes the two ordered lists `ensureSchemaImpl()` runs on every boot (`buildUpgradeDdl()` then `buildCatalogDdl()`). **Statement order is load-bearing** — append inside the domain module and leave the composer order alone. See `db/schema/README.md` for the module catalog. || `pgTimestamp.js` | `mirrorTimestamp(value, fallback)` — coerce a hand-editable timestamp into a value Postgres TIMESTAMPTZ always accepts (or fall back), guarding boot-time binds against `Date.parse` rollover + out-of-range years. |-| `pgTools.js` | `pg_dump` binary resolution shared by the backup snapshot path and the native↔Docker export path: `resolvePgDumpBinary(serverMajor)` (PORTOS_PGDUMP override → version-aware auto-select → bare `pg_dump`), plus the lower-level `pickPgDump` / `discoverPgDumpCandidates` / `resolvePgDump`. Picks the closest installed `pg_dump` whose major is ≥ the running server's. |+| `pgTools.js` | `buildPgToolEnv(config)` isolates libpq connection/TLS settings from inherited PG variables; `pg_dump` binary resolution shared by the backup snapshot path and the native↔Docker export path: `resolvePgDumpBinary(serverMajor)` (PORTOS_PGDUMP override → version-aware auto-select → bare `pg_dump`), plus the lower-level `pickPgDump` / `discoverPgDumpCandidates` / `resolvePgDump`. Picks the closest installed `pg_dump` whose major is ≥ the running server's. || `ecosystemProcessPorts.js` | Attributes a parsed PM2 ecosystem config's port labels to the app that OWNS them (#7357): `processSurface(name)` (a process name minus one trailing role suffix, so `portos-server`/`portos-ui` share surface `portos` while `portos-autofixer-ui` does not), `attributeProcessPorts(processes, app)` (`api`/`ui`/`devUi` resolved from the app's own surface first, then from a carrier whose name declares no role at all, and left undefined when none — which is what lets the served-by-API `uiPort` derivation take over), and `findCrossProcessPortCollision(processes, edits)` (the pre-write guard: a port another process in the same config already holds). Shared by `services/appPortConfig.js` (write-back) and `services/appListEnrichment.js` (read/derive) so a displayed port and a rewritten port can never disagree about whose it is. || `ports.js` | Canonical `PORTS` object (mirroring `ecosystem.config.cjs`, pinned by `ports.test.js`), `DEFAULT_PEER_PORT`, and `resolvePostgresPort(pgMode)`. A pure leaf: `client/src/lib/ports.js` re-exports it, so nothing here may read `process.env` at module scope — the env-derived origins live in `portosUrls.js`. || `portosUrls.js` | `PORTOS_UI_URL` / `PORTOS_API_URL` — the origins PortOS interpolates into prompts and links, resolved from `PORTOS_*` / `PORT` at module load. Split out of `ports.js` so that module stays free of module-scope `process.env` reads and can be re-exported to the client. |diff --git a/server/lib/db.js b/server/lib/db.jsindex 424644cca9..4179b2d8e9 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -29,12 +29,16 @@ if (!process.env.PGPASSWORD) {// need a SECOND, independent connection to the same database (a raw `pg`// client outside the pool) don't have to re-derive these defaults and risk// drifting from them — see server/lib/db.test.js.+// Capture node-postgres's supported TLS environment once, alongside the endpoint.+const poolTls = new pg.Client().connectionParameters;export const POOL_CONFIG = Object.freeze({host: process.env.PGHOST || 'localhost',port: parseInt(process.env.PGPORT || '5432', 10),database: process.env.PGDATABASE || 'portos',user: process.env.PGUSER || 'portos',password: process.env.PGPASSWORD || 'portos',+ ssl: poolTls.ssl && typeof poolTls.ssl === 'object' ? Object.freeze({ ...poolTls.ssl }) : poolTls.ssl,+ sslnegotiation: poolTls.sslnegotiation || 'postgres',});const pool = new Pool({diff --git a/server/lib/db.schemaLifecycle.test.js b/server/lib/db.schemaLifecycle.test.jsindex efc13b1e3a..85ecd62175 100644--- a/server/lib/db.schemaLifecycle.test.js+++ b/server/lib/db.schemaLifecycle.test.js@@ -3,7 +3,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const state = vi.hoisted(() => ({query: vi.fn(), release: vi.fn(), connect: vi.fn(),}));-vi.mock('pg', () => ({ default: {+vi.mock('pg', async (importOriginal) => ({ default: {+ Client: (await importOriginal()).default.Client,Pool: class {on() {}connect = state.connect;diff --git a/server/lib/db.transaction.test.js b/server/lib/db.transaction.test.jsindex 586673a275..5bf4169978 100644--- a/server/lib/db.transaction.test.js+++ b/server/lib/db.transaction.test.js@@ -7,8 +7,9 @@ const pool = vi.hoisted(() => ({query: vi.fn(),}));-vi.mock('pg', () => ({+vi.mock('pg', async (importOriginal) => ({default: {+ Client: (await importOriginal()).default.Client,Pool: vi.fn(function Pool() { return pool; }),types: { setTypeParser: vi.fn() },},diff --git a/server/lib/pgTools.js b/server/lib/pgTools.jsindex e57f777d1e..ca9ba9f942 100644--- a/server/lib/pgTools.js+++ b/server/lib/pgTools.js@@ -15,6 +15,8 @@* imports out to other PortOS services.*/+import { randomUUID } from 'node:crypto';+import { tmpdir } from 'node:os';import { readdir } from 'fs/promises';import { join } from 'path';import { execFileAsync } from './fileUtils.js';@@ -133,3 +135,30 @@ export async function resolvePgDumpBinary(serverMajor) {}return { binary: 'pg_dump', satisfies: true };}++/** Build a libpq environment from the pool's captured connection policy.+ * Keep executable resolution and locale, but never inherit a second PG policy.+ * Inline certificate material needs a separate managed-file adapter; refuse it+ * rather than silently sending a child with weaker authentication.+ */+export function buildPgToolEnv(config, inherited = process.env) {+ const env = Object.fromEntries(Object.entries(inherited).filter(([key]) => !/^PG/i.test(key)));+ const ssl = config.ssl;+ if (ssl && typeof ssl === 'object' && Object.keys(ssl).some(key => key !== 'rejectUnauthorized')) {+ throw new Error('PostgreSQL tools do not support inline pool TLS certificate settings');+ }+ env.PGPASSWORD = config.password;+ env.PGSSLMODE = ssl ? (ssl.rejectUnauthorized === false ? 'require' : 'verify-full') : 'disable';+ // Verified node-postgres TLS uses the system trust store, never ~/.postgresql.+ if (env.PGSSLMODE === 'verify-full') env.PGSSLROOTCERT = 'system';+ // libpq's require mode verifies a default root.crt when one exists. An+ // intentionally absent, unique path preserves node-postgres no-verify TLS.+ if (env.PGSSLMODE === 'require') env.PGSSLROOTCERT = join(tmpdir(), `portos-unused-root-${randomUUID()}.crt`);+ // libpq otherwise discovers client identity files in the user's home; the+ // pool does not load them. Missing explicit paths disable that discovery.+ const unusedIdentity = join(tmpdir(), `portos-unused-identity-${randomUUID()}`);+ env.PGSSLCERT = `${unusedIdentity}.crt`;+ env.PGSSLKEY = `${unusedIdentity}.key`;+ env.PGSSLNEGOTIATION = config.sslnegotiation || 'postgres';+ return env;+}diff --git a/server/lib/pgTools.test.js b/server/lib/pgTools.test.jsindex 0dc16a3f9a..f2ea9dfdde 100644--- a/server/lib/pgTools.test.js+++ b/server/lib/pgTools.test.js@@ -27,6 +27,7 @@ vi.mock('./fileUtils.js', async (importOriginal) => {import { readdir } from 'fs/promises';import { execFileAsync } from './fileUtils.js';import {+ buildPgToolEnv,pickPgDump,discoverPgDumpCandidates,resolvePgDump,@@ -173,3 +174,21 @@ describe('resolvePgDumpBinary', () => {expect(execFileAsync).not.toHaveBeenCalled();});});++describe('PostgreSQL tool TLS policy', () => {+ it('uses system trust for verified TLS and preserves direct negotiation', () => {+ expect(buildPgToolEnv({ password: 'example', ssl: true, sslnegotiation: 'direct' }, { PATH: '/example/bin', PGSSLROOTCERT: 'poisoned', PGSSLMODE: 'disable' })).toMatchObject({+ PATH: '/example/bin', PGPASSWORD: 'example', PGSSLMODE: 'verify-full', PGSSLROOTCERT: 'system', PGSSLNEGOTIATION: 'direct',+ });+ });++ it('requires encrypted no-verify TLS without loading ambient root certificates', () => {+ const env = buildPgToolEnv({ ssl: { rejectUnauthorized: false } }, {});+ expect(env.PGSSLMODE).toBe('require');+ expect(env.PGSSLROOTCERT).toMatch(/portos-unused-root-.*\.crt$/);+ });++ it('refuses inline certificates rather than discarding the pool authentication policy', () => {+ expect(() => buildPgToolEnv({ ssl: { ca: 'example-ca' } }, {})).toThrow('inline pool TLS');+ });+});diff --git a/server/services/backup.js b/server/services/backup.jsindex 93cb376d67..0e4c94b302 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -17,8 +17,8 @@ import { PATHS, ensureDir, readJSONFile, readJSONFileStrict, atomicWrite, sha256import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { createLineReader } from '../lib/streamLines.js';import { getEvent } from './eventScheduler.js';-import { checkHealth, ensureSchema, getServerMajorVersion, query, withDatabaseMaintenance } from '../lib/db.js';-import { resolvePgDumpBinary } from '../lib/pgTools.js';+import { POOL_CONFIG, checkHealth, ensureSchema, getServerMajorVersion, query, withDatabaseMaintenance } from '../lib/db.js';+import { buildPgToolEnv, resolvePgDumpBinary } from '../lib/pgTools.js';import { inspectDatabaseDump } from './backupDatabaseDump.js';import { syncFeedTables, syncFeedSequenceName } from '../lib/db/schema/syncFeed.js';import { getBackendName } from './memoryBackend.js';@@ -693,14 +693,9 @@ export async function dumpPostgres(outputPath) {return { status: 'skipped', reason: 'not_configured' };}- const pgHost = process.env.PGHOST || 'localhost';- const pgPort = process.env.PGPORT || '5432';- const pgDb = process.env.PGDATABASE || 'portos';- const pgUser = process.env.PGUSER || 'portos';-- if (!process.env.PGPASSWORD) {- console.warn('⚠️ PGPASSWORD not set for pg_dump — using default');- }+ const { host: pgHost, port, database: pgDb, user: pgUser } = POOL_CONFIG;+ const pgPort = String(port);+ const pgEnv = buildPgToolEnv(POOL_CONFIG);// pg_dump must be >= the server's major version or it aborts on a "server// version mismatch". On machines with multiple Postgres installs (the common@@ -733,7 +728,7 @@ export async function dumpPostgres(outputPath) {'-f', outputPath], {shell: false,- env: { ...process.env, PGPASSWORD: process.env.PGPASSWORD || 'portos' }+ env: pgEnv});let stderr = '';@@ -1607,10 +1602,9 @@ async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotIreturn withDatabaseMaintenance(async () => {// Read before the replay rewinds them to the dump's values.const feedPositions = await captureSyncFeedPositions();- const pgHost = process.env.PGHOST || 'localhost';- const pgPort = process.env.PGPORT || '5432';- const pgDb = process.env.PGDATABASE || 'portos';- const pgUser = process.env.PGUSER || 'portos';+ const { host: pgHost, port, database: pgDb, user: pgUser } = POOL_CONFIG;+ const pgPort = String(port);+ const pgEnv = buildPgToolEnv(POOL_CONFIG);const replay = await new Promise((resolveP) => {// ON_ERROR_STOP=1 aborts on the first failed statement; --single-transaction@@ -1625,7 +1619,7 @@ async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotI'--single-transaction','--echo-all','-h', pgHost, '-p', pgPort, '-U', pgUser, '-d', pgDb, '-c', reset, '-f', spoolPath- ], { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PGPASSWORD: process.env.PGPASSWORD || 'portos' } });+ ], { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: pgEnv });let stderr = '';const watchdog = watchBackupProcess(proc, { label: 'PostgreSQL restore' });diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex 46fa984c0c..27836d22c1 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -47,7 +47,9 @@ afterAll(() => {// Mock the DB health check and child_process.spawn before importing backup.js+const poolConfig = vi.hoisted(() => Object.freeze({ host: 'db.example.test', port: 5439, database: 'example_db', user: 'example_user', password: 'example-secret', ssl: false, sslnegotiation: 'postgres' }));vi.mock('../lib/db.js', () => ({+ POOL_CONFIG: poolConfig,checkHealth: vi.fn(),query: vi.fn().mockResolvedValue({ rows: [] }),withDatabaseMaintenance: vi.fn(fn => fn()),@@ -825,6 +827,18 @@ describe('openSnapshotStream', () => {});});++function assertPoolToolSpawn([, args, { env }]) {+ for (const [flag, key] of [['-h', 'host'], ['-p', 'port'], ['-U', 'user'], ['-d', 'database']]) {+ expect(args[args.indexOf(flag) + 1]).toBe(String(poolConfig[key]));+ }+ expect(env.PGPASSWORD).toBe(poolConfig.password);+ expect(env.PGSSLMODE).toBe('disable');+ expect(env.PGSSLNEGOTIATION).toBe('postgres');+ for (const key of ['PGHOSTADDR', 'PGSERVICE', 'PGSERVICEFILE', 'PGOPTIONS', 'PGHOST', 'PGDATABASE']) expect(env).not.toHaveProperty(key);+ expect(env.PATH).toBe(process.env.PATH);+}+describe('dumpPostgres status classification', () => {let dumpPostgres;beforeEach(async () => {@@ -921,6 +935,21 @@ describe('dumpPostgres status classification', () => {if (prev === undefined) delete process.env.MEMORY_BACKEND; else process.env.MEMORY_BACKEND = prev;});+ it('dumps the checked pool endpoint despite changed credentials and poisoned libpq settings', async () => {+ for (const key of ['PGHOST', 'PGPORT', 'PGUSER', 'PGDATABASE', 'PGPASSWORD', 'PGHOSTADDR', 'PGSERVICE', 'PGSERVICEFILE', 'PGOPTIONS', 'PGSSLMODE']) vi.stubEnv(key, 'poisoned');+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096 });+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ createReadStream.mockImplementation(() => Readable.from([Buffer.from('CREATE TABLE public.memories (id uuid);\n')]));+ const result = dumpPostgres('/tmp/example.sql');+ await flush();+ assertPoolToolSpawn(spawn.mock.calls[0]);+ proc.emit('close', 0);+ expect(await result).toMatchObject({ status: 'ok' });+ vi.unstubAllEnvs();+ });+it('returns failed/pg_dump_missing when spawn errors', async () => {checkHealth.mockResolvedValue({ connected: true, hasSchema: true });const proc = fakeProc();@@ -1627,7 +1656,7 @@ describe('restorePostgres', () => {// and --single-transaction rolls the whole replay back, so a failed restore// leaves the live DB untouched instead of half-dropped. Both flags are load// bearing — a refactor that drops either turns a failed restore into data loss.- it('passes --single-transaction and ON_ERROR_STOP=1 with the default PGPASSWORD', async () => {+ it('passes atomic replay flags with the captured pool credentials', async () => {vi.stubEnv('PGPASSWORD', '');vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });mockLegacyDumpRead();@@ -1644,11 +1673,11 @@ describe('restorePostgres', () => {// Assert the flag/value pairing, not just membership: '-v' followed by// something else would still satisfy arrayContaining.expect(args[args.indexOf('-v') + 1]).toBe('ON_ERROR_STOP=1');- expect(opts.env.PGPASSWORD).toBe('portos');+ expect(opts.env.PGPASSWORD).toBe(poolConfig.password);});- it('prefers an explicit PGPASSWORD over the portos default', async () => {- vi.stubEnv('PGPASSWORD', 'from-env');+ it('ignores changed endpoint, password and inherited libpq policy during restore', async () => {+ for (const key of ['PGHOST', 'PGPORT', 'PGUSER', 'PGDATABASE', 'PGPASSWORD', 'PGHOSTADDR', 'PGSERVICE', 'PGSERVICEFILE', 'PGOPTIONS', 'PGSSLMODE']) vi.stubEnv(key, 'poisoned');vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });mockLegacyDumpRead();checkHealth.mockResolvedValue({ connected: true, hasSchema: true });@@ -1658,7 +1687,7 @@ describe('restorePostgres', () => {await flush();proc.emit('close', 0);await p;- expect(spawn.mock.calls[0][2].env.PGPASSWORD).toBe('from-env');+ assertPoolToolSpawn(spawn.mock.calls[0]);});});