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 database deletion to the inactive backend (#7212)
[._.]/ Adam Eivy646eed645b10
diff --git a/server/routes/database.test.js b/server/routes/database.test.jsindex 3c2d54af68..fa539caa7f 100644--- a/server/routes/database.test.js+++ b/server/routes/database.test.js@@ -5,7 +5,7 @@* we can control every shell invocation without touching the real filesystem* or running actual Docker/psql commands.*/-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';@@ -229,6 +229,10 @@ describe('POST /api/database/destroy', () => {vi.clearAllMocks();});+ afterEach(() => {+ vi.unstubAllEnvs();+ });+describe('input validation', () => {it('returns 400 when backend is missing', async () => {const app = makeApp();@@ -290,6 +294,8 @@ describe('POST /api/database/destroy', () => {describe('docker destroy path', () => {it('invokes docker stop, rm, and volume rm commands when destroying non-active docker backend', async () => {+ vi.stubEnv('PGHOST', 'localhost');+ vi.stubEnv('PGPORT', '5432');// Call order:// 0: runDbScript(['status']) → mode is "native" (so docker is the non-active backend)// 1: docker compose stop db@@ -324,11 +330,14 @@ describe('POST /api/database/destroy', () => {c => c[1].includes('volume') && c[1].includes('rm'));expect(volumeRmCall).toBeDefined();+ expect(execFile.mock.calls.some(c => c[0] === 'psql')).toBe(false);});});describe('native destroy path', () => {- it('invokes psql DROP DATABASE when destroying the non-active native backend', async () => {+ it('targets the canonical native endpoint instead of the active Docker port', async () => {+ vi.stubEnv('PGHOST', 'localhost');+ vi.stubEnv('PGPORT', '5561');// Call order:// 0: runDbScript(['status']) → mode is "docker" (so native is non-active)// 1: psql DROP DATABASE …@@ -350,6 +359,48 @@ describe('POST /api/database/destroy', () => {expect(psqlCall).toBeDefined();// The args should contain a DROP DATABASE statementexpect(psqlCall[1].join(' ')).toMatch(/DROP DATABASE/i);+ expect(psqlCall[1][psqlCall[1].indexOf('-p') + 1]).toBe('5432');+ expect(psqlCall[1]).not.toContain('5561');+ });+ });++ describe('endpoint identity safety', () => {+ it.each([+ ['native', 'docker', '5432', '127.0.0.1'],+ ['docker', 'native', '5561', '::1'],+ ])('refuses %s when its target aliases the active %s endpoint', async (backend, mode, port, host) => {+ vi.stubEnv('PGHOST', host);+ vi.stubEnv('PGPORT', port);+ mockExecFile([+ { exitCode: 0, stdout: `Current mode: ${mode}`, stderr: '' },+ ]);++ const app = makeApp();+ const res = await request(app)+ .post('/api/database/destroy')+ .send({ backend });++ expect(res.status).toBe(400);+ expect(res.body.error).toMatch(/active backend/i);+ expect(execFile).toHaveBeenCalledTimes(1);+ });++ it.each([+ ['failed', { exitCode: 1, stdout: '', stderr: 'status failed' }],+ ['unparseable', { exitCode: 0, stdout: 'Database status unavailable', stderr: '' }],+ ])('fails closed on a %s status probe', async (_case, statusResponse) => {+ vi.stubEnv('PGHOST', 'localhost');+ vi.stubEnv('PGPORT', '5561');+ mockExecFile([statusResponse]);++ const app = makeApp();+ const res = await request(app)+ .post('/api/database/destroy')+ .send({ backend: 'native' });++ expect(res.status).toBe(500);+ expect(res.body.error).toMatch(/cannot verify/i);+ expect(execFile).toHaveBeenCalledTimes(1);});});});diff --git a/server/services/dbAdmin.js b/server/services/dbAdmin.jsindex 14d6eb204b..b6b6b46abf 100644--- a/server/services/dbAdmin.js+++ b/server/services/dbAdmin.js@@ -7,6 +7,7 @@ import { PATHS } from '../lib/fileUtils.js';import { stripAnsi } from '../lib/ansiStrip.js';import { resolvePgDumpBinary } from '../lib/pgTools.js';import { resolveBashBinary, toBashPath } from '../lib/bashResolver.js';+import { resolvePostgresPort } from '../lib/ports.js';const rootDir = PATHS.root;const dbScript = toBashPath(join(rootDir, 'scripts', 'db.sh'));@@ -262,9 +263,20 @@ const pgQuoteIdentifier = (name) => `"${String(name).replace(/"/g, '""')}"`;// Safely escape a PostgreSQL string literal value by doubling single-quotes.const pgEscapeString = (val) => String(val).replace(/'/g, "''");-// Native (5432) and Docker (5561) use different ports, so both can run simultaneously.-const NATIVE_PORT = '5432';-const DOCKER_PORT = '5561';+// Native and Docker use different ports, so both can run simultaneously. Resolve+// them through the canonical port map rather than inheriting PGPORT, which names+// whichever backend this server process is actively connected to.+const NATIVE_PORT = String(resolvePostgresPort('native'));+const DOCKER_PORT = String(resolvePostgresPort('docker'));++const normalizePgHost = (host) => {+ const value = String(host || 'localhost').trim().toLowerCase();+ return ['localhost', '127.0.0.1', '::1', '[::1]'].includes(value) ? 'loopback' : value;+};++const endpointsAlias = (leftHost, leftPort, rightHost, rightPort) =>+ normalizePgHost(leftHost) === normalizePgHost(rightHost)+ && Number(leftPort) === Number(rightPort);// Prefer Homebrew postgresql@17 binaries over system pg (avoids version mismatch)// Check both arm64 (/opt/homebrew) and Intel (/usr/local) prefixes@@ -519,13 +531,30 @@ export async function stopDatabase(backend) {/** Destroy an inactive database backend's data. */export async function destroyDatabase(backend) {- // Safety: don't destroy the active backend+ // Safety: authorize deletion only from a successful, recognized mode probe.+ // parseDbMode intentionally has a Docker fallback for non-destructive callers,+ // so destruction validates the probe independently and fails closed.const statusResult = await runDbScript(['status']);- const currentMode = parseDbMode(statusResult.stdout);+ const currentMode = statusResult.exitCode === 0+ ? statusResult.stdout.match(/Current mode:\s*(docker|native)\b/)?.[1]+ : null;+ if (!currentMode) {+ throw new ServerError('Cannot verify the active database backend. No data was destroyed.', { status: 500 });+ }if (backend === currentMode) {throw new ServerError('Cannot destroy the active backend. Switch to the other backend first.', { status: 400 });}+ // The requested backend owns the destructive target. PGPORT/PGHOST describe+ // the active pool and must never redirect an inactive-backend deletion. Refuse+ // the operation if the independently-resolved target still aliases that pool.+ const targetPort = backend === 'native' ? NATIVE_PORT : DOCKER_PORT;+ const activePort = process.env.PGPORT || String(resolvePostgresPort(currentMode));+ const activeHost = process.env.PGHOST || 'localhost';+ if (endpointsAlias('localhost', targetPort, activeHost, activePort)) {+ throw new ServerError('Cannot destroy a database endpoint used by the active backend.', { status: 400 });+ }+if (backend === 'docker') {// Stop and remove container + volumeawait runCmd('docker', ['compose', 'stop', 'db'], 15_000);@@ -538,9 +567,8 @@ export async function destroyDatabase(backend) {// Native: drop the portos database (system pg stays running)const sysUser = process.env.USER || 'portos';- const nativePort = process.env.PGPORT || '5432';const result = await runCmd('psql', [- '-h', 'localhost', '-p', nativePort, '-U', sysUser, '-d', 'postgres',+ '-h', 'localhost', '-p', NATIVE_PORT, '-U', sysUser, '-d', 'postgres','-c', `DROP DATABASE IF EXISTS ${pgQuoteIdentifier(pgDb)}`], 15_000);return { success: result.exitCode === 0, output: result.stdout };