"use strict"; const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); const httpMod = require("http"); const zlib = require("zlib"); const { atomicWriteFileSync } = require("./atomic-file"); // ─── Configuration ────────────────────────────────────────────── const TOKEN_TTL_MS = 10 * 60 * 1000; // 10 minutes, sliding while in active use const TOKEN_BYTES = 16; const CLEANUP_INTERVAL_MS = 60 * 1000; // sweep every 60s const MAX_SESSIONS = 500; // hard cap to prevent RAM bloat const PHPMYADMIN_INTERNAL_PORT = 9082; const DB_ACCESS_PREFIX = "/db-access/"; const PROXY_COOKIE_PREFIX = "adpanel.dbproxy."; const HEARTBEAT_PATH = "/__heartbeat"; const HEARTBEAT_INTERVAL_MS = 45 * 1000; // Panel cookies that must never be forwarded to the proxied backends: the // backends only need their own session cookies, and echoing panel secrets // (session id, remember-login, stealth gate, proxy tokens) into third-party // code/logs is pure downside. The prefix catches adpanel.sid, // adpanel.remember, adpanel.bp and the adpanel.dbproxy.* token cookies; // PANEL_COOKIE_NAMES catches panel cookies that live outside the prefix // (the stealth gate cookie "adpanel_gate" uses an underscore). The panel // registers its live cookie names at mount time (see createProxyMiddleware) // because the stealth name is operator-configurable. const PANEL_COOKIE_NAME_PREFIX = "adpanel."; const PANEL_COOKIE_NAMES = new Set(["adpanel.sid", "adpanel.remember", "adpanel.bp", "adpanel_gate"]); function registerPanelCookieNames(names) { if (!Array.isArray(names)) return; for (const raw of names) { const name = String(raw || "").trim(); if (name) PANEL_COOKIE_NAMES.add(name); } } function isPanelCookieName(name) { return name.startsWith(PANEL_COOKIE_NAME_PREFIX) || PANEL_COOKIE_NAMES.has(name); } // ─── Cluster-Safe Token Store ─────────────────────────────────── // // The panel's production topology is multi-worker: PM2 cluster mode with // INSTANCES = cores - 2 (scripts/generate-ecosystem.sh). A per-process Map // breaks the "Open phpMyAdmin/pgAdmin" flow under that topology — the POST // to /api/settings/database/access-token that mints the token and the // /db-access// navigation that spends it can land on different // workers — so the store must be shared. Backends, in priority order: // // 1. Redis (index.js injects its session Redis client): one key per token // with an EX TTL plus a ZSET index (member = token hash, score = // expiresAt) that makes user/service/session-wide revocation a bounded // lookup instead of a SCAN. Cluster-safe across workers and restarts. // 2. Flat JSON files under data/db-proxy-tokens/ (the same durability // pattern as the install-job mirror): Redis is not guaranteed on every // install (SESSION_STORE=file leaves redisClient null), and PM2 cluster // workers share the host filesystem, so files restore cross-worker // visibility for the standard multi-worker, file-session topology. // 3. Process memory (the legacy store) when no data dir was configured — // single-worker behavior, unchanged from before this fix. // // Credential hygiene for the shared stores. Anything that can read the // panel's data dir or Redis can already read the live admin session records // (session-file-store filenames / connect-redis keys), so this is defense in // depth rather than the primary boundary — but new copies of credentials // must not be created where none existed: // - Records are keyed by SHA-256(token); the raw token (128 random bits) // is never persisted anywhere. // - Records carry SHA-256(sessionId) instead of the raw panel session id, // so the store cannot be mined for replayable adpanel.sid cookie values. // The proxy still re-validates the LIVE session on every request // (sessionMatchesToken), which is the actual authorization boundary. // - File records are 0600 inside a 0700 directory, written atomically // (utils/atomic-file.js) so a crash never leaves a torn record behind. // // Failure policy: // - Minting fails CLOSED: generateToken returns null → the route 500s. // A token the store could not persist could not be revoked cross-worker // either, so it must never be issued. // - Validation failures fail CLOSED but KEEP the cookie (503 + Retry-After // from the middleware): a transient store outage must not be confused // with a stale token (which 404s AND clears the cookie, forcing a // re-mint), and must not strand an open tab. // - Revocation never throws (logout must always complete); failures are // logged. The token alone is inert — every use also requires the live // minting admin session (sessionMatchesToken), and logout / session // revoke destroy that session independently of this store. // - A file store that cannot write (full or unwritable disk) degrades to // the per-process memory backend for this process's lifetime — exactly // the behavior this fix replaces — and says so loudly in the log. // // Known-benign races on the shared stores (documented, accepted): a touch // racing a revocation can re-persist a just-deleted record, and a revocation // scan racing a touch can miss it for one pass. Every such token remains // bound to its minting admin session and capped by the sliding TTL, and the // revocation paths that matter (logout, session revoke) destroy that session // independently, so no privilege boundary depends on the store winning. const MAX_TOKEN_LENGTH = 128; // real tokens are "v-tmp-" + 32 hex chars const TOUCH_REWRITE_SLACK_MS = 60 * 1000; // file-backend IO throttle window const TOKEN_FILE_DIR_NAME = "db-proxy-tokens"; const TOKEN_FILE_NAME_RE = /^([0-9a-f]{64})\.json$/; const HASHED_KEY_RE = /^[0-9a-f]{64}$/; class StoreUnavailableError extends Error { constructor(message) { super(message); this.name = "StoreUnavailableError"; } } let logger = console; let storeConfig = { redisGetter: null, dataDir: null, redisOpTimeoutMs: 1500 }; // Called once by index.js at boot (after the Redis client exists). Optional: // without it the module keeps the legacy per-process memory behavior. function configureTokenStore(options = {}) { storeConfig = { redisGetter: typeof options.redis === "function" ? options.redis : null, dataDir: typeof options.dataDir === "string" && options.dataDir.trim() ? options.dataDir : null, redisOpTimeoutMs: Number.isFinite(options.redisOpTimeoutMs) && options.redisOpTimeoutMs >= 0 ? options.redisOpTimeoutMs : 1500, }; fileStoreInstance = null; } function logStoreError(op, err) { const message = err && err.message ? err.message : String(err); if (err instanceof StoreUnavailableError) { logger.error(`[db-proxy] token store unavailable during ${op}: ${message}`); } else { logger.error(`[db-proxy] token store ${op} failed: ${message}`); } } function hashStoreKey(token) { return crypto.createHash("sha256").update(String(token), "utf8").digest("hex"); } function hashSessionId(sessionId) { const raw = String(sessionId == null ? "" : sessionId); // Empty stays empty (a token minted without a session can never match one // — sessionMatchesToken fails closed on an empty hash), instead of hashing // to a constant. return raw ? crypto.createHash("sha256").update(raw, "utf8").digest("hex") : ""; } function timingSafeHexEqual(a, b) { const ab = Buffer.from(String(a), "utf8"); const bb = Buffer.from(String(b), "utf8"); if (ab.length === 0 || ab.length !== bb.length) return false; return crypto.timingSafeEqual(ab, bb); } // Rebuild a record from untrusted JSON with a strict shape. Anything that // does not match is treated as absent (the store answers "miss"), never as // an authoritative record with attacker-chosen fields. function sanitizeRecord(parsed) { if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null; const service = parsed.service; if (typeof service !== "string" || !Object.prototype.hasOwnProperty.call(SERVICE_TARGETS, service)) return null; if (typeof parsed.username !== "string") return null; const sessionIdHash = typeof parsed.sessionIdHash === "string" && HASHED_KEY_RE.test(parsed.sessionIdHash) ? parsed.sessionIdHash : ""; const createdAt = Number(parsed.createdAt); const expiresAt = Number(parsed.expiresAt); if (!Number.isFinite(createdAt) || !Number.isFinite(expiresAt)) return null; return { service, userIp: typeof parsed.userIp === "string" ? parsed.userIp : "", username: parsed.username, sessionIdHash, createdAt, expiresAt, }; } function safeJsonParse(raw) { if (typeof raw !== "string" || !raw) return null; try { return JSON.parse(raw); } catch { return null; } } // ── Backend 3: process memory (legacy behavior) ───────────────── const memoryStore = { kind: "memory", ioThrottled: false, map: new Map(), async put(hash, record) { this.map.set(hash, record); return true; }, async get(hash) { return this.map.get(hash) || null; }, // has() guard: a refresh must not resurrect an entry a concurrent same- // process revocation just deleted. async refresh(hash, record) { if (!this.map.has(hash)) return false; this.map.set(hash, record); return true; }, async remove(hash) { this.map.delete(hash); }, async listLive() { const now = Date.now(); const out = []; for (const [hash, record] of this.map) { if (record.expiresAt > now) out.push({ hash, record }); else this.map.delete(hash); } return out; }, async countLive() { await this.listLive(); // lazily drops expired entries first return this.map.size; }, async evictOldest(count) { if (count <= 0) return; const victims = [...this.map.entries()] .sort((a, b) => a[1].createdAt - b[1].createdAt) .slice(0, count); for (const [hash] of victims) this.map.delete(hash); }, }; // ── Backend 2: flat JSON files (cluster-safe without Redis) ───── function createFileStore(dataDir) { const dir = path.join(dataDir, TOKEN_FILE_DIR_NAME); let dirReady = false; let broken = false; function tokenPath(hash) { // Hashes are produced by hashStoreKey, but the shape is enforced anyway // so no caller can ever turn store input into a filesystem path (same // discipline as the install-job store's id validation). if (!HASHED_KEY_RE.test(hash)) throw new Error(`[db-proxy] invalid token hash: ${JSON.stringify(String(hash))}`); return path.join(dir, `${hash}.json`); } function markBroken(err) { if (broken) return; broken = true; logger.warn(`[db-proxy] Token file store at ${dir} is unwritable (${err && err.message ? err.message : err}); degrading to per-process memory for this worker. Multi-worker installs will NOT share db-proxy tokens for this process — fix the disk/permissions or configure Redis.`); } function removeFile(hash) { try { fs.unlinkSync(tokenPath(hash)); } catch (err) { if (err && err.code !== "ENOENT") throw err; } } return { kind: "file", // File writes cost tmp+rename+fsync, so touchToken skips rewrites that // would not move the persisted window meaningfully (see touchToken). ioThrottled: true, isBroken: () => broken, async put(hash, record) { if (broken) return false; try { if (!dirReady) { fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); try { fs.chmodSync(dir, 0o700); } catch { /* umask-covered mode is fine */ } dirReady = true; } atomicWriteFileSync(tokenPath(hash), JSON.stringify(record), { mode: 0o600 }); return true; } catch (err) { markBroken(err); return false; } }, async get(hash) { let raw; try { raw = fs.readFileSync(tokenPath(hash), "utf8"); } catch (err) { if (err && err.code === "ENOENT") return null; throw new StoreUnavailableError(`file store read failed: ${err && err.message ? err.message : err}`); } const record = sanitizeRecord(safeJsonParse(raw)); if (!record) { // A torn/corrupt record fails closed (miss) and is dropped: it is // worthless as telemetry and would otherwise linger forever. try { fs.unlinkSync(tokenPath(hash)); } catch { /* sweep will retry */ } } return record; }, // rename(2) cannot be made conditional the way Redis SET XX can, so a // refresh racing a cross-worker revocation can overwrite the deletion — // the documented benign race above (session-bound token, TTL-capped). async refresh(hash, record) { return this.put(hash, record); }, async remove(hash) { try { removeFile(hash); } catch (err) { throw new StoreUnavailableError(`file store delete failed: ${err && err.message ? err.message : err}`); } }, async listLive() { let names; try { names = fs.readdirSync(dir); } catch (err) { if (err && err.code === "ENOENT") return []; throw new StoreUnavailableError(`file store scan failed: ${err && err.message ? err.message : err}`); } const now = Date.now(); const out = []; for (const name of names) { const match = TOKEN_FILE_NAME_RE.exec(name); if (!match) continue; // tmp fragments from atomic writes never match let record = null; try { record = sanitizeRecord(safeJsonParse(fs.readFileSync(path.join(dir, name), "utf8"))); } catch { record = null; } if (!record || record.expiresAt <= now) continue; // dead weight: sweep's job out.push({ hash: match[1], record }); } return out; }, async countLive() { return (await this.listLive()).length; }, async evictOldest(count) { const victims = (await this.listLive()) .sort((a, b) => a.record.createdAt - b.record.createdAt) .slice(0, Math.max(0, count)); for (const { hash } of victims) { try { removeFile(hash); } catch { /* best effort */ } } }, // Periodic garbage collection of expired/corrupt records. Never creates // the directory (only put does) and never throws. async sweep() { if (broken) return; let names; try { names = fs.readdirSync(dir); } catch (err) { if (err && err.code === "ENOENT") return; return; // unreadable dir: the next tick retries } for (const name of names) { if (!TOKEN_FILE_NAME_RE.test(name)) continue; const filePath = path.join(dir, name); let record = null; try { record = sanitizeRecord(safeJsonParse(fs.readFileSync(filePath, "utf8"))); } catch { record = null; } if (record && record.expiresAt > Date.now()) continue; try { fs.unlinkSync(filePath); } catch { /* gone or busy: next tick */ } } }, }; } // ── Backend 1: Redis (cluster-safe with the panel's session Redis) ── function createRedisStore(client, opTimeoutMs) { const PREFIX = "adpanel:dbproxy:"; const INDEX_KEY = PREFIX + "index"; // ZSET: member = token hash, score = expiresAt (ms) function tokenKey(hash) { return PREFIX + "tok:" + hash; } function ttlSeconds(ms) { return Math.max(1, Math.ceil(ms / 1000)); } // Every store operation races a timeout: node-redis queues commands while // reconnecting, and an unbounded wait would stall the whole /db-access // pipeline (and pile up sockets) during a Redis blip. Both failure shapes // — error and timeout — surface as StoreUnavailableError so callers fail // closed uniformly. function op(promise, label) { let timer = null; const timeout = new Promise((_, reject) => { // NOT unref'd on purpose: it is cleared in the finally below, and while // it is pending it is the only thing guaranteeing the process stays // alive long enough for the race to resolve. timer = setTimeout(() => reject(new Error(`redis ${label} timed out after ${opTimeoutMs}ms`)), opTimeoutMs); }); return Promise.race([promise, timeout]) .finally(() => { if (timer) clearTimeout(timer); }) .catch((err) => { throw new StoreUnavailableError(`redis ${label} failed: ${err && err.message ? err.message : err}`); }); } function guardReady(label) { // node-redis exposes isReady; a client mid-reconnect fails fast instead // of relying on the offline queue. Clients without the flag (fakes, // other drivers) are not filtered. if (client && client.isReady === false) { throw new StoreUnavailableError(`redis ${label} aborted: client not ready`); } } return { kind: "redis", ioThrottled: false, async put(hash, record, ttlMs) { guardReady("set"); await op(client.set(tokenKey(hash), JSON.stringify(record), { EX: ttlSeconds(ttlMs) }), "set"); await op(client.zAdd(INDEX_KEY, [{ score: record.expiresAt, value: hash }]), "zadd"); return true; }, async get(hash) { guardReady("get"); const raw = await op(client.get(tokenKey(hash)), "get"); return sanitizeRecord(safeJsonParse(raw)); }, // SET with XX (exists-only): slides the TTL and rewrites expiresAt in // one atomic step, and can never resurrect a token that a concurrent // revocation just deleted (a bare SET would — the same record would come // back with a fresh TTL after DEL). A nil reply means the token died // between validate and touch. async refresh(hash, record, ttlMs) { guardReady("set"); const reply = await op(client.set(tokenKey(hash), JSON.stringify(record), { XX: true, EX: ttlSeconds(ttlMs) }), "set"); if (reply !== "OK") return false; // Plain ZADD is safe here (unlike the bare SET above): the successful // SET XX already proved the token key exists, so re-adding the index // member re-indexes a live token — it cannot resurrect a revoked one. // With XX, a lazy index purge landing in the sub-millisecond window // between the two ops could permanently strand a live token outside // the revocation scans; without it, the next touch re-indexes it. await op(client.zAdd(INDEX_KEY, [{ score: record.expiresAt, value: hash }]), "zadd"); return true; }, async remove(hash) { guardReady("del"); await op(client.del(tokenKey(hash)), "del"); await op(client.zRem(INDEX_KEY, hash), "zrem"); }, async listLive() { guardReady("zrangebyscore"); const now = Date.now(); const members = await op(client.zRangeByScore(INDEX_KEY, String(now), "+inf"), "zrangebyscore"); if (!members || members.length === 0) return []; const raws = await op(client.mGet(members.map(tokenKey)), "mget"); const out = []; for (let i = 0; i < members.length; i++) { const record = sanitizeRecord(safeJsonParse(raws[i])); if (!record || record.expiresAt <= now) continue; out.push({ hash: members[i], record }); } return out; }, async countLive() { guardReady("zcard"); // Lazy purge first: expired token keys vanish via their own TTL, but // their index members linger until removed here. await op(client.zRemRangeByScore(INDEX_KEY, "-inf", String(Date.now())), "zremrangebyscore"); return await op(client.zCard(INDEX_KEY), "zcard"); }, async evictOldest(count) { if (count <= 0) return; guardReady("zrangewithscores"); // Lowest score = soonest original expiry ≈ least-recently-touched. const victims = await op(client.zRangeWithScores(INDEX_KEY, 0, count - 1), "zrangewithscores"); for (const victim of victims || []) { await op(client.del(tokenKey(victim.value)), "del"); await op(client.zRem(INDEX_KEY, victim.value), "zrem"); } }, }; } let fileStoreInstance = null; function activeStore() { let client = null; try { client = storeConfig.redisGetter ? storeConfig.redisGetter() : null; } catch { client = null; } if (client) return createRedisStore(client, storeConfig.redisOpTimeoutMs); if (storeConfig.dataDir) { if (!fileStoreInstance) fileStoreInstance = createFileStore(storeConfig.dataDir); if (!fileStoreInstance.isBroken()) return fileStoreInstance; // broken → memory (degraded mode is logged once by markBroken) } return memoryStore; } // Periodic sweep: memory lazily drops expired entries, files are garbage- // collected, Redis TTLs expire keys on their own (index members are purged // lazily at mint time). const _cleanupTimer = setInterval(() => { (async () => { const store = activeStore(); if (store.kind === "file") await store.sweep(); else if (store.kind === "memory") await store.listLive(); })().catch(() => { /* store unavailable: the next tick retries */ }); }, CLEANUP_INTERVAL_MS); if (_cleanupTimer.unref) _cleanupTimer.unref(); // ─── Service Targets ──────────────────────────────────────────── const SERVICE_TARGETS = { phpmyadmin: { host: "127.0.0.1", port: PHPMYADMIN_INTERNAL_PORT, backendPath: "/phpmyadmin", label: "phpMyAdmin" }, pgadmin: { host: "127.0.0.1", port: 5050, backendPath: "/pgadmin4", label: "pgAdmin4" } }; // ─── Helpers ──────────────────────────────────────────────────── function normalizeIp(ip) { if (!ip || typeof ip !== "string") return ""; let normalized = ip.trim(); if (normalized.startsWith("::ffff:")) normalized = normalized.slice(7); return normalized; } function normalizeServiceSlug(raw) { return String(raw || "").trim().toLowerCase(); } // The proxy token never travels in a URL. It is delivered as a short-lived // HttpOnly cookie scoped to /db-access/, so it cannot leak via browser // history, the Referer header, or shared-link copying. The cookie alone is // inert: every request must ALSO present the admin session that minted the // token (see sessionMatchesToken). function proxyCookieName(service) { return PROXY_COOKIE_PREFIX + service; } function proxyCookiePath() { // No trailing slash on purpose: RFC 6265 path-match then covers both // /db-access/ (redirect targets without a slash) and everything // below it. return DB_ACCESS_PREFIX.replace(/\/+$/, ""); } // maxAge is in milliseconds — express's res.cookie() converts to seconds. function proxyCookieAttributes(secure, ttlMs = TOKEN_TTL_MS) { return { path: proxyCookiePath(), httpOnly: true, sameSite: "lax", secure: !!secure, maxAge: ttlMs }; } function setProxyTokenCookie(res, service, token, secure) { if (!SERVICE_TARGETS[service] || !token || typeof token !== "string") return false; if (typeof res.cookie !== "function") return false; res.cookie(proxyCookieName(service), token, proxyCookieAttributes(secure)); return true; } function clearProxyTokenCookie(res, service, secure) { if (!SERVICE_TARGETS[service]) return false; if (typeof res.clearCookie !== "function") return false; res.clearCookie(proxyCookieName(service), proxyCookieAttributes(secure, 0)); return true; } function clearProxyTokenCookies(res, secure) { for (const service of Object.keys(SERVICE_TARGETS)) { clearProxyTokenCookie(res, service, secure); } } function readProxyCookieToken(rawCookieHeader, service) { if (!rawCookieHeader || typeof rawCookieHeader !== "string") return ""; const wanted = proxyCookieName(service); const pairs = rawCookieHeader.split(";"); for (const pair of pairs) { const eq = pair.indexOf("="); if (eq === -1) continue; if (pair.slice(0, eq).trim() !== wanted) continue; return pair.slice(eq + 1).trim(); } return ""; } function buildBackendCookieHeader(rawCookie) { if (!rawCookie || typeof rawCookie !== "string") return ""; const kept = []; for (const pair of rawCookie.split(";")) { if (!pair.trim()) continue; const eq = pair.indexOf("="); const name = (eq === -1 ? pair : pair.slice(0, eq)).trim(); if (isPanelCookieName(name)) continue; kept.push(pair.trim()); } return kept.join("; "); } // A token is only usable together with the exact browser session that minted // it. There is deliberately NO IP-based fallback: source IPs are shared behind // NAT, spoofable through misconfigured proxies, and stay stable after logout, // so matching them authorizes the wrong people (see audit finding 2.4). // Session ids are stored hashed (sessionIdHash) so the shared store cannot be // mined for replayable panel cookie values; the comparison runs on the hashes. function sessionMatchesToken(sess, req) { if (!sess || !sess.sessionIdHash) return false; if (!req || !req.sessionID) return false; const requestHash = hashSessionId(req.sessionID); if (!requestHash || !timingSafeHexEqual(requestHash, sess.sessionIdHash)) return false; const requestUser = req.session && req.session.user ? String(req.session.user) : ""; return !!requestUser && requestUser === sess.username; } // ─── Token Management ─────────────────────────────────────────── // // All operations are async (Redis backends are promise-based). Error contract: // validateToken — throws StoreUnavailableError (the middleware turns it // into a cookie-preserving 503); returns null on a miss. // generateToken — never throws; null means "fail closed" (route → 500). // touchToken — never throws; false means the token could not be slid. // revoke* — never throw; failures are logged (logout must complete). async function generateToken(service, userIp, username, sessionId = null) { if (!SERVICE_TARGETS[service]) return null; let store = activeStore(); // Hard cap against RAM/Redis bloat. On shared backends the cap is now // GLOBAL across workers (stricter than the old per-worker Map); eviction // is oldest-first and only when the cap would otherwise be exceeded. try { const live = await store.countLive(); if (live >= MAX_SESSIONS) await store.evictOldest(live - MAX_SESSIONS + 1); } catch (err) { // Best-effort hygiene: a cap failure must never block minting. logStoreError("cap check", err); } const token = "v-tmp-" + crypto.randomBytes(TOKEN_BYTES).toString("hex"); const now = Date.now(); const record = { service, userIp: normalizeIp(userIp), // audit trail only — never used for authorization username: String(username == null ? "" : username), sessionIdHash: hashSessionId(sessionId), createdAt: now, expiresAt: now + TOKEN_TTL_MS, }; let stored = false; try { stored = await store.put(hashStoreKey(token), record, TOKEN_TTL_MS); } catch (err) { logStoreError("mint", err); } // A file store that just degraded (unwritable disk) flips to the memory // backend; retry once so this mint still succeeds on the legacy path. if (!stored && store.kind === "file") { store = activeStore(); try { stored = await store.put(hashStoreKey(token), record, TOKEN_TTL_MS); } catch (err) { logStoreError("mint", err); } } // Fail closed: an unpersistable token could be minted but never revoked // cross-worker, so it must not be issued. if (!stored) return null; return { token, expiresAt: record.expiresAt }; } // Store cleanup that must never make noise on the request path (expired // records are swept anyway; this just tidies up earlier). function removeQuietly(hash) { Promise.resolve() .then(() => activeStore().remove(hash)) .catch((err) => logStoreError("cleanup", err)); } async function validateToken(token) { if (!token || typeof token !== "string" || token.length > MAX_TOKEN_LENGTH) return null; const record = await activeStore().get(hashStoreKey(token)); if (!record) return null; if (Date.now() > record.expiresAt) { removeQuietly(hashStoreKey(token)); return null; } return record; } async function touchToken(token, ttlMs = TOKEN_TTL_MS, knownRecord = null) { if (!token || typeof token !== "string" || token.length > MAX_TOKEN_LENGTH) return false; const store = activeStore(); const hash = hashStoreKey(token); let record = null; try { record = knownRecord && typeof knownRecord === "object" ? { ...knownRecord } : await store.get(hash); } catch (err) { logStoreError("touch", err); return false; } if (!record) return false; const now = Date.now(); if (now > record.expiresAt) return false; // IO throttle for file-backed stores: rewriting on every proxied request // (phpMyAdmin loads dozens of assets) costs tmp+rename+fsync each time. // Skip while the persisted window still covers TTL minus one slack period — // the token then still lives at least TTL - TOUCH_REWRITE_SLACK_MS after // the last request, and the persisted expiresAt always stays ahead of the // sweeper. Memory/Redis stores rewrite every time (no IO cost). if (store.ioThrottled && record.expiresAt - now > ttlMs - TOUCH_REWRITE_SLACK_MS) return true; record.expiresAt = now + ttlMs; try { return await store.refresh(hash, record, ttlMs); } catch (err) { logStoreError("touch", err); return false; } } async function revokeToken(token) { if (!token || typeof token !== "string") return; try { await activeStore().remove(hashStoreKey(token)); } catch (err) { logStoreError("revoke", err); } } async function revokeMatching(predicate, label) { try { const store = activeStore(); for (const { hash, record } of await store.listLive()) { if (predicate(record)) await store.remove(hash); } } catch (err) { logStoreError(label, err); } } async function revokeAllForUser(username) { const wanted = String(username == null ? "" : username); if (!wanted) return; await revokeMatching((record) => record.username === wanted, "revokeAllForUser"); } async function revokeAllForUserAndService(username, service) { const wantedUser = String(username == null ? "" : username); const wantedService = normalizeServiceSlug(service); if (!wantedUser || !wantedService) return; await revokeMatching((record) => record.username === wantedUser && record.service === wantedService, "revokeAllForUserAndService"); } async function revokeAllForSessionId(sessionId) { const wantedHash = hashSessionId(sessionId); if (!wantedHash) return; await revokeMatching((record) => !!record.sessionIdHash && record.sessionIdHash === wantedHash, "revokeAllForSessionId"); } // ─── Streaming Proxy Middleware ───────────────────────────────── function rewriteCookiePaths(headers, backendPath, cookiePath) { const raw = headers["set-cookie"]; if (!raw) return; const cookies = Array.isArray(raw) ? raw : [raw]; headers["set-cookie"] = cookies.map(c => c.replace(new RegExp("path=" + backendPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "/?", "gi"), "path=" + cookiePath) ); } // ─── Proxy request header policy (audit finding 2.5) ──────────── // Hop-by-hop request headers (RFC 7230 §6.1) must never be forwarded. const HOP_BY_HOP_REQUEST_HEADERS = [ "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade" ]; // Headers that must never reach the backends, on top of hop-by-hop: // - host/cookie: set explicitly below from vetted values only; // - authorization: panel-origin Basic/bearer credentials would be replayed // by phpMyAdmin's HTTP-auth mode and land in backend logs; // - forwarded/x-forwarded-*/x-real-ip/x-scheme/x-original-*/x-host: many // backends TRUST these as proxy-provided facts, so a client-sent value // must not be laundered through the proxy; // - expect/max-forwards: 100-continue and TRACE/TRACE-like plumbing that // the Node client handles (or refuses) itself. const REQUEST_HEADER_DENYLIST = new Set([ ...HOP_BY_HOP_REQUEST_HEADERS, "host", "cookie", "authorization", "expect", "max-forwards", "forwarded", "x-forwarded-for", "x-forwarded-host", "x-forwarded-port", "x-forwarded-proto", "x-forwarded-server", "x-real-ip", "x-scheme", "x-original-host", "x-original-url", "x-host", "x-rewrite-url" ]); // Standard headers with a legitimate function for the backends: content // negotiation, request bodies (with their exact length — gunicorn does not // accept chunked request bodies), conditional requests/caching, and the // browser metadata PHP/Python apps branch on. Node exposes request header // names lowercased, so the comparison is exact. const REQUEST_HEADER_ALLOWLIST = new Set([ "accept", "accept-charset", "accept-datetime", "accept-encoding", "accept-language", "cache-control", "content-encoding", "content-length", "content-type", "dnt", "if-match", "if-modified-since", "if-none-match", "if-range", "if-unmodified-since", "origin", "pragma", "range", "referer", "sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform", "sec-fetch-dest", "sec-fetch-mode", "sec-fetch-site", "sec-fetch-user", "sec-gpc", "user-agent", "x-requested-with" ]); // Build the outbound header set from an EMPTY object — never a copy of // req.headers (audit finding 2.5): only allowlisted standard headers plus // non-denied "x-*" customs are copied. The custom-header passthrough is // deliberate: the backends' own frontends need them (pgAdmin sends // X-pgA-CSRFToken on every API call) and the CORS model already prevents // any other origin from attaching custom headers to a same-origin request. function buildProxyRequestHeaders(req) { const src = (req && req.headers) || {}; const out = {}; for (const name of Object.keys(src)) { const value = src[name]; if (value === undefined || value === null) continue; if (REQUEST_HEADER_DENYLIST.has(name)) continue; if (REQUEST_HEADER_ALLOWLIST.has(name) || name.startsWith("x-")) { out[name] = value; } } return out; } // ─── Proxy response header policy (audit finding 2.5) ─────────── // Hop-by-hop headers (RFC 7230 §6.1) never cross a proxy. const HOP_BY_HOP_RESPONSE_HEADERS = [ "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade" ]; // Upstream headers that only fingerprint the backend stack (nginx/PHP/ // Python versions). Pure disclosure to the browser — no function. const FINGERPRINT_RESPONSE_HEADERS = [ "server", "x-powered-by", "via", "x-generator", "x-aspnet-version", "x-aspnetmvc-version", "x-runtime" ]; // Obsolete security headers. X-Content-Security-Policy and X-WebKit-CSP // predate the standardized CSP header and are only honored by long-dead // browsers (IE10, Safari ≤ 6). X-XSS-Protection's auditor was itself // exploitable and every current browser ignores or removed it — modern // guidance (helmet, OWASP) is to send neither. const OBSOLETE_SECURITY_RESPONSE_HEADERS = [ "x-content-security-policy", "x-webkit-csp", "x-xss-protection" ]; // Fallback policy when the backend sends no CSP of its own (pgAdmin does // not). Mirrors the policy phpMyAdmin ships for itself — inline scripts and // styles allowed so the bundled UIs and the heartbeat script injected below // keep working — while still banning plugins, base-tag hijacking, // off-origin form posts, and all framing. const FALLBACK_CSP = [ "default-src 'self'", "script-src 'self' 'unsafe-inline' 'unsafe-eval'", "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob:", "font-src 'self' data:", "connect-src 'self'", "media-src 'self'", "worker-src 'self' blob:", "object-src 'none'", "base-uri 'self'", "form-action 'self'", "frame-ancestors 'none'" ].join("; "); // Appended as a SECOND policy next to any upstream CSP. Browsers enforce // the intersection of multiple policies, so this tightens framing without // touching the app-tuned script/style allowances of the upstream one — it // can never loosen or break the backend's own policy. const SUPPLEMENTAL_FRAME_CSP = "frame-ancestors 'none'"; // Remove only what genuinely must not cross the proxy: hop-by-hop framing // headers, stack fingerprinting, and obsolete pseudo-security headers. Every // real security header the upstream produced (CSP, X-Frame-Options, nosniff, // Referrer-Policy, …) is deliberately KEPT — phpMyAdmin ships a CSP with // 'unsafe-inline' scripts and X-Frame-Options: DENY that used to be // discarded here (audit finding 2.5). function sanitizeUpstreamResponseHeaders(headers) { for (const name of HOP_BY_HOP_RESPONSE_HEADERS) delete headers[name]; for (const name of FINGERPRINT_RESPONSE_HEADERS) delete headers[name]; for (const name of OBSOLETE_SECURITY_RESPONSE_HEADERS) delete headers[name]; } // Establish the security baseline the browser can rely on no matter what the // backend sent. The db tools are opened as top-level tabs (GET /db-open/… // renders an interstitial that navigates), never framed by the panel, so // framing can be denied outright; that is the clickjacking half of finding // 2.5. Applied after the panel's own helmet headers have been cleared from // the response (helmet's nonce-based CSP would brick the backends' inline // scripts — see the middleware below). function applyProxyResponseSecurityHeaders(headers) { headers["x-frame-options"] = "DENY"; const upstreamCsp = headers["content-security-policy"]; if (upstreamCsp === undefined) { headers["content-security-policy"] = FALLBACK_CSP; } else { const policies = Array.isArray(upstreamCsp) ? upstreamCsp.slice() : [upstreamCsp]; policies.push(SUPPLEMENTAL_FRAME_CSP); headers["content-security-policy"] = policies; } if (headers["x-content-type-options"] === undefined) headers["x-content-type-options"] = "nosniff"; if (headers["referrer-policy"] === undefined) headers["referrer-policy"] = "no-referrer"; if (headers["x-robots-tag"] === undefined) headers["x-robots-tag"] = "noindex, nofollow"; } function buildHeartbeatScript(service) { const safePath = JSON.stringify(DB_ACCESS_PREFIX + normalizeServiceSlug(service) + HEARTBEAT_PATH); return ``; } function denyNotFound(res) { res.setHeader("Cache-Control", "no-store"); res.status(404).end(); } // The token store could not answer (Redis down, data dir unreadable). Fail // closed, but do NOT clear the token cookie: a store blip must not log the // admin out of the proxy (a cleared cookie turns a transient outage into a // forced re-mint), and it must stay distinguishable from a stale-token 404. function denyUnavailable(res) { res.setHeader("Cache-Control", "no-store"); res.setHeader("Retry-After", "2"); res.status(503).end(); } function createProxyMiddleware(options = {}) { // The panel registers its live cookie names (the stealth gate cookie is // operator-configurable) so cookie filtering cannot miss one. registerPanelCookieNames(options.panelCookieNames); const cookieSecureForRequest = typeof options.cookieSecure === "function" ? options.cookieSecure : (req) => Boolean(req && ((req.connection && req.connection.encrypted) || req.secure === true)); async function handleHeartbeat(req, res, serviceSlug) { const secure = !!cookieSecureForRequest(req); const token = readProxyCookieToken(req.headers && req.headers.cookie, serviceSlug); const sess = await validateToken(token); // throws StoreUnavailableError → outer catch if (!sess || sess.service !== serviceSlug || !sessionMatchesToken(sess, req)) { if (token) clearProxyTokenCookie(res, serviceSlug, secure); if (req.resume) req.resume(); denyNotFound(res); return; } await touchToken(token, TOKEN_TTL_MS, sess); // Slide the browser cookie forward together with the server-side TTL so // an actively used tab never loses its cookie mid-session. setProxyTokenCookie(res, serviceSlug, token, secure); if (req.resume) req.resume(); res.setHeader("Cache-Control", "no-store"); res.status(204).end(); } return async function dbProxyMiddleware(req, res, next) { if (!req.url || !req.url.startsWith(DB_ACCESS_PREFIX)) return next(); try { // Parse: /db-access//... // The first segment is the service slug (public information, not a // credential). The credential lives solely in the HttpOnly cookie. const withoutPrefix = req.url.slice(DB_ACCESS_PREFIX.length); const slashIdx = withoutPrefix.indexOf("/"); const serviceSlug = normalizeServiceSlug(slashIdx === -1 ? withoutPrefix : withoutPrefix.slice(0, slashIdx)); const remainingPath = slashIdx === -1 ? "/" : withoutPrefix.slice(slashIdx); const routePath = remainingPath.split("?")[0]; if (routePath === HEARTBEAT_PATH) { if (req.method !== "POST") { denyNotFound(res); return; } await handleHeartbeat(req, res, serviceSlug); return; } const target = SERVICE_TARGETS[serviceSlug]; if (!target) { denyNotFound(res); return; } const secure = !!cookieSecureForRequest(req); const token = readProxyCookieToken(req.headers && req.headers.cookie, serviceSlug); // validateToken consults the cluster-safe store, so a token minted by // another worker validates here. A store outage lands in the catch // below instead of looking like a missing token. const sess = await validateToken(token); if (!sess || sess.service !== serviceSlug || !sessionMatchesToken(sess, req)) { // Drop the stale/forged cookie so a dead tab cannot keep retrying with // it and the browser stops offering it on every /db-access request. if (token) clearProxyTokenCookie(res, serviceSlug, secure); denyNotFound(res); return; } // Sliding TTL while actively used so refreshes in an active session keep working. await touchToken(token, TOKEN_TTL_MS, sess); const serviceBase = DB_ACCESS_PREFIX + serviceSlug; // e.g. /db-access/phpmyadmin const servicePath = serviceBase + "/"; const proxyPath = target.backendPath + (remainingPath === "/" ? "/" : remainingPath); // Forward only what the backends legitimately need (audit finding 2.5). // proxyHeaders is built from an EMPTY object — never a copy of // req.headers — so panel credentials (Authorization, panel cookies) and // spoofable proxy-trust headers (X-Forwarded-For & friends) can never be // echoed into the backends' logs, forms, or cookie jars. const proxyHeaders = buildProxyRequestHeaders(req); // Cookies are vetted separately: only backend-issued cookies survive // (every adpanel.* / registered panel cookie is stripped). const backendCookie = buildBackendCookieHeader(req.headers && req.headers["cookie"]); if (backendCookie) { proxyHeaders["cookie"] = backendCookie; } // Host: pinned for phpMyAdmin (its nginx vhost matches on it); for // pgAdmin the original Host is kept so any absolute redirect it builds // still names the address the browser actually reached. if (sess.service === "phpmyadmin") { proxyHeaders["host"] = "127.0.0.1:" + PHPMYADMIN_INTERNAL_PORT; } else if (req.headers && req.headers["host"]) { proxyHeaders["host"] = req.headers["host"]; } // Request uncompressed content for text so we can rewrite paths const likelyText = req.method === "GET" && ( remainingPath === "/" || remainingPath.endsWith(".php") || remainingPath.endsWith(".html") || !remainingPath.includes(".") ); if (likelyText) { proxyHeaders["accept-encoding"] = "identity"; } const proxyOpts = { hostname: target.host, port: target.port, path: proxyPath, method: req.method, headers: proxyHeaders, timeout: 300000 }; // adpanel:upstream-error-listeners — ONE idempotent failure finisher for // the whole proxy exchange, shared by the upstream response's // error/aborted handlers (the services/node-http.js posture): a backend // reset mid-stream emits 'error' on the proxyRes IncomingMessage where // no outer try/catch can catch it — an unhandled 'error' event here is // a worker crash. Exactly one settle wins: before headers the failure // degrades to a 502; after headers the truncated exchange can never be // completed, so the client socket is destroyed instead of re-writing // headers or ending a content-length-violating stream. The backend half // is torn down too (unpipe + request destroy) so a dead upstream cannot // leak its socket. let proxyFailureSettled = false; const finishProxyFailure = (upstreamRes) => { if (proxyFailureSettled) return; proxyFailureSettled = true; try { if (upstreamRes && typeof upstreamRes.unpipe === "function") upstreamRes.unpipe(res); } catch { } try { proxyReq.destroy(); } catch { } try { if (upstreamRes && typeof upstreamRes.destroy === "function") upstreamRes.destroy(); } catch { } if (res.headersSent) { try { res.destroy(); } catch { } } else if (!res.writableEnded) { try { res.status(502).end(); } catch { } } }; // adpanel:db-proxy-client-close — when the CLIENT disappears before the // exchange completed (dial in flight or mid-stream), the backend would // otherwise keep streaming into a dead socket until the response ended // on its own: the 300s `timeout` above is an INACTIVITY timer and never // fires on an active stream. The close routes through the SAME // idempotent finisher — one teardown path, the same single-settle // contract as the upstream error/aborted pair below. 'close' also fires // after NORMAL completion (both branches call res.end() before 'close' // can fire on success — proxyRes 'end' → pipe's end:true / the text // branch's res.end(text) → res 'finish' → res 'close'), so the guard is // the exchange's completion state: res.writableEnded is true by then and // the success path is a provable no-op here. The listener lives on THIS // request's res object (the middleware is per-request; attached in this // synchronous block, before the dial, never on the app), so nothing // leaks across requests; the capability guard keeps event-less mock // responses (scripts/verify-db-proxy-session-auth.js) on the legacy // behavior. let proxyResRef = null; if (typeof res.on === "function") { res.on("close", () => { if (res.writableEnded) return; finishProxyFailure(proxyResRef); }); } const proxyReq = httpMod.request(proxyOpts, (proxyRes) => { // The upstream response of THIS exchange, for the client-close handler // above: null until the response callback runs — a close before that // has no upstream response to unpipe, which the finisher guards. proxyResRef = proxyRes; // Registered BEFORE either response branch (the header rewrites below // are synchronous, so nothing can fire between) — every response path // inherits the error/aborted posture from this one pair. proxyRes.on("aborted", () => finishProxyFailure(proxyRes)); proxyRes.on("error", () => finishProxyFailure(proxyRes)); // Rewrite Location headers const location = proxyRes.headers["location"]; if (location) { let rewritten = location; if (sess.service === "phpmyadmin" && location.includes("/phpmyadmin")) { rewritten = location.replace(/\/phpmyadmin/g, serviceBase); } else if (sess.service === "pgadmin") { if (location.includes("/pgadmin4")) { rewritten = location.replace(/\/pgadmin4/g, serviceBase); } else if (location.includes("/pgadmin")) { rewritten = location.replace(/\/pgadmin/g, serviceBase); } } proxyRes.headers["location"] = rewritten; } // Rewrite Set-Cookie paths so cookies work on the proxy URL rewriteCookiePaths(proxyRes.headers, target.backendPath, serviceBase); // Sanitize upstream headers: only hop-by-hop, fingerprinting, and // obsolete headers are removed; the backend's own CSP / X-Frame-Options // / nosniff stay (audit finding 2.5 — they used to be discarded). sanitizeUpstreamResponseHeaders(proxyRes.headers); // Clear headers previously set by panel middleware (helmet, etc.): // helmet's nonce-based CSP would block the backends' inline scripts, // so panel headers must not leak into the proxied response. The proxy // then re-establishes its own security baseline right below. const prevHeaders = res.getHeaderNames ? res.getHeaderNames() : []; for (const h of prevHeaders) res.removeHeader(h); // Baseline the browser can rely on regardless of upstream: framing // denied (X-Frame-Options + supplementary frame-ancestors CSP policy), // nosniff, no-referrer, noindex. applyProxyResponseSecurityHeaders(proxyRes.headers); const respContentType = (proxyRes.headers["content-type"] || "").toLowerCase(); const isHtmlContent = respContentType.includes("text/html"); const isTextContent = respContentType.includes("text/html") || respContentType.includes("javascript") || respContentType.includes("text/css"); if (isTextContent) { delete proxyRes.headers["content-length"]; const encoding = proxyRes.headers["content-encoding"]; delete proxyRes.headers["content-encoding"]; res.writeHead(proxyRes.statusCode, proxyRes.headers); const chunks = []; let totalSize = 0; const MAX_REWRITE_SIZE = 5 * 1024 * 1024; proxyRes.on("data", (chunk) => { if (proxyFailureSettled) return; totalSize += chunk.length; if (totalSize > MAX_REWRITE_SIZE) { chunks.length = 0; finishProxyFailure(proxyRes); return; } chunks.push(chunk); }); proxyRes.on("end", () => { // A settled failure owns the response from here on: a destroyed // upstream must never deliver its buffered (partial) body as a // clean end on top of the finisher's teardown. if (proxyFailureSettled) return; if (req.method === "HEAD") { res.end(); return; } let body = Buffer.concat(chunks); // adpanel:db-proxy-rewrite-budget - the wire cap alone cannot // bound compressed expansion; invalid data is never HTML. try { if (encoding === "gzip") { body = zlib.gunzipSync(body, { maxOutputLength: MAX_REWRITE_SIZE }); } else if (encoding === "deflate") { body = zlib.inflateSync(body, { maxOutputLength: MAX_REWRITE_SIZE }); } else if (encoding && encoding !== "identity") { throw new Error("Unsupported compressed proxy response"); } } catch { finishProxyFailure(proxyRes); return; } let text = body.toString("utf8"); if (sess.service === "pgadmin") { text = text.replace(/\/pgadmin4\//g, servicePath); text = text.replace(/"\/pgadmin4"/g, '"' + serviceBase + '"'); text = text.replace(/'\/pgadmin4'/g, "'" + serviceBase + "'"); } else if (sess.service === "phpmyadmin") { text = text.replace(/\/phpmyadmin\//g, servicePath); text = text.replace(/"\/phpmyadmin"/g, '"' + serviceBase + '"'); text = text.replace(/'\/phpmyadmin'/g, "'" + serviceBase + "'"); } if (isHtmlContent) { const hb = buildHeartbeatScript(serviceSlug); if (/<\/body>/i.test(text)) { text = text.replace(/<\/body>/i, hb + ""); } else { text += hb; } } res.end(text); }); // No per-branch error listener here: the upstream response's // error/aborted pair above settles every failure exactly once // through the shared finisher (a mid-buffering error destroys the // truncated exchange instead of ending it "cleanly" half-written). } else { // Stream directly — no buffering res.writeHead(proxyRes.statusCode, proxyRes.headers); proxyRes.pipe(res, { end: true }); } }); proxyReq.on("error", (err) => { console.error("[db-proxy] Proxy error:", err.message); if (!res.headersSent) { // Pre-headers failure: this 502 wins the settle — any later // timeout/aborted stays a no-op. After headers the settle is left // to the proxyRes error/aborted finisher, which owns the // after-headers client teardown (this handler must not suppress // it, nor double-respond with it). proxyFailureSettled = true; res.status(502).end(); } }); proxyReq.on("timeout", () => { // Settle BEFORE destroying: the teardown makes the in-flight response // emit aborted/error, and this handler's 504 must win that race — the // shared finisher stays a no-op afterwards (no double response). // After headers the stalled stream can never complete, so the client // socket is destroyed instead of hanging forever. if (proxyFailureSettled) { try { proxyReq.destroy(); } catch { } return; } proxyFailureSettled = true; proxyReq.destroy(); if (!res.headersSent) res.status(504).end(); else { try { res.destroy(); } catch { } } }); req.pipe(proxyReq, { end: true }); } catch (err) { // All store work happens before any proxying, so the response headers // can never have been sent by the failure being handled here. if (err instanceof StoreUnavailableError) { logger.error(`[db-proxy] token store unavailable, denying ${req.method || ""} ${req.url || ""}: ${err.message}`); if (!res.headersSent) denyUnavailable(res); return; } logger.error(`[db-proxy] middleware error on ${req.method || ""} ${req.url || ""}: ${err && err.message ? err.message : err}`); if (!res.headersSent) { res.setHeader("Cache-Control", "no-store"); res.status(500).end(); } else if (typeof res.end === "function") { res.end(); } } }; } // ─── Stats ────────────────────────────────────────────────────── async function getSessionCount() { try { return await activeStore().countLive(); } catch (err) { logStoreError("count", err); return 0; } } module.exports = { generateToken, validateToken, touchToken, revokeToken, revokeAllForUser, revokeAllForUserAndService, revokeAllForSessionId, createProxyMiddleware, configureTokenStore, StoreUnavailableError, getSessionCount, normalizeIp, setProxyTokenCookie, clearProxyTokenCookie, clearProxyTokenCookies, proxyCookieName, proxyCookiePath, proxyCookieAttributes, readProxyCookieToken, buildBackendCookieHeader, registerPanelCookieNames, isPanelCookieName, buildProxyRequestHeaders, sanitizeUpstreamResponseHeaders, applyProxyResponseSecurityHeaders, sessionMatchesToken, SERVICE_TARGETS, TOKEN_TTL_MS, PHPMYADMIN_INTERNAL_PORT };