"use strict"; const fs = require("fs"); const mysql = require("mysql2/promise"); const path = require("path"); const { URL } = require("url"); const { ensureServerAgentChatOwnerSchema, ensureServerAgentChatActionSchema, backfillServerAgentChatOwners } = require("./services/server-agent-chat-ownership"); const { ensureAgentAttachmentSchema } = require("./AgentWorker/attachments"); const MYSQL_URL = String(process.env.MYSQL_URL || "").trim(); const MYSQL_HOST = String(process.env.MYSQL_HOST || "127.0.0.1").trim(); const MYSQL_PORT = parseInt(process.env.MYSQL_PORT || "3306", 10); const MYSQL_USER = String(process.env.MYSQL_USER || "root").trim(); const MYSQL_PASSWORD = String(process.env.MYSQL_PASSWORD || "").trim(); const MYSQL_DATABASE = String(process.env.MYSQL_DATABASE || process.env.MYSQL_DB || "").trim(); const MYSQL_POOL_SIZE = parseInt(process.env.MYSQL_POOL_SIZE || "10", 10); const WEB_POOL_LIMIT = Math.max(1, parseInt(process.env.ADPANEL_WEB_DB_CONNECTION_LIMIT || "96", 10) || 96); const WEB_POOL_SIZE = Math.max(1, Math.min(WEB_POOL_LIMIT, Number.isSafeInteger(MYSQL_POOL_SIZE) ? MYSQL_POOL_SIZE : 10)); function configFromUrl(raw) { if (!raw) return null; try { const url = new URL(raw); if (url.protocol !== "mysql:") return null; return { host: url.hostname, port: url.port ? Number(url.port) : 3306, user: decodeURIComponent(url.username || ""), password: decodeURIComponent(url.password || ""), database: url.pathname ? url.pathname.replace(/^\//, "") : "", }; } catch { return null; } } const urlConfig = configFromUrl(MYSQL_URL); const dbName = (urlConfig && urlConfig.database) || MYSQL_DATABASE; if (!dbName) { console.warn("[db] MYSQL_DATABASE is not set; database selection may fail."); } // adpanel:session-tz-assumption — the pool is deliberately left on mysql2's // default timezone:'local' interpretation: TIMESTAMPs are session-tz wall // clocks parsed as Node-local. The planner CAS (index.js, // adpanel:planner-edit-integrity) is immune to tz skew because it compares // DATE_FORMAT strings inside one session timezone, but client-facing // relative-time rendering (bot.js formatRelativeTime) assumes the Node // process TZ equals the MySQL session TZ — a deployment where they differ // skews every "Xm ago" badge by exactly that offset. Align the two sides at // the deployment level (same TZ for both); do not "fix" rendering by setting // only the pool's timezone option without moving the session TZ with it. function createPanelDatabasePool({ connectionLimit = WEB_POOL_SIZE, queueLimit = 5000 } = {}) { return mysql.createPool({ host: (urlConfig && urlConfig.host) || MYSQL_HOST, port: (urlConfig && urlConfig.port) || MYSQL_PORT || 3306, user: (urlConfig && urlConfig.user) || MYSQL_USER, password: (urlConfig && urlConfig.password) || MYSQL_PASSWORD, ...(dbName ? { database: dbName } : {}), waitForConnections: true, connectionLimit, queueLimit, connectTimeout: 10000, decimalNumbers: true, }); } const pool = createPanelDatabasePool(); async function query(sql, params = []) { const [rows] = await pool.execute(sql, params); return rows; } function parseSchemaStatements(sql) { return String(sql) .split(";") .map((stmt) => stmt.trim()) .filter(Boolean); } // nodes.name is resolved case-insensitively all over the panel (LOWER(name) // lookups in nodes.js), so duplicate node names must be impossible at the DB // level too: the app-level checks are check-then-insert sequences that race, // and a UNIQUE key is the only real backstop. Fresh installs get the index // from mysql-schema.sql (uniq_nodes_name); live databases that predate it get // it here. Safe to run on every boot: it short-circuits once the index exists. async function ensureNodesNameUniqueIndex() { const TABLE = "nodes"; const INDEX = "uniq_nodes_name"; // Never run when the table does not exist yet (empty/new database): the // schema replay above already creates it with the unique index included. const [tables] = await pool.query( "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?", [TABLE] ); if (!tables || tables.length === 0) return; // Idempotency guard: skip everything when the index is already in place. const [idxRows] = await pool.query( "SELECT INDEX_NAME FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND INDEX_NAME = ? LIMIT 1", [TABLE, INDEX] ); if (idxRows && idxRows.length > 0) return; // The unique index cannot be created while duplicates exist, and the // duplicate-name vulnerability was exploitable, so live data may already // contain them. Detect collisions case-insensitively (matching the app's // LOWER(name) resolution), then rename deterministically. const [dupGroups] = await pool.query( "SELECT LOWER(name) AS k, COUNT(*) AS c FROM nodes GROUP BY LOWER(name) HAVING COUNT(*) > 1" ); if (dupGroups && dupGroups.length > 0) { const [allRows] = await pool.query("SELECT id, name FROM nodes ORDER BY id"); // Every name in the table (case-folded) is off-limits for a rename, not // just the ones inside duplicate groups. const taken = new Set( (allRows || []).map((r) => String(r.name || "").toLowerCase()) ); for (const group of dupGroups) { const key = String(group.k || "").toLowerCase(); const members = (allRows || []).filter( (r) => String(r.name || "").toLowerCase() === key ); // Keep the lowest-id row's name unchanged; append -2, -3, ... to the rest. for (let i = 1; i < members.length; i++) { const row = members[i]; const oldName = String(row.name || ""); let candidate = null; for (let n = 2; n <= 100000; n++) { const suffix = "-" + n; // Respect VARCHAR(120) (characters): truncate the base before // suffixing. Rename output stays within the app's name charset // (sanitizeName allows [A-Za-z0-9_. -]; the suffix is "-"). const base = oldName.slice(0, 120 - suffix.length); const proposed = base + suffix; if (!taken.has(proposed.toLowerCase())) { candidate = proposed; break; } } if (!candidate) { console.warn( `[db] Could not derive a free name for duplicate node name "${oldName}" (id=${row.id}); leaving it unchanged.` ); continue; } await pool.query("UPDATE nodes SET name = ? WHERE id = ?", [ candidate, row.id, ]); // Keep the old folded name in `taken` even though this row no longer // holds it: the kept member of the group may hold the same folded name // in a different case, and later candidates must never collide with it. taken.add(candidate.toLowerCase()); console.warn( `[db] Renamed duplicate node name "${oldName}" (id=${row.id}) -> "${candidate}" so the uniq_nodes_name unique index can be created.` ); } } } try { await pool.query(`ALTER TABLE ${TABLE} ADD UNIQUE KEY ${INDEX} (name)`); console.log( "[db] Added unique index uniq_nodes_name on nodes(name); duplicate node names are now rejected by the database." ); } catch (err) { if (err && err.code === "ER_DUP_ENTRY") { // A concurrent writer re-created a duplicate between the rename pass // and the ALTER (or unexpected residue slipped through). Never crash // the panel for a migration, but make it impossible to miss. console.error( "[db] FAILED to add unique index uniq_nodes_name on nodes(name): duplicate node names are still present. " + "Find them with: SELECT id, name FROM nodes ORDER BY id; " + "resolve the duplicates and restart the panel. Until then the database will keep accepting duplicate node names." ); } else if (err && err.code === "ER_DUP_KEYNAME") { // Index already exists (a concurrent boot won the race) — fine. } else { console.warn( "[db] nodes.name unique index migration note:", (err && err.message) || err ); } } } // users.session_epoch is the per-account session discriminator: CLI credential // mutations (scripts/create-user.js) re-seed it and the running panel revokes // any browser session whose stored epoch no longer matches, so a credential // can never outlive the account it was issued to. Fresh installs get the // column from mysql-schema.sql; live databases that predate it get it here. // Best-effort like ensureNodesNameUniqueIndex: a failed migration logs loudly // but never blocks startup. async function ensureUsersSessionEpochColumn() { const TABLE = "users"; const COLUMN = "session_epoch"; const DEFINITION = "BIGINT UNSIGNED NOT NULL DEFAULT 0"; // Never run when the table does not exist yet (empty/new database): the // schema replay above already creates it with the column included. const [tables] = await pool.query( "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?", [TABLE] ); if (!tables || tables.length === 0) return; // Idempotency guard: skip everything once the column is in place. const [cols] = await pool.query( "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?", [TABLE, COLUMN] ); if (cols && cols.length > 0) return; // `ADD COLUMN IF NOT EXISTS` is MariaDB-only; MySQL rejects the syntax, so // the fallback re-checks via SHOW COLUMNS before the plain ALTER (mirrors // ensureUsersColumn in scripts/create-user.js). try { await pool.query(`ALTER TABLE ${TABLE} ADD COLUMN IF NOT EXISTS ${COLUMN} ${DEFINITION}`); console.log(`[db] Added ${TABLE}.${COLUMN}; CLI credential mutations now bump the session epoch.`); } catch (err) { if (err && String(err.message || "").includes("Duplicate column")) return; try { const [live] = await pool.query(`SHOW COLUMNS FROM ${TABLE} LIKE '${COLUMN}'`); if (!live || live.length === 0) { await pool.query(`ALTER TABLE ${TABLE} ADD COLUMN ${COLUMN} ${DEFINITION}`); console.log(`[db] Added ${TABLE}.${COLUMN}; CLI credential mutations now bump the session epoch.`); } } catch (fallbackErr) { console.warn( "[db] users.session_epoch migration note:", (fallbackErr && fallbackErr.message) || fallbackErr ); } } } // destructive_action_grants.proof_strength records how strong the step-up // proof that minted a grace grant was ('password+totp' / 'password' / 'totp', // NULL = unknown); grant consumption refuses to satisfy a STRONGER // verification requirement with a weaker proof, and NULL/unknown grants only // ever satisfy weaker gates. Fresh installs get the column from // mysql-schema.sql; live databases that predate it get it here, following the // ensureUsersSessionEpochColumn boot-ALTER pattern. Best-effort: while the // column is missing, the grant INSERT/SELECT degrade to the strength-less // shapes and the panel stays conservative (a pre-migration grant never // satisfies a password-first requirement) — a failed migration logs loudly // but never blocks startup. async function ensureDestructiveActionGrantsProofStrengthColumn() { const TABLE = "destructive_action_grants"; const COLUMN = "proof_strength"; const DEFINITION = "VARCHAR(16) NULL"; // Never run when the table does not exist yet (empty/new database): the // schema replay above already creates it with the column included. const [tables] = await pool.query( "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?", [TABLE] ); if (!tables || tables.length === 0) return; // Idempotency guard: skip everything once the column is in place. const [cols] = await pool.query( "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?", [TABLE, COLUMN] ); if (cols && cols.length > 0) return; // `ADD COLUMN IF NOT EXISTS` is MariaDB-only; MySQL rejects the syntax, so // the fallback re-checks via SHOW COLUMNS before the plain ALTER (mirrors // ensureUsersSessionEpochColumn). try { await pool.query(`ALTER TABLE ${TABLE} ADD COLUMN IF NOT EXISTS ${COLUMN} ${DEFINITION}`); console.log(`[db] Added ${TABLE}.${COLUMN}; grace grants now record their minting proof strength.`); } catch (err) { if (err && String(err.message || "").includes("Duplicate column")) return; try { const [live] = await pool.query(`SHOW COLUMNS FROM ${TABLE} LIKE '${COLUMN}'`); if (!live || live.length === 0) { await pool.query(`ALTER TABLE ${TABLE} ADD COLUMN ${COLUMN} ${DEFINITION}`); console.log(`[db] Added ${TABLE}.${COLUMN}; grace grants now record their minting proof strength.`); } } catch (fallbackErr) { console.warn( "[db] destructive_action_grants.proof_strength migration note:", (fallbackErr && fallbackErr.message) || fallbackErr ); } } } async function ensureSchema() { const schemaPath = path.join(__dirname, "mysql-schema.sql"); if (!fs.existsSync(schemaPath)) { throw new Error("mysql-schema.sql not found"); } const sql = fs.readFileSync(schemaPath, "utf8"); const statements = parseSchemaStatements(sql); if (!statements.length) { throw new Error("mysql-schema.sql is empty"); } const conn = await pool.getConnection(); try { for (const stmt of statements) { await conn.query(stmt); } } finally { conn.release(); } await ensureServerAgentChatOwnerSchema({ query }); await backfillServerAgentChatOwners({ query }); await ensureAgentAttachmentSchema({ query }); await ensureServerAgentChatActionSchema({ query }); try { await query("ALTER TABLE server_planner_items ADD COLUMN prompt_author_id BIGINT UNSIGNED NULL"); } catch (err) { if (err.code !== "ER_DUP_FIELDNAME") throw err; } try { await query("CREATE INDEX idx_server_planner_prompt_author ON server_planner_items (prompt_author_id)"); } catch (err) { if (err.code !== "ER_DUP_KEYNAME") throw err; } // After the schema replay: live databases that predate uniq_nodes_name get // the index (and a duplicate-name cleanup) here. Best-effort, mirroring the // panel's migration style: a failed migration logs loudly but never blocks // startup. try { await ensureNodesNameUniqueIndex(); } catch (err) { console.warn( "[db] nodes.name unique index migration skipped:", (err && err.message) || err ); } // users.session_epoch: live databases that predate the column get it here, // same best-effort policy. try { await ensureUsersSessionEpochColumn(); } catch (err) { console.warn( "[db] users.session_epoch migration skipped:", (err && err.message) || err ); } // destructive_action_grants.proof_strength: live databases that predate the // column get it here (adpanel:stepup-proof-strength), same best-effort // policy. try { await ensureDestructiveActionGrantsProofStrengthColumn(); } catch (err) { console.warn( "[db] destructive_action_grants.proof_strength migration skipped:", (err && err.message) || err ); } } module.exports = { pool, query, createPanelDatabasePool, ensureSchema, async close() { await pool.end(); }, };