Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+146
View File
@@ -0,0 +1,146 @@
"use strict";
const { newSessionEpochDifferentFrom } = require("../utils/session-epoch");
function accountActionScope(user) {
const id = Number(user?.id);
if (!Number.isSafeInteger(id) || id <= 0) throw new TypeError("Invalid account identity");
return `user-id:${id}`;
}
// adpanel:account-action-identity - retries and grants bind the selected row,
// not an email that can be reused by a different account.
function requireAccountActionTarget(req, res, target) {
const expected = req?.body?.expectedTargetId;
if (Number.isSafeInteger(expected) && expected > 0 && expected === Number(target?.id)) return true;
res.status(409).json({ error: "account state changed; reload accounts and try again", code: "account-target-changed" });
return false;
}
async function lockAccountActor(connection, actor) {
// adpanel:account-actor-commit - the locked actor must still hold the
// credential generation that authorized this write.
const [admins] = await connection.execute("SELECT id, admin, suspended, session_epoch FROM users WHERE admin = 1 ORDER BY id FOR UPDATE");
const ok = Number.isSafeInteger(Number(actor?.id)) && Number(actor.id) > 0 &&
Number.isSafeInteger(actor?.session_epoch) && actor.session_epoch >= 0 &&
admins.some((row) => Number(row.id) === Number(actor.id) && Number(row.admin) === 1 && Number(row.suspended) === 0 && Number(row.session_epoch) === actor.session_epoch);
return { ok, admins };
}
async function withAccountActionTransaction(db, actor, target, operation, { allowAdminTarget = false } = {}) {
const connection = await db.pool.getConnection();
try {
await connection.beginTransaction();
const actorState = await lockAccountActor(connection, actor);
if (!actorState.ok) {
await connection.rollback();
return { ok: false, reason: "actor" };
}
let live = null;
if (target) {
const [targets] = await connection.execute("SELECT id, email, admin, session_epoch FROM users WHERE id = ? FOR UPDATE", [target.id]);
live = targets[0];
if (!live || Number(live.id) === Number(actor.id) || (!allowAdminTarget && Number(live.admin) !== 0) ||
String(live.email).trim().toLowerCase() !== String(target.email).trim().toLowerCase()) {
await connection.rollback();
return { ok: false, reason: "target" };
}
}
const result = await operation(connection, live);
if (!result.ok) {
await connection.rollback();
return result;
}
await connection.commit();
return result;
} catch (error) {
try { await connection.rollback(); } catch (_) { }
throw error;
} finally {
connection.release();
}
}
// adpanel:account-acl-atomic - only this server's locked ACL and this user's
// access row change; no whole-index snapshot can erase unrelated state.
async function setAccountPermissions(db, actor, target, serverName, permissions, serverId) {
return withAccountActionTransaction(db, actor, target, async (connection, live) => {
const [servers] = await connection.execute("SELECT id, name, status, acl FROM servers WHERE name = ? FOR UPDATE", [serverName]);
const server = servers[0];
if (!server || !Number.isSafeInteger(serverId) || Number(server.id) !== serverId || String(server.status || "").toLowerCase() === "deleting") return { ok: false, reason: "server" };
const acl = server.acl == null ? {} : typeof server.acl === "string" ? JSON.parse(server.acl) : server.acl;
if (!acl || typeof acl !== "object" || Array.isArray(acl)) throw new Error("Invalid stored server ACL");
const email = String(live.email).trim().toLowerCase();
const previousPerms = acl[email] || null;
acl[email] = { ...permissions };
await connection.execute("UPDATE servers SET acl = ? WHERE name = ?", [JSON.stringify(acl), server.name]);
await connection.execute("INSERT IGNORE INTO user_access (user_id, server_name) VALUES (?, ?)", [live.id, server.name]);
return { ok: true, previousPerms };
});
}
async function changeAccountAccess(db, actor, target, serverName, add, serverId) {
return withAccountActionTransaction(db, actor, target, async (connection, live) => {
if (add && serverName !== "all") {
const [servers] = await connection.execute("SELECT id, name, status FROM servers WHERE name = ? FOR UPDATE", [serverName]);
const server = servers[0];
if (!server || !Number.isSafeInteger(serverId) || Number(server.id) !== serverId || String(server.status || "").toLowerCase() === "deleting") return { ok: false, reason: "server" };
}
if (!add && serverName !== "all") {
const [access] = await connection.execute("SELECT server_name FROM user_access WHERE user_id = ?", [live.id]);
if (access.some((row) => String(row.server_name).toLowerCase() === "all")) return { ok: false, reason: "wildcard" };
}
if (add) {
await connection.execute("INSERT IGNORE INTO user_access (user_id, server_name) VALUES (?, ?)", [live.id, serverName]);
} else {
await connection.execute("DELETE FROM user_access WHERE user_id = ? AND server_name = ?", [live.id, serverName]);
}
return { ok: true };
});
}
async function setAccountAgentAccess(db, actor, target, enabled) {
return withAccountActionTransaction(db, actor, target, async (connection, live) => {
await connection.execute("UPDATE users SET agent_access = ? WHERE id = ? AND admin = 0", [enabled ? 1 : 0, live.id]);
return { ok: true };
});
}
async function setAccountSuspension(db, actor, target, suspended, suspendedAt, suspendedBy) {
return withAccountActionTransaction(db, actor, target, async (connection, live) => {
// adpanel:account-suspension-epoch - missed sessions must remain revoked
// after unsuspension; retries also invalidate sessions created in flight.
const newEpoch = suspended ? newSessionEpochDifferentFrom(Number(live.session_epoch || 0)) : live.session_epoch;
await connection.execute("UPDATE users SET suspended = ?, suspended_at = ?, suspended_by = ?, session_epoch = ? WHERE id = ? AND admin = 0", [suspended ? 1 : 0, suspendedAt, suspendedBy, newEpoch, live.id]);
return { ok: true };
});
}
async function cleanupOrphanAccountAcls(db) {
const connection = await db.pool.getConnection();
try {
await connection.beginTransaction();
await connection.execute("SELECT id, admin, suspended FROM users WHERE admin = 1 ORDER BY id FOR UPDATE");
const [users] = await connection.execute("SELECT id, email FROM users ORDER BY id FOR UPDATE");
const emails = new Set(users.map((user) => String(user.email).trim().toLowerCase()));
const [servers] = await connection.execute("SELECT name, acl FROM servers ORDER BY id FOR UPDATE");
let changed = 0;
for (const server of servers) {
const acl = server.acl == null ? null : typeof server.acl === "string" ? JSON.parse(server.acl) : server.acl;
if (!acl || typeof acl !== "object" || Array.isArray(acl)) continue;
const retained = Object.fromEntries(Object.entries(acl).filter(([email]) => emails.has(email.trim().toLowerCase())));
if (Object.keys(retained).length === Object.keys(acl).length) continue;
await connection.execute("UPDATE servers SET acl = ? WHERE name = ?", [JSON.stringify(retained), server.name]);
changed += 1;
}
await connection.commit();
return changed;
} catch (error) {
try { await connection.rollback(); } catch (_) { }
throw error;
} finally {
connection.release();
}
}
module.exports = { accountActionScope, requireAccountActionTarget, lockAccountActor, withAccountActionTransaction, setAccountPermissions, changeAccountAccess, setAccountAgentAccess, setAccountSuspension, cleanupOrphanAccountAcls };
+101
View File
@@ -0,0 +1,101 @@
"use strict";
const { newSessionEpoch, newSessionEpochDifferentFrom } = require("../utils/session-epoch");
const { withAccountActionTransaction } = require("./account-actions");
// adpanel:credential-generation-cas - every self-service credential commit
// pins the generation its proof authorized, not only the field it changes.
// Credential and generation move atomically; missing or stale proofs write
// nothing. MFA proofs use the generation captured when setup was authorized.
const CREDENTIAL_COMMIT_SQL = Object.freeze({
password: "UPDATE users SET password = ?, session_epoch = ? WHERE id = ? AND password = ? AND session_epoch = ?",
email: "UPDATE users SET email = ?, session_epoch = ? WHERE id = ? AND password = ? AND LOWER(email) = LOWER(?) AND session_epoch = ?",
// adpanel:totp-confirm-atomic-burn - a new seed must never be visible without its consumed step.
twoFactor: "UPDATE users SET secret = ?, recovery_codes = ?, session_epoch = ?, totp_last_counter = GREATEST(COALESCE(totp_last_counter, 0), ?) WHERE id = ? AND secret <=> ? AND session_epoch = ?",
});
// adpanel:recovery-proof-commit - a reset or code-set replacement during hashing
// invalidates the proof; a successful inventory replacement keeps sessions live.
const RECOVERY_CODES_COMMIT_SQL = "UPDATE users SET recovery_codes = ? WHERE id = ? AND password = ? AND session_epoch = ? AND recovery_codes <=> ?";
function createCredentialCommitService({ db } = {}) {
if (typeof db?.query !== "function") throw new TypeError("db.query dependency is required");
async function commit(kind, user, newEpoch, params, provedEpoch) {
if (!user?.id || !Number.isSafeInteger(provedEpoch) || provedEpoch < 0 ||
provedEpoch !== user.session_epoch || !Number.isSafeInteger(newEpoch) ||
newEpoch <= 0 || newEpoch === provedEpoch) {
return { affectedRows: 0 };
}
const result = await db.query(CREDENTIAL_COMMIT_SQL[kind], [...params, provedEpoch]);
return result?.affectedRows === 1 ? result : { affectedRows: 0 };
}
return {
commitPassword: (user, password, newEpoch) =>
commit("password", user, newEpoch, [password, newEpoch, user?.id, user?.password], user?.session_epoch),
commitEmail: (user, email, oldEmail, newEpoch) =>
commit("email", user, newEpoch, [email, newEpoch, user?.id, user?.password, oldEmail], user?.session_epoch),
async commitTwoFactor(user, secret, recoveryCodes, priorSecret, newEpoch, provedEpoch, verifiedStep) {
if (!Number.isSafeInteger(verifiedStep) || verifiedStep < 0) return { affectedRows: 0 };
return commit("twoFactor", user, newEpoch, [secret, recoveryCodes, newEpoch, verifiedStep, user?.id, priorSecret], provedEpoch);
},
async commitRecoveryCodes(user, recoveryCodes, priorRecoveryCodes) {
if (!user?.id || !user.password || !Number.isSafeInteger(user.session_epoch) || user.session_epoch < 0 ||
(priorRecoveryCodes !== null && typeof priorRecoveryCodes !== "string")) {
return { affectedRows: 0 };
}
const result = await db.query(RECOVERY_CODES_COMMIT_SQL, [recoveryCodes, user.id, user.password, user.session_epoch, priorRecoveryCodes]);
return result?.affectedRows === 1 ? result : { affectedRows: 0 };
},
};
}
// adpanel:account-actor-commit - provisioning and credential overrides lock
// the acting administrator's proved generation and the selected target row.
async function createProvisionedAccount(db, actor, { email, passwordHash, admin, avatarUrl }) {
return withAccountActionTransaction(db, actor, null, async (connection) => {
const [result] = await connection.execute(
"INSERT INTO users (email, password, secret, admin, recovery_codes, avatar_url, session_epoch) VALUES (?, ?, NULL, ?, NULL, ?, ?)",
[email, passwordHash, admin ? 1 : 0, avatarUrl, newSessionEpoch()]
);
return { ok: result?.affectedRows === 1 };
});
}
async function resetAccountPassword(db, targetUser, passwordHash, actor) {
const outcome = await withAccountActionTransaction(db, actor, targetUser, async (connection, live) => {
const [result] = await connection.execute(
"UPDATE users SET password = ?, session_epoch = ? WHERE id = ?",
[passwordHash, newSessionEpochDifferentFrom(Number(live.session_epoch || 0)), live.id]
);
return { ok: result?.affectedRows === 1 };
}, { allowAdminTarget: true });
return outcome.ok;
}
async function resetAccountTwoFactor(db, targetUser, actor) {
const outcome = await withAccountActionTransaction(db, actor, targetUser, async (connection, live) => {
// adpanel:admin-2fa-recovery-revocation - backup codes must not outlive
// the authenticator reset; revoke both factors with the session generation.
const [result] = await connection.execute(
"UPDATE users SET secret = NULL, recovery_codes = NULL, session_epoch = ? WHERE id = ?",
[newSessionEpochDifferentFrom(Number(live.session_epoch || 0)), live.id]
);
return { ok: result?.affectedRows === 1 };
}, { allowAdminTarget: true });
return outcome.ok;
}
async function resetAccountRecoveryCodes(db, targetUser, recoveryCodes, actor) {
const outcome = await withAccountActionTransaction(db, actor, targetUser, async (connection, live) => {
const [result] = await connection.execute(
"UPDATE users SET recovery_codes = ? WHERE id = ? AND admin = 0",
[recoveryCodes, live.id]
);
return { ok: result?.affectedRows === 1 };
});
return outcome.ok;
}
module.exports = { createProvisionedAccount, resetAccountPassword, resetAccountTwoFactor, resetAccountRecoveryCodes, createCredentialCommitService, CREDENTIAL_COMMIT_SQL, RECOVERY_CODES_COMMIT_SQL };
+182
View File
@@ -0,0 +1,182 @@
"use strict";
// adpanel:admin-2fa-reset-preflight — ONE shared implementation of the admin
// 2FA reset pipeline. Express 4 cannot catch rejected handler promises: an
// `await` that is not lexically enclosed by a try-with-catch turns any
// transient rejection (DB hiccup, Redis timeout, session-store reset) into a
// request that is never answered — the process-level unhandledRejection
// handler only logs, and the client hangs. The ENTIRE awaited pipeline of
// this handler — admin gate, action-token gate, target/acting-admin lookups,
// self-reset refusal, destructive step-up, the secret-clearing write, the
// session/socket evictions, the audit entry and the response — sits inside
// ONE guard try whose catch logs its own bracketed marker and answers the
// headersSent-guarded 500 (ending an already-answered response exactly once
// instead of writing a second body). HARD CONTRACT: the exported handler
// NEVER REJECTS — this is what makes the thin expression-bodied arrow
// adapters in index.js safe under Express 4.
//
// Every capability arrives through the injected `deps` object (the
// dependency-injection pattern of services/server-create.js): this module
// must never require index.js. index.js constructs the service once next to
// the two route registrations and keeps only auth-adjacent wiring there.
// adpanel:credential-generation — the ONE shared session-epoch generator
// (one-way dependency: services -> utils). The secret-clearing write below
// bumps the epoch in the SAME statement as the credential.
const { resetAccountTwoFactor } = require("./account-credentials");
const { accountActionScope, requireAccountActionTarget } = require("./account-actions");
// adpanel:session-inventory-error-propagation — the ONE shared renderer for
// the response's sessionInvalidationWarnings: a degraded inventory scan
// (scanIncomplete) surfaces as a truthful warning even when it produced no
// per-session error strings. The note is true here: the epoch rode the
// secret-clearing write below, so any session the sweep missed fails the
// binding check on its next request.
const { renderSessionInvalidationWarnings } = require("../utils/session-invalidation-warnings");
// adpanel:admin-reset-target-pinning — the ONE stale-target wire string,
// byte-identical to the credential CAS 409 that index.js carries as exactly
// three inline literals (pinned by tests/credential-change-atomic-guard.test.js
// — this constant must never be re-inlined into index.js, which would add a
// fourth occurrence). index.js imports it, injects it back into this service
// for the reset flow and reuses it for the admin recovery-code reset route, so
// every admin reset surface answers a stale target with the same wire string.
const STALE_TARGET_409_MESSAGE = "Your credentials were just changed in another session or by an administrator. Re-verify and try again.";
// Shared implementation for POST /api/admin/user/reset-2fa (canonical) and
// POST /api/admin/user/confirm-2fa-reset (backward-compatibility alias for
// older clients). One implementation prevents the privileged flow from
// drifting between copies (the alias had already lost its audit trail once).
// The routes stay separately registered because action tokens are bound to
// the exact action string, so a token minted for one route must not
// authorize the other.
//
// Security model: the admin must NEVER learn the target user's TOTP seed,
// otherwise the admin could generate valid codes for that account and
// non-repudiation is broken. The old confirm-2fa-reset flow generated a TOTP
// seed on the admin's behalf and saved it here, which exposed the seed to the
// admin. Instead of generating a new secret on the admin's behalf, this
// handler clears the user's 2FA. The user re-enrolls their own authenticator
// from account settings after their next login.
function createAdminTwoFactorResetService(deps) {
const {
isAdmin,
requireActionTokenOr403,
findUserByEmail,
requireDestructiveActionStepUp,
db,
destroyBrowserSessionsForUser,
disconnectSocketsForUser,
recordActivity,
getRequestIp,
normalizeAdminTargetEmail,
stripLogControlChars,
// adpanel:admin-reset-target-pinning — injectable so a variant surface can
// reword the stale 409; the default keeps the ONE shared wire string.
staleTarget409Message = STALE_TARGET_409_MESSAGE,
logger = console,
} = deps || {};
// Fail closed: a miswired construction site must die at boot, not silently
// answer every request 500 (or worse, half-run the pipeline).
for (const [name, value] of [
["isAdmin", isAdmin],
["requireActionTokenOr403", requireActionTokenOr403],
["findUserByEmail", findUserByEmail],
["requireDestructiveActionStepUp", requireDestructiveActionStepUp],
["destroyBrowserSessionsForUser", destroyBrowserSessionsForUser],
["disconnectSocketsForUser", disconnectSocketsForUser],
["recordActivity", recordActivity],
["getRequestIp", getRequestIp],
["normalizeAdminTargetEmail", normalizeAdminTargetEmail],
["stripLogControlChars", stripLogControlChars],
]) {
if (typeof value !== "function") {
throw new Error(`[admin-2fa-reset] missing required dep: ${name}`);
}
}
if (!db || typeof db.query !== "function") {
throw new Error("[admin-2fa-reset] missing required dep: db.query");
}
async function handleAdmin2faReset(req, res, { action, proofLabel, logSuffix }) {
try {
if (!(await isAdmin(req))) {
return res.status(403).json({ error: "Admin access required" });
}
if (!await requireActionTokenOr403(req, res, action)) return;
const { email } = req.body || {};
const targetEmail = normalizeAdminTargetEmail(email);
if (!targetEmail) {
return res.status(400).json({ error: "invalid email" });
}
const targetEmailLower = targetEmail.toLowerCase();
const targetUser = await findUserByEmail(targetEmail);
if (!targetUser) {
return res.status(404).json({ error: "User not found" });
}
if (!requireAccountActionTarget(req, res, targetUser)) return;
if (targetUser.email.toLowerCase() === req.session.user.toLowerCase()) {
return res.status(400).json({ error: "Cannot reset your own 2FA through admin panel. Use account settings." });
}
// Step-up authentication: the acting admin must re-verify with their own
// password or 2FA before this destructive action is allowed. This mirrors
// the protection used by other destructive admin actions (maintenance,
// session revoke) and prevents abuse via a hijacked admin session.
const actingAdmin = req.currentUser || await findUserByEmail(req.session.user);
if (!actingAdmin || !actingAdmin.admin) {
return res.status(403).json({ error: "Admin access required" });
}
const stepUp = await requireDestructiveActionStepUp(req, res, actingAdmin, "Admin 2FA reset", { scopeKey: accountActionScope(targetUser), credentialFlow: "password-then-totp" });
if (!stepUp.ok) return;
// adpanel:account-actor-commit - the shared transaction pins both the
// admitted actor generation and the target ID before clearing 2FA.
if (!await resetAccountTwoFactor(db, targetUser, actingAdmin)) {
logger.log(`[SECURITY] Admin 2FA reset hit a stale target (row deleted/recreated between lookup and write) | Requested for: ${stripLogControlChars(targetUser.email)} by admin ${stripLogControlChars(req.session.user)} | IP: ${getRequestIp(req)}`);
return res.status(409).json({ error: staleTarget409Message });
}
logger.log(`[admin] 2FA cleared${logSuffix} for user ${stripLogControlChars(targetUser.email)} by admin ${stripLogControlChars(req.session.user)} | IP: ${getRequestIp(req)}`);
// Evict the target's sessions and remember-me tokens: clearing 2FA is a
// remediation action, so a stolen session must not outlive it. The acting
// admin's own session is never the target (self-reset is rejected above).
const sessionInvalidation = await destroyBrowserSessionsForUser(targetUser);
const socketsDisconnected = disconnectSocketsForUser(targetUser.email, "2fa-reset-by-admin", { accountId: targetUser.id });
logger.log(`[SECURITY] Admin 2FA reset evictions | Target: ${stripLogControlChars(targetUser.email)} | Sessions destroyed: ${sessionInvalidation.destroyed} | Sockets disconnected: ${socketsDisconnected}`);
try {
recordActivity("_system", "admin_reset_2fa", `Reset (cleared) 2FA for ${targetUser.email}`, req.session.user, getRequestIp(req));
} catch (_) { }
return res.json({
ok: true,
email: targetUser.email,
cleared: true,
sessionsDestroyed: sessionInvalidation.destroyed,
socketsDisconnected,
rememberLoginsRevoked: sessionInvalidation.rememberLoginsRevoked,
sessionInvalidationWarnings: renderSessionInvalidationWarnings(sessionInvalidation),
message: "2FA has been reset. The user must set up 2FA again from their account settings.",
});
} catch (err) {
// adpanel:admin-2fa-reset-preflight — the whole awaited pipeline is
// lexically inside the guard try above, so a rejection lands here
// instead of escaping into the Express-4 void. A gate that already
// answered (403 action-token/step-up challenge) must not be written
// again: end that response exactly once, never a second body.
logger.error("[admin-2fa-reset] pre-flight failed:", err);
if (!res.headersSent) return res.status(500).json({ error: "internal error" });
res.end();
}
}
return { handleAdmin2faReset };
}
module.exports = { createAdminTwoFactorResetService, STALE_TARGET_409_MESSAGE };
+225
View File
@@ -0,0 +1,225 @@
"use strict";
const { AsyncLocalStorage } = require("node:async_hooks");
function accountChanged() {
const error = new Error("The assistant account changed. Sign in again before continuing.");
error.code = "ASSISTANT_ACCOUNT_CHANGED";
return error;
}
// adpanel:assistant-history-owner - email reuse never transfers conversations;
// legacy rows without a provable account ID stay unassigned and unreadable.
function createDashboardAssistantHistory({ db, findUserByEmail, title = "ADPanel Assistant" } = {}) {
const owners = new AsyncLocalStorage();
let initPromise = null;
const emailKey = (email) => String(email || "").trim().toLowerCase();
const owner = () => {
const current = owners.getStore();
if (!current) throw accountChanged();
return current;
};
async function runForUser(email, operation, expectedId) {
const current = owners.getStore();
if (current) {
if (emailKey(email) !== current.email || (expectedId != null && Number(expectedId) !== current.id)) throw accountChanged();
return operation();
}
const user = await findUserByEmail(emailKey(email));
const id = Number(user?.id);
if (!Number.isSafeInteger(id) || id <= 0 || user.suspended ||
(expectedId != null && Number(expectedId) !== id)) throw accountChanged();
return owners.run(Object.freeze({ id, email: emailKey(user.email) }), operation);
}
async function ensureTables() {
if (initPromise) return initPromise;
initPromise = (async () => {
await db.query(`CREATE TABLE IF NOT EXISTS dashboard_assistant_chats (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id BIGINT UNSIGNED NULL,
user_email VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL DEFAULT 'ADPanel Assistant',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_dashboard_assistant_chats_user (user_email),
KEY idx_dashboard_assistant_chats_owner (user_id, updated_at),
KEY idx_dashboard_assistant_chats_updated (updated_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`);
for (const [sql, duplicateCode] of [
["ALTER TABLE dashboard_assistant_chats ADD COLUMN user_id BIGINT UNSIGNED NULL AFTER id", "ER_DUP_FIELDNAME"],
["ALTER TABLE dashboard_assistant_chats ADD KEY idx_dashboard_assistant_chats_owner (user_id, updated_at)", "ER_DUP_KEYNAME"]
]) {
try { await db.query(sql); } catch (error) { if (error.code !== duplicateCode) throw error; }
}
await db.query(`CREATE TABLE IF NOT EXISTS dashboard_assistant_messages (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
chat_id BIGINT UNSIGNED NOT NULL,
role ENUM('user', 'assistant', 'system') NOT NULL,
content LONGTEXT NOT NULL,
model VARCHAR(255) NULL,
thinking_time_ms INT UNSIGNED NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_dashboard_assistant_messages_chat (chat_id),
KEY idx_dashboard_assistant_messages_created (created_at),
CONSTRAINT fk_dashboard_assistant_messages_chat FOREIGN KEY (chat_id)
REFERENCES dashboard_assistant_chats(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`);
})().catch((error) => { initPromise = null; throw error; });
return initPromise;
}
async function withLiveOwner(operation) {
const current = owner();
await ensureTables();
const connection = await db.pool.getConnection();
try {
await connection.beginTransaction();
const [users] = await connection.execute("SELECT id, email, suspended FROM users WHERE id = ? AND LOWER(email) = LOWER(?) FOR UPDATE", [current.id, current.email]);
if (!users[0] || Number(users[0].suspended) !== 0 || emailKey(users[0].email) !== current.email) throw accountChanged();
const result = await operation(connection, current);
await connection.commit();
return result;
} catch (error) {
try { await connection.rollback(); } catch (_) { }
throw error;
} finally {
connection.release();
}
}
const chatSql = `SELECT c.id, c.title, c.created_at, c.updated_at
FROM dashboard_assistant_chats c JOIN users u ON u.id = c.user_id
WHERE c.user_id = ? AND u.suspended = 0`;
async function getChatById(email, chatId) {
await ensureTables();
const id = Number(chatId);
if (!Number.isSafeInteger(id) || id <= 0) return null;
return (await db.query(`${chatSql} AND c.id = ? LIMIT 1`, [owner().id, id]))[0] || null;
}
async function createFreshChat(email) {
return withLiveOwner(async (connection, current) => {
const [result] = await connection.execute("INSERT INTO dashboard_assistant_chats (user_id, user_email, title) VALUES (?, ?, ?)", [current.id, current.email, title]);
const [rows] = await connection.execute("SELECT id, title, created_at, updated_at FROM dashboard_assistant_chats WHERE id = ? AND user_id = ? LIMIT 1", [result.insertId, current.id]);
return rows[0];
});
}
async function getPrimaryChat(email) {
await ensureTables();
const rows = await db.query(`${chatSql} ORDER BY c.updated_at DESC, c.id DESC LIMIT 1`, [owner().id]);
return rows[0] || createFreshChat(email);
}
async function resetChat(email) {
return withLiveOwner(async (connection, current) => {
const [empty] = await connection.execute(`SELECT c.id FROM dashboard_assistant_chats c
WHERE c.user_id = ? AND NOT EXISTS (
SELECT 1 FROM dashboard_assistant_messages m WHERE m.chat_id = c.id)
ORDER BY c.updated_at DESC, c.id DESC LIMIT 1 FOR UPDATE`, [current.id]);
let chatId = empty[0]?.id;
if (chatId) {
await connection.execute("UPDATE dashboard_assistant_chats SET updated_at = NOW() WHERE id = ? AND user_id = ?", [chatId, current.id]);
await connection.execute(`DELETE FROM dashboard_assistant_chats WHERE user_id = ? AND id <> ?
AND NOT EXISTS (SELECT 1 FROM dashboard_assistant_messages m WHERE m.chat_id = dashboard_assistant_chats.id)`, [current.id, chatId]);
} else {
const [result] = await connection.execute("INSERT INTO dashboard_assistant_chats (user_id, user_email, title) VALUES (?, ?, ?)", [current.id, current.email, title]);
chatId = result.insertId;
}
const [rows] = await connection.execute("SELECT id, title, created_at, updated_at FROM dashboard_assistant_chats WHERE id = ? AND user_id = ? LIMIT 1", [chatId, current.id]);
return rows[0];
});
}
async function getChatMessages(chatId, limit = 60) {
await ensureTables();
const safeLimit = Math.max(1, Math.min(200, parseInt(limit, 10) || 60));
const select = `SELECT m.id, m.role, m.content, m.model, m.thinking_time_ms, m.created_at
FROM dashboard_assistant_messages m JOIN dashboard_assistant_chats c ON c.id = m.chat_id
JOIN users u ON u.id = c.user_id WHERE m.chat_id = ? AND c.user_id = ? AND u.suspended = 0`;
const rows = await db.query(`${select} ORDER BY m.id DESC LIMIT ${safeLimit}`, [chatId, owner().id]);
const windowRows = (rows || []).slice().sort((left, right) => Number(left.id) - Number(right.id));
if (!windowRows.length) return [];
const windowIds = windowRows.map((row) => Number(row.id));
const systemRows = await db.query(`${select} AND m.role = 'system' AND m.id NOT IN (${windowIds.map(() => "?").join(", ")})
ORDER BY m.created_at ASC, m.id ASC LIMIT ${safeLimit}`, [chatId, owner().id, ...windowIds]);
return [...(systemRows || []), ...windowRows].sort((left, right) => Number(left.id) - Number(right.id));
}
async function getChatMessageCount(chatId) {
await ensureTables();
const rows = await db.query(`SELECT COUNT(*) AS total FROM dashboard_assistant_messages m
JOIN dashboard_assistant_chats c ON c.id = m.chat_id JOIN users u ON u.id = c.user_id
WHERE m.chat_id = ? AND c.user_id = ? AND u.suspended = 0 AND m.role IN ('user', 'assistant')`, [chatId, owner().id]);
return Number(rows[0]?.total || 0);
}
async function addMessage(chatId, { role, content, model = null, thinkingTimeMs = null }) {
return withLiveOwner(async (connection, current) => {
const [chats] = await connection.execute("SELECT id FROM dashboard_assistant_chats WHERE id = ? AND user_id = ? FOR UPDATE", [chatId, current.id]);
if (!chats[0]) throw accountChanged();
await connection.execute("INSERT INTO dashboard_assistant_messages (chat_id, role, content, model, thinking_time_ms) VALUES (?, ?, ?, ?, ?)", [chatId, role, String(content || ""), model, thinkingTimeMs]);
await connection.execute("UPDATE dashboard_assistant_chats SET updated_at = NOW() WHERE id = ? AND user_id = ?", [chatId, current.id]);
});
}
async function deleteChat(email, chatId) {
return withLiveOwner(async (connection, current) => {
await connection.execute("DELETE FROM dashboard_assistant_messages WHERE chat_id IN (SELECT id FROM dashboard_assistant_chats WHERE id = ? AND user_id = ?)", [chatId, current.id]);
await connection.execute("DELETE FROM dashboard_assistant_chats WHERE id = ? AND user_id = ?", [chatId, current.id]);
});
}
async function maybeUpdateChatTitle(chatId, userMessage) {
return withLiveOwner(async (connection, current) => {
const [rows] = await connection.execute("SELECT title FROM dashboard_assistant_chats WHERE id = ? AND user_id = ? FOR UPDATE", [chatId, current.id]);
if (!rows[0]) throw accountChanged();
if (rows[0].title && rows[0].title !== title) return;
await connection.execute("UPDATE dashboard_assistant_chats SET title = ? WHERE id = ? AND user_id = ?", [String(userMessage || "").trim().slice(0, 80) || title, chatId, current.id]);
});
}
return { runForUser, ensureTables, getPrimaryChat, createFreshChat, resetChat, getChatById, getChatMessages, getChatMessageCount, addMessage, deleteChat, maybeUpdateChatTitle };
}
async function deleteAccountAssistantHistory(connection, userId, email) {
// adpanel:assistant-history-delete - the caller holds the user row lock;
// history writes take that same lock and cannot outlive the account.
let predicate = "user_id = ? OR (user_id IS NULL AND user_email = ?)";
let params = [userId, email];
try {
await connection.execute(`SELECT id FROM dashboard_assistant_chats WHERE ${predicate} FOR UPDATE`, params);
} catch (error) {
if (error.code === "ER_NO_SUCH_TABLE") return;
if (error.code !== "ER_BAD_FIELD_ERROR" || !String(error.message).includes("user_id")) throw error;
predicate = "user_email = ?";
params = [email];
await connection.execute(`SELECT id FROM dashboard_assistant_chats WHERE ${predicate} FOR UPDATE`, params);
}
try {
await connection.execute(`DELETE FROM dashboard_assistant_messages WHERE chat_id IN (SELECT id FROM dashboard_assistant_chats WHERE ${predicate})`, params);
} catch (error) { if (error.code !== "ER_NO_SUCH_TABLE") throw error; }
await connection.execute(`DELETE FROM dashboard_assistant_chats WHERE ${predicate}`, params);
}
async function cleanupOrphanAssistantHistory(db) {
let predicate = "(user_id IS NOT NULL AND user_id NOT IN (SELECT id FROM users)) OR (user_id IS NULL AND user_email NOT IN (SELECT email FROM users))";
try {
await db.query(`SELECT id FROM dashboard_assistant_chats WHERE ${predicate} LIMIT 1`);
} catch (error) {
if (error.code === "ER_NO_SUCH_TABLE") return;
if (error.code !== "ER_BAD_FIELD_ERROR" || !String(error.message).includes("user_id")) throw error;
predicate = "user_email NOT IN (SELECT email FROM users)";
}
try {
await db.query(`DELETE FROM dashboard_assistant_messages WHERE chat_id IN (SELECT id FROM dashboard_assistant_chats WHERE ${predicate})`);
} catch (error) { if (error.code !== "ER_NO_SUCH_TABLE") throw error; }
await db.query(`DELETE FROM dashboard_assistant_chats WHERE ${predicate}`);
}
module.exports = { createDashboardAssistantHistory, deleteAccountAssistantHistory, cleanupOrphanAssistantHistory };
+42
View File
@@ -0,0 +1,42 @@
"use strict";
// adpanel:grace-shared-authority - a local cache is never required proof of a
// grant; every reuse validates the shared row and its current count.
async function readVerifiedActionGrant({ db, withTimeout, candidate, safeCompare, normalizeStepUpProofStrength, clear, logger = console, now = Date.now }) {
try {
let rows;
try {
rows = await withTimeout(db.query(
"SELECT grant_id, user_id, email, session_hash, secret_hash, ip_hash, ua_hash, verified_at, expires_at, revoked_at, use_count, proof_strength FROM destructive_action_grants WHERE grant_id = ? LIMIT 1",
[candidate.grantId]
), 5000, "stepup-grace-validate-timeout");
} catch (error) {
if (!((error?.code === "ER_BAD_FIELD_ERROR" || String(error?.message || "").includes("Unknown column")) && String(error?.message || "").includes("proof_strength"))) throw error;
rows = await withTimeout(db.query(
"SELECT grant_id, user_id, email, session_hash, secret_hash, ip_hash, ua_hash, verified_at, expires_at, revoked_at, use_count FROM destructive_action_grants WHERE grant_id = ? LIMIT 1",
[candidate.grantId]
), 5000, "stepup-grace-validate-timeout");
}
const row = Array.isArray(rows) ? rows[0] : null;
if (!row || row.revoked_at != null || Number(row.user_id) !== candidate.userId ||
String(row.email || "").trim().toLowerCase() !== candidate.email ||
Number(row.verified_at) !== candidate.verifiedAt || Number(row.expires_at) !== candidate.expiresAt ||
Number(row.expires_at) <= now() ||
!["session", "secret", "ip", "ua"].every((field) => safeCompare(String(row[`${field}_hash`] || ""), candidate[`${field}Hash`]))) {
clear();
return null;
}
return {
email: candidate.email, userId: candidate.userId, grantId: candidate.grantId,
verifiedAt: candidate.verifiedAt, expiresAt: candidate.expiresAt,
useCount: Math.max(0, Number(row.use_count || 0)),
proofStrength: normalizeStepUpProofStrength(row.proof_strength)
};
} catch (error) {
logger.warn("[security] Destructive action grant DB validation failed:", error?.message || error);
clear();
return null;
}
}
module.exports = { readVerifiedActionGrant };
+150
View File
@@ -0,0 +1,150 @@
"use strict";
// adpanel:rate-limit-policy-owner — the ONE home of the Redis-backed global
// /api rate-limit POLICY (the limiter mounted via app.use("/api/") in
// index.js). Nothing else may construct a parallel global limiter or render
// its wire strings; entry points keep only their mount + hook wiring.
//
// adpanel:rate-limit-shared-revision - the generation-scoped prefix derives
// from the policy store's persisted revision, never this worker's diagnostic
// generation counter. Workers with different restart histories therefore
// increment the same IP bucket for the same committed policy.
// express-rate-limit bakes windowMs at construction, so a changed window OR
// shared revision needs a fresh limiter/store instance. Revision comparison
// also catches a missed window round trip. Limit-only and flag-only edits
// remain live without resetting counters. Atomic committed publications and
// reconciled manual edits call applyPolicy through the injected live getter.
//
// Postures preserved exactly as they were when the options lived in index.js:
// - the injected redisSendCommand is index.js's hardened
// safeRedisSendCommand closure (fail-open placeholder reply with
// positiveHits-valid totalHits 1, NOSCRIPT rethrow for
// retryableIncrement's self-heal) — this module never re-implements a
// client wrapper;
// - passOnStoreError: true keeps the boot-down SCRIPT-LOAD rejection
// fail-open (abuse brake, not an auth control);
// - the skip order is rate_limiting gate → trusted-subnet bypass →
// exempt-path consult through the ONE shared isRateLimitExempt helper
// (single source for both limiter stores), reading the ORIGINAL request
// path because app.use("/api/") strips the mount prefix before the skip
// runs;
// - the 429 shape is the JSON handler with the same message string.
const { policyWindowMs: effectiveWindowMs, policyRevision } = require("./security-policy");
function createGlobalRateLimitOwner(deps) {
const {
rateLimit,
RateLimitRedisStore,
getSecurity,
redisSendCommand,
isRequestFromTrustedSubnet,
isRateLimitExempt,
basePrefix = "rl",
} = deps;
if (typeof rateLimit !== "function") throw new TypeError("createGlobalRateLimitOwner: rateLimit dependency is required");
if (typeof RateLimitRedisStore !== "function") throw new TypeError("createGlobalRateLimitOwner: RateLimitRedisStore dependency is required");
if (typeof getSecurity !== "function") throw new TypeError("createGlobalRateLimitOwner: getSecurity dependency is required (index.js reassigns the security binding on fs.watch — a captured object reference would go stale)");
if (typeof isRequestFromTrustedSubnet !== "function") throw new TypeError("createGlobalRateLimitOwner: isRequestFromTrustedSubnet dependency is required");
if (typeof isRateLimitExempt !== "function") throw new TypeError("createGlobalRateLimitOwner: isRateLimitExempt dependency is required");
const hasRedis = typeof redisSendCommand === "function";
let generation = 0;
let currentWindowMs = null;
let currentRevision = null;
const getMaxRequests = () => {
const limit = parseInt(getSecurity().limit, 10);
return Number.isFinite(limit) && limit > 0 ? limit : 100;
};
const buildLimiter = () => {
const windowMs = effectiveWindowMs(getSecurity());
const revision = policyRevision(getSecurity()) || `legacy-w${windowMs}`;
generation += 1;
// adpanel:rate-limit-shared-revision - each local limiter owns its store
// instance while all workers share this revision's counter namespace.
const store = new RateLimitRedisStore({
prefix: `${basePrefix}:${revision}:`,
sendCommand: redisSendCommand,
});
const limiter = rateLimit({
windowMs,
max: getMaxRequests,
standardHeaders: true,
legacyHeaders: false,
store,
// adpanel:store-fallback-valid-hits — fail-open on the one error class
// the injected wrapper cannot absorb (Redis down since boot leaves the
// store's un-awaited SCRIPT LOAD rejected and increment() rejecting;
// without this option the rejection rethrows out of the middleware and
// 500s every /api/* request).
passOnStoreError: true,
message: "Too many requests from this IP, please try again later.",
skip: (req) => {
const security = getSecurity();
if (!security || security.rate_limiting !== true) return true;
if (isRequestFromTrustedSubnet(req)) return true;
// app.use("/api/") strips the mount prefix before this skip runs, so
// req.path here would be "/me", not "/api/me" — the exempt consult
// below must read the original request path or it silently never
// matches (the same desync note the in-memory limiter carries).
const path = String(req.originalUrl || req.url || "").split("?")[0];
if (isRateLimitExempt(path, req.method)) return true;
return false;
},
handler: (req, res, next, options) => {
res.status(options.statusCode).json({ error: options.message });
},
});
currentWindowMs = windowMs;
currentRevision = revision;
return limiter;
};
const owner = {
// The CURRENT generation's limiter, swapped by applyPolicy(). The wrapper
// indirection is what makes the swap safe for the mounted middleware:
// Express captured `owner.middleware` once at mount time, and every
// request reads owner.current at dispatch — an in-flight request that
// already entered the previous instance finishes under the previous
// policy, every new request enters the rebuilt one.
middleware: (req, res, next) => {
const limiter = owner.current;
if (!limiter) return next();
return limiter(req, res, next);
},
current: null,
// Repeated publication is idempotent; revision adoption also rebuilds a
// worker that missed intermediate changes but retained the same window.
applyPolicy() {
if (!hasRedis) return { rebuilt: false, reason: "no-redis-at-boot" };
const windowMs = effectiveWindowMs(getSecurity());
const revision = policyRevision(getSecurity()) || `legacy-w${windowMs}`;
if (owner.current && windowMs === currentWindowMs && revision === currentRevision) {
return { rebuilt: false, generation, windowMs };
}
owner.current = buildLimiter();
return { rebuilt: true, generation, windowMs: currentWindowMs };
},
describePolicy() {
return {
mounted: hasRedis,
enforcing: hasRedis && owner.current !== null,
generation: hasRedis ? generation : 0,
windowMs: hasRedis ? currentWindowMs : null,
};
},
};
if (hasRedis) {
owner.current = buildLimiter(); // generation 1 at boot, exactly one mount
}
return owner;
}
module.exports = { createGlobalRateLimitOwner };
File diff suppressed because it is too large. Load diff
+592
View File
@@ -0,0 +1,592 @@
"use strict";
// adpanel:relay-helper-consolidation — ONE shared implementation of the
// panel→node HTTP plumbing (Wave 2 Step A of the relay consolidation
// campaign, see .campaign/spec-relay.md §6). index.js and nodes.js carried
// drifting twins of every helper below; the twins are deleted from both
// monoliths and re-bound here under the SAME identifier names, so no call
// site changed. This module requires ONLY utils/* and node builtins — it
// must NEVER require index.js or nodes.js (dependency direction is one-way:
// the monoliths require this module). Boot-time capabilities that still live
// in index.js (the mTLS agent, the SSRF-pinned request agent builders used
// by the non-node branch) arrive through configureNodeHttp() and are read at
// CALL time, never at require time.
//
// TWO FLAGGED SAFETY HARDENINGS land with this extraction (both fail-closed
// on malformed node configurations, neither can reject a legitimate one):
// 1. Credential-in-URL rejection in buildNodeBaseUrl
// (`u.username || u.password → null`) — previously index.js-only; the
// nodes.js twin silently forwarded node addresses like
// `https://user:pass@host` and leaked the credentials into every relayed
// upstream URL. Now enforced on BOTH surfaces.
// 2. The stricter safeJoinUnix union lives in services/node-fs-relay.js
// (documented there).
//
// Every other behavioral delta between the former twins (port clamping,
// trailing-slash/origin URL form, the
// X-Node-Token-Id header shape, the local-daemon token branch) is preserved
// EXACTLY per caller behind factory parameters — byte-identical outputs on
// both surfaces for every input either surface can receive today.
const http = require("http");
const https = require("https");
const { isIP } = require("node:net");
const nodeSsrfGuard = require("../utils/node-ssrf-guard");
const remoteUrlGuard = require("../utils/remote-url-guard");
const { destroyStreams } = require("../utils/stream-lifecycle");
// ---------------------------------------------------------------------------
// Injectable boot-time capabilities (set once by index.js at startup; read at
// call time so module-load ordering can never observe a half-built agent).
// ---------------------------------------------------------------------------
const deps = {
// index.js builds an https.Agent for node mTLS at boot (let nodeMtlsAgent,
// lazily assigned); httpRequestJson attaches it to https dials that carry
// node credentials. Getter, not value: the agent is assigned after modules
// load.
getNodeMtlsAgent: () => null,
// SSRF-pinned agent builders shared with index.js's ssrfPipedHttpGet —
// they stay defined in index.js (their only other consumer) and are
// injected here so the non-node branch of httpRequestJson keeps its exact
// dial posture (IP-pinned agent + SNI servername).
createSsrfSafeAgent: null,
tlsServernameForHost: null,
};
function configureNodeHttp(patch) {
Object.assign(deps, patch || {});
}
// adpanel:node-mtls-parity - every TLS transport must use the configured node identity and CA.
function nodeTlsAgent(url) {
if (typeof url !== "string" || !/^(?:https|wss):/.test(url)) return undefined;
return deps.getNodeMtlsAgent() || undefined;
}
function hasVerifiedNodeHttps(fullUrl) {
if (typeof fullUrl !== "string" || !fullUrl.startsWith("https://") || process.env.NODE_TLS_REJECT_UNAUTHORIZED === "0") return false;
const { options } = nodeTlsAgent(fullUrl) || https.globalAgent;
return options?.rejectUnauthorized !== false && !options?.checkServerIdentity;
}
// ---------------------------------------------------------------------------
// httpRequestJson — moved verbatim from index.js (its previous and only
// definition site). Since the Wave 3 HTTP-helper convergence, the nodes.js
// helpers of the same family (httpJson, the GET-probe httpRequestJson) are
// thin wrappers over THIS implementation via the `opts` param below — the
// crash-class hardening (response error AND aborted listeners, hard
// total-duration timer + inactivity timeout + request error listener,
// single-settle finish, Content-Length pre-check + streaming 16 MiB cap) is
// enforced exactly once, here. Everything the panel call sites closed over
// in index.js is either required directly above or injected via
// configureNodeHttp.
// ---------------------------------------------------------------------------
// opts (Wave 3 HTTP-helper convergence, all flags default off so the panel's
// 54 existing call sites dial exactly as before):
// opts.includeText — the nodes.js httpJson contract: the result carries the
// raw body as `text` (on the end path) and `text: null` on the guard /
// response-error / too-large paths, exactly as that helper always
// resolved them. Deliberately NOT added to the timeout / request-error /
// setup-failure paths — the former httpJson resolved those WITHOUT the
// text key, and the shape is preserved verbatim.
// opts.nodeDial — force the node branch of the SSRF guard regardless of
// headers. The branch condition below ("headers carry the node's bearer
// credential") fits every panel caller, but the nodes.js surface's
// helpers historically applied the node guard chain UNCONDITIONALLY —
// including the unauthenticated /health probe, which dials the node's
// custom api_port with no auth headers and would otherwise fall into the
// external-URL branch, whose 80/443 port allowlist rejects every real
// node address. The nodes.js wrappers pass this so their guard posture
// stays byte-identical.
function httpRequestJson(fullUrl, method = "GET", headers = {}, body = null, timeoutMs = 15000, maxBytes = null, opts = null) {
const includeText = !!(opts && opts.includeText);
const nodeDial = !!(opts && opts.nodeDial);
// The failure shapes without a body. includeText adds `text: null` on
// exactly the paths the former nodes.js httpJson resolved it on (guard
// error, response error, aborted, too large) and leaves the timeout /
// request-error / setup-failure shapes without the key.
const noBodyResult = () => (includeText ? { status: 0, json: null, text: null } : { status: 0, json: null });
return new Promise(async (resolve) => {
let settled = false;
const finish = (out) => {
if (settled) return;
settled = true;
try { clearTimeout(hardTimer); } catch { }
resolve(out);
};
let hardTimer = null;
let req = null;
let response = null;
const deadline = Date.now() + timeoutMs;
const fail = (out) => {
if (settled) return;
finish(out);
destroyStreams(response, req);
};
// adpanel:node-http-total-deadline - external DNS validation belongs to
// the same budget as the dial and body; expiry must forbid a late dial.
hardTimer = setTimeout(() => fail({ status: 0, json: null }), timeoutMs);
try {
const isInternalNodeRequest = nodeDial || !!(headers && (headers["X-Node-Token"] || headers["Authorization"]));
let requestOptions;
let lib;
if (isInternalNodeRequest) {
// SSRF guard (finding 3.3): pre-flight for literal-IP hosts (Node skips
// custom lookup for them); the guarded lookup below re-validates
// resolved IPs at connect time. Every dial to a node goes through this
// guard: the request headers carry the node's bearer credential.
const guardError = nodeSsrfGuard.assertNodeUrlHostAllowed(fullUrl);
if (guardError) return finish(noBodyResult());
const isHttps = fullUrl.startsWith("https:");
lib = isHttps ? https : http;
requestOptions = { method, headers, lookup: nodeSsrfGuard.guardedNodeLookup, agent: nodeTlsAgent(fullUrl) };
} else {
let validated;
try {
validated = await remoteUrlGuard.assertSafeRemoteUrlWithResolvedIp(fullUrl);
} catch (e) {
return finish({ status: 0, json: null });
}
if (settled || Date.now() >= deadline) return fail({ status: 0, json: null });
const { url: u, resolvedIp, originalHostname } = validated;
lib = u.protocol === "https:" ? https : http;
const agent = deps.createSsrfSafeAgent(resolvedIp, u.protocol, originalHostname);
requestOptions = {
method,
hostname: resolvedIp,
port: u.port || (u.protocol === "https:" ? 443 : 80),
path: u.pathname + u.search,
headers: {
...headers,
"Host": originalHostname,
},
agent: agent,
...(u.protocol === "https:" ? { servername: deps.tlsServernameForHost(originalHostname) } : {}),
};
fullUrl = null;
}
if (settled || Date.now() >= deadline) return fail({ status: 0, json: null });
req = fullUrl
? lib.request(fullUrl, requestOptions, handleResponse)
: lib.request(requestOptions, handleResponse);
// Panel-side cap for buffered node responses. The daemon serves file
// reads up to 10 MiB (maxEditorRead = 10 << 20, handleFSRead in main.go)
// and puts no size cap on /v1/fs/list output, so a legal payload can
// reach ~10 MiB before JSON encoding; base64 encoding inflates it 4/3
// (~13.7 MiB) and JSON string escaping adds more for escape-heavy text.
// 16 MiB fits every daemon-legal read/list response with headroom; a
// body beyond it fails as { error: "response too large", tooLarge: true }
// so routes can answer node_response_too_large instead of node_offline.
const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
const tooLargeResult = () => (includeText
? { status: 0, json: null, text: null, error: "response too large", tooLarge: true }
: { status: 0, json: null, error: "response too large", tooLarge: true });
function handleResponse(res) {
response = res;
// adpanel:node-http-cap-error-listeners - even a header-only refusal
// destroys a response that can emit a late error or aborted event.
res.on("error", () => fail(noBodyResult()));
res.on("aborted", () => fail(noBodyResult()));
res.on("close", () => { if (!settled) fail(noBodyResult()); });
if (settled) {
destroyStreams(res, req);
return;
}
if (Date.now() >= deadline) {
fail({ status: 0, json: null });
return;
}
const statusCode = res.statusCode || 0;
const chunks = [];
let totalBytes = 0;
// maxBytes is an optional per-call cap for callers that must not
// buffer large bodies. Callers that omit it get MAX_RESPONSE_BYTES.
const byteCap = Number.isFinite(maxBytes) && maxBytes > 0 ? maxBytes : MAX_RESPONSE_BYTES;
{
const contentLength = parseInt(res.headers["content-length"], 10);
// Compare against byteCap (not raw maxBytes) so a non-finite or
// non-positive maxBytes falls back to the MAX_RESPONSE_BYTES guard
// here exactly as the streaming check below does.
if (Number.isFinite(contentLength) && contentLength > byteCap) {
// Settle BEFORE destroying: destroy() on a mid-message
// IncomingMessage emits 'aborted' synchronously, and finish() is
// single-settle — destroying first let the aborted handler's
// tooLarge-less shape win the race, misreporting an over-cap
// dial as a generic transport failure instead of
// node_response_too_large (surfaced by the Wave 3 behavioral
// convergence tests; the old inline helpers never hit it because
// they registered no aborted listener at all).
fail(tooLargeResult());
return;
}
}
res.on("data", (d) => {
if (settled) return;
totalBytes += d.length;
if (totalBytes > byteCap) {
// Settle-then-destroy, for the same aborted-listener race as the
// Content-Length pre-check above. Destroying still stops the
// drain (the over-cap remainder is never buffered); the promise
// is already settled, so the destroy's own error/aborted events
// are no-ops.
fail(tooLargeResult());
return;
}
chunks.push(d);
});
res.on("end", () => {
if (settled) return;
const bodyStr = Buffer.concat(chunks).toString("utf8");
try {
const json = bodyStr ? JSON.parse(bodyStr) : null;
finish(includeText ? { status: statusCode, json, text: bodyStr } : { status: statusCode, json });
} catch {
finish(includeText ? { status: statusCode, json: null, text: bodyStr } : { status: statusCode, json: null });
}
});
}
req.on("timeout", () => {
fail({ status: 0, json: null });
});
req.on("error", () => fail({ status: 0, json: null }));
req.setTimeout(Math.max(1, deadline - Date.now()));
// Bodies go out chunked (no explicit Content-Length): the Go daemon's
// net/http server decodes both identically. The former nodes.js httpJson
// set Content-Length explicitly — the relay consolidation accepted the
// chunked form as the one request-wire delta of the hardened core
// (Wave 2 review note).
if (body != null) req.write(typeof body === "string" ? body : JSON.stringify(body));
req.end();
} catch {
fail({ status: 0, json: null });
}
});
}
function httpStreamRequest(fullUrl, { method = "GET", headers = {}, bodyStream = null, timeoutMs = 120000, onRequest = null, nodeDial = false, idleTimeoutMs = 0 } = {}) {
return new Promise((resolve, reject) => {
let settled = false;
let finished = false;
let responseEnded = false;
let req = null;
let response = null;
let hardTimer = null;
const deadline = Date.now() + timeoutMs;
const complete = () => {
if (finished) return;
finished = true;
clearTimeout(hardTimer);
};
const fail = (error) => {
if (finished) return;
complete();
if (bodyStream && req) bodyStream.unpipe(req);
// adpanel:node-stream-lifetime - response headers transfer ownership,
// not completion; late dial failures must still reach the body reader.
if (response && !response.destroyed) response.destroy(error);
destroyStreams(req, bodyStream);
if (!settled) {
settled = true;
reject(error);
}
};
const active = () => {
if (finished) return false;
if (Date.now() >= deadline) {
fail(new Error("timeout"));
return false;
}
return true;
};
hardTimer = setTimeout(() => fail(new Error("timeout")), timeoutMs);
if (bodyStream) {
bodyStream.on("error", fail);
bodyStream.on("close", () => {
if (!bodyStream.readableEnded) fail(new Error("Request body closed before end"));
});
if (bodyStream.destroyed && !bodyStream.readableEnded) {
fail(bodyStream.errored || new Error("Request body closed before end"));
return;
}
}
try {
const isNodeAuthenticated = nodeDial || (headers && (headers["X-Node-Token"] || headers["Authorization"]));
if (isNodeAuthenticated) {
const guardError = nodeSsrfGuard.assertNodeUrlHostAllowed(fullUrl);
if (guardError) return fail(guardError);
}
if (!active()) return;
const isHttps = fullUrl.startsWith("https:");
const lib = isHttps ? https : http;
const requestOptions = { method, headers };
if (isNodeAuthenticated) requestOptions.lookup = nodeSsrfGuard.guardedNodeLookup;
const agent = nodeTlsAgent(fullUrl);
if (agent) requestOptions.agent = agent;
req = lib.request(fullUrl, requestOptions, (res) => {
response = res;
res.on("error", fail);
res.on("aborted", () => fail(new Error("Node response aborted")));
res.on("close", () => {
if (!responseEnded) fail(new Error("Node response closed before end"));
});
res.once("end", () => { responseEnded = true; complete(); });
if (!active()) {
destroyStreams(res, req);
return;
}
if (idleTimeoutMs > 0 && res.statusCode === 200) {
clearTimeout(hardTimer);
req.setTimeout(idleTimeoutMs);
}
settled = true;
resolve({ req, res });
});
req.on("error", fail);
req.on("timeout", () => fail(new Error("timeout")));
req.on("close", () => {
if (!response) fail(new Error("Node request closed before headers"));
});
if (typeof onRequest === "function") {
try { onRequest(req); } catch { }
}
if (!active()) { destroyStreams(req, bodyStream); return; }
req.setTimeout(Math.max(1, deadline - Date.now()));
if (bodyStream) bodyStream.pipe(req);
else req.end();
} catch (error) {
fail(error);
}
});
}
// ---------------------------------------------------------------------------
// Node base-URL plumbing — the byte-identical micro-helpers both former
// buildNodeBaseUrl twins closed over. They were duplicated verbatim in
// index.js and nodes.js; the monoliths now import THESE copies (same
// identifiers) so the set cannot drift again.
// ---------------------------------------------------------------------------
function truthyFlag(value) {
if (typeof value === "boolean") return value;
if (typeof value === "number") return value === 1;
if (typeof value === "string") {
const normalized = value.trim().toLowerCase();
return normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on";
}
return false;
}
const CLOUDFLARE_HTTPS_EDGE_PORTS = new Set([443, 2053, 2083, 2087, 2096, 8443]);
// Formerly a twin pair: index.js clamped with clampApiPort, nodes.js with its
// clampPort. The clamp is now a parameter; each caller's factory binds its own
// so outputs stay byte-identical. Module-private: only the shared
// buildNodeBaseUrl below calls it.
function cloudflareHttpsEdgePort(port, clamp) {
const p = clamp(port || 443);
return CLOUDFLARE_HTTPS_EDGE_PORTS.has(p) ? p : 443;
}
function hasExplicitHostPort(host) {
const value = String(host || "").trim();
if (value.startsWith("[")) return /\]:\d+$/.test(value);
return /^[^:]+:\d+$/.test(value);
}
function explicitHostPort(host) {
const value = String(host || "").trim();
const match = value.startsWith("[")
? value.match(/\]:(\d+)$/)
: value.match(/^[^:]+:(\d+)$/);
return match ? Number(match[1]) : null;
}
function stripExplicitHostPort(host) {
const value = String(host || "").trim();
if (!hasExplicitHostPort(value)) return value;
if (value.startsWith("[")) return value.replace(/\]:\d+$/, "]");
return value.replace(/:\d+$/, "");
}
// ---------------------------------------------------------------------------
// buildNodeBaseUrl — index.js's version is the shared one, with every
// nodes.js delta parameterized so BOTH callers keep byte-identical outputs:
// clampEdgePort index.js: clampApiPort nodes.js: clampPort
// clampUrlPathPort index.js: clampApiPort nodes.js: identity (the
// nodes.js twin did NOT clamp an explicit-URL branch port)
// clampBareHostPort index.js: clampApiPort nodes.js: clampPort
// returnOrigin index.js: true (u.origin) nodes.js: false
// (u.toString().replace(/\/$/, ""))
// THE ONE UNCONDITIONAL HARDENING (both surfaces): credential-in-URL
// rejection. A node address embedding user:pass is a malformed configuration;
// the former nodes.js twin forwarded it verbatim (credentials leaking into
// every upstream URL), index.js already refused. Fail-closed on both now.
// ---------------------------------------------------------------------------
function createBuildNodeBaseUrl(opts = {}) {
const clampEdgePort = opts.clampEdgePort;
const clampUrlPathPort = opts.clampUrlPathPort;
const clampBareHostPort = opts.clampBareHostPort;
const returnOrigin = opts.returnOrigin === true;
if (typeof clampEdgePort !== "function" || typeof clampUrlPathPort !== "function" || typeof clampBareHostPort !== "function") {
throw new Error("createBuildNodeBaseUrl requires clampEdgePort, clampUrlPathPort and clampBareHostPort functions");
}
return function buildNodeBaseUrl(address, port, sslEnabled, underCloudflare = false) {
let base = String(address || "").trim();
if (!base) return null;
const cloudflareProxy = truthyFlag(underCloudflare);
if (/^https?:\/\//i.test(base)) {
try {
const u = new URL(base);
// adpanel:relay-helper-consolidation — HARDENING (both surfaces): a
// node address embedding credentials is malformed config; refuse it
// instead of dialing with the credentials in every upstream URL.
if (u.username || u.password) return null;
u.hash = "";
u.search = "";
u.pathname = "";
const authority = base.match(/^https?:\/\/([^/?#\\]*)/i)?.[1];
const addressPort = u.port || explicitHostPort(authority);
if (cloudflareProxy) {
u.protocol = "https:";
const edgePort = cloudflareHttpsEdgePort(addressPort || port, clampEdgePort);
u.port = edgePort === 443 ? "" : String(edgePort);
return returnOrigin ? u.origin : u.toString().replace(/\/$/, "");
}
// adpanel:node-tls — an explicit HTTP address cannot override enabled TLS.
if (sslEnabled) u.protocol = "https:";
u.port = String(addressPort || clampUrlPathPort(port || 8080));
return returnOrigin ? u.origin : u.toString().replace(/\/$/, "");
} catch { }
}
if (cloudflareProxy) {
base = base.split(/[/?#]/)[0];
const edgePort = cloudflareHttpsEdgePort(explicitHostPort(base) || port, clampEdgePort);
base = stripExplicitHostPort(base);
if (edgePort !== 443) base += `:${edgePort}`;
return `https://${base}`;
}
// adpanel:node-tls-default - node routes must not downgrade the panel's configured default.
const configuredScheme = String(process.env.NODE_DEFAULT_SCHEME || "http").trim().toLowerCase();
const defaultScheme = sslEnabled ? "https" : configuredScheme;
if (defaultScheme !== "http" && defaultScheme !== "https") return null;
base = base.split(/[/?#]/)[0];
if (hasExplicitHostPort(base)) return `${defaultScheme}://${base}`;
if (isIP(base) === 6) base = `[${base}]`;
return `${defaultScheme}://${base}:${clampBareHostPort(port || 8080)}`;
};
}
// ---------------------------------------------------------------------------
// Node auth headers — one core, two former twins behind parameters:
// index.js nodeAuthHeadersFor(node, isRemote): Content-Type on EVERY header
// set; remote token resolved as node.token || node.secret || node.api_key;
// X-Node-Token-Id only when token_id is truthy; non-remote (local daemon)
// dials authenticate with index.js's LOCAL_NODE_TOKEN (injected by the
// caller — it is index.js module state).
// nodes.js nodeHeaders(node): no Content-Type; token from node.token only;
// X-Node-Token-Id ALWAYS present, possibly "" (alwaysSendTokenId).
// Each caller keeps its exact current header shape and key set.
// ---------------------------------------------------------------------------
function buildNodeAuthHeaders(node, opts = {}) {
const isRemote = opts.isRemote !== false;
const includeContentType = opts.includeContentType !== false;
const alwaysSendTokenId = opts.alwaysSendTokenId === true;
const tokenFields = opts.tokenFields || ["token", "secret", "api_key"];
const localNodeToken = opts.localNodeToken || null;
const h = includeContentType ? { "Content-Type": "application/json" } : {};
const remoteToken = node && tokenFields.map((f) => node[f]).find((v) => v);
if (isRemote && (remoteToken || alwaysSendTokenId)) {
const token = remoteToken || "";
h.Authorization = `Bearer ${token}`;
h["X-Node-Token"] = token;
if (alwaysSendTokenId) h["X-Node-Token-Id"] = node.token_id || "";
else if (node.token_id) h["X-Node-Token-Id"] = node.token_id;
return h;
}
if (!isRemote && localNodeToken) {
h.Authorization = `Bearer ${localNodeToken}`;
h["X-Node-Token"] = localNodeToken;
}
return h;
}
// The nodes.js relay shape, verbatim (the twin nodes.js carried): every dial
// identifies the token slot even when the token/token_id fields are empty.
function nodeHeaders(node) {
return buildNodeAuthHeaders(node, {
isRemote: true,
includeContentType: false,
alwaysSendTokenId: true,
tokenFields: ["token"],
});
}
function nodeUnderCloudflare(node) {
const bc = node?.buildConfig;
// adpanel:node-proxy-state — a saved disable must override the row's stale derived flag.
if (typeof bc?.under_cloudflare !== "undefined") return truthyFlag(bc.under_cloudflare);
return truthyFlag(node?.under_cloudflare)
|| truthyFlag(node?.cloudflare_proxy)
|| truthyFlag(bc?.cloudflare_proxy);
}
function nodeConnectionState(node, patch = {}, build = false) {
const currentTls = !!node.buildConfig?.ssl_enabled;
const ssl = patch.ssl_enabled === undefined ? currentTls : truthyFlag(patch.ssl_enabled);
const rawProxy = build ? patch.under_cloudflare ?? patch.cloudflare_proxy
: patch.under_cloudflare === undefined ? patch.cloudflare_proxy : patch.under_cloudflare;
const currentProxy = nodeUnderCloudflare(node);
const hasProxyFlag = patch.under_cloudflare !== undefined || patch.cloudflare_proxy !== undefined;
const proxy = hasProxyFlag ? ssl && truthyFlag(rawProxy)
: patch.ssl_enabled !== undefined && !ssl ? false : currentProxy;
const rawPort = !build && patch.api_port !== undefined ? patch.api_port : node.api_port;
const port = Math.round(Number(rawPort));
const address = !build && patch.address !== undefined ? patch.address : node.address;
return JSON.stringify([String(address || "").trim(), port >= 1 && port <= 65535 ? port : 8080, ssl, proxy]);
}
// adpanel:console-stream-deadline - wait for headers, then allow for the
// daemon's 15-second heartbeats without keeping a stalled tail registered.
function openNodeConsoleLogStream(url, headers, onRequest) {
const streamHeaders = { ...headers, Accept: "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" };
delete streamHeaders["Content-Type"];
return httpStreamRequest(url, { headers: streamHeaders, onRequest, nodeDial: true, timeoutMs: 15_000, idleTimeoutMs: 45_000 });
}
module.exports = {
httpStreamRequest,
openNodeConsoleLogStream,
configureNodeHttp,
httpRequestJson,
hasVerifiedNodeHttps,
nodeTlsAgent,
truthyFlag,
CLOUDFLARE_HTTPS_EDGE_PORTS,
hasExplicitHostPort,
explicitHostPort,
stripExplicitHostPort,
createBuildNodeBaseUrl,
buildNodeAuthHeaders,
nodeHeaders,
nodeUnderCloudflare,
nodeConnectionState,
};
+478
View File
@@ -0,0 +1,478 @@
"use strict";
const fs = require("node:fs");
const path = require("node:path");
const { execFile } = require("node:child_process");
const { promisify } = require("node:util");
const { setTimeout: delay } = require("node:timers/promises");
const recovery = require("../scripts/panel-update-recovery.cjs");
const { pm2List } = require("../utils/panel-metrics");
const RESTART_GRACE_MS = 30_000;
const RESTART_MAX_ATTEMPTS = 3;
const RESTART_RPC_TIMEOUT_MS = 15_000;
const execFileAsync = promisify(execFile);
function matchesPanelApp(worker) {
const env = worker?.pm2_env;
return !!env && env.name === process.env.name && env.pm_cwd === process.env.pm_cwd &&
env.namespace === process.env.namespace && env.pm_exec_path === process.env.pm_exec_path;
}
async function readAgentUnit() {
if (!fs.existsSync("/run/systemd/system")) return null;
const fields = ["LoadState", "WorkingDirectory", "ExecStart", "ExecCondition", "ExecStartPre", "NeedDaemonReload", "MainPID"];
const { stdout } = await execFileAsync("/usr/bin/systemctl", ["show", `--property=${fields.join(",")}`, "adpanel-agent.service"], {
timeout: 4000, maxBuffer: 16 * 1024,
}).catch(err => {
if (err.code === 1 && /^LoadState=not-found$/m.test(err.stdout || "")) return err;
throw err;
});
return stdout;
}
async function verifyAgentUpdateLauncher(panelRoot, {
readUnit = readAgentUnit,
readArgs = pid => fs.readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").filter(Boolean),
} = {}) {
try {
const stdout = await readUnit();
if (stdout === null) return;
const values = Object.fromEntries(stdout.trim().split("\n").map(line => {
const separator = line.indexOf("=");
return [line.slice(0, separator), line.slice(separator + 1)];
}));
const launcher = path.join(panelRoot, "scripts/panel-update-recovery.cjs");
const starts = [...(values.ExecStart || "").matchAll(/argv\[\]=([^;]+);/g)];
const pid = Number(values.MainPID);
const isLauncher = ([node, memory, entry, mode, ...extra]) => path.isAbsolute(node || "") && path.basename(node) === "node" &&
/^--max-old-space-size=\d+$/.test(memory) && entry === launcher && mode === "--agent" && !extra.length;
if (values.LoadState === "not-found" && (!values.MainPID || pid === 0)) return;
if (values.LoadState !== "loaded" || values.WorkingDirectory !== panelRoot || values.ExecCondition || values.ExecStartPre ||
values.NeedDaemonReload !== "no" || starts.length !== 1 || !isLauncher(starts[0][1].trim().split(/\s+/)) ||
!Number.isSafeInteger(pid) || pid < 0) {
throw new Error("The registered Agent unit does not use the protected launcher");
}
if (pid && !isLauncher(readArgs(pid))) {
throw new Error("The running Agent did not start through the protected launcher");
}
} catch (cause) {
throw Object.assign(new Error("Could not verify the Agent worker's update launcher. Apply a maintenance upgrade before updating.", { cause }), { statusCode: 409 });
}
}
async function capturePanelWorkers(panelRoot, verifyAgentLauncher) {
const list = await pm2List();
const appName = process.env.name;
const group = (Array.isArray(list) ? list : []).filter(worker => worker?.pm2_env?.name === appName);
if (!appName || !group.some(worker => worker.pid === process.pid) || group.some(worker =>
!matchesPanelApp(worker) || worker.pm2_env.status !== "online")) {
throw Object.assign(new Error("Could not verify the active PM2 panel workers. Retry after the service has settled."), { statusCode: 409 });
}
if (group.some(({ pm2_env: env }) => String(env.autorestart) === "false" || [].concat(env.stop_exit_codes ?? []).length)) {
throw Object.assign(new Error("Panel updates require PM2 automatic restarts without stop exit codes so a failed release can be recovered."), { statusCode: 409 });
}
if (group.some(({ pm2_env: env }) => env.max_restarts !== undefined &&
(!Number.isSafeInteger(Number(env.max_restarts)) || Number(env.max_restarts) < 3))) {
throw Object.assign(new Error("Panel updates require a PM2 unstable restart limit of at least three to allow a planned stop, a failed trial, and a recovery start."), { statusCode: 409 });
}
const previous = group.map(worker => recovery.panelWorkerIdentity(worker.pid));
const slots = group.map(worker => worker.pm_id);
const supervisor = recovery.panelWorkerIdentity(process.ppid);
if (!supervisor?.bootId || previous.some(worker => !worker) || slots.some(slot => !Number.isSafeInteger(slot) || slot < 0) ||
new Set(slots).size !== slots.length) {
throw Object.assign(new Error("Could not verify the PM2 worker set and host boot identity. Retry after the service has settled."), { statusCode: 409 });
}
await verifyAgentLauncher(panelRoot);
return { appName, expected: previous.length, previous, slots, supervisor };
}
async function requestPanelRestart(cohort, dispatch) {
await delay(2000, undefined, { ref: false });
const { DAEMON_RPC_PORT, PM2_PID_FILE_PATH } = require("pm2/paths")();
const supervisorMatches = () => {
const pm2 = recovery.panelWorkerIdentity(process.ppid);
return pm2 && pm2.pid === cohort?.supervisor?.pid && pm2.startTicks === cohort.supervisor.startTicks &&
pm2.bootId === cohort.supervisor.bootId && Number(fs.readFileSync(PM2_PID_FILE_PATH, "utf8")) === pm2.pid;
};
if (!supervisorMatches() || !fs.lstatSync(DAEMON_RPC_PORT).isSocket()) {
throw new Error("Could not verify the active panel's PM2 restart socket");
}
// adpanel:update-restart - queue every slot on the daemon before the requesting worker exits.
const socket = require("pm2/modules/pm2-axon").socket("req");
socket.set("retry timeout", 0);
const client = new (require("pm2/modules/pm2-axon-rpc").Client)(socket);
await new Promise((resolve, reject) => {
let settled = false;
const finish = err => {
if (settled) return;
settled = true;
clearTimeout(timeout);
try { socket.close(); } catch (closeError) { err ||= closeError; }
if (err) reject(err);
else resolve();
};
const timeout = setTimeout(() => finish(new Error("PM2 restart request timed out")), RESTART_RPC_TIMEOUT_MS);
socket.on("error", finish);
socket.once("disconnect", () => finish(new Error("PM2 disconnected before acknowledging the restart")));
socket.once("connect", () => {
try {
client.call("getMonitorData", {}, async (err, list) => {
if (settled || err) return finish(err);
try {
const ownSlot = Number(process.env.pm_id);
const slots = (Array.isArray(list) ? list : []).filter(matchesPanelApp).map(worker => worker.pm_id);
if (!slots.includes(ownSlot) || slots.some(slot => !Number.isSafeInteger(slot) || slot < 0) ||
new Set(slots).size !== slots.length || (cohort.slots &&
(slots.length !== cohort.slots.length || !cohort.slots.every(slot => slots.includes(slot))))) {
throw new Error("Could not verify the PM2 slots to restart");
}
const orderedSlots = [...slots.filter(slot => slot !== ownSlot), ...slots.filter(slot => slot === ownSlot)];
const dispatched = await dispatch(() => {
if (settled) return;
if (!supervisorMatches()) throw new Error("The panel's PM2 supervisor changed before restart");
let remaining = orderedSlots.length;
let restartError;
for (const id of orderedSlots) client.call("restartProcessId", { id }, error => {
restartError ||= error;
if (--remaining === 0) finish(restartError);
});
});
if (!dispatched) finish();
} catch (error) {
finish(error);
}
});
} catch (err) {
finish(err);
}
});
try { socket.connect(DAEMON_RPC_PORT); } catch (err) { finish(err); }
});
}
function failureReason(err) {
if (err?.code === "ENOSPC" || err?.code === "EDQUOT") return "storage";
if (err?.code === "PANEL_UPDATE_DOWNLOAD_FAILED") return "download";
if (err?.code === "PANEL_UPDATE_INTEGRITY_FAILED") return "integrity";
if (err?.code === "PANEL_UPDATE_DEPENDENCIES") return "dependencies";
if (err?.code === "PANEL_UPDATE_STARTUP_FORMAT") return "startupFormat";
if (err?.code === "PANEL_UPDATE_RESTART_FAILED") return "restart";
return "install";
}
const FAILURE_DETAILS = {
download: "The release could not be downloaded.",
integrity: "The release did not pass integrity verification.",
dependencies: "The release requires different runtime dependencies and needs a maintenance upgrade.",
startupFormat: "The release changes the panel's startup format and needs a maintenance upgrade.",
storage: "The update ran out of storage space.",
restart: "The panel could not restart to load the release.",
startup: "The new release did not finish starting.",
commit: "The verified release could not be safely recorded.",
interrupted: "The install was interrupted.",
install: "The release could not be installed.",
};
function renderPanelUpdateFailure({ version, reason, restored, backupMayShareLiveFiles, cleanupRequired }) {
const detail = Object.hasOwn(FAILURE_DETAILS, reason) ? FAILURE_DETAILS[reason] : FAILURE_DETAILS.install;
if (cleanupRequired) return `Update to ${version} failed. ${detail} No panel files were changed. Updates are paused because the staged update could not be cleaned up. Check the panel logs and storage.`;
if (restored === false) return `Update to ${version} failed. ${detail} Automatic recovery could not finish. Review the panel logs and restore from backup before restarting.`;
const result = restored ? "The previous version was restored." : "No panel files were changed.";
const backup = backupMayShareLiveFiles ? " Keep a separate backup: this recovery snapshot may share files with the live panel." : "";
return `Update to ${version} failed. ${detail} ${result}${backup} Automatic updates will wait for a newer release.`;
}
function createPanelUpdateCoordinator({
panelInfoFile, readPanelInfo, checkUpdate, installUpdate, compareVersions, intervalMs, logger = console,
launchRestart = requestPanelRestart, armTimer = setTimeout, isStopping = () => false, now = Date.now,
recoveryAvailable = recovery.isManagedRecoveryLauncher, captureWorkers = capturePanelWorkers,
verifyAgentLauncher = verifyAgentUpdateLauncher,
acquireScaleLock = () => recovery.createPanelScaleMutex(panelInfoFile).tryAcquire(),
getLoadedUpdateId = recovery.getLoadedUpdateId,
}) {
const mutex = recovery.createPanelUpdateMutex(panelInfoFile);
const state = recovery.createPanelUpdateState(panelInfoFile, logger);
let interval = null;
let recoveryErrorId;
function acquireUpdateLock() {
const release = mutex.tryAcquire();
if (release) return release;
const err = new Error("A panel update is already in progress. Try again when it finishes.");
err.statusCode = 409;
throw err;
}
function setPanelAutoUpdateEnabled(enabled) {
const release = acquireUpdateLock();
try {
if (enabled) requireRecoveryLauncher();
assertIdle();
recovery.writePanelUpdateInfo(panelInfoFile, { "panel-auto-update": enabled });
} finally {
release();
}
}
function requireRecoveryLauncher() {
if (recoveryAvailable()) return;
throw Object.assign(new Error("Updates require the recovery-enabled panel service. Deploy it through a maintenance upgrade before updating."), { statusCode: 409 });
}
function assertIdle() {
if (state.read().pending) throw Object.assign(new Error("A panel update is awaiting recovery or restart"), { statusCode: 409 });
}
function isPanelReleaseDeferred(version, current = state.read()) {
return !!current.ignoredThrough && compareVersions(current.ignoredThrough, version) <= 0;
}
function offerUnavailable(version, installedVersion, current) {
return compareVersions(installedVersion, version) <= 0 || isPanelReleaseDeferred(version, current);
}
function needsRecovery(pending) {
if (!pending) return false;
if (pending.phase === "starting" || pending.phase === "committing") return recovery.trialHasFailed(pending);
return pending.phase !== "restart" || !!recovery.getRestartRecoveryReason(pending, now());
}
function recoveryReason(pending) {
return pending.reason || (pending.phase === "restart" ? recovery.getRestartRecoveryReason(pending, now()) || "restart"
: pending.phase === "starting" ? "startup" : "interrupted");
}
function getPanelUpdateStatus(offer, installedVersion) {
let status;
let release;
let recoveryAbandoned = false;
let recoveryFailure;
try {
status = state.read();
if (needsRecovery(status.pending) && !status.pending.needsOperator) {
release = mutex.tryAcquire();
if (release) {
status = state.read();
recoveryAbandoned = needsRecovery(status.pending);
}
}
if (status.pending) recoveryFailure = state.readRecoveryError(status.pending.id);
} catch {
return {
restartPending: false, updateBlocked: true,
updateError: "The panel cannot read its update recovery record. Updates are paused. Check the panel logs and backups before restarting.",
};
} finally {
release?.();
}
const { pending, failure, checkFailed, ignoredThrough, verified } = status;
const loaded = getLoadedUpdateId();
const unpublished = recovery.isUnpublishedUpdate(pending);
const onDiskId = unpublished ? verified?.id : pending?.id || verified?.id;
const details = {
ignoredThrough, verifiedUpdate: verified,
...(loaded !== undefined && onDiskId && { restartRequired: loaded !== onDiskId }),
...(typeof offer === "string" && { offeredVersion: offer, offerUnavailable: offerUnavailable(offer, installedVersion, status) }),
};
if (pending && !pending.needsOperator && !recoveryFailure && pending.id !== recoveryErrorId) {
return { ...details, restartPending: true, recoveryPending: recoveryAbandoned, updateBlocked: true, updateError: "" };
}
const outcome = pending ? {
version: pending.version, reason: recoveryFailure?.reason || recoveryReason(pending),
...(unpublished ? { restored: null, cleanupRequired: true } : { restored: false }),
} : failure;
return {
...details, failedUpdate: outcome,
restartPending: false,
updateBlocked: !!pending,
updateError: outcome ? renderPanelUpdateFailure(outcome)
: checkFailed ? "The last automatic check could not verify a stable GitHub release." : "",
};
}
function scheduleRestart({ id, cohort }) {
const attempt = state.recordRestartAttempt(id, now() + RESTART_GRACE_MS);
const dispatch = async send => {
if (isStopping()) return false;
const release = await mutex.acquire();
try {
const current = state.read().pending;
if (current?.id !== id || current.phase !== "restart" || current.restartAttempts !== attempt || isStopping() ||
now() >= current.restartNextAt || recovery.getRestartRecoveryReason(current, now()) || state.readRecoveryError(id)) return false;
send();
return true;
} finally {
release();
}
};
Promise.resolve(launchRestart(cohort, dispatch)).catch(err => logger.error("[panel-update] Could not request the PM2 restart:", err));
armTimer(() => recoverAbandonedPanelUpdate(id), RESTART_GRACE_MS)?.unref?.();
}
function recoverAbandonedPanelUpdate(expectedId) {
if (isStopping()) return;
const canAdvance = pending => pending && !pending.needsOperator && (!expectedId || pending.id === expectedId) &&
(needsRecovery(pending) || (pending.phase === "restart" && now() >= (pending.restartNextAt || 0)));
let release;
let recoveringId;
try {
if (!canAdvance(state.read().pending)) return;
release = mutex.tryAcquire();
if (!release) return;
const { pending } = state.read();
if (!canAdvance(pending)) return;
if (pending.phase === "restart" && !needsRecovery(pending) && !state.readRecoveryError(pending.id) &&
(pending.restartAttempts || 0) < RESTART_MAX_ATTEMPTS) {
scheduleRestart(pending);
return;
}
recoveringId = pending.id;
if (state.recover(pending.id, recoveryReason(pending)) === false) logger.error("[panel-update] Abandoned update recovery was incomplete.");
if (recoveryErrorId === recoveringId) recoveryErrorId = undefined;
} catch (err) {
if (recoveringId) recoveryErrorId = recoveringId;
logger.error("[panel-update] Abandoned update recovery failed:", err);
} finally {
release?.();
}
}
async function applyPanelRelease(version, apply) {
const releaseScaling = acquireScaleLock();
if (!releaseScaling) throw Object.assign(new Error("The panel worker count is changing. Retry when PM2 has settled."), { statusCode: 409 });
let previous;
let ignoredThrough;
let id;
let stage;
try {
try {
const cohort = await captureWorkers(path.dirname(panelInfoFile), verifyAgentLauncher);
previous = state.read();
const keepFailure = !!(previous.ignoredThrough && compareVersions(version, previous.ignoredThrough) > 0);
ignoredThrough = keepFailure ? previous.ignoredThrough : version;
id = state.prepare(version, ignoredThrough, keepFailure, cohort);
} finally {
releaseScaling();
}
const result = await apply(() => {
if (stage) throw new Error("Panel update already began");
stage = state.openStage(id);
return stage.write;
});
if (!stage) throw new Error("Panel update completed without staging a release");
stage.seal();
try {
scheduleRestart(state.read().pending);
} catch (cause) {
logger.error("[panel-update] Could not schedule the restart:", cause);
throw Object.assign(new Error("Panel restart could not be scheduled"), { code: "PANEL_UPDATE_RESTART_FAILED", cause });
}
return {
...result, updateId: id, restartScheduled: true,
message: "Update prepared. Restarting the panel to verify the new version.",
};
} catch (err) {
if (!previous) throw err;
logger.error("[panel-update] Release failed:", err);
const reason = failureReason(err);
let failureSaved = !id && err?.panelUpdateFailureSaved === true;
let savedFailure;
try {
const current = state.read();
if (id || current.pending?.version === version) {
failureSaved = state.recover(id || current.pending.id, reason);
} else if (!current.pending && !failureSaved) {
state.write({ ...previous, ignoredThrough, failure: { version, at: new Date().toISOString(), reason, restored: null } });
failureSaved = true;
}
if (failureSaved) savedFailure = state.read().failure;
} catch (recoveryError) {
if (id) recoveryErrorId = id;
logger.error("[panel-update] Could not save or complete recovery:", recoveryError);
}
throw Object.assign(new Error(err?.message || "Update installation failed", { cause: err }), {
code: err?.code,
statusCode: err?.statusCode,
panelUpdateMessage: failureSaved ? renderPanelUpdateFailure(savedFailure || { version, reason, restored: null })
: "The update failed before replacing panel files. The failed release could not be saved; check the panel logs.",
});
}
}
async function installPanelUpdate(targetVersion, checkedOffer = false) {
const release = acquireUpdateLock();
try {
requireRecoveryLauncher();
assertIdle();
if (checkedOffer && offerUnavailable(targetVersion, readPanelInfo().version)) {
throw Object.assign(new Error("This offer is no longer available. Check again."), { statusCode: 409 });
}
return await installUpdate(targetVersion, "manual");
} finally {
release();
}
}
async function runPanelAutoUpdateCycle(trigger = "interval") {
if (!readPanelInfo().autoUpdate) return;
const release = mutex.tryAcquire();
if (!release) return;
try {
if (!readPanelInfo().autoUpdate) return;
const previousState = state.read();
if (previousState.pending) return;
let check;
try {
check = await checkUpdate();
} catch (err) {
if (!previousState.checkFailed) state.write({ ...previousState, checkFailed: true });
throw err;
}
try {
if (!check.updateAvailable) {
logger.log(`[panel-auto-update] No update available (trigger: ${trigger}, current: ${check.currentVersion}).`);
return;
}
if (isPanelReleaseDeferred(check.latestVersion, previousState)) return;
logger.log(`[panel-auto-update] Update found ${check.currentVersion} -> ${check.latestVersion} (trigger: ${trigger}). Installing...`);
requireRecoveryLauncher();
await installUpdate(check.latestVersion, `auto:${trigger}`, check.latestRelease);
} finally {
if (previousState.checkFailed) {
try {
const current = state.read();
if (current.checkFailed && !current.pending) state.write({ ...current, checkFailed: undefined });
} catch (err) {
logger.error("[panel-auto-update] Could not clear the previous feed error:", err);
}
}
}
} catch (err) {
logger.error("[panel-auto-update] Cycle failed:", err?.message || err);
} finally {
release();
}
}
function startPanelAutoUpdateScheduler() {
if (interval) return;
setInterval(recoverAbandonedPanelUpdate, 10_000).unref();
interval = setInterval(() => {
runPanelAutoUpdateCycle("interval").catch(() => { });
}, intervalMs);
interval.unref();
setTimeout(() => {
runPanelAutoUpdateCycle("startup").catch(() => { });
}, 10000).unref();
}
return {
installPanelUpdate, runPanelAutoUpdateCycle, setPanelAutoUpdateEnabled, startPanelAutoUpdateScheduler,
applyPanelRelease, getPanelUpdateStatus, isPanelReleaseDeferred, recoverAbandonedPanelUpdate,
};
}
module.exports = { createPanelUpdateCoordinator, verifyAgentUpdateLauncher, ...recovery };
+51
View File
@@ -0,0 +1,51 @@
"use strict";
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { execFile } = require("node:child_process");
const { promisify } = require("node:util");
const semver = require("semver");
const execFileAsync = promisify(execFile);
async function verifyPanelUpdateDependencies(panelRoot, manifest) {
let packageInfo;
try {
packageInfo = JSON.parse(manifest.toString("utf8"));
} catch (cause) {
throw Object.assign(new Error("The release contains an invalid package manifest", { cause }), { statusCode: 502 });
}
if (!packageInfo || typeof packageInfo !== "object" || Array.isArray(packageInfo) ||
(packageInfo.type !== undefined && packageInfo.type !== "commonjs")) {
throw Object.assign(new Error("This release changes the panel's startup format. Use a maintenance upgrade for this release."), {
code: "PANEL_UPDATE_STARTUP_FORMAT", statusCode: 409,
});
}
if (packageInfo.engines?.node !== undefined && (typeof packageInfo.engines.node !== "string" ||
!semver.satisfies(process.versions.node, packageInfo.engines.node))) {
throw Object.assign(new Error("This release requires a different Node.js version. Use a maintenance upgrade for this release."), {
code: "PANEL_UPDATE_DEPENDENCIES", statusCode: 409,
});
}
const stagingDir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-update-deps-"));
try {
fs.writeFileSync(path.join(stagingDir, "package.json"), manifest);
fs.symlinkSync(path.join(panelRoot, "node_modules"), path.join(stagingDir, "node_modules"), "dir");
try {
await execFileAsync("npm", [
"ls", "--all", "--omit=dev", "--offline", "--ignore-scripts", "--loglevel=error", "--logs-max=0",
], { cwd: stagingDir, timeout: 30000, maxBuffer: 1024 * 1024 });
} catch (cause) {
if (cause.code !== 1 || cause.killed) throw cause;
const err = new Error("This release's runtime dependencies do not match the installed packages. Use a maintenance upgrade for this release.", { cause });
err.code = "PANEL_UPDATE_DEPENDENCIES";
err.statusCode = 409;
throw err;
}
} finally {
fs.rmSync(stagingDir, { recursive: true, force: true });
}
}
module.exports = { verifyPanelUpdateDependencies };
+49
View File
@@ -0,0 +1,49 @@
"use strict";
const { getLatestStableRelease } = require("../utils/update-version");
const RELEASES_URL = "https://api.github.com/repos/antonndev/ADPanel/releases";
const PAGE_SIZE = 100;
const MAX_PAGES = 5;
const LOOKUP_TIMEOUT_MS = 15_000;
const HEADERS = { Accept: "application/vnd.github.v3+json", "User-Agent": "ADPanel-Updater" };
function unavailable(message = "failed to fetch releases from GitHub") {
return Object.assign(new Error(message), { statusCode: 502 });
}
function createPanelReleaseLookup(httpRequestJson) {
function request(suffix, deadline) {
const remaining = deadline - Date.now();
if (remaining <= 0) throw unavailable("panel release lookup timed out");
return httpRequestJson(RELEASES_URL + suffix, "GET", HEADERS, null, remaining);
}
async function fetchPanelRelease(tag) {
const deadline = Date.now() + LOOKUP_TIMEOUT_MS;
const alternate = /^v/i.test(tag) ? tag.slice(1) : `v${tag}`;
for (const candidate of [tag, alternate]) {
const result = await request(`/tags/${encodeURIComponent(candidate)}`, deadline);
if (result?.status === 404) continue;
if (result?.status !== 200 || result.json?.tag_name !== candidate) throw unavailable();
if (!result.json.draft) return result.json;
}
return null;
}
async function fetchLatestStablePanelRelease() {
const deadline = Date.now() + LOOKUP_TIMEOUT_MS;
let latest = null;
for (let page = 1; page <= MAX_PAGES; page++) {
const result = await request(`?per_page=${PAGE_SIZE}&page=${page}`, deadline);
if (result?.status !== 200 || !Array.isArray(result.json) || result.json.length > PAGE_SIZE) throw unavailable();
latest = getLatestStableRelease(latest ? [latest, ...result.json] : result.json);
if (result.json.length < PAGE_SIZE) return latest;
}
throw unavailable("panel release feed exceeded the supported page limit");
}
return { fetchPanelRelease, fetchLatestStablePanelRelease };
}
module.exports = { createPanelReleaseLookup };
+38
View File
@@ -0,0 +1,38 @@
"use strict";
function schedulerJobBelongsToServer(job, canonicalServer, serverId) {
return serverId != null && job?.data?.serverId != null &&
String(job.data.serverId) === String(serverId) &&
String(job.data.serverName || "").toLowerCase() === canonicalServer.toLowerCase();
}
async function resolveSchedulerRepeatablesForServer(queue, templates, canonicalServer, serverId) {
if (serverId == null) return [];
const canonicalKey = canonicalServer.toLowerCase();
const results = await Promise.all(templates.map(async (template) => {
let definition;
try { definition = JSON.parse(template.name || "{}"); } catch { return null; }
if (String(definition?.serverName || "").toLowerCase() !== canonicalKey) return null;
const { serverId: boundId, ...scheduleDefinition } = definition;
if (boundId != null) {
return { template, definition: scheduleDefinition, owned: String(boundId) === String(serverId) };
}
// adpanel:scheduler-server-identity-bind - legacy templates need proof from their current occurrence.
const next = Number(template.next);
let owned = null;
if (Number.isSafeInteger(next) && next > 0) {
const repeat = await queue.repeat;
const occurrenceId = repeat.getRepeatJobKey(template.name, next, template.key, null);
const occurrence = await queue.getJob(occurrenceId);
const repeatKey = occurrence?.repeatJobKey || occurrence?.opts?.repeat?.key;
if (repeatKey === template.key && Number(occurrence?.opts?.prevMillis) === next && occurrence?.data?.serverId != null) {
owned = schedulerJobBelongsToServer(occurrence, canonicalServer, serverId);
}
}
return { template, definition: scheduleDefinition, owned };
}));
return results.filter(Boolean);
}
module.exports = { schedulerJobBelongsToServer, resolveSchedulerRepeatablesForServer };
+87
View File
@@ -0,0 +1,87 @@
"use strict";
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const { atomicWriteFileSync } = require("../utils/atomic-file");
const { createCrossProcessOperationMutex } = require("../utils/cross-process-mutex");
function policyWindowMs(policy) {
const seconds = parseInt(policy?.window_seconds, 10);
return (Number.isFinite(seconds) && seconds > 0 ? seconds : 120) * 1000;
}
function policyRevision(policy) {
const revision = policy?.rate_limit_revision;
if (typeof revision === "string" && /^[a-f0-9]{32}$/.test(revision) && Number(policy.rate_limit_revision_window_ms) === policyWindowMs(policy)) return revision;
return null;
}
// adpanel:security-policy-commit - disk commit precedes publication; a shared
// window revision survives worker restarts and missed intermediate edits.
function createSecurityPolicyStore({ filePath, defaults, parse = JSON.parse, write = atomicWriteFileSync, mutex, publish = () => {} }) {
const lock = mutex || createCrossProcessOperationMutex({ label: "[security-policy]", lockFilePath: `${filePath}.lock` });
const baseline = { ...defaults };
delete baseline.rate_limit_revision;
delete baseline.rate_limit_revision_window_ms;
let snapshot = { ...baseline };
const read = () => {
const parsed = parse(fs.readFileSync(filePath, "utf8"));
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Invalid security policy object");
return { ...baseline, ...parsed };
};
const reconcile = (policy) => {
if (policyRevision(policy)) return policy;
return { ...policy, rate_limit_revision: crypto.randomBytes(16).toString("hex"), rate_limit_revision_window_ms: policyWindowMs(policy) };
};
const persist = (policy) => {
const result = write(filePath, JSON.stringify(policy, null, 2), { mode: 0o600 });
if (result === false) throw new Error("Security policy persistence failed");
snapshot = policy;
publish(policy);
return policy;
};
return {
get: () => snapshot,
async initialize() {
return lock.runExclusive(() => {
const policy = fs.existsSync(filePath) ? read() : { ...baseline };
const reconciled = reconcile(policy);
if (reconciled !== policy || !fs.existsSync(filePath)) return persist(reconciled);
snapshot = reconciled;
publish(snapshot);
return snapshot;
});
},
async reload() {
return lock.runExclusive(() => {
const policy = read();
const reconciled = reconcile(policy);
if (reconciled !== policy) return persist(reconciled);
snapshot = policy;
publish(policy);
return policy;
});
},
async save(changes) {
return lock.runExclusive(() => {
const previous = read();
const candidate = { ...previous, ...changes };
if (policyWindowMs(candidate) !== policyWindowMs(previous)) {
delete candidate.rate_limit_revision;
}
return persist(reconcile(candidate));
});
},
watch(logger = console) {
const watcher = fs.watch(path.dirname(filePath), (_event, name) => {
if (name && String(name) !== path.basename(filePath)) return;
this.reload().catch((error) => logger.warn("[security-policy] Reload failed; retaining last committed policy:", error.message));
});
watcher.unref();
return watcher;
}
};
}
module.exports = { createSecurityPolicyStore, policyWindowMs, policyRevision };
+125
View File
@@ -0,0 +1,125 @@
"use strict";
const { readableImageSql } = require("../AgentWorker/attachments");
const { reviewProjection, REVIEW_SOURCE_REF_PREFIX } = require("../AgentWorker/action-proposal");
const { safeTruncateUtf16 } = require("../utils/safe-truncate");
const CHAT_HISTORY_PAGE_ROWS = 50;
const CHAT_HISTORY_PAGE_BYTES = 12 * 1024 * 1024;
const GENERATED_CHAT_TITLE_LENGTH = 80;
function deriveAiAgentChatTitle(prompt, fallback = "ADPanel Agent") {
const clean = String(prompt || fallback || "ADPanel Agent").trim().replace(/\s+/g, " ");
if (!clean) return "ADPanel Agent";
return clean.length > GENERATED_CHAT_TITLE_LENGTH ? `${safeTruncateUtf16(clean, GENERATED_CHAT_TITLE_LENGTH - 3)}...` : clean;
}
async function readFirstAgentChatTitle(db, row, prompt) {
const [chat] = await db.query(`SELECT chat.title FROM ai_chats chat
JOIN ai_messages submission ON submission.id = ? AND submission.chat_id = chat.id AND submission.role = 'user'
WHERE chat.id = ? AND chat.created_by = ? AND NOT EXISTS (
SELECT 1 FROM ai_messages earlier WHERE earlier.chat_id = chat.id AND earlier.role = 'user' AND earlier.id < submission.id
)`, [row.submission_message_id, row.chat_id, row.user_id]);
const title = chat?.title;
return title === "New Chat" || title === deriveAiAgentChatTitle(prompt) ? title : null;
}
function isValidServerAgentChatCursor(value) {
return typeof value === "string" && /^[1-9]\d{0,19}$/.test(value) && BigInt(value) <= 18446744073709551615n;
}
async function readOwnedServerAgentChat(db, chatId, ownerId, source) {
const [chat] = await db.query(`SELECT chat.*, job.status AS latest_job_status, job.error AS latest_job_error,
CASE WHEN job.status IN ('queued','running') THEN CAST(job.id AS CHAR) END AS active_job_id,
CASE WHEN job.submission_message_id IS NULL AND job.source_ref LIKE '${REVIEW_SOURCE_REF_PREFIX}%' THEN 1 ELSE 0 END AS active_job_is_review,
${reviewProjection},
(SELECT CAST(MAX(message.id) AS CHAR) FROM ai_messages message WHERE message.chat_id = chat.id) AS latest_message_id
FROM ai_chats chat LEFT JOIN ai_agent_jobs job ON job.id = (SELECT recent.id FROM ai_agent_jobs recent
WHERE recent.chat_id = chat.id AND recent.user_id = chat.created_by AND recent.source = ? ORDER BY recent.id DESC LIMIT 1)
WHERE chat.id = ? AND chat.created_by = ?`, [source, chatId, ownerId]);
return chat;
}
async function readServerAgentChatPage(db, chatId, beforeId) {
const values = beforeId === undefined ? [chatId] : [chatId, beforeId];
const cursorClause = beforeId === undefined ? "" : " AND id < CAST(? AS UNSIGNED)";
// adpanel:agent-history-budget - never fetch whole attachment bodies to decide which messages fit.
const candidates = await db.query(`SELECT CAST(id AS CHAR) AS cursor_id, role, created_at,
OCTET_LENGTH(content) + COALESCE(OCTET_LENGTH(agent_actions), 0) + COALESCE(OCTET_LENGTH(${readableImageSql}), 0) +
COALESCE(OCTET_LENGTH(thinking_content), 0) + COALESCE(OCTET_LENGTH(model), 0) AS stored_bytes
FROM ai_messages WHERE chat_id = ?${cursorClause}
ORDER BY id DESC LIMIT ${CHAT_HISTORY_PAGE_ROWS + 1}`, values);
let size = 0;
const ids = [];
for (const row of candidates.slice(0, CHAT_HISTORY_PAGE_ROWS)) {
size += Number(row.stored_bytes);
if (size > CHAT_HISTORY_PAGE_BYTES) break;
ids.push(row.cursor_id);
}
if (ids.length) {
const messages = await db.query(`SELECT id, role, content, agent_actions, ${readableImageSql} AS image_data, thinking_time_ms, thinking_content, model, created_at
FROM ai_messages WHERE chat_id = ? AND id IN (${ids.map(() => "CAST(? AS UNSIGNED)").join(", ")})
ORDER BY id ASC`, [chatId, ...ids]);
return { messages, nextBeforeId: candidates.length > ids.length ? ids.at(-1) : null };
}
const oversized = candidates[0];
if (!oversized) return { messages: [], nextBeforeId: null };
return {
messages: [{ id: oversized.cursor_id, role: oversized.role, created_at: oversized.created_at, content: "[Message exceeds the transcript size limit]" }],
nextBeforeId: candidates.length > 1 ? oversized.cursor_id : null,
};
}
async function ensureServerAgentChatOwnerSchema(db) {
try {
await db.query("ALTER TABLE ai_chats ADD COLUMN created_by BIGINT UNSIGNED NULL");
} catch (error) {
if (error.code !== "ER_DUP_FIELDNAME") throw error;
}
try {
await db.query("CREATE INDEX idx_ai_chats_owner_updated ON ai_chats (created_by, updated_at)");
} catch (error) {
if (error.code !== "ER_DUP_KEYNAME") throw error;
}
}
async function ensureServerAgentChatActionSchema(db) {
try {
await db.query("ALTER TABLE ai_messages ADD COLUMN agent_actions MEDIUMTEXT NULL");
} catch (error) {
if (error.code !== "ER_DUP_FIELDNAME") throw error;
}
}
async function backfillServerAgentChatOwners(db) {
// adpanel:agent-chat-owner - a current email match cannot prove historical ownership.
return db.query(`UPDATE ai_chats AS chat
JOIN (
SELECT chat_id, MIN(user_id) AS owner_id
FROM ai_agent_jobs GROUP BY chat_id HAVING MIN(user_id) = MAX(user_id)
) AS evidence ON evidence.chat_id = chat.id
JOIN users AS owner ON owner.id = evidence.owner_id
SET chat.created_by = evidence.owner_id, chat.updated_at = chat.updated_at
WHERE chat.created_by IS NULL`);
}
async function createServerAgentChat(db, user, title, connection = null) {
const ownerId = Number(user?.id);
if (!Number.isSafeInteger(ownerId) || ownerId <= 0) throw new TypeError("Invalid Agent chat owner");
const sql = "INSERT INTO ai_chats (created_by, user_email, title) VALUES (?, ?, ?)";
const values = [ownerId, String(user.email || "").trim().toLowerCase(), title];
const result = connection ? (await connection.execute(sql, values))[0] : await db.query(sql, values);
return result.insertId;
}
async function deleteAccountServerAgentChats(connection, accountId) {
await connection.execute("DELETE FROM ai_messages WHERE chat_id IN (SELECT id FROM ai_chats WHERE created_by = ?)", [accountId]);
await connection.execute("DELETE FROM ai_chats WHERE created_by = ?", [accountId]);
}
module.exports = { ensureServerAgentChatOwnerSchema, ensureServerAgentChatActionSchema, backfillServerAgentChatOwners, createServerAgentChat,
deleteAccountServerAgentChats, isValidServerAgentChatCursor, readOwnedServerAgentChat, readServerAgentChatPage,
deriveAiAgentChatTitle, readFirstAgentChatTitle, GENERATED_CHAT_TITLE_LENGTH };
+112
View File
@@ -0,0 +1,112 @@
"use strict";
const { parseAiAgentFileOperations } = require("./server-agent-file-directives");
const { safeJoinUnix, buildFsListPayload, relayFsJson, renderFsListOutcome, renderFsReadOutcome } = require("./node-fs-relay");
const { safeTruncateUtf16 } = require("../utils/safe-truncate");
const { AiAgentJobDeadlineExceeded, assertAiAgentJobDeadline } = require("../AgentWorker/run-deadline");
const { MAX_ACTION_TEXT_BYTES } = require("../AgentWorker/action-proposal");
const { hashAgentFile } = require("../AgentWorker/file-edit");
const MAX_OPERATIONS = 12;
const FILE_DIAGNOSTIC_TIMEOUT_MS = 8000;
const MAX_RESULT_CHARS = 32_000;
function createAgentFileDiagnostics({ resolveRemoteFsContext, fsRelayDeps, env = process.env }) {
const readLimit = Math.max(2000, Math.min(50_000, parseInt(env.AI_AGENT_FILE_READ_MAX_CHARS, 10) || 18_000));
const listLimit = Math.max(20, Math.min(500, parseInt(env.AI_AGENT_FILE_LIST_MAX_ITEMS, 10) || 120));
function summarizeDirectory({ entries, truncated }) {
const lines = entries.slice(0, listLimit).map((entry) => {
const name = String(entry?.name || "").trim();
const directory = entry?.isDirectory === true || entry?.type === "dir" || entry?.type === "directory";
const size = !directory && entry?.size ? ` (${entry.size} bytes)` : "";
return `${directory ? "[dir]" : "[file]"} ${name}${size}`;
});
if (truncated || entries.length > listLimit) lines.push("...[listing truncated]");
return lines.join("\n") || "(empty)";
}
async function executeAiAgentFileOperations({ operations, serverName, serverId, req, structured = false, includeEditVersion = false }) {
const results = [];
const add = (ok, text, code, editVersion) => {
const message = safeTruncateUtf16(text, MAX_RESULT_CHARS);
results.push(structured ? (ok ? { ok, result: message, ...(editVersion && { editVersion }) } : { ok, code, error: message }) : message);
};
const deadline = Date.now() + FILE_DIAGNOSTIC_TIMEOUT_MS;
for (const { action, path: relative } of operations.slice(0, MAX_OPERATIONS)) {
if (typeof relative !== "string" || !relative) {
add(false, "Skipped one file operation because the path was invalid.", "file_path_invalid");
continue;
}
// adpanel:agent-file-diagnostics - neither legacy directives nor native tools may dispatch a mutation here.
if (action !== "list" && action !== "read") {
add(false, `ADPanel Agent cannot change ${relative}. Use the file manager to make changes.`, "file_operation_not_allowed");
continue;
}
const checkDeadline = () => { req.aiAgentChatSignal?.throwIfAborted(); assertAiAgentJobDeadline(req); };
checkDeadline();
try {
const context = await resolveRemoteFsContext(serverName);
if (!(await req.readAiAgentFilePermissions())?.files_read) {
add(false, `No permission to read ${relative}.`, "file_read_denied");
continue;
}
if (!context.remote || (serverId != null && String(context.serverId) !== String(serverId))) {
add(false, `Could not access node files for ${serverName}.`, "file_target_unavailable");
continue;
}
const full = safeJoinUnix(context.baseDir, relative);
checkDeadline();
const remaining = deadline - Date.now();
if (remaining <= 0) {
add(false, `Could not ${action} ${relative}: the file diagnostic deadline was reached.`, "file_node_unavailable");
continue;
}
const listing = action === "list";
const payload = listing ? buildFsListPayload(full, context.serverName) : { path: full, server: context.serverName, encoding: "base64" };
const outcome = await relayFsJson(fsRelayDeps, context.node, `/v1/fs/${action}`, payload, remaining);
checkDeadline();
const response = listing ? renderFsListOutcome(outcome, relative) : renderFsReadOutcome(outcome, relative, { strictText: true });
if (response.status !== 200) {
const [code, detail] = outcome.kind === "not_found" ? ["file_not_found", listing ? "directory not found" : "file not found"]
: outcome.kind === "offline" ? ["file_node_unavailable", "the server node did not respond"]
: outcome.kind === "too_large" ? ["file_response_too_large", response.json.message]
: outcome.kind === "ok" ? ["file_invalid_content", "the server node did not return valid file content"]
: ["file_read_failed", "the server node refused the request"];
add(false, `Could not ${action} ${relative}: ${detail.replace(/\.$/, "")}.`, code);
} else if (listing) {
add(true, `Contents of ${relative}:\n${summarizeDirectory(response.json)}`);
} else if (response.json.binary) {
add(false, `Cannot read ${relative}: binary file (not readable as text).`, "file_not_text");
} else {
const content = response.json.content;
const text = safeTruncateUtf16(content, Math.min(readLimit, MAX_RESULT_CHARS - 2100));
const truncated = text.length < content.length ? "\n...[truncated]" : "";
const editVersion = includeEditVersion && context.nodeId && !truncated && Buffer.byteLength(content) <= MAX_ACTION_TEXT_BYTES
? { sha256: hashAgentFile(content), nodeId: context.nodeId, path: full } : null;
const message = content === "" ? `Read ${relative}: the file exists and is empty (0 bytes).`
: `Read ${relative}:\n\`\`\`\n${text}${truncated}\n\`\`\``;
add(true, message, undefined, editVersion);
}
} catch (error) {
if (error?.status === 403 || error instanceof AiAgentJobDeadlineExceeded || req.aiAgentChatSignal?.aborted) throw error;
add(false, `Could not ${action} ${relative}: file diagnostics failed.`, "file_read_failed");
}
}
if (operations.length > MAX_OPERATIONS) add(false, `Skipped ${operations.length - MAX_OPERATIONS} extra file operation(s) to keep this job bounded.`, "file_operation_limit");
return results;
}
async function postProcessAiAgentResponse({ content, serverName, serverId, req }) {
const { operations, message } = parseAiAgentFileOperations(content);
if (!operations.length) return String(content || "").trim();
const results = await executeAiAgentFileOperations({ operations, serverName, serverId, req });
return [message, ...results].filter(Boolean).join("\n\n") || "Done.";
}
return { executeAiAgentFileOperations, postProcessAiAgentResponse };
}
module.exports = { createAgentFileDiagnostics };
+63
View File
@@ -0,0 +1,63 @@
"use strict";
const FILE_CONTENT_START = "---FILE_CONTENT_START---";
const FILE_CONTENT_END = "---FILE_CONTENT_END---";
function sanitizeAiAgentFilePath(value) {
let rel = String(value || "").replace(/\0/g, "").trim();
if (rel === ".") return rel;
rel = rel.replace(/^["'`]+|["'`]+$/g, "").replace(/[.,!?;:]+$/g, "").trim();
while (rel.startsWith("/")) rel = rel.slice(1);
if (!rel || rel.length > 2048 || /[\r\n]/.test(rel)) return "";
return rel;
}
function parseAiAgentFileOperations(content) {
const lines = String(content || "").split(/\r?\n/);
const operations = [];
const message = [];
const seen = new Set();
let fence = "";
// adpanel:agent-file-directives - quoted examples and file bodies are data, never nested actions.
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index];
const fenceMarker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1] || "";
if (fence || fenceMarker) {
message.push(line);
if (!fence) fence = fenceMarker;
else if (fenceMarker[0] === fence[0] && fenceMarker.length >= fence.length && line.trim() === fenceMarker) fence = "";
continue;
}
const directive = /^FILE_(LIST|READ|MKDIR|DELETE|CREATE|WRITE):([^\s]+)[ \t]*$/i.exec(line);
const action = directive?.[1].toLowerCase();
const writesContent = action === "create" || action === "write";
let body;
if (line === FILE_CONTENT_START || (writesContent && lines[index + 1] === FILE_CONTENT_START)) {
const start = index;
const bodyStart = index + (writesContent ? 2 : 1);
index = bodyStart;
while (index < lines.length && lines[index] !== FILE_CONTENT_END) index += 1;
if (index === lines.length || !writesContent) {
message.push(lines.slice(start, index + 1).join("\n"));
continue;
}
body = lines.slice(bodyStart, index).join("\n");
}
if (!directive || (writesContent && body === undefined)) {
message.push(line);
continue;
}
const filePath = sanitizeAiAgentFilePath(directive[2]);
const key = `${action}:${filePath}`;
if (!filePath || seen.has(key)) continue;
seen.add(key);
operations.push(writesContent ? { action, path: filePath, content: body } : { action, path: filePath });
}
return { operations, message: message.join("\n").trim() };
}
module.exports = { parseAiAgentFileOperations, sanitizeAiAgentFilePath };
+54
View File
@@ -0,0 +1,54 @@
"use strict";
function forbidden(message) {
return Object.assign(new Error(message), { status: 403 });
}
function createServerAgentJobPermissionReader(deps, { job, runner, serverName, serverId, requiredPermission, isSourceCurrent }) {
const { db, findUserById, userCanUseAdpanelAgent, findServer, isServerSuspended, userHasAccessToServer, getEffectivePermsForUserOnServer } = deps;
async function readServerPerms(user, target, expectedId) {
const entry = await findServer(target);
if (!entry || isServerSuspended(entry) || String(entry.id) !== String(expectedId)) {
throw forbidden("The target server is no longer available to this Agent job.");
}
if (!user.admin && !(await userHasAccessToServer(user.email, entry.name))) {
throw forbidden("Server access was revoked for this Agent job.");
}
return getEffectivePermsForUserOnServer(user.email, entry.name);
}
return async function readAgentJobPermissions(target = serverName, targetId = serverId) {
// adpanel:agent-job-live-auth - stored job data cannot stand in for current authority.
const user = await findUserById(job.user_id);
if (!user || user.suspended || !userCanUseAdpanelAgent(user) ||
String(user.id) !== String(runner.id) || user.email !== runner.email ||
user.session_epoch !== runner.session_epoch || Boolean(user.admin) !== Boolean(runner.admin)) {
throw forbidden("The account no longer authorizes this Agent job.");
}
const originPerms = await readServerPerms(user, serverName, serverId);
if (!originPerms || (requiredPermission && originPerms[requiredPermission] !== true)) {
throw forbidden("The permission to run this Agent job was revoked.");
}
const perms = target === serverName && String(targetId) === String(serverId)
? originPerms
: await readServerPerms(user, target, targetId);
const active = job.claim_token
? await db.query(`SELECT 1 FROM ai_agent_jobs job JOIN ai_agent_worker_state state ON state.id = 1
WHERE job.id = ? AND job.user_id = ? AND job.status = 'running' AND job.claim_token = ?
AND state.enabled = TRUE AND job.feature_generation = state.generation LIMIT 1`, [job.id, job.user_id, job.claim_token])
: await db.query(
"SELECT 1 FROM ai_agent_jobs WHERE id = ? AND user_id = ? AND status = 'running' AND started_at = ? LIMIT 1",
[job.id, job.user_id, job.started_at]
);
if (!perms || !active?.[0]) throw forbidden("This Agent job is no longer active.");
// adpanel:agent-planner-live-source - editing, completing or removing an item revokes its running prompt.
if (isSourceCurrent && !(await isSourceCurrent())) {
throw forbidden("The Planner prompt changed or is no longer active.");
}
return perms;
};
}
module.exports = { createServerAgentJobPermissionReader };
+62
View File
@@ -0,0 +1,62 @@
"use strict";
const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
class AiProviderError extends Error {
constructor(message, { status, failureCode, responseData, cause } = {}) {
super(message || "AI request failed.", { cause });
this.name = "AiProviderError";
this.status = status;
this.failureCode = failureCode;
this.responseData = responseData;
}
}
function responseTooLarge() {
return new AiProviderError("AI provider response is too large", { failureCode: "agent_provider_response_too_large" });
}
async function proxyAiRequest(url, options, timeoutMs = 60000) {
// adpanel:agent-provider-budget - headers, body and decompressed bytes share one bounded exchange.
const timeoutSignal = AbortSignal.timeout(timeoutMs);
const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
try {
const response = await fetch(url, {
method: options.method || "POST",
headers: options.headers,
body: options.body,
redirect: "manual",
signal,
});
if (Number(response.headers.get("content-length")) > MAX_RESPONSE_BYTES) {
await response.body?.cancel();
throw responseTooLarge();
}
const chunks = [];
let size = 0;
if (response.body) {
for await (const chunk of response.body) {
size += chunk.byteLength;
if (size > MAX_RESPONSE_BYTES) throw responseTooLarge();
chunks.push(chunk);
}
}
signal.throwIfAborted();
const raw = Buffer.concat(chunks, size).toString("utf8");
let data;
try {
data = JSON.parse(raw);
} catch {
data = { raw };
}
return { status: response.status, data, headers: Object.fromEntries(response.headers) };
} catch (error) {
options.signal?.throwIfAborted();
if (timeoutSignal.aborted) throw new AiProviderError("Request timeout", { failureCode: "agent_provider_timeout", cause: error });
if (error instanceof AiProviderError) throw error;
throw new AiProviderError("Could not connect to the AI provider", { failureCode: "agent_provider_unreachable", cause: error });
}
}
module.exports = { AiProviderError, proxyAiRequest };
+70
View File
@@ -0,0 +1,70 @@
"use strict";
const BASE_ACTIVE_CAPACITY = 200;
const SERVER_AGENT_MAX_CONCURRENCY = 500;
const ACCOUNTS_PER_STEP = 10;
const SLOTS_PER_STEP = 5;
// adpanel:agent-rollback - old workers only match feature_generation, which consented jobs get on claim.
const AGENT_JOB_GENERATION_SQL = `((auto_approve_file_edits = FALSE AND feature_generation = ?)
OR (auto_approve_file_edits = TRUE AND auto_file_edit_generation = ?
AND ((status = 'queued' AND feature_generation IS NULL)
OR (status = 'running' AND feature_generation = auto_file_edit_generation))))`;
async function assertServerAgentQueueCapacity(connection, { accountId, maxPending, maxPendingPerAccount, source }) {
const limit = Math.max(1, Math.min(5000, Math.trunc(maxPending)));
// A locking read sees committed rows even if the outer Planner transaction has an older snapshot.
const [rows] = await connection.execute(`SELECT user_id, source FROM ai_agent_jobs
WHERE status IN ('queued','running') LIMIT ${limit} FOR UPDATE`);
const accountPending = rows.filter((row) => String(row.user_id) === String(accountId)).length;
const background = rows.filter((row) => row.source !== "live_chat").length;
if (rows.length >= limit || (source !== "live_chat" && background >= Math.max(1, Math.floor(limit * 0.35)))) {
throw Object.assign(new Error("ADPanel Agent queue is full. Please try again shortly."), { status: 503 });
}
if (accountPending >= maxPendingPerAccount) {
throw Object.assign(new Error("ADPanel Agent per-user queue limit reached. Please wait for your queued or running jobs to finish before queueing more."), { status: 503 });
}
}
function createServerAgentJobPump({ query, canPump, runJob, onJobError, onJobSettled, maxActive = SERVER_AGENT_MAX_CONCURRENCY, lane, generation }) {
const activeJobs = new Set();
let pumping = false;
return async function pumpAiAgentJobs() {
if (pumping || activeJobs.size >= maxActive || !canPump()) return;
pumping = true;
try {
// adpanel:agent-active-slots - count local reservations before their claims become visible in the database.
const reserved = [...activeJobs];
const unreserved = reserved.length ? ` AND id NOT IN (${reserved.map(() => "?").join(", ")})` : "";
const scope = lane === "live" ? " AND feature_generation = ? AND source = 'live_chat'"
: lane === "background" ? ` AND ${AGENT_JOB_GENERATION_SQL} AND source <> 'live_chat'` : "";
const params = lane === "background" ? [...reserved, generation, generation] : scope ? [...reserved, generation] : reserved;
const [stats] = await query(`SELECT COUNT(DISTINCT CASE WHEN status = 'queued' THEN user_id END) AS waiting_accounts,
COUNT(CASE WHEN status = 'running' THEN 1 END) AS running_count
FROM ai_agent_jobs WHERE status IN ('queued','running')${unreserved}${scope}`, params);
const waitingAccounts = Number(stats.waiting_accounts);
const limit = Math.min(maxActive, BASE_ACTIVE_CAPACITY + Math.floor(waitingAccounts / ACCOUNTS_PER_STEP) * SLOTS_PER_STEP);
const slots = limit - reserved.length - Number(stats.running_count);
if (!waitingAccounts || !(slots > 0) || !canPump()) return;
const accountSlots = scope ? ` AND (SELECT COUNT(*) FROM ai_agent_jobs active
WHERE active.user_id = ai_agent_jobs.user_id AND active.status = 'running') < 2` : "";
const rows = await query(`SELECT id FROM ai_agent_jobs WHERE status = 'queued'${unreserved}${scope}${accountSlots}
ORDER BY created_at ASC, id ASC LIMIT ${slots}`, params);
if (!canPump()) return;
for (const { id } of rows) {
activeJobs.add(id);
runJob(id).catch((error) => onJobError(id, error)).finally(() => {
activeJobs.delete(id);
onJobSettled();
});
}
} finally {
pumping = false;
}
};
}
module.exports = { AGENT_JOB_GENERATION_SQL, SERVER_AGENT_MAX_CONCURRENCY, assertServerAgentQueueCapacity, createServerAgentJobPump };
+83
View File
@@ -0,0 +1,83 @@
"use strict";
const { randomBytes } = require("node:crypto");
const { posix } = require("node:path");
const { nodeConnectionState } = require("./node-http");
const ARCHIVE_EXTENSIONS = [".zip", ".rar", ".7z", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2"];
function archiveExtension(url) {
try {
const parsed = new URL(url);
if (!["http:", "https:"].includes(parsed.protocol)) return null;
return ARCHIVE_EXTENSIONS.find(extension => parsed.pathname.toLowerCase().endsWith(extension)) || null;
} catch {
return null;
}
}
function isValidArchiveUrl(url) {
return archiveExtension(url) !== null;
}
function createDeferredServerImport(deps) {
return async function runDeferredServerImport(node, serverName, importUrl, rowId) {
const extension = archiveExtension(importUrl);
if (!extension || !Number.isSafeInteger(rowId) || rowId <= 0) {
console.error(`[server-import] "${serverName}": archive type or committed server identity unavailable; import skipped`);
return;
}
try {
const ready = await deps.waitForServerReady(node, serverName, {
timeoutMs: 45 * 60 * 1000,
intervalMs: 3000,
check: info => info.setupStatus === "failed" ? false
: (info.isInstalling || info.status === "installing" || (info.setupStatus && info.setupStatus !== "ready")) ? null : info,
});
if (!ready) {
console.error(`[server-import] "${serverName}": node did not finish setup successfully; import skipped`);
return;
}
// adpanel:create-import-identity - never apply a deferred archive to a replacement, suspended or moving server.
const completed = await deps.withReinstallSuspensionLock(serverName, false, async () => {
const entry = await deps.findServer(serverName);
if (entry?.name !== serverName || entry.rowId !== rowId || deps.isServerSuspended(entry) || deps.isGuardedServerStatus(entry.status)) return false;
const ctx = await deps.resolveRemoteFsContext(serverName);
if (!ctx.remote || ctx.node?.id !== node.id || ctx.node.uuid !== node.uuid || nodeConnectionState(ctx.node) !== nodeConnectionState(node)) return false;
const targetDir = deps.safeJoinUnix(ctx.baseDir, "");
const filename = `adpanel-import-${randomBytes(16).toString("hex")}${extension}`;
const archivePath = posix.join(targetDir, filename);
const maxUploadMb = ctx.node.max_upload_mb || 10240;
const maxUploadBytes = maxUploadMb * 1024 * 1024;
const fetched = await deps.ssrfPipedHttpGet(importUrl, { maxBytes: Math.min(maxUploadBytes, deps.maxBytes) });
// adpanel:create-import-staging - an archive's public filename must not overwrite and then delete a server file.
const upload = await deps.streamPanelUploadToNode(ctx.node, fetched.stream, filename, targetDir, maxUploadBytes, maxUploadMb, ctx.serverName, true);
if (upload.status !== 200 || upload.json?.ok !== true) throw new Error(`archive upload failed (HTTP ${upload.status})`);
const target = { path: archivePath, server: ctx.serverName };
try {
const extracted = await deps.nodeFsPost(ctx.node, "/v1/fs/extract", { ...target, overwrite: true }, 630_000);
if (extracted.status !== 200 || extracted.json?.ok !== true) throw new Error(`extraction failed (HTTP ${extracted.status})`);
} finally {
try {
const removed = await deps.nodeFsPost(ctx.node, "/v1/fs/delete", { ...target, isDir: false }, 120_000);
if (removed.status !== 200 || removed.json?.ok !== true) console.warn(`[server-import] "${serverName}": staging cleanup failed (HTTP ${removed.status})`);
} catch (error) {
console.warn(`[server-import] "${serverName}": staging cleanup failed:`, error?.message || error);
}
}
if (!ready.eulaRequired) await deps.startServerOnNode(ctx.node, ctx.serverName, entry.port);
return true;
});
if (completed) console.log(`[server-import] "${serverName}": archive import completed`);
else console.warn(`[server-import] "${serverName}": server changed or is busy; import skipped`);
} catch (error) {
console.error(`[server-import] "${serverName}": deferred import failed:`, error?.message || error);
}
};
}
module.exports = { createDeferredServerImport, isValidArchiveUrl };
File diff suppressed because it is too large. Load diff
+132
View File
@@ -0,0 +1,132 @@
"use strict";
const { destroyStreams } = require("../utils/stream-lifecycle");
function createServerTransferStreamer(deps) {
async function streamExportToImport({ sourceNode, destNode, serverName, transferId, targetDiskId, onProgress, onImportRequest }) {
if (typeof transferId !== "string" || !/^[a-f0-9]{32}$/.test(transferId)) throw new Error("Missing transfer identity");
const sourceBase = deps.buildNodeBaseUrl(sourceNode.address, sourceNode.api_port || 8080, sourceNode.ssl_enabled, deps.nodeUnderCloudflare(sourceNode));
const destBase = deps.buildNodeBaseUrl(destNode.address, destNode.api_port || 8080, destNode.ssl_enabled, deps.nodeUnderCloudflare(destNode));
if (!sourceBase) throw new Error("invalid source node address");
if (!destBase) throw new Error("invalid destination node address");
const srcUrl = `${sourceBase}/v1/servers/${encodeURIComponent(serverName)}/export?${new URLSearchParams({ transferId })}`;
const params = new URLSearchParams({ transferId });
if (typeof targetDiskId === "string" && targetDiskId.trim() && targetDiskId.trim() !== "primary") params.set("diskId", targetDiskId.trim());
const dstUrl = `${destBase}/v1/servers/${encodeURIComponent(serverName)}/import-tar?${params}`;
const srcHeaders = {
Authorization: `Bearer ${sourceNode.token}`,
"X-Node-Token": sourceNode.token || "",
"X-Node-Token-Id": sourceNode.token_id || "",
};
const dstHeaders = {
Authorization: `Bearer ${destNode.token}`,
"X-Node-Token": destNode.token || "",
"X-Node-Token-Id": destNode.token_id || "",
"Content-Type": "application/x-tar",
};
let srcReq = null;
let srcRes = null;
let dstReqRef = null;
let dstRes = null;
let failure = null;
let completed = false;
let sourceEnded = false;
let rejectFailure;
const failed = new Promise((resolve, reject) => { rejectFailure = reject; });
failed.catch(() => {});
const fail = (error) => {
if (failure || completed) return;
failure = error;
// adpanel:transfer-coupled-cancel - an import failure owns both ends;
// no export may keep draining or writing after the job has failed.
destroyStreams(srcRes, srcReq, dstRes, dstReqRef);
rejectFailure(error);
};
function readReply(response) {
return new Promise((resolve, reject) => {
const chunks = [];
let total = 0;
let ended = false;
response.on("error", reject);
response.on("aborted", () => reject(new Error("Transfer response aborted")));
response.on("close", () => { if (!ended) reject(new Error("Transfer response closed before end")); });
if (response.destroyed && !response.readableEnded) {
reject(response.errored || new Error("Transfer response closed before end"));
return;
}
response.on("data", (chunk) => {
if (failure || total >= 64 * 1024) return;
const accepted = chunk.subarray(0, 64 * 1024 - total);
chunks.push(accepted);
total += accepted.length;
});
response.on("end", () => { ended = true; resolve(Buffer.concat(chunks).toString("utf8")); });
});
}
try {
({ req: srcReq, res: srcRes } = await deps.httpStreamRequest(srcUrl, { method: "GET", headers: srcHeaders, timeoutMs: 10 * 60 * 1000 }));
srcRes.on("error", fail);
srcRes.on("aborted", () => fail(new Error("Export response aborted")));
srcRes.on("close", () => { if (!sourceEnded) fail(new Error("Export response closed before end")); });
srcRes.once("end", () => { sourceEnded = true; });
if (srcRes.destroyed && !srcRes.readableEnded) throw srcRes.errored || new Error("Export response closed before end");
if (srcRes.statusCode !== 200) {
const body = await Promise.race([readReply(srcRes), failed]);
throw new Error(`export failed (${srcRes.statusCode}): ${body.slice(0, 500) || "no body"}`);
}
if (srcRes.headers["x-adpanel-transfer-id"] !== transferId) {
throw new Error("Source daemon does not confirm protected exports. Update it before retrying.");
}
const totalBytesHeader = srcRes.headers["x-adpanel-server-bytes"] || srcRes.headers["content-length"];
const totalBytes = totalBytesHeader ? Number(totalBytesHeader) : 0;
let transferred = 0;
srcRes.on("data", (chunk) => {
if (failure) return;
transferred += chunk.length;
if (typeof onProgress === "function") {
const percent = totalBytes > 0 ? Math.min(100, Math.floor((transferred / totalBytes) * 100)) : null;
try { onProgress({ transferred, totalBytes, percent }); } catch (error) { fail(error); }
}
});
srcRes.once("end", () => {
if (failure) return;
try {
if (typeof onProgress === "function") onProgress({ transferred, totalBytes, percent: 100 });
} catch { }
});
const destination = deps.httpStreamRequest(dstUrl, {
method: "PUT", headers: dstHeaders, bodyStream: srcRes, timeoutMs: 30 * 60 * 1000,
onRequest: (req) => { dstReqRef = req; onImportRequest?.(); },
});
destination.then((result) => {
if (failure) destroyStreams(result.res, result.req);
}, fail);
({ res: dstRes } = await Promise.race([destination, failed]));
const dstBody = await Promise.race([readReply(dstRes), failed]);
if (dstRes.statusCode === 404 || dstRes.statusCode === 405) {
throw new Error("Destination daemon does not support protected transfers. Update it before retrying.");
}
if (dstRes.statusCode !== 200) {
throw new Error(`import failed (${dstRes.statusCode}): ${dstBody.slice(0, 500) || "no body"}`);
}
let parsed = null;
try { parsed = JSON.parse(dstBody); } catch { }
if (parsed?.ok !== true) throw new Error(parsed?.error || "Destination did not confirm the import");
if (parsed.transferId !== transferId) throw new Error("Destination did not confirm this transfer");
if (!sourceEnded) throw new Error("import completed before export end");
completed = true;
} catch (error) {
fail(error);
throw failure || error;
}
}
return streamExportToImport;
}
module.exports = { createServerTransferStreamer };
+170
View File
@@ -0,0 +1,170 @@
"use strict";
const { nodeConnectionState } = require("./node-http");
const { resolveServerCreateBindAddress, renderServerCreateOutcome, scanNodeStorageCollisions } = require("./server-create");
const { serverEntryAssignedHostPorts } = require("../utils/server-host-ports");
function computeTransferEffectiveResources(serverResources, sourceNode, destNode) {
const inRes = (serverResources && typeof serverResources === "object") ? serverResources : {};
const out = { ...inRes };
const srcRam = Number(sourceNode?.ram_mb || 0);
const dstRam = Number(destNode?.ram_mb || 0);
const srcDisk = Number(sourceNode?.disk_gb || 0);
const dstDisk = Number(destNode?.disk_gb || 0);
const srcCores = Number(sourceNode?.buildConfig?.cpu_cores || sourceNode?.buildConfig?.cpuCores || 0);
const dstCores = Number(destNode?.buildConfig?.cpu_cores || destNode?.buildConfig?.cpuCores || 0);
const coerceInt = (value) => {
const number = Number(value);
return Number.isFinite(number) ? Math.trunc(number) : null;
};
const coerceFloat = (value) => {
const number = Number(value);
return Number.isFinite(number) ? number : null;
};
const isUnlimitedOrNodeMaxInt = (value, srcMax) => {
if (value == null) return true;
const number = coerceInt(value);
if (number == null || number <= 0) return true;
return srcMax > 0 && number === Math.trunc(srcMax);
};
const isUnlimitedOrNodeMaxFloat = (value, srcMax) => {
if (value == null) return true;
const number = coerceFloat(value);
if (number == null || number <= 0) return true;
return srcMax > 0 && Math.abs(number - srcMax) < 0.0001;
};
if (dstRam > 0) {
const current = coerceInt(inRes.ramMb);
if (isUnlimitedOrNodeMaxInt(inRes.ramMb, srcRam)) out.ramMb = Math.trunc(dstRam);
else if (current != null && current > Math.trunc(dstRam)) out.ramMb = Math.trunc(dstRam);
}
const storageField = inRes.storageMb != null ? "storageMb" : "storageGb";
const storageSrcMax = storageField === "storageMb" ? srcDisk * 1024 : srcDisk;
const storageDstMax = storageField === "storageMb" ? dstDisk * 1024 : dstDisk;
if (storageDstMax > 0) {
const current = coerceInt(inRes[storageField]);
if (isUnlimitedOrNodeMaxInt(inRes[storageField], storageSrcMax)) out[storageField] = Math.trunc(storageDstMax);
else if (current != null && current > Math.trunc(storageDstMax)) out[storageField] = Math.trunc(storageDstMax);
}
if (dstCores > 0) {
const current = coerceFloat(inRes.cpuCores);
if (isUnlimitedOrNodeMaxFloat(inRes.cpuCores, srcCores)) out.cpuCores = dstCores;
else if (current != null && current > dstCores) out.cpuCores = dstCores;
}
return out;
}
async function checkTransferDestinationPorts({ checkDestinationNodePort, loadServersIndexIncludingDeleting }, node, entry) {
const ports = serverEntryAssignedHostPorts({ ...entry, runtime: null });
const assignedEntries = ports.length ? await loadServersIndexIncludingDeleting(node) : [];
const allocations = [];
const deadline = Date.now() + 20_000;
const runtime = entry.runtime || entry.docker || null;
const minecraft = String(entry.type || entry.template || "").toLowerCase() === "minecraft";
const defaultProtocols = minecraft || [runtime?.providerId, runtime?.id].includes("minecraft") ? ["tcp", "udp"] : ["tcp"];
for (const port of ports) {
const outcome = await checkDestinationNodePort(node, port, {
excludeName: entry.name,
docker: runtime,
assignedEntries,
checkLive: true,
deadline,
containerPort: minecraft && port === Number(entry.port) ? 25565 : port,
defaultProtocols,
});
if (!outcome.ok) return outcome;
const binding = resolveServerCreateBindAddress(node, port);
if (binding.error) {
const { status, body } = renderServerCreateOutcome(binding.error, "panel");
return { ok: false, statusCode: status, error: body.error };
}
allocations.push({ port, ip: binding.address });
}
return { ok: true, allocations };
}
async function checkTransferAdmission(deps, sourceNode, destNode, entry) {
// adpanel:transfer-storage-ownership - both the source cleanup and destination import must have an unambiguous storage owner.
for (const [node, excludeName] of [[sourceNode, entry.name], [destNode, ""]]) {
const conflict = await scanNodeStorageCollisions(deps, node, entry.name, { uuidFallbackId: true, excludeName });
if (conflict) {
return { ok: false, statusCode: 409, error: `Transfer refused: server storage on ${node === sourceNode ? "the source" : "the destination"} is also claimed by "${conflict.data.collidingName}".` };
}
}
return checkTransferDestinationPorts(deps, destNode, entry);
}
async function finishTransferSource(deps, node, name, transferId, { cleanup = false } = {}) {
if (typeof transferId !== "string" || !/^[a-f0-9]{32}$/.test(transferId)) throw new Error("Missing transfer identity");
const baseUrl = deps.buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, deps.nodeUnderCloudflare(node));
if (!baseUrl) throw new Error("invalid source node address");
const params = new URLSearchParams({ transferId, ...(cleanup ? { cleanup: "true" } : {}) });
const response = await deps.httpRequestJson(
`${baseUrl}/v1/servers/${encodeURIComponent(name)}/export?${params}`,
"DELETE", deps.nodeAuthHeadersFor(node, true), null, 30_000
);
if (!cleanup && response.status === 404) return;
if (response.status !== 200 || response.json?.ok !== true || response.json.transferId !== transferId) {
throw new Error(response.json?.error || `source transfer could not be settled (${response.status})`);
}
}
async function finalizeTransferDestination(deps, { sourceNode, destNode, serverEntry, sourceMeta, defaultBackupsMax }) {
// adpanel:transfer-port-claim - pool removal and competing claims must wait until the destination assignment is durable.
return deps.withKeyedLock(`node-ports:${destNode.id}`, async () => {
const current = await deps.findNodeByIdOrName(destNode.id);
if (!current || current.id !== destNode.id) throw new Error("destination node no longer exists");
if (nodeConnectionState(current) !== nodeConnectionState(destNode)) {
throw new Error("destination node connection changed while transferring");
}
const resources = computeTransferEffectiveResources(serverEntry.resources, sourceNode, current);
if (resources.backupsMax == null) resources.backupsMax = defaultBackupsMax;
const primaryPort = deps.validatePort(serverEntry.port) || deps.validatePort(sourceMeta?.hostPort);
const portless = sourceMeta?.runtime != null
&& ["python", "nodejs", "discord-bot", "runtime"].includes(String(sourceMeta.type).toLowerCase())
&& (sourceMeta.hostPort == null || sourceMeta.hostPort === 0 || sourceMeta.hostPort === "0");
if (!primaryPort && !portless) throw new Error("cannot verify the source server's main port");
const additionalPorts = Array.isArray(resources.ports) ? resources.ports : sourceMeta?.resources?.ports;
if (!sourceMeta && !Array.isArray(additionalPorts)) throw new Error("cannot verify the source server's additional ports");
resources.ports = Array.isArray(additionalPorts) ? additionalPorts.map(deps.validatePort) : [];
if (resources.ports.includes(null)) throw new Error("the source server has an invalid additional port");
const outcome = await checkTransferDestinationPorts(deps, current, {
...serverEntry, type: sourceMeta?.type, runtime: sourceMeta?.runtime || serverEntry.runtime, port: primaryPort, resources,
});
if (!outcome.ok) throw new Error(outcome.error);
const primaryAddress = outcome.allocations.find(({ port }) => port === primaryPort)?.ip || current.address;
resources.portAllocations = outcome.allocations;
const baseUrl = deps.buildNodeBaseUrl(current.address, current.api_port || 8080, current.ssl_enabled, deps.nodeUnderCloudflare(current));
if (!baseUrl) throw new Error("invalid destination node address");
const patch = await deps.httpRequestJson(
`${baseUrl}/v1/servers/${encodeURIComponent(serverEntry.name)}/resources`,
"PATCH", deps.nodeAuthHeadersFor(current, true), {
resources, ...(primaryPort ? { mainPort: primaryPort, bind_ip: primaryAddress, ip: primaryAddress } : {}),
}, 30_000
);
if (patch.status !== 200 || !patch.json?.ok) {
throw new Error(patch.json?.error || patch.json?.detail || `failed to apply resources (${patch.status})`);
}
await deps.startServerOnNode(current, serverEntry.name, primaryPort);
const status = "online";
const saved = await deps.db.query(
"UPDATE servers SET node_id = ?, ip = ?, port = ?, resources = ?, status = ? WHERE id = ? AND name = ? AND node_id = ? AND status = 'transferring' AND suspended = 0",
[current.id, primaryAddress || null, primaryPort || null, JSON.stringify(resources), status, serverEntry.rowId, serverEntry.name, serverEntry.nodeId]
);
if (saved?.affectedRows !== 1) throw new Error("transfer assignment is no longer pending");
return { node: current, status };
});
}
module.exports = { checkTransferAdmission, finalizeTransferDestination, finishTransferSource };
+55
View File
@@ -0,0 +1,55 @@
"use strict";
const { createAccountOperationLimiter } = require("../utils/login-throttle");
// adpanel:settings-operation-budgets - authenticated work remains bounded
// across IP rotation and session churn, independently of the global toggle.
const SETTINGS_OPERATION_POLICIES = Object.freeze({
serverAgentChatRateLimiter: { prefix: "agent-chat:", windowMs: 5 * 60 * 1000, sessionMax: 12, code: "agent-chat-rate-limit", error: "Too many Agent messages. Please wait a few minutes and try again." },
serverAgentCancelRateLimiter: { prefix: "agent-cancel:", windowMs: 60 * 1000, sessionMax: 20, code: "agent-cancel-rate-limit", error: "Too many Agent cancellation requests." },
serverAgentModelRateLimiter: { prefix: "agent-model:", windowMs: 5 * 60 * 1000, sessionMax: 18, code: "agent-model-rate-limit", error: "Too many Agent model requests. Please wait a few minutes and try again." },
serverAgentHistoryReadRateLimiter: { prefix: "agent-history-read:", windowMs: 60 * 1000, sessionMax: 20, code: "agent-history-read-rate-limit", error: "Too many Agent history requests. Please wait a minute and try again." },
serverAgentHistoryWriteRateLimiter: { prefix: "agent-history-write:", windowMs: 5 * 60 * 1000, sessionMax: 40, code: "agent-history-write-rate-limit", error: "Too many Agent history changes. Please wait a few minutes and try again." },
recoveryRateLimiter: { prefix: "recovery:", windowMs: 15 * 60 * 1000, sessionMax: 5, code: "recovery-rate-limit", error: "Too many recovery attempts. Please wait 15 minutes before trying again." },
serverReinstallRateLimiter: { prefix: "server-reinstall:", windowMs: 10 * 60 * 1000, sessionMax: 5, code: "reinstall-rate-limit", error: "Too many reinstall attempts. Please wait 10 minutes and try again." },
serverTemplateChangeRateLimiter: { prefix: "template-change:", windowMs: 10 * 60 * 1000, sessionMax: 5, code: "template-change-rate-limit", error: "Too many template change attempts. Please wait 10 minutes and try again." },
serverCreateRateLimiter: { prefix: "server-create:", windowMs: 10 * 60 * 1000, sessionMax: 10, code: "create-rate-limit", error: "Too many server creation attempts. Please wait 10 minutes and try again." },
serverTransferRateLimiter: { prefix: "server-transfer:", windowMs: 10 * 60 * 1000, sessionMax: 5, code: "transfer-rate-limit", error: "Too many transfer attempts. Please wait 10 minutes and try again." },
brandingWriteRateLimiter: { prefix: "branding-write:", windowMs: 15 * 60 * 1000, sessionMax: 20, code: "branding-write-rate-limit", error: "Too many branding updates. Please wait 15 minutes and try again." },
storeApplyRateLimiter: { prefix: "store-apply:", windowMs: 10 * 60 * 1000, sessionMax: 15, code: "store-apply-rate-limit", error: "Too many version installs. Please wait 10 minutes and try again." },
serverPermissionsMintRateLimiter: { prefix: "perms-mint:", windowMs: 5 * 60 * 1000, sessionMax: 60, code: "perm-mint-rate-limit", error: "Too many permission requests. Please wait a few minutes and try again." },
databaseUserWriteRateLimiter: { prefix: "database-user-write:", windowMs: 10 * 60 * 1000, sessionMax: 30, code: "database-user-rate-limit", error: "Too many database account changes. Please wait 10 minutes and try again." },
databaseUserReadRateLimiter: { prefix: "database-user-read:", windowMs: 5 * 60 * 1000, sessionMax: 120, code: "database-user-read-rate-limit", error: "Too many database settings loads. Please wait a few minutes and try again." }
});
function createSettingsRateLimiters({ rateLimit, buildStore, securityLog }) {
return Object.fromEntries(Object.entries(SETTINGS_OPERATION_POLICIES).map(([name, policy]) => [name,
createAccountOperationLimiter({
rateLimit, buildStore, ...policy,
handler: (req, res) => {
securityLog(`${name} exceeded`, req);
const body = { error: policy.error };
if (name !== "recoveryRateLimiter") body.code = policy.code;
if (name === "storeApplyRateLimiter") body.ok = false;
res.status(429).json(body);
}
})
]));
}
function createSettingsDatabaseRateLimitGate({ databaseUserWriteRateLimiter, databaseUserReadRateLimiter }) {
return (req, res, next) => {
const path = String(req.path || "/").replace(/\/$/, "").toLowerCase();
const method = String(req.method || "").toUpperCase();
if ((method === "POST" && /^(?:\/mongodb)?\/users(?:\/[^/]+\/password)?$/.test(path)) ||
(method === "DELETE" && /^(?:\/mongodb)?\/users\/[^/]+$/.test(path))) {
return databaseUserWriteRateLimiter(req, res, next);
}
if (["GET", "HEAD"].includes(method) && ["", "/mongodb/status", "/mongodb/users"].includes(path)) {
return databaseUserReadRateLimiter(req, res, next);
}
return next();
};
}
module.exports = { createSettingsRateLimiters, createSettingsDatabaseRateLimitGate, SETTINGS_OPERATION_POLICIES };
+37
View File
@@ -0,0 +1,37 @@
"use strict";
const totpSecretCrypto = require("../utils/totp-secret-crypto");
async function migratePlaintextTotpSecrets({ db, secretCrypto = totpSecretCrypto, logger = console } = {}) {
if (typeof db?.pool?.query !== "function" || typeof db?.query !== "function") {
throw new TypeError("TOTP migration requires the database query dependencies");
}
let sealedCount = 0;
try {
const [plainRows] = await db.pool.query(
"SELECT id, secret FROM users WHERE secret IS NOT NULL AND secret != ''"
);
for (const row of plainRows || []) {
const stored = String(row.secret || "").trim();
if (!stored || secretCrypto.isTotpSecretEnvelope(stored)) continue;
const sealed = secretCrypto.encryptTotpSecret(stored);
if (!sealed) {
logger.warn("[db] Skipped sealing a users.secret row: SESSION_SECRET is not set or sealing failed");
break;
}
// adpanel:totp-migration-cas - sealing must not reinstate a seed
// revoked or rotated since the read, including during rolling startup.
const result = await db.query(
"UPDATE users SET secret = ? WHERE id = ? AND BINARY secret = BINARY ?",
[sealed, row.id, row.secret]
);
if (result?.affectedRows === 1) sealedCount += 1;
}
if (sealedCount > 0) logger.log(`[db] Sealed ${sealedCount} plaintext TOTP seed row(s) (AES-256-GCM)`);
} catch (err) {
logger.debug("[db] TOTP seed sealing migration note:", err?.message || err);
}
return sealedCount;
}
module.exports = { migratePlaintextTotpSecrets };