Fix: apply .gitignore and remove untracked files
This commit is contained in:
commit
b0bf3b7167
94 files changed
+123744
No files matched your search
@@ -0,0 +1,19 @@
|
||||
module.exports = { makeCssBackground };
|
||||
|
||||
function makeCssBackground(type, value) {
|
||||
if (typeof value !== "string") return null;
|
||||
const v = value.trim();
|
||||
|
||||
if (type === "color") {
|
||||
return /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(v) ? v : null;
|
||||
}
|
||||
|
||||
if (type === "url" || type === "upload" || type === "image") {
|
||||
if (/^https?:\/\//i.test(v)) return `url("${v.replace(/["\\\n\r\f()<>]/g, encodeURIComponent)}")`;
|
||||
if (/^data:image\/(png|jpe?g|webp|gif);base64,[A-Za-z0-9+/=]+$/i.test(v)) return `url("${v}")`;
|
||||
if (/^\/[a-z0-9/_\-.]+$/i.test(v) && !v.includes('..')) return `url("${v}?v=${Date.now()}")`;
|
||||
return null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,580 @@
|
||||
"use strict";
|
||||
|
||||
const MAX_BOT_TOOL_LOOPS = 8;
|
||||
const MAX_PROMPT_SERVER_NAMES = 80;
|
||||
|
||||
const BOT_TOOL_PARAMETER_SCHEMAS = Object.freeze({
|
||||
list_accessible_servers: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
required: [],
|
||||
},
|
||||
inspect_server: {
|
||||
type: "object",
|
||||
properties: {
|
||||
server: {
|
||||
type: "string",
|
||||
description: "The accessible server name, display name, alias, or the user's raw server wording.",
|
||||
},
|
||||
},
|
||||
required: ["server"],
|
||||
},
|
||||
power_server: {
|
||||
type: "object",
|
||||
properties: {
|
||||
server: {
|
||||
type: "string",
|
||||
description: "The accessible server name, display name, alias, or the user's raw server wording.",
|
||||
},
|
||||
action: {
|
||||
type: "string",
|
||||
enum: ["start", "stop", "restart", "kill"],
|
||||
description: "The power action to run.",
|
||||
},
|
||||
},
|
||||
required: ["server", "action"],
|
||||
},
|
||||
query_console: {
|
||||
type: "object",
|
||||
properties: {
|
||||
server: {
|
||||
type: "string",
|
||||
description: "The accessible server name, display name, alias, or the user's raw server wording.",
|
||||
},
|
||||
question: {
|
||||
type: "string",
|
||||
description: "Optional focus question about the console output.",
|
||||
},
|
||||
limit: {
|
||||
type: "number",
|
||||
description: "Optional number of recent console lines to inspect, capped at 100.",
|
||||
},
|
||||
},
|
||||
required: ["server"],
|
||||
},
|
||||
send_console_command: {
|
||||
type: "object",
|
||||
properties: {
|
||||
server: {
|
||||
type: "string",
|
||||
description: "The accessible server name, display name, alias, or the user's raw server wording.",
|
||||
},
|
||||
command: {
|
||||
type: "string",
|
||||
description: "One real console command to send.",
|
||||
},
|
||||
},
|
||||
required: ["server", "command"],
|
||||
},
|
||||
list_backups: {
|
||||
type: "object",
|
||||
properties: {
|
||||
server: {
|
||||
type: "string",
|
||||
description: "The accessible server name, display name, alias, or the user's raw server wording.",
|
||||
},
|
||||
},
|
||||
required: ["server"],
|
||||
},
|
||||
create_backup: {
|
||||
type: "object",
|
||||
properties: {
|
||||
server: {
|
||||
type: "string",
|
||||
description: "The accessible server name, display name, alias, or the user's raw server wording.",
|
||||
},
|
||||
name: {
|
||||
type: "string",
|
||||
description: "Optional backup name.",
|
||||
},
|
||||
description: {
|
||||
type: "string",
|
||||
description: "Optional backup description.",
|
||||
},
|
||||
},
|
||||
required: ["server"],
|
||||
},
|
||||
restore_backup: {
|
||||
type: "object",
|
||||
properties: {
|
||||
server: {
|
||||
type: "string",
|
||||
description: "The accessible server name, display name, alias, or the user's raw server wording.",
|
||||
},
|
||||
backup: {
|
||||
type: "string",
|
||||
description: "A backup id, name, archive name, or the user's raw backup wording.",
|
||||
},
|
||||
deleteOldFiles: {
|
||||
type: "boolean",
|
||||
description: "Whether old files should be removed before restoring.",
|
||||
},
|
||||
},
|
||||
required: ["server", "backup"],
|
||||
},
|
||||
delete_backup: {
|
||||
type: "object",
|
||||
properties: {
|
||||
server: {
|
||||
type: "string",
|
||||
description: "The accessible server name, display name, alias, or the user's raw server wording.",
|
||||
},
|
||||
backup: {
|
||||
type: "string",
|
||||
description: "A backup id, name, archive name, or the user's raw backup wording.",
|
||||
},
|
||||
},
|
||||
required: ["server", "backup"],
|
||||
},
|
||||
});
|
||||
|
||||
const BOT_TOOL_DEFINITIONS = Object.freeze([
|
||||
{
|
||||
name: "list_accessible_servers",
|
||||
description: "List the servers the current user can access.",
|
||||
args: {},
|
||||
},
|
||||
{
|
||||
name: "inspect_server",
|
||||
description: "Inspect one accessible server, including its status and the current user's permissions.",
|
||||
args: {
|
||||
server: "string",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "power_server",
|
||||
description: "Start, stop, restart, or kill one accessible server when the user has permission.",
|
||||
args: {
|
||||
server: "string",
|
||||
action: "start|stop|restart|kill",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "query_console",
|
||||
description: "Read up to 100 recent console lines from one accessible server and return them for analysis.",
|
||||
args: {
|
||||
server: "string",
|
||||
question: "string?",
|
||||
limit: "number?",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "send_console_command",
|
||||
description: "Send one real console command to one accessible server when the user explicitly asked for it and has console_write permission.",
|
||||
args: {
|
||||
server: "string",
|
||||
command: "string",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "list_backups",
|
||||
description: "List backups for one accessible server when the user has backups_view permission.",
|
||||
args: {
|
||||
server: "string",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "create_backup",
|
||||
description: "Create one backup for an accessible server when the user has backups_create permission.",
|
||||
args: {
|
||||
server: "string",
|
||||
name: "string?",
|
||||
description: "string?",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "restore_backup",
|
||||
description: "Restore one backup on an accessible server when the user has backups_create permission.",
|
||||
args: {
|
||||
server: "string",
|
||||
backup: "string",
|
||||
deleteOldFiles: "boolean?",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "delete_backup",
|
||||
description: "Delete one backup on an accessible server when the user has backups_delete permission.",
|
||||
args: {
|
||||
server: "string",
|
||||
backup: "string",
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const BOT_OPENAI_TOOL_DEFINITIONS = Object.freeze(
|
||||
BOT_TOOL_DEFINITIONS.map((tool) => ({
|
||||
type: "function",
|
||||
function: {
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
parameters: BOT_TOOL_PARAMETER_SCHEMAS[tool.name] || { type: "object", properties: {}, required: [] },
|
||||
},
|
||||
}))
|
||||
);
|
||||
|
||||
const BOT_GOOGLE_FUNCTION_DECLARATIONS = Object.freeze(
|
||||
BOT_TOOL_DEFINITIONS.map((tool) => ({
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
parameters: BOT_TOOL_PARAMETER_SCHEMAS[tool.name] || { type: "object", properties: {}, required: [] },
|
||||
}))
|
||||
);
|
||||
|
||||
function stripDiacritics(value) {
|
||||
return String(value || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "");
|
||||
}
|
||||
|
||||
function normalizeLookupText(value) {
|
||||
return stripDiacritics(value)
|
||||
.toLowerCase()
|
||||
.replace(/[`"'“”‘’()[\]{}<>]/g, " ")
|
||||
.replace(/[_./-]+/g, " ")
|
||||
.replace(/[^a-z0-9 ]+/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
function compactLookupText(value) {
|
||||
return normalizeLookupText(value).replace(/\s+/g, "");
|
||||
}
|
||||
|
||||
function getServerAliases(entry) {
|
||||
const aliases = new Set();
|
||||
for (const value of [
|
||||
entry?.name,
|
||||
entry?.displayName,
|
||||
entry?.bot,
|
||||
entry?.legacy_id,
|
||||
entry?.legacyId,
|
||||
entry?.id,
|
||||
]) {
|
||||
const clean = String(value || "").trim();
|
||||
if (!clean) continue;
|
||||
aliases.add(clean);
|
||||
aliases.add(clean.replace(/[_./-]+/g, " ").replace(/\s+/g, " ").trim());
|
||||
}
|
||||
return Array.from(aliases).filter(Boolean);
|
||||
}
|
||||
|
||||
function getCurrentServerReference(currentServerName, accessibleServers) {
|
||||
const currentName = String(currentServerName || "").trim();
|
||||
if (!currentName) return null;
|
||||
const target = compactLookupText(currentName);
|
||||
return (Array.isArray(accessibleServers) ? accessibleServers : []).find((entry) => {
|
||||
return getServerAliases(entry).some((alias) => compactLookupText(alias) === target);
|
||||
}) || null;
|
||||
}
|
||||
|
||||
function isCurrentServerReference(value) {
|
||||
const normalized = normalizeLookupText(value);
|
||||
if (!normalized) return true;
|
||||
return [
|
||||
"current",
|
||||
"current server",
|
||||
"this",
|
||||
"this server",
|
||||
"server",
|
||||
"serverul",
|
||||
"serverul curent",
|
||||
"serverul asta",
|
||||
"asta",
|
||||
"curent",
|
||||
"it",
|
||||
].includes(normalized);
|
||||
}
|
||||
|
||||
function resolveServerFromAccessibleList(accessibleServers, requestedServer, currentServerName = "") {
|
||||
const entries = Array.isArray(accessibleServers) ? accessibleServers.filter((entry) => entry?.name) : [];
|
||||
if (!entries.length) {
|
||||
return { entry: null, error: "You do not have access to any servers." };
|
||||
}
|
||||
|
||||
const raw = String(requestedServer || "").trim();
|
||||
if (!raw || isCurrentServerReference(raw)) {
|
||||
const currentEntry = getCurrentServerReference(currentServerName, entries);
|
||||
if (currentEntry) return { entry: currentEntry };
|
||||
if (entries.length === 1) return { entry: entries[0] };
|
||||
return {
|
||||
entry: null,
|
||||
error: "The target server is not clear.",
|
||||
candidates: entries.slice(0, 5).map((entry) => entry.displayName || entry.name),
|
||||
};
|
||||
}
|
||||
|
||||
const normalizedRequested = normalizeLookupText(raw);
|
||||
const compactRequested = compactLookupText(raw);
|
||||
const scored = entries.map((entry) => {
|
||||
let best = 0;
|
||||
for (const alias of getServerAliases(entry)) {
|
||||
const normalizedAlias = normalizeLookupText(alias);
|
||||
const compactAlias = compactLookupText(alias);
|
||||
if (!normalizedAlias && !compactAlias) continue;
|
||||
|
||||
if (normalizedRequested && normalizedAlias === normalizedRequested) {
|
||||
best = Math.max(best, 1600 + normalizedAlias.length);
|
||||
}
|
||||
if (compactRequested && compactAlias === compactRequested) {
|
||||
best = Math.max(best, 1550 + compactAlias.length);
|
||||
}
|
||||
if (normalizedRequested && normalizedAlias && normalizedRequested.includes(normalizedAlias)) {
|
||||
best = Math.max(best, 900 + normalizedAlias.length);
|
||||
}
|
||||
if (normalizedRequested && normalizedAlias && normalizedAlias.includes(normalizedRequested)) {
|
||||
best = Math.max(best, 880 + normalizedRequested.length);
|
||||
}
|
||||
if (compactRequested && compactAlias && compactRequested.includes(compactAlias)) {
|
||||
best = Math.max(best, 760 + compactAlias.length);
|
||||
}
|
||||
|
||||
const aliasTokens = normalizedAlias.split(" ").filter(Boolean);
|
||||
const requestedTokens = normalizedRequested.split(" ").filter(Boolean);
|
||||
if (aliasTokens.length && requestedTokens.length) {
|
||||
const overlap = aliasTokens.filter((token) => requestedTokens.includes(token)).length;
|
||||
if (overlap === aliasTokens.length) {
|
||||
best = Math.max(best, 680 + aliasTokens.length * 30);
|
||||
} else if (overlap > 0) {
|
||||
best = Math.max(best, 280 + overlap * 45);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { entry, score: best };
|
||||
}).filter((item) => item.score > 0).sort((left, right) => right.score - left.score);
|
||||
|
||||
if (!scored.length) {
|
||||
return {
|
||||
entry: null,
|
||||
error: "I could not match that server to one you can access.",
|
||||
candidates: entries.slice(0, 5).map((entry) => entry.displayName || entry.name),
|
||||
};
|
||||
}
|
||||
|
||||
const [best, second] = scored;
|
||||
if (second && best.score < second.score + 140) {
|
||||
return {
|
||||
entry: null,
|
||||
error: "That server name is ambiguous.",
|
||||
candidates: scored.slice(0, 5).map((item) => item.entry.displayName || item.entry.name),
|
||||
};
|
||||
}
|
||||
|
||||
return { entry: best.entry };
|
||||
}
|
||||
|
||||
function resolveBackupFromList(backups, requestedBackup) {
|
||||
const items = Array.isArray(backups) ? backups : [];
|
||||
const raw = String(requestedBackup || "").trim();
|
||||
if (!raw) {
|
||||
return { backup: null, error: "A backup identifier is required." };
|
||||
}
|
||||
|
||||
const normalizedRequested = normalizeLookupText(raw);
|
||||
const compactRequested = compactLookupText(raw);
|
||||
const scored = items.map((backup) => {
|
||||
const aliases = [
|
||||
backup?.id,
|
||||
backup?.name,
|
||||
backup?.archive_name,
|
||||
backup?.archiveName,
|
||||
backup?.uuid,
|
||||
].map((value) => String(value || "").trim()).filter(Boolean);
|
||||
|
||||
let best = 0;
|
||||
for (const alias of aliases) {
|
||||
const normalizedAlias = normalizeLookupText(alias);
|
||||
const compactAlias = compactLookupText(alias);
|
||||
if (!normalizedAlias && !compactAlias) continue;
|
||||
|
||||
if (normalizedAlias === normalizedRequested) best = Math.max(best, 1600 + normalizedAlias.length);
|
||||
if (compactAlias === compactRequested) best = Math.max(best, 1550 + compactAlias.length);
|
||||
if (normalizedRequested && normalizedAlias.includes(normalizedRequested)) best = Math.max(best, 900 + normalizedRequested.length);
|
||||
if (normalizedRequested && normalizedRequested.includes(normalizedAlias)) best = Math.max(best, 880 + normalizedAlias.length);
|
||||
if (compactRequested && compactRequested.includes(compactAlias)) best = Math.max(best, 760 + compactAlias.length);
|
||||
}
|
||||
|
||||
return { backup, score: best };
|
||||
}).filter((item) => item.score > 0).sort((left, right) => right.score - left.score);
|
||||
|
||||
if (!scored.length) {
|
||||
return { backup: null, error: "I could not match that backup." };
|
||||
}
|
||||
|
||||
const [best, second] = scored;
|
||||
if (second && best.score < second.score + 120) {
|
||||
return {
|
||||
backup: null,
|
||||
error: "That backup reference is ambiguous.",
|
||||
candidates: scored.slice(0, 5).map((item) => item.backup?.name || item.backup?.id).filter(Boolean),
|
||||
};
|
||||
}
|
||||
|
||||
return { backup: best.backup };
|
||||
}
|
||||
|
||||
function extractJsonObjectFromText(value) {
|
||||
const text = String(value || "").trim();
|
||||
if (!text) return "";
|
||||
|
||||
const taggedMatch = text.match(/<adpanel_tool_plan>\s*([\s\S]*?)\s*<\/adpanel_tool_plan>/i);
|
||||
if (taggedMatch && taggedMatch[1]) {
|
||||
return String(taggedMatch[1]).trim();
|
||||
}
|
||||
|
||||
const fencedMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
||||
if (fencedMatch && fencedMatch[1]) {
|
||||
return String(fencedMatch[1]).trim();
|
||||
}
|
||||
|
||||
const firstBrace = text.indexOf("{");
|
||||
const lastBrace = text.lastIndexOf("}");
|
||||
if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) {
|
||||
return text.slice(firstBrace, lastBrace + 1).trim();
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
function parseBotAssistantToolPlan(rawContent) {
|
||||
const extracted = extractJsonObjectFromText(rawContent);
|
||||
if (!extracted) return null;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(extracted);
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
||||
const toolCalls = Array.isArray(parsed.tool_calls) ? parsed.tool_calls : [];
|
||||
return {
|
||||
reply: String(parsed.reply || "").trim(),
|
||||
tool_calls: toolCalls
|
||||
.filter((item) => item && typeof item === "object")
|
||||
.map((item) => ({
|
||||
name: String(item.name || "").trim(),
|
||||
args: item.args && typeof item.args === "object" && !Array.isArray(item.args) ? item.args : {},
|
||||
}))
|
||||
.filter((item) => item.name),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function formatPermissionSummary(perms) {
|
||||
const entries = [];
|
||||
if (perms?.server_start) entries.push("start");
|
||||
if (perms?.server_stop) entries.push("stop");
|
||||
if (perms?.console_read) entries.push("read console");
|
||||
if (perms?.console_write) entries.push("send console commands");
|
||||
if (perms?.backups_view) entries.push("view backups");
|
||||
if (perms?.backups_create) entries.push("create or restore backups");
|
||||
if (perms?.backups_delete) entries.push("delete backups");
|
||||
return entries.length ? entries.join(", ") : "no elevated server actions";
|
||||
}
|
||||
|
||||
function buildBotAssistantSystemPrompt({ currentServerName = "", accessibleServers = [], currentServerPerms = null }) {
|
||||
const currentServer = String(currentServerName || "").trim();
|
||||
const visibleServerNames = (Array.isArray(accessibleServers) ? accessibleServers : [])
|
||||
.slice(0, MAX_PROMPT_SERVER_NAMES)
|
||||
.map((entry) => entry?.displayName || entry?.name)
|
||||
.filter(Boolean);
|
||||
const currentPermSummary = formatPermissionSummary(currentServerPerms);
|
||||
|
||||
return [
|
||||
"You are ADPanel Agent inside a server page.",
|
||||
"Always reply in English.",
|
||||
"Keep replies short, natural, and precise.",
|
||||
"Use one short sentence by default.",
|
||||
"Never narrate internal planning, tool selection, or hidden reasoning.",
|
||||
"Never say phrases like 'The user wants', 'I need to', 'I should use', 'Plan', or 'Current page server'.",
|
||||
"You may still use the existing file command format from other system instructions for file tasks.",
|
||||
"For sensitive server actions, use only the native tool plan format below.",
|
||||
"Never use SERVER_START, SERVER_STOP, SERVER_RESTART, or SERVER_KILL text lines.",
|
||||
"When you need a native server action, your entire reply must be one <adpanel_tool_plan> JSON block with no extra text.",
|
||||
'Schema: {"reply":"short queued reply","tool_calls":[{"name":"tool_name","args":{}}]}',
|
||||
"Set tool_calls to an empty array when no native tool is needed.",
|
||||
'Example for current server start: <adpanel_tool_plan>{"reply":"Starting it now.","tool_calls":[{"name":"power_server","args":{"server":"current server","action":"start"}}]}</adpanel_tool_plan>',
|
||||
'Example for status check: <adpanel_tool_plan>{"reply":"Checking it now.","tool_calls":[{"name":"inspect_server","args":{"server":"current server"}}]}</adpanel_tool_plan>',
|
||||
'Example for status plus console check: <adpanel_tool_plan>{"reply":"Checking that now.","tool_calls":[{"name":"inspect_server","args":{"server":"current server"}},{"name":"query_console","args":{"server":"current server","limit":60}}]}</adpanel_tool_plan>',
|
||||
'Example for an explicit console command: <adpanel_tool_plan>{"reply":"Sending it now.","tool_calls":[{"name":"send_console_command","args":{"server":"current server","command":"say hello"}}]}</adpanel_tool_plan>',
|
||||
"Only claim a sensitive action succeeded after the tool result confirms it.",
|
||||
"If you need more than one tool, call multiple tools in the same tool plan or ask for another tool plan after tool results.",
|
||||
"For console analysis, use query_console.",
|
||||
"For real console execution, use send_console_command only when the user explicitly asked to run a command; the backend will deny it unless the user has console_write.",
|
||||
"For backup restore or delete, list backups first when the backup identifier is unclear.",
|
||||
"If the user says this server or current server, use the current page server.",
|
||||
"If the user names a server unclearly, you may pass the raw wording in args.server and the backend will resolve it safely.",
|
||||
`Current page server: ${currentServer || "unknown"}.`,
|
||||
`Current page server permissions: ${currentPermSummary}.`,
|
||||
visibleServerNames.length
|
||||
? `Accessible servers visible to this user: ${visibleServerNames.join(", ")}.`
|
||||
: "No accessible servers were preloaded.",
|
||||
"Allowed native tools:",
|
||||
BOT_TOOL_DEFINITIONS.map((tool) => `${tool.name}: ${tool.description}`).join(" "),
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
function buildBotReplyFromToolResult(toolName, toolResult) {
|
||||
const name = String(toolName || "").trim();
|
||||
const result = toolResult && typeof toolResult === "object" ? toolResult : {};
|
||||
if (result.ok === false) {
|
||||
return String(result.error || result.detail || "That action could not be completed.").trim();
|
||||
}
|
||||
|
||||
switch (name) {
|
||||
case "list_accessible_servers": {
|
||||
const servers = Array.isArray(result.servers) ? result.servers : [];
|
||||
if (!servers.length) return "You do not have access to any servers.";
|
||||
const labels = servers.slice(0, 6).map((entry) => entry.displayName || entry.name).filter(Boolean);
|
||||
return `You can access ${servers.length} server${servers.length === 1 ? "" : "s"}: ${labels.join(", ")}.`;
|
||||
}
|
||||
case "inspect_server":
|
||||
return result.server?.name
|
||||
? `${result.server.displayName || result.server.name} is ${result.server.status || "unknown"}.`
|
||||
: "I checked that server.";
|
||||
case "power_server":
|
||||
if (!(result.server && result.action)) return "Power action sent.";
|
||||
return `Sent the ${result.action} request for ${result.server.displayName || result.server.name}.`;
|
||||
case "query_console":
|
||||
return result.server ? `I checked the recent console output for ${result.server.displayName || result.server.name}.` : "I checked the recent console output.";
|
||||
case "send_console_command":
|
||||
return result.server ? `Sent that command to ${result.server.displayName || result.server.name}.` : "Sent that command.";
|
||||
case "list_backups":
|
||||
return result.server
|
||||
? `I found ${Number(result.total || 0)} backup${Number(result.total || 0) === 1 ? "" : "s"} for ${result.server.displayName || result.server.name}.`
|
||||
: "I checked the backups.";
|
||||
case "create_backup":
|
||||
return result.server ? `Created a backup for ${result.server.displayName || result.server.name}.` : "Created the backup.";
|
||||
case "restore_backup":
|
||||
return result.server ? `Started restoring that backup on ${result.server.displayName || result.server.name}.` : "Started restoring that backup.";
|
||||
case "delete_backup":
|
||||
return result.server ? `Deleted that backup from ${result.server.displayName || result.server.name}.` : "Deleted that backup.";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function capitalize(value) {
|
||||
const text = String(value || "").trim();
|
||||
return text ? `${text[0].toUpperCase()}${text.slice(1)}` : "";
|
||||
}
|
||||
|
||||
function formatPowerProgressLabel(action) {
|
||||
const normalized = String(action || "").trim().toLowerCase();
|
||||
const labels = {
|
||||
start: "Starting",
|
||||
stop: "Stopping",
|
||||
restart: "Restarting",
|
||||
kill: "Killing",
|
||||
};
|
||||
return labels[normalized] || `${capitalize(normalized)}ing`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
BOT_GOOGLE_FUNCTION_DECLARATIONS,
|
||||
BOT_TOOL_DEFINITIONS,
|
||||
BOT_OPENAI_TOOL_DEFINITIONS,
|
||||
MAX_BOT_TOOL_LOOPS,
|
||||
buildBotAssistantSystemPrompt,
|
||||
buildBotReplyFromToolResult,
|
||||
extractJsonObjectFromText,
|
||||
parseBotAssistantToolPlan,
|
||||
resolveBackupFromList,
|
||||
resolveServerFromAccessibleList,
|
||||
};
|
||||
@@ -0,0 +1,550 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
|
||||
const BRANDING_CONFIG_PATH = path.join(__dirname, "..", "data", "branding.json");
|
||||
|
||||
|
||||
let brandingCache = null;
|
||||
let brandingCacheTime = 0;
|
||||
const CACHE_TTL = 60000;
|
||||
|
||||
|
||||
const DEFAULT_BRANDING = {
|
||||
appName: "ADPanel",
|
||||
logoUrl: null,
|
||||
localLogoPath: null,
|
||||
loginWatermarkUrl: "https://stalwart-pegasus-2c2ca4.netlify.app/watermark.webp",
|
||||
localLoginWatermarkPath: null,
|
||||
loginBackgroundType: "video",
|
||||
loginBackgroundExternalUrl: null,
|
||||
localLoginBackgroundPath: null,
|
||||
loginBackgroundMimeType: "video/webm"
|
||||
};
|
||||
|
||||
|
||||
const ALLOWED_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "ico", "svg"];
|
||||
const ALLOWED_VIDEO_EXTENSIONS = ["webm", "mp4", "ogg", "ogv"];
|
||||
const DEFAULT_LOGIN_BACKGROUND_URL = "/images/bgvid.webm";
|
||||
const PUBLIC_IMAGES_DIR = path.join(__dirname, "..", "public", "images");
|
||||
|
||||
|
||||
const IMAGE_MAGIC_BYTES = {
|
||||
png: [0x89, 0x50, 0x4E, 0x47],
|
||||
jpg: [0xFF, 0xD8, 0xFF],
|
||||
jpeg: [0xFF, 0xD8, 0xFF],
|
||||
webp: [0x52, 0x49, 0x46, 0x46],
|
||||
ico: [0x00, 0x00, 0x01, 0x00],
|
||||
svg: null
|
||||
};
|
||||
|
||||
const VIDEO_MIME_TYPES = {
|
||||
webm: "video/webm",
|
||||
mp4: "video/mp4",
|
||||
ogg: "video/ogg",
|
||||
ogv: "video/ogg"
|
||||
};
|
||||
|
||||
// Prevent path traversal in local asset filenames
|
||||
function safeBasename(p) {
|
||||
if (!p || typeof p !== 'string') return null;
|
||||
const b = path.basename(p);
|
||||
return (b && b !== '.' && b !== '..') ? b : null;
|
||||
}
|
||||
|
||||
function getBrandingAssetVersionSuffix(branding) {
|
||||
const updatedAt = typeof branding?.updatedAt === "string" ? branding.updatedAt.trim() : "";
|
||||
return updatedAt ? `?v=${encodeURIComponent(updatedAt)}` : "";
|
||||
}
|
||||
|
||||
function resolveLocalBrandingAssetUrl(filename, branding) {
|
||||
const safe = safeBasename(filename);
|
||||
if (!safe) return null;
|
||||
|
||||
const assetPath = path.join(PUBLIC_IMAGES_DIR, safe);
|
||||
if (!fs.existsSync(assetPath)) return null;
|
||||
|
||||
return `/images/${safe}${getBrandingAssetVersionSuffix(branding)}`;
|
||||
}
|
||||
|
||||
function resolveLoginWatermarkAssetUrl(branding) {
|
||||
const config = branding && typeof branding === "object" ? branding : loadBrandingConfig();
|
||||
const localUrl = resolveLocalBrandingAssetUrl(config.localLoginWatermarkPath, config);
|
||||
if (localUrl) return localUrl;
|
||||
if (config.loginWatermarkUrl) {
|
||||
return `/branding-media/login-watermark${getBrandingAssetVersionSuffix(config)}`;
|
||||
}
|
||||
return DEFAULT_BRANDING.loginWatermarkUrl;
|
||||
}
|
||||
|
||||
function resolveLoginBackgroundAssetUrl(branding) {
|
||||
const config = branding && typeof branding === "object" ? branding : loadBrandingConfig();
|
||||
const localUrl = resolveLocalBrandingAssetUrl(config.localLoginBackgroundPath, config);
|
||||
if (localUrl) return localUrl;
|
||||
if (config.loginBackgroundExternalUrl) {
|
||||
return `/branding-media/login-background${getBrandingAssetVersionSuffix(config)}`;
|
||||
}
|
||||
return DEFAULT_LOGIN_BACKGROUND_URL;
|
||||
}
|
||||
|
||||
function resolveFaviconAssetUrl(branding) {
|
||||
const config = branding && typeof branding === "object" ? branding : loadBrandingConfig();
|
||||
return `/auth-assets/favicon${getBrandingAssetVersionSuffix(config)}`;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function loadBrandingConfig() {
|
||||
const now = Date.now();
|
||||
|
||||
|
||||
if (brandingCache && (now - brandingCacheTime) < CACHE_TTL) {
|
||||
return brandingCache;
|
||||
}
|
||||
|
||||
try {
|
||||
if (fs.existsSync(BRANDING_CONFIG_PATH)) {
|
||||
const data = fs.readFileSync(BRANDING_CONFIG_PATH, "utf8");
|
||||
const config = JSON.parse(data);
|
||||
|
||||
|
||||
brandingCache = {
|
||||
...DEFAULT_BRANDING,
|
||||
...config
|
||||
};
|
||||
brandingCacheTime = now;
|
||||
return brandingCache;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[branding] Error loading config:", err.message);
|
||||
}
|
||||
|
||||
|
||||
brandingCache = { ...DEFAULT_BRANDING };
|
||||
brandingCacheTime = now;
|
||||
return brandingCache;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function saveBrandingConfig(config) {
|
||||
try {
|
||||
|
||||
const dataDir = path.dirname(BRANDING_CONFIG_PATH);
|
||||
if (!fs.existsSync(dataDir)) {
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
}
|
||||
|
||||
|
||||
const existing = loadBrandingConfig();
|
||||
const newConfig = {
|
||||
...existing,
|
||||
...config,
|
||||
updatedAt: new Date().toISOString()
|
||||
};
|
||||
|
||||
|
||||
const tempPath = BRANDING_CONFIG_PATH + ".tmp";
|
||||
fs.writeFileSync(tempPath, JSON.stringify(newConfig, null, 2), { mode: 0o600 });
|
||||
fs.renameSync(tempPath, BRANDING_CONFIG_PATH);
|
||||
|
||||
|
||||
brandingCache = null;
|
||||
brandingCacheTime = 0;
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error("[branding] Error saving config:", err.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function generateSafeLogoFilename(extension) {
|
||||
const randomId = crypto.randomBytes(8).toString("hex");
|
||||
return `logo-${randomId}.${extension}`;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function validateBase64Image(base64Data) {
|
||||
try {
|
||||
|
||||
let cleanBase64 = base64Data;
|
||||
if (base64Data.includes(",")) {
|
||||
cleanBase64 = base64Data.split(",")[1];
|
||||
}
|
||||
|
||||
|
||||
const buffer = Buffer.from(cleanBase64, "base64");
|
||||
|
||||
|
||||
if (buffer.length < 8) {
|
||||
return { valid: false, error: "Image data too small" };
|
||||
}
|
||||
|
||||
|
||||
if (buffer.length > 5 * 1024 * 1024) {
|
||||
return { valid: false, error: "Image too large (max 5MB)" };
|
||||
}
|
||||
|
||||
|
||||
let validType = false;
|
||||
for (const [type, magic] of Object.entries(IMAGE_MAGIC_BYTES)) {
|
||||
if (magic === null) continue;
|
||||
|
||||
let matches = true;
|
||||
for (let i = 0; i < magic.length; i++) {
|
||||
if (buffer[i] !== magic[i]) {
|
||||
matches = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matches) {
|
||||
validType = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!validType) {
|
||||
const text = buffer.toString("utf8", 0, Math.min(100, buffer.length)).toLowerCase();
|
||||
if (text.includes("<svg") || text.includes("<?xml")) {
|
||||
|
||||
const fullText = buffer.toString("utf8").toLowerCase();
|
||||
if (fullText.includes("<script") || fullText.includes("javascript:") || /\bon[a-z]+\s*=/.test(fullText)) {
|
||||
return { valid: false, error: "SVG contains potentially dangerous content" };
|
||||
}
|
||||
validType = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!validType) {
|
||||
return { valid: false, error: "Unrecognized image format" };
|
||||
}
|
||||
|
||||
return { valid: true, data: buffer };
|
||||
} catch (err) {
|
||||
return { valid: false, error: "Failed to decode image data" };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function getValidatedExtension(filename) {
|
||||
if (!filename || typeof filename !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
const parts = filename.toLowerCase().split(".");
|
||||
if (parts.length < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const ext = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
|
||||
|
||||
if (ALLOWED_EXTENSIONS.includes(ext)) {
|
||||
return ext;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function getValidatedVideoExtension(filename) {
|
||||
if (!filename || typeof filename !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parts = filename.toLowerCase().split(".");
|
||||
if (parts.length < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const ext = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
|
||||
if (ALLOWED_VIDEO_EXTENSIONS.includes(ext)) {
|
||||
return ext;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function getMimeTypeForExtension(extension) {
|
||||
if (!extension || typeof extension !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = extension.toLowerCase().replace(/[^a-z0-9]/g, "");
|
||||
if (normalized === "png") return "image/png";
|
||||
if (normalized === "jpg" || normalized === "jpeg") return "image/jpeg";
|
||||
if (normalized === "webp") return "image/webp";
|
||||
if (normalized === "ico") return "image/x-icon";
|
||||
if (normalized === "svg") return "image/svg+xml";
|
||||
return VIDEO_MIME_TYPES[normalized] || null;
|
||||
}
|
||||
|
||||
function getMediaTypeFromFilename(filename) {
|
||||
if (getValidatedExtension(filename)) return "image";
|
||||
if (getValidatedVideoExtension(filename)) return "video";
|
||||
return null;
|
||||
}
|
||||
|
||||
function getMediaTypeFromUrl(url) {
|
||||
if (!url || typeof url !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const pathname = (parsed.pathname || "").toLowerCase();
|
||||
const ext = pathname.includes(".") ? pathname.slice(pathname.lastIndexOf(".") + 1) : "";
|
||||
if (!ext) return null;
|
||||
if (ALLOWED_EXTENSIONS.includes(ext)) return "image";
|
||||
if (ALLOWED_VIDEO_EXTENSIONS.includes(ext)) return "video";
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function getExtensionFromUrl(url) {
|
||||
if (!url || typeof url !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const pathname = (parsed.pathname || "").toLowerCase();
|
||||
if (!pathname.includes(".")) return null;
|
||||
const ext = pathname.slice(pathname.lastIndexOf(".") + 1).replace(/[^a-z0-9]/g, "");
|
||||
if (ALLOWED_EXTENSIONS.includes(ext) || ALLOWED_VIDEO_EXTENSIONS.includes(ext)) {
|
||||
return ext;
|
||||
}
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function validateBase64Video(base64Data, expectedExt) {
|
||||
try {
|
||||
let cleanBase64 = base64Data;
|
||||
let declaredMime = "";
|
||||
if (typeof base64Data === "string" && base64Data.startsWith("data:")) {
|
||||
const match = base64Data.match(/^data:([^;,]+)[;,]/i);
|
||||
declaredMime = match ? String(match[1] || "").toLowerCase() : "";
|
||||
}
|
||||
if (typeof base64Data === "string" && base64Data.includes(",")) {
|
||||
cleanBase64 = base64Data.split(",")[1];
|
||||
}
|
||||
|
||||
const buffer = Buffer.from(cleanBase64, "base64");
|
||||
if (buffer.length < 32) {
|
||||
return { valid: false, error: "Video data too small" };
|
||||
}
|
||||
if (buffer.length > 40 * 1024 * 1024) {
|
||||
return { valid: false, error: "Video too large (max 40MB)" };
|
||||
}
|
||||
|
||||
const ext = String(expectedExt || "").toLowerCase();
|
||||
let valid = false;
|
||||
|
||||
if (ext === "webm") {
|
||||
valid = buffer[0] === 0x1a && buffer[1] === 0x45 && buffer[2] === 0xdf && buffer[3] === 0xa3;
|
||||
} else if (ext === "mp4") {
|
||||
valid = buffer.slice(4, 8).toString("ascii") === "ftyp";
|
||||
} else if (ext === "ogg" || ext === "ogv") {
|
||||
valid = buffer.slice(0, 4).toString("ascii") === "OggS";
|
||||
}
|
||||
|
||||
if (!valid) {
|
||||
return { valid: false, error: "Unrecognized video format" };
|
||||
}
|
||||
|
||||
if (declaredMime && !declaredMime.startsWith("video/")) {
|
||||
return { valid: false, error: "Invalid video MIME type" };
|
||||
}
|
||||
|
||||
return { valid: true, data: buffer };
|
||||
} catch (err) {
|
||||
return { valid: false, error: "Failed to decode video data" };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
function invalidateBrandingCache() {
|
||||
brandingCache = null;
|
||||
brandingCacheTime = 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function sanitizeAppName(appName) {
|
||||
if (!appName || typeof appName !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
const trimmed = appName.trim().slice(0, 50);
|
||||
|
||||
|
||||
|
||||
const sanitized = trimmed.replace(/[^a-zA-Z0-9\s\-_.!]/g, "");
|
||||
|
||||
if (sanitized.length < 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function isPrivateOrReservedHost(hostname) {
|
||||
if (!hostname) return true;
|
||||
const h = hostname.toLowerCase();
|
||||
|
||||
if (h === "localhost" || h.endsWith(".localhost")) return true;
|
||||
|
||||
const ipv4 = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
||||
if (ipv4) {
|
||||
const [a, b] = [parseInt(ipv4[1], 10), parseInt(ipv4[2], 10)];
|
||||
if (a === 0) return true; // 0.0.0.0/8
|
||||
if (a === 10) return true; // 10.0.0.0/8
|
||||
if (a === 127) return true; // 127.0.0.0/8
|
||||
if (a === 169 && b === 254) return true; // 169.254.0.0/16 (link-local / cloud metadata)
|
||||
if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12
|
||||
if (a === 192 && b === 168) return true; // 192.168.0.0/16
|
||||
return false;
|
||||
}
|
||||
|
||||
// IPv6 (Node.js URL parser may keep brackets)
|
||||
const ipv6 = h.startsWith("[") && h.endsWith("]") ? h.slice(1, -1) : h;
|
||||
if (ipv6 === "::1" || ipv6 === "::" || ipv6.startsWith("fe80:") || ipv6.startsWith("fc") || ipv6.startsWith("fd")) return true;
|
||||
if (ipv6.startsWith("::ffff:")) {
|
||||
const mapped = ipv6.slice(7);
|
||||
// Dotted-decimal form (::ffff:127.0.0.1)
|
||||
if (mapped.includes(".")) return isPrivateOrReservedHost(mapped);
|
||||
// Hex form (::ffff:7f00:1) — convert to IPv4
|
||||
const hex = mapped.replace(":", "").padStart(8, "0");
|
||||
const a = parseInt(hex.slice(0, 2), 16), b = parseInt(hex.slice(2, 4), 16);
|
||||
const c = parseInt(hex.slice(4, 6), 16), d = parseInt(hex.slice(6, 8), 16);
|
||||
return isPrivateOrReservedHost(`${a}.${b}.${c}.${d}`);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function sanitizeLogoUrl(url) {
|
||||
if (!url || typeof url !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const trimmed = url.trim();
|
||||
|
||||
|
||||
if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const parsed = new URL(trimmed);
|
||||
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Block requests to internal/private network addresses (SSRF protection)
|
||||
if (isPrivateOrReservedHost(parsed.hostname)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return parsed.href;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function brandingMiddleware(req, res, next) {
|
||||
const branding = loadBrandingConfig();
|
||||
const safeLogo = safeBasename(branding.localLogoPath);
|
||||
const safeWatermark = safeBasename(branding.localLoginWatermarkPath);
|
||||
|
||||
|
||||
res.locals.branding = {
|
||||
appName: branding.appName || DEFAULT_BRANDING.appName,
|
||||
faviconUrl: resolveFaviconAssetUrl(branding),
|
||||
logoUrl: safeLogo
|
||||
? `/images/${safeLogo}`
|
||||
: (branding.logoUrl || null),
|
||||
loginWatermarkUrl: safeWatermark
|
||||
? `/images/${safeWatermark}`
|
||||
: resolveLoginWatermarkAssetUrl(branding),
|
||||
loginBackgroundType: branding.loginBackgroundType || DEFAULT_BRANDING.loginBackgroundType,
|
||||
loginBackgroundUrl: resolveLoginBackgroundAssetUrl(branding),
|
||||
loginBackgroundMimeType: branding.loginBackgroundMimeType || DEFAULT_BRANDING.loginBackgroundMimeType
|
||||
};
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
brandingMiddleware,
|
||||
loadBrandingConfig,
|
||||
saveBrandingConfig,
|
||||
sanitizeAppName,
|
||||
sanitizeLogoUrl,
|
||||
generateSafeLogoFilename,
|
||||
validateBase64Image,
|
||||
validateBase64Video,
|
||||
getValidatedExtension,
|
||||
getValidatedVideoExtension,
|
||||
getMimeTypeForExtension,
|
||||
getMediaTypeFromFilename,
|
||||
getMediaTypeFromUrl,
|
||||
getExtensionFromUrl,
|
||||
getBrandingAssetVersionSuffix,
|
||||
resolveFaviconAssetUrl,
|
||||
resolveLoginWatermarkAssetUrl,
|
||||
resolveLoginBackgroundAssetUrl,
|
||||
invalidateBrandingCache,
|
||||
DEFAULT_BRANDING,
|
||||
DEFAULT_LOGIN_BACKGROUND_URL
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,395 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const httpMod = require("http");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const ipRangeCheck = require("ip-range-check");
|
||||
|
||||
// ─── Configuration ──────────────────────────────────────────────
|
||||
const TOKEN_TTL_MS = 30 * 60 * 1000; // 30 minutes
|
||||
const TOKEN_BYTES = 16;
|
||||
const CLEANUP_INTERVAL_MS = 60 * 1000; // sweep every 60s
|
||||
const MAX_SESSIONS = 500; // hard cap to prevent RAM bloat
|
||||
const PHPMYADMIN_INTERNAL_PORT = 9082;
|
||||
|
||||
// ─── Token Store (self-cleaning Map) ────────────────────────────
|
||||
const sessions = new Map();
|
||||
|
||||
function scheduleExpiryTimer(token, ttlMs) {
|
||||
const timer = setTimeout(() => {
|
||||
sessions.delete(token);
|
||||
}, ttlMs);
|
||||
if (timer.unref) timer.unref();
|
||||
return timer;
|
||||
}
|
||||
|
||||
function setSessionExpiry(token, sess, ttlMs = TOKEN_TTL_MS) {
|
||||
if (!sess) return false;
|
||||
if (sess._timer) clearTimeout(sess._timer);
|
||||
sess.expiresAt = Date.now() + ttlMs;
|
||||
sess._timer = scheduleExpiryTimer(token, ttlMs);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Periodic sweep for expired sessions
|
||||
const _cleanupTimer = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [token, sess] of sessions) {
|
||||
if (now > sess.expiresAt) {
|
||||
clearTimeout(sess._timer);
|
||||
sessions.delete(token);
|
||||
}
|
||||
}
|
||||
}, CLEANUP_INTERVAL_MS);
|
||||
if (_cleanupTimer.unref) _cleanupTimer.unref();
|
||||
|
||||
// ─── Service Targets ────────────────────────────────────────────
|
||||
const SERVICE_TARGETS = {
|
||||
phpmyadmin: {
|
||||
host: "127.0.0.1",
|
||||
port: PHPMYADMIN_INTERNAL_PORT,
|
||||
backendPath: "/phpmyadmin",
|
||||
label: "phpMyAdmin"
|
||||
},
|
||||
pgadmin: {
|
||||
host: "127.0.0.1",
|
||||
port: 5050,
|
||||
backendPath: "/pgadmin4",
|
||||
label: "pgAdmin4"
|
||||
}
|
||||
};
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────────
|
||||
|
||||
function normalizeIp(ip) {
|
||||
if (!ip || typeof ip !== "string") return "";
|
||||
let normalized = ip.trim();
|
||||
if (normalized.startsWith("::ffff:")) normalized = normalized.slice(7);
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function loadTrustedSubnets() {
|
||||
try {
|
||||
const secPath = path.join(__dirname, "..", "security.json");
|
||||
const sec = JSON.parse(fs.readFileSync(secPath, "utf8"));
|
||||
if (Array.isArray(sec.trusted_subnets)) {
|
||||
return sec.trusted_subnets.filter(s => typeof s === "string" && s.length > 0);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
return [];
|
||||
}
|
||||
|
||||
function isIpAuthorized(requestIp, sessionIp) {
|
||||
const normReq = normalizeIp(requestIp);
|
||||
const normSess = normalizeIp(sessionIp);
|
||||
|
||||
if (normReq === normSess) return true;
|
||||
|
||||
const subnets = loadTrustedSubnets();
|
||||
if (subnets.length > 0) {
|
||||
const reqInSubnet = ipRangeCheck(normReq, subnets);
|
||||
const sessInSubnet = ipRangeCheck(normSess, subnets);
|
||||
if (reqInSubnet && sessInSubnet) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// ─── Token Management ───────────────────────────────────────────
|
||||
|
||||
function generateToken(service, userIp, username, sessionId = null) {
|
||||
if (!SERVICE_TARGETS[service]) return null;
|
||||
|
||||
if (sessions.size >= MAX_SESSIONS) {
|
||||
let oldestToken = null, oldestTime = Infinity;
|
||||
for (const [t, s] of sessions) {
|
||||
if (s.createdAt < oldestTime) { oldestTime = s.createdAt; oldestToken = t; }
|
||||
}
|
||||
if (oldestToken) {
|
||||
clearTimeout(sessions.get(oldestToken)._timer);
|
||||
sessions.delete(oldestToken);
|
||||
}
|
||||
}
|
||||
|
||||
const token = "v-tmp-" + crypto.randomBytes(TOKEN_BYTES).toString("hex");
|
||||
const now = Date.now();
|
||||
const expiresAt = now + TOKEN_TTL_MS;
|
||||
|
||||
const _timer = scheduleExpiryTimer(token, TOKEN_TTL_MS);
|
||||
|
||||
sessions.set(token, {
|
||||
service,
|
||||
userIp: normalizeIp(userIp),
|
||||
username,
|
||||
sessionId: sessionId ? String(sessionId) : null,
|
||||
createdAt: now,
|
||||
expiresAt,
|
||||
_timer
|
||||
});
|
||||
|
||||
return { token, expiresAt };
|
||||
}
|
||||
|
||||
function validateToken(token) {
|
||||
if (!token || typeof token !== "string") return null;
|
||||
const sess = sessions.get(token);
|
||||
if (!sess) return null;
|
||||
if (Date.now() > sess.expiresAt) {
|
||||
clearTimeout(sess._timer);
|
||||
sessions.delete(token);
|
||||
return null;
|
||||
}
|
||||
return sess;
|
||||
}
|
||||
|
||||
function touchToken(token, ttlMs = TOKEN_TTL_MS) {
|
||||
if (!token || typeof token !== "string") return false;
|
||||
const sess = sessions.get(token);
|
||||
if (!sess) return false;
|
||||
if (Date.now() > sess.expiresAt) {
|
||||
clearTimeout(sess._timer);
|
||||
sessions.delete(token);
|
||||
return false;
|
||||
}
|
||||
return setSessionExpiry(token, sess, ttlMs);
|
||||
}
|
||||
|
||||
function revokeToken(token) {
|
||||
const sess = sessions.get(token);
|
||||
if (sess) {
|
||||
clearTimeout(sess._timer);
|
||||
sessions.delete(token);
|
||||
}
|
||||
}
|
||||
|
||||
function revokeAllForUser(username) {
|
||||
for (const [token, sess] of sessions) {
|
||||
if (sess.username === username) {
|
||||
clearTimeout(sess._timer);
|
||||
sessions.delete(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Streaming Proxy Middleware ─────────────────────────────────
|
||||
|
||||
function rewriteCookiePaths(headers, backendPath, tokenPath) {
|
||||
const raw = headers["set-cookie"];
|
||||
if (!raw) return;
|
||||
const cookies = Array.isArray(raw) ? raw : [raw];
|
||||
headers["set-cookie"] = cookies.map(c =>
|
||||
c.replace(new RegExp("path=" + backendPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "/?", "gi"), "path=" + tokenPath)
|
||||
);
|
||||
}
|
||||
|
||||
function stripUpstreamSecurityHeaders(headers) {
|
||||
// Remove backend security headers that conflict with our proxy context
|
||||
delete headers["x-frame-options"];
|
||||
delete headers["content-security-policy"];
|
||||
delete headers["x-content-security-policy"];
|
||||
delete headers["x-webkit-csp"];
|
||||
delete headers["x-xss-protection"];
|
||||
delete headers["x-robots-tag"];
|
||||
delete headers["x-permitted-cross-domain-policies"];
|
||||
delete headers["server"];
|
||||
delete headers["x-powered-by"];
|
||||
delete headers["via"];
|
||||
delete headers["x-generator"];
|
||||
delete headers["x-aspnet-version"];
|
||||
}
|
||||
|
||||
function buildHeartbeatScript(token) {
|
||||
const safeToken = JSON.stringify(String(token || ""));
|
||||
return `<script>(function(){try{var t=${safeToken};if(!t)return;var beat=function(){fetch('/api/settings/database/access-heartbeat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({token:t}),keepalive:true}).catch(function(){});};beat();setInterval(beat,45000);window.addEventListener('pageshow',beat);}catch(e){}})();</script>`;
|
||||
}
|
||||
|
||||
function createProxyMiddleware() {
|
||||
const DB_ACCESS_PREFIX = "/db-access/";
|
||||
|
||||
return function dbProxyMiddleware(req, res, next) {
|
||||
if (!req.url.startsWith(DB_ACCESS_PREFIX)) return next();
|
||||
|
||||
// Parse: /db-access/<token>/...
|
||||
const withoutPrefix = req.url.slice(DB_ACCESS_PREFIX.length);
|
||||
const slashIdx = withoutPrefix.indexOf("/");
|
||||
const token = slashIdx === -1 ? withoutPrefix : withoutPrefix.slice(0, slashIdx);
|
||||
const remainingPath = slashIdx === -1 ? "/" : withoutPrefix.slice(slashIdx);
|
||||
|
||||
const sess = validateToken(token);
|
||||
if (!sess) { res.status(404).end(); return; }
|
||||
|
||||
const requestIp = req.ip || req.connection?.remoteAddress || "";
|
||||
const requestSessionId = req.sessionID ? String(req.sessionID) : "";
|
||||
const requestUser = req.session?.user ? String(req.session.user) : "";
|
||||
const sessionMatched = !!(
|
||||
sess.sessionId &&
|
||||
requestSessionId &&
|
||||
sess.sessionId === requestSessionId &&
|
||||
requestUser &&
|
||||
requestUser === sess.username
|
||||
);
|
||||
|
||||
if (!sessionMatched && !isIpAuthorized(requestIp, sess.userIp)) {
|
||||
res.status(404).end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Sliding TTL while actively used so refreshes in an active session keep working.
|
||||
touchToken(token);
|
||||
|
||||
const target = SERVICE_TARGETS[sess.service];
|
||||
if (!target) { res.status(404).end(); return; }
|
||||
|
||||
const tokenPath = DB_ACCESS_PREFIX + token + "/";
|
||||
const proxyPath = target.backendPath + (remainingPath === "/" ? "/" : remainingPath);
|
||||
|
||||
// Rewrite cookies coming from the browser: change tokenPath back to backendPath
|
||||
const incomingCookie = req.headers["cookie"];
|
||||
if (incomingCookie) {
|
||||
req.headers["cookie"] = incomingCookie;
|
||||
}
|
||||
|
||||
const proxyHeaders = Object.assign({}, req.headers);
|
||||
delete proxyHeaders["connection"];
|
||||
delete proxyHeaders["upgrade"];
|
||||
if (sess.service === "phpmyadmin") {
|
||||
proxyHeaders["host"] = "127.0.0.1:" + PHPMYADMIN_INTERNAL_PORT;
|
||||
}
|
||||
|
||||
// Request uncompressed content for text so we can rewrite paths
|
||||
const likelyText = req.method === "GET" && (
|
||||
remainingPath === "/" ||
|
||||
remainingPath.endsWith(".php") ||
|
||||
remainingPath.endsWith(".html") ||
|
||||
!remainingPath.includes(".")
|
||||
);
|
||||
if (likelyText) {
|
||||
proxyHeaders["accept-encoding"] = "identity";
|
||||
}
|
||||
|
||||
const proxyOpts = {
|
||||
hostname: target.host,
|
||||
port: target.port,
|
||||
path: proxyPath,
|
||||
method: req.method,
|
||||
headers: proxyHeaders,
|
||||
timeout: 300000
|
||||
};
|
||||
|
||||
const proxyReq = httpMod.request(proxyOpts, (proxyRes) => {
|
||||
// Rewrite Location headers
|
||||
const location = proxyRes.headers["location"];
|
||||
if (location) {
|
||||
let rewritten = location;
|
||||
if (sess.service === "phpmyadmin" && location.includes("/phpmyadmin")) {
|
||||
rewritten = location.replace(/\/phpmyadmin/g, DB_ACCESS_PREFIX + token);
|
||||
} else if (sess.service === "pgadmin") {
|
||||
if (location.includes("/pgadmin4")) {
|
||||
rewritten = location.replace(/\/pgadmin4/g, DB_ACCESS_PREFIX + token);
|
||||
} else if (location.includes("/pgadmin")) {
|
||||
rewritten = location.replace(/\/pgadmin/g, DB_ACCESS_PREFIX + token);
|
||||
}
|
||||
}
|
||||
proxyRes.headers["location"] = rewritten;
|
||||
}
|
||||
|
||||
// Rewrite Set-Cookie paths so cookies work on the proxy URL
|
||||
rewriteCookiePaths(proxyRes.headers, target.backendPath, tokenPath);
|
||||
// Remove upstream security headers to avoid conflicts with our proxy
|
||||
stripUpstreamSecurityHeaders(proxyRes.headers);
|
||||
|
||||
// Clear any headers previously set by Express middleware (helmet, etc.)
|
||||
// to prevent them from leaking into the proxied response
|
||||
const prevHeaders = res.getHeaderNames ? res.getHeaderNames() : [];
|
||||
for (const h of prevHeaders) res.removeHeader(h);
|
||||
|
||||
const respContentType = (proxyRes.headers["content-type"] || "").toLowerCase();
|
||||
const isHtmlContent = respContentType.includes("text/html");
|
||||
const isTextContent = respContentType.includes("text/html") || respContentType.includes("javascript") || respContentType.includes("text/css");
|
||||
|
||||
if (isTextContent) {
|
||||
delete proxyRes.headers["content-length"];
|
||||
const encoding = proxyRes.headers["content-encoding"];
|
||||
delete proxyRes.headers["content-encoding"];
|
||||
|
||||
res.writeHead(proxyRes.statusCode, proxyRes.headers);
|
||||
|
||||
const chunks = [];
|
||||
let totalSize = 0;
|
||||
const MAX_REWRITE_SIZE = 5 * 1024 * 1024;
|
||||
|
||||
proxyRes.on("data", (chunk) => {
|
||||
totalSize += chunk.length;
|
||||
if (totalSize <= MAX_REWRITE_SIZE) chunks.push(chunk);
|
||||
});
|
||||
proxyRes.on("end", () => {
|
||||
let body = Buffer.concat(chunks);
|
||||
if (encoding === "gzip") {
|
||||
try { body = require("zlib").gunzipSync(body); } catch { /* use as-is */ }
|
||||
} else if (encoding === "deflate") {
|
||||
try { body = require("zlib").inflateSync(body); } catch { /* use as-is */ }
|
||||
}
|
||||
let text = body.toString("utf8");
|
||||
if (sess.service === "pgadmin") {
|
||||
text = text.replace(/\/pgadmin4\//g, tokenPath);
|
||||
text = text.replace(/"\/pgadmin4"/g, '"' + DB_ACCESS_PREFIX + token + '"');
|
||||
text = text.replace(/'\/pgadmin4'/g, "'" + DB_ACCESS_PREFIX + token + "'");
|
||||
} else if (sess.service === "phpmyadmin") {
|
||||
text = text.replace(/\/phpmyadmin\//g, tokenPath);
|
||||
text = text.replace(/"\/phpmyadmin"/g, '"' + DB_ACCESS_PREFIX + token + '"');
|
||||
text = text.replace(/'\/phpmyadmin'/g, "'" + DB_ACCESS_PREFIX + token + "'");
|
||||
}
|
||||
|
||||
if (isHtmlContent) {
|
||||
const hb = buildHeartbeatScript(token);
|
||||
if (/<\/body>/i.test(text)) {
|
||||
text = text.replace(/<\/body>/i, hb + "</body>");
|
||||
} else {
|
||||
text += hb;
|
||||
}
|
||||
}
|
||||
|
||||
res.end(text);
|
||||
});
|
||||
proxyRes.on("error", () => res.end());
|
||||
} else {
|
||||
// Stream directly — no buffering
|
||||
res.writeHead(proxyRes.statusCode, proxyRes.headers);
|
||||
proxyRes.pipe(res, { end: true });
|
||||
}
|
||||
});
|
||||
|
||||
proxyReq.on("error", (err) => {
|
||||
console.error("[db-proxy] Proxy error:", err.message);
|
||||
if (!res.headersSent) res.status(502).end();
|
||||
});
|
||||
|
||||
proxyReq.on("timeout", () => {
|
||||
proxyReq.destroy();
|
||||
if (!res.headersSent) res.status(504).end();
|
||||
});
|
||||
|
||||
req.pipe(proxyReq, { end: true });
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Stats ──────────────────────────────────────────────────────
|
||||
function getSessionCount() {
|
||||
return sessions.size;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
generateToken,
|
||||
validateToken,
|
||||
touchToken,
|
||||
revokeToken,
|
||||
revokeAllForUser,
|
||||
createProxyMiddleware,
|
||||
getSessionCount,
|
||||
normalizeIp,
|
||||
isIpAuthorized,
|
||||
SERVICE_TARGETS,
|
||||
TOKEN_TTL_MS,
|
||||
PHPMYADMIN_INTERNAL_PORT
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
"use strict";
|
||||
|
||||
const os = require("os");
|
||||
|
||||
const TOTAL_MEM_BYTES = os.totalmem();
|
||||
const BASELINE_MEM_BYTES = 4 * 1024 * 1024 * 1024; // 4 GB reference
|
||||
const MEM_SCALE = Math.min(1.0, Math.max(0.125, TOTAL_MEM_BYTES / BASELINE_MEM_BYTES));
|
||||
const LOW_MEMORY = TOTAL_MEM_BYTES <= 1024 * 1024 * 1024; // ≤1 GB
|
||||
|
||||
/**
|
||||
* Scale a capacity value proportionally to available system RAM.
|
||||
* On 4 GB the value is unchanged; on 512 MB it shrinks to 1/8th.
|
||||
* @param {number} base - The baseline value (tuned for a 4 GB box).
|
||||
* @param {number} [floor=10] - Minimum value to return.
|
||||
* @returns {number}
|
||||
*/
|
||||
function scaleForMemory(base, floor = 10) {
|
||||
return Math.max(floor, Math.round(base * MEM_SCALE));
|
||||
}
|
||||
|
||||
module.exports = { scaleForMemory, MEM_SCALE, LOW_MEMORY, TOTAL_MEM_BYTES };
|
||||
@@ -0,0 +1,261 @@
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const fsp = require("fs/promises");
|
||||
const httpMod = require("http");
|
||||
const https = require("https");
|
||||
const os = require("os");
|
||||
const path = require("path");
|
||||
const FormData = require("form-data");
|
||||
const { getTechnicalServerName } = require("./server-name");
|
||||
|
||||
function safeJoinUnix(baseDir, rel) {
|
||||
const base = path.posix.normalize(String(baseDir || "")).replace(/\0/g, "");
|
||||
const raw = String(rel || "").replace(/\0/g, "");
|
||||
if (path.posix.isAbsolute(raw)) {
|
||||
throw new Error("Absolute path not allowed");
|
||||
}
|
||||
const normalized = path.posix.normalize(`/${raw}`).replace(/^\/+/, "");
|
||||
if (normalized === ".." || normalized.startsWith("../") || normalized.includes("/../")) {
|
||||
throw new Error("Path traversal detected");
|
||||
}
|
||||
return path.posix.join(base, normalized);
|
||||
}
|
||||
|
||||
async function uploadFileToNode({
|
||||
node,
|
||||
uploadUrl,
|
||||
headers,
|
||||
filePath,
|
||||
filename,
|
||||
targetDir,
|
||||
}) {
|
||||
const form = new FormData();
|
||||
form.append("dir", targetDir);
|
||||
form.append("file", fs.createReadStream(filePath), { filename });
|
||||
|
||||
const requestHeaders = Object.assign({}, headers);
|
||||
delete requestHeaders["Content-Type"];
|
||||
Object.assign(requestHeaders, form.getHeaders());
|
||||
|
||||
const parsedUrl = new URL(uploadUrl);
|
||||
const lib = uploadUrl.startsWith("https:") ? https : httpMod;
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
const req = lib.request({
|
||||
method: "POST",
|
||||
hostname: parsedUrl.hostname,
|
||||
port: parsedUrl.port || (uploadUrl.startsWith("https:") ? 443 : 80),
|
||||
path: parsedUrl.pathname + parsedUrl.search,
|
||||
headers: requestHeaders,
|
||||
timeout: 600_000,
|
||||
}, (res) => {
|
||||
const chunks = [];
|
||||
let total = 0;
|
||||
res.on("data", (chunk) => {
|
||||
if (total < 65_536) {
|
||||
chunks.push(chunk);
|
||||
total += chunk.length;
|
||||
}
|
||||
});
|
||||
res.on("end", () => {
|
||||
if (res.statusCode === 200) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const body = Buffer.concat(chunks).toString().slice(0, 2000);
|
||||
const error = new Error(`Node upload failed: ${res.statusCode} ${body}`);
|
||||
error.nodeStatusCode = res.statusCode;
|
||||
error.nodeBody = body;
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
|
||||
req.on("error", reject);
|
||||
req.on("timeout", () => {
|
||||
req.destroy();
|
||||
reject(new Error("Upload request timed out"));
|
||||
});
|
||||
form.pipe(req);
|
||||
});
|
||||
}
|
||||
|
||||
async function applyRemoteAssetToServer(deps, { serverName, entry, url, destPath }) {
|
||||
if (!deps || typeof deps !== "object") {
|
||||
throw new Error("Asset apply dependencies are required.");
|
||||
}
|
||||
|
||||
const bot = String(serverName || entry?.name || "").trim();
|
||||
if (!bot) {
|
||||
return { ok: false, statusCode: 400, error: "missing-bot" };
|
||||
}
|
||||
|
||||
const resolvedEntry = entry || (typeof deps.findServer === "function" ? await deps.findServer(bot) : null);
|
||||
if (!resolvedEntry) {
|
||||
return { ok: false, statusCode: 404, error: "server-not-found" };
|
||||
}
|
||||
if (!deps.isRemoteEntry(resolvedEntry)) {
|
||||
return { ok: false, statusCode: 400, error: "server-not-on-node" };
|
||||
}
|
||||
|
||||
const node = await deps.findNodeByIdOrName(resolvedEntry.nodeId);
|
||||
if (!node) {
|
||||
return { ok: false, statusCode: 400, error: "node-not-found" };
|
||||
}
|
||||
|
||||
const underCloudflare = typeof deps.nodeUnderCloudflare === "function"
|
||||
? deps.nodeUnderCloudflare(node)
|
||||
: !!node.under_cloudflare;
|
||||
const baseUrl = deps.buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, underCloudflare);
|
||||
if (!baseUrl) {
|
||||
return { ok: false, statusCode: 400, error: "invalid-node-address" };
|
||||
}
|
||||
|
||||
const headers = deps.nodeAuthHeadersFor(node, true);
|
||||
const technicalName = getTechnicalServerName(resolvedEntry, bot);
|
||||
|
||||
let safeUrl = String(url || "").trim();
|
||||
if (!safeUrl) {
|
||||
return { ok: false, statusCode: 400, error: "missing-url" };
|
||||
}
|
||||
|
||||
try {
|
||||
const validated = await deps.assertSafeRemoteUrl(safeUrl);
|
||||
safeUrl = validated.toString();
|
||||
} catch {
|
||||
return { ok: false, statusCode: 400, error: "invalid-url" };
|
||||
}
|
||||
|
||||
let destRel = String(destPath || "").trim();
|
||||
if (!destRel) destRel = "server.jar";
|
||||
destRel = destRel.replace(/^\/+/, "");
|
||||
if (destRel.includes("..") || destRel.includes("\\")) {
|
||||
return { ok: false, statusCode: 400, error: "invalid-destPath" };
|
||||
}
|
||||
|
||||
const destFile = path.posix.basename(destRel);
|
||||
if (!destFile || destFile === "." || destFile === "..") {
|
||||
return { ok: false, statusCode: 400, error: "invalid-destPath" };
|
||||
}
|
||||
|
||||
if (deps.remoteApplyProxyDownload) {
|
||||
const ctx = await deps.resolveRemoteFsContext(bot);
|
||||
if (!ctx.remote || !ctx.node) {
|
||||
return { ok: false, statusCode: 404, error: "server-not-on-node" };
|
||||
}
|
||||
|
||||
try {
|
||||
const pingRes = await deps.nodeFsPost(ctx.node, "/v1/fs/list", { path: ctx.baseDir, depth: 0 }, 5000);
|
||||
if (pingRes.status === 401) {
|
||||
return {
|
||||
ok: false,
|
||||
statusCode: 502,
|
||||
error: "node-auth-failed",
|
||||
detail: "Token mismatch. Re-deploy config.yml to the node.",
|
||||
};
|
||||
}
|
||||
if (pingRes.status === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
statusCode: 502,
|
||||
error: "node-unreachable",
|
||||
detail: "Cannot connect to node agent.",
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
|
||||
let buffer;
|
||||
try {
|
||||
buffer = await deps.httpGetRaw(safeUrl, {
|
||||
maxBytes: deps.remoteApplyMaxBytes,
|
||||
timeoutMs: deps.remoteApplyTimeoutMs,
|
||||
maxRedirects: deps.remoteFetchMaxRedirects,
|
||||
});
|
||||
} catch {
|
||||
return { ok: false, statusCode: 400, error: "remote-download-failed" };
|
||||
}
|
||||
|
||||
let targetDir = ctx.baseDir;
|
||||
try {
|
||||
const destDirRel = path.posix.dirname(destRel);
|
||||
targetDir = safeJoinUnix(ctx.baseDir, destDirRel === "." ? "" : destDirRel);
|
||||
} catch {
|
||||
return { ok: false, statusCode: 400, error: "invalid-destPath" };
|
||||
}
|
||||
|
||||
const tmpFile = path.join(os.tmpdir(), `adpanel-apply-${crypto.randomBytes(8).toString("hex")}`);
|
||||
try {
|
||||
await fsp.writeFile(tmpFile, buffer);
|
||||
const uploadUrl = `${baseUrl}/v1/fs/upload`;
|
||||
await uploadFileToNode({
|
||||
node: ctx.node,
|
||||
uploadUrl,
|
||||
headers,
|
||||
filePath: tmpFile,
|
||||
filename: destFile,
|
||||
targetDir,
|
||||
});
|
||||
return { ok: true, remote: true, msg: "downloaded-and-uploaded", destPath: destRel };
|
||||
} catch (error) {
|
||||
const detail = error.message || "stream-upload-failed";
|
||||
if (error.nodeStatusCode === 507) {
|
||||
try {
|
||||
const nodeJson = JSON.parse(error.nodeBody);
|
||||
if (nodeJson.error === "disk_limit_exceeded") {
|
||||
return Object.assign({ ok: false, statusCode: 507 }, nodeJson);
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
if (detail.includes("401")) {
|
||||
return {
|
||||
ok: false,
|
||||
statusCode: 502,
|
||||
error: "node-auth-failed",
|
||||
detail: "Token mismatch. Re-deploy config.yml to the node.",
|
||||
};
|
||||
}
|
||||
return { ok: false, statusCode: 502, error: "node_upload_failed", detail };
|
||||
} finally {
|
||||
try {
|
||||
await fsp.unlink(tmpFile);
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const forwardUrl = `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/apply-version`;
|
||||
const response = await deps.httpRequestJson(
|
||||
forwardUrl,
|
||||
"POST",
|
||||
headers,
|
||||
{ url: safeUrl, nodeId: resolvedEntry.nodeId, destPath: destRel },
|
||||
60_000
|
||||
);
|
||||
|
||||
if (response.status === 507 && response.json?.error === "disk_limit_exceeded") {
|
||||
return Object.assign({ ok: false, statusCode: 507 }, response.json);
|
||||
}
|
||||
if (response.status !== 200 || !(response.json && response.json.ok)) {
|
||||
const detail = response.json && (response.json.detail || response.json.error)
|
||||
? (response.json.detail || response.json.error)
|
||||
: `node-status-${response.status}`;
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
return {
|
||||
ok: false,
|
||||
statusCode: 502,
|
||||
error: "node-auth-failed",
|
||||
detail: "Token or HMAC mismatch. Re-deploy config.yml to the node.",
|
||||
};
|
||||
}
|
||||
return { ok: false, statusCode: 502, error: detail || `node-forward-failed-${response.status}` };
|
||||
}
|
||||
|
||||
return { ok: true, remote: true, msg: "forwarded-to-node", destPath: destRel };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
applyRemoteAssetToServer,
|
||||
};
|
||||
@@ -0,0 +1,95 @@
|
||||
"use strict";
|
||||
|
||||
const { getTechnicalServerName } = require("./server-name");
|
||||
|
||||
async function deleteServerByName(deps, rawName) {
|
||||
if (!deps || typeof deps !== "object") {
|
||||
throw new Error("Server delete dependencies are required.");
|
||||
}
|
||||
|
||||
let nameParam = rawName || "";
|
||||
try {
|
||||
nameParam = decodeURIComponent(nameParam);
|
||||
} catch {
|
||||
}
|
||||
|
||||
const name = String(nameParam || "").trim();
|
||||
if (!name) {
|
||||
return { ok: false, statusCode: 400, error: "missing name" };
|
||||
}
|
||||
|
||||
const entry = await deps.findServer(name);
|
||||
if (!entry) {
|
||||
await deps.deleteServerSchedules(name);
|
||||
await deps.removeServerIndexEntry(name);
|
||||
return { ok: true };
|
||||
}
|
||||
const technicalName = getTechnicalServerName(entry, name);
|
||||
|
||||
if (!deps.isRemoteEntry(entry)) {
|
||||
return { ok: false, statusCode: 400, error: "server-not-on-node" };
|
||||
}
|
||||
|
||||
const node = await deps.findNodeByIdOrName(entry.nodeId);
|
||||
if (!node) {
|
||||
return { ok: false, statusCode: 400, error: "node not found for server" };
|
||||
}
|
||||
|
||||
const underCloudflare = typeof deps.nodeUnderCloudflare === "function"
|
||||
? deps.nodeUnderCloudflare(node)
|
||||
: !!node.under_cloudflare;
|
||||
const baseUrl = deps.buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, underCloudflare);
|
||||
if (!baseUrl) {
|
||||
return { ok: false, statusCode: 400, error: "invalid node address" };
|
||||
}
|
||||
|
||||
const headers = deps.nodeAuthHeadersFor(node, true);
|
||||
|
||||
try {
|
||||
await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/kill`, "POST", headers, null, 30_000);
|
||||
console.log(`[delete] Force-stopped server ${name}`);
|
||||
} catch (error) {
|
||||
console.log(`[delete] Could not force-stop server ${name} (may already be stopped): ${error.message}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const backupsRes = await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/backups`, "GET", headers, null, 10_000);
|
||||
if (backupsRes.status === 200 && backupsRes.json?.backups) {
|
||||
for (const backup of backupsRes.json.backups) {
|
||||
if (!backup?.id) continue;
|
||||
await deps.httpRequestJson(
|
||||
`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/backups/${encodeURIComponent(backup.id)}`,
|
||||
"DELETE",
|
||||
headers,
|
||||
null,
|
||||
30_000
|
||||
);
|
||||
console.log(`[delete] Deleted backup ${backup.id} for server ${name}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`[delete] Could not delete backups for ${name}: ${error.message}`);
|
||||
}
|
||||
|
||||
await deps.deleteServerSchedules(name);
|
||||
|
||||
const response = await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}`, "DELETE", headers, null, 60_000);
|
||||
if (response.status !== 200 || !(response.json && response.json.ok)) {
|
||||
const message = response.json && (response.json.error || response.json.detail)
|
||||
? (response.json.error || response.json.detail)
|
||||
: `remote delete failed (${response.status})`;
|
||||
return { ok: false, statusCode: 502, error: message };
|
||||
}
|
||||
|
||||
try {
|
||||
await deps.removeAccessForServerName(name);
|
||||
} catch {
|
||||
}
|
||||
|
||||
await deps.removeServerIndexEntry(name);
|
||||
return { ok: true, remote: true };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
deleteServerByName,
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
"use strict";
|
||||
|
||||
function sanitizeServerToken(raw) {
|
||||
let name = String(raw || "").trim();
|
||||
if (!name) return "";
|
||||
if (name.includes("..") || /[\/\\]/.test(name) || name.length > 120) return "";
|
||||
name = name.replace(/\s+/g, "-").replace(/[^\w\-_.]/g, "").replace(/^-+|-+$/g, "");
|
||||
return name;
|
||||
}
|
||||
|
||||
function getCanonicalServerName(entry, fallback = "") {
|
||||
return sanitizeServerToken(entry?.name || fallback || "");
|
||||
}
|
||||
|
||||
function getTechnicalServerName(entry, fallback = "") {
|
||||
const technical = sanitizeServerToken(entry?.bot || "");
|
||||
if (technical) return technical;
|
||||
return getCanonicalServerName(entry, fallback);
|
||||
}
|
||||
|
||||
function escapeRegExp(value) {
|
||||
return String(value || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
function rewriteStartupCommandServerName(command, oldName, newName) {
|
||||
const cleanCommand = String(command || "").trim();
|
||||
const cleanOldName = sanitizeServerToken(oldName);
|
||||
const cleanNewName = sanitizeServerToken(newName);
|
||||
|
||||
if (!cleanCommand || !cleanOldName || !cleanNewName || cleanOldName === cleanNewName) {
|
||||
return cleanCommand;
|
||||
}
|
||||
|
||||
const escapedOld = escapeRegExp(cleanOldName);
|
||||
const patterns = [
|
||||
new RegExp(`(^|\\s)(--name\\s+)(["']?)${escapedOld}\\3(?=\\s|$)`, "g"),
|
||||
new RegExp(`(^|\\s)(--name=)(["']?)${escapedOld}\\3(?=\\s|$)`, "g"),
|
||||
new RegExp(`(^|\\s)(container_name=)(["']?)${escapedOld}\\3(?=\\s|$)`, "g"),
|
||||
];
|
||||
|
||||
let rewritten = cleanCommand;
|
||||
for (const pattern of patterns) {
|
||||
rewritten = rewritten.replace(pattern, (_match, prefix, flag, quote) => {
|
||||
const safeQuote = quote || "";
|
||||
return `${prefix}${flag}${safeQuote}${cleanNewName}${safeQuote}`;
|
||||
});
|
||||
}
|
||||
|
||||
return rewritten;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getCanonicalServerName,
|
||||
getTechnicalServerName,
|
||||
rewriteStartupCommandServerName,
|
||||
sanitizeServerToken,
|
||||
};
|
||||
@@ -0,0 +1,507 @@
|
||||
"use strict";
|
||||
|
||||
const { sanitizeServerToken } = require("./server-name");
|
||||
|
||||
function cleanString(value) {
|
||||
return String(value || "").trim();
|
||||
}
|
||||
|
||||
function toPositiveNumber(value) {
|
||||
const numeric = Number(value);
|
||||
return Number.isFinite(numeric) && numeric > 0 ? numeric : 0;
|
||||
}
|
||||
|
||||
function parseStrictPort(value) {
|
||||
if (value === undefined || value === null) return null;
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isInteger(value) || value < 1 || value > 65535) return null;
|
||||
return value;
|
||||
}
|
||||
const str = cleanString(value);
|
||||
if (!/^[1-9]\d{0,4}$/.test(str)) return null;
|
||||
const numeric = Number(str);
|
||||
if (!Number.isInteger(numeric) || numeric < 1 || numeric > 65535) return null;
|
||||
return numeric;
|
||||
}
|
||||
|
||||
function parseShellArgs(input) {
|
||||
const src = cleanString(input);
|
||||
const args = [];
|
||||
let current = "";
|
||||
let quote = "";
|
||||
let escapeNext = false;
|
||||
|
||||
for (let i = 0; i < src.length; i++) {
|
||||
const ch = src[i];
|
||||
if (escapeNext) {
|
||||
current += ch;
|
||||
escapeNext = false;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\\") {
|
||||
escapeNext = true;
|
||||
continue;
|
||||
}
|
||||
if (quote) {
|
||||
if (ch === quote) {
|
||||
quote = "";
|
||||
} else {
|
||||
current += ch;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (ch === '"' || ch === "'") {
|
||||
quote = ch;
|
||||
continue;
|
||||
}
|
||||
if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") {
|
||||
if (current) {
|
||||
args.push(current);
|
||||
current = "";
|
||||
}
|
||||
continue;
|
||||
}
|
||||
current += ch;
|
||||
}
|
||||
|
||||
if (current) args.push(current);
|
||||
return args;
|
||||
}
|
||||
|
||||
function extractHostPortFromMapping(mapping) {
|
||||
let value = cleanString(mapping);
|
||||
const slashIdx = value.indexOf("/");
|
||||
if (slashIdx >= 0) value = value.slice(0, slashIdx);
|
||||
const parts = value.split(":");
|
||||
if (parts.length === 2) return parseStrictPort(parts[0]) || 0;
|
||||
if (parts.length === 3) return parseStrictPort(parts[1]) || 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function normalizeDockerImage(raw) {
|
||||
let image = cleanString(raw);
|
||||
if (!image) return "";
|
||||
const digestIdx = image.indexOf("@");
|
||||
if (digestIdx > 0) image = image.slice(0, digestIdx);
|
||||
const tagIdx = image.lastIndexOf(":");
|
||||
if (tagIdx > 0) {
|
||||
const afterColon = image.slice(tagIdx + 1);
|
||||
if (!afterColon.includes("/")) image = image.slice(0, tagIdx);
|
||||
}
|
||||
image = image.toLowerCase().replace(/^docker\.io\//, "").replace(/^index\.docker\.io\//, "");
|
||||
if (!image.includes("/")) image = `library/${image}`;
|
||||
return image;
|
||||
}
|
||||
|
||||
const DOCKER_RUN_FLAGS_WITH_VALUE = new Set([
|
||||
"-e", "--env", "-v", "--volume", "-p", "--publish", "-w", "--workdir",
|
||||
"--name", "-m", "--memory", "--cpus", "--memory-swap", "--memory-reservation", "--cpu-period", "--cpu-quota",
|
||||
"-u", "--user", "-h", "--hostname", "--network", "--net", "--restart",
|
||||
"-l", "--label", "--entrypoint", "--mount", "--tmpfs", "--device",
|
||||
"--pid", "--ipc", "--userns", "--uts", "--cgroupns", "--shm-size",
|
||||
"--ulimit", "--dns", "--dns-search", "--add-host", "--log-driver", "--log-opt",
|
||||
"--stop-signal", "--stop-timeout", "--health-cmd", "--health-interval",
|
||||
"--health-retries", "--health-timeout", "--runtime", "--platform", "--pull",
|
||||
"--ip", "--ip6", "--mac-address", "--expose", "--link", "--cidfile",
|
||||
]);
|
||||
|
||||
const DOCKER_RUN_SAFE_STANDALONE_FLAGS = new Set([
|
||||
"-d", "--detach", "-i", "--interactive", "-t", "--tty", "--rm", "--init", "--read-only",
|
||||
]);
|
||||
|
||||
const DOCKER_RUN_BLOCKED_FLAGS = new Set([
|
||||
"--privileged",
|
||||
"--cap-add",
|
||||
"--cap-drop",
|
||||
"--security-opt",
|
||||
"--volumes-from",
|
||||
"--env-file",
|
||||
"--device",
|
||||
"--device-cgroup-rule",
|
||||
"--sysctl",
|
||||
"--oom-kill-disable",
|
||||
"--oom-score-adj",
|
||||
]);
|
||||
|
||||
const DOCKER_RUN_HOST_NAMESPACE_FLAGS = new Set([
|
||||
"--network", "--net", "--pid", "--userns", "--ipc", "--uts", "--cgroupns",
|
||||
]);
|
||||
|
||||
function isSafeShortDockerFlagCluster(flag) {
|
||||
return /^-[dit]+$/i.test(flag);
|
||||
}
|
||||
|
||||
function readDockerFlagValue(args, index, inlineValue) {
|
||||
if (inlineValue) return { value: inlineValue, nextIndex: index };
|
||||
if (index + 1 >= args.length) return { value: "", nextIndex: index };
|
||||
return { value: args[index + 1], nextIndex: index + 1 };
|
||||
}
|
||||
|
||||
function extractDockerImageFromCommand(cmdStr) {
|
||||
const cmd = cleanString(cmdStr);
|
||||
if (!/^docker run(?:\s|$)/i.test(cmd)) return "";
|
||||
const args = parseShellArgs(cmd.slice("docker run".length).trim());
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const token = cleanString(args[i]);
|
||||
if (!token) continue;
|
||||
const tokenLower = token.toLowerCase();
|
||||
if (!tokenLower.startsWith("-")) return token;
|
||||
|
||||
let flagName = tokenLower;
|
||||
let inlineValue = "";
|
||||
if (tokenLower.startsWith("--") && tokenLower.includes("=")) {
|
||||
const cutIdx = tokenLower.indexOf("=");
|
||||
flagName = tokenLower.slice(0, cutIdx);
|
||||
inlineValue = token.slice(cutIdx + 1);
|
||||
}
|
||||
|
||||
if (isSafeShortDockerFlagCluster(flagName) || DOCKER_RUN_SAFE_STANDALONE_FLAGS.has(flagName)) {
|
||||
continue;
|
||||
}
|
||||
if (DOCKER_RUN_FLAGS_WITH_VALUE.has(flagName)) {
|
||||
const valueInfo = readDockerFlagValue(args, i, inlineValue);
|
||||
i = valueInfo.nextIndex;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function validateDockerRunCommandSafety(command, options = {}) {
|
||||
const cmd = cleanString(command);
|
||||
if (!cmd) return null;
|
||||
if (!/^docker run(?:\s|$)/i.test(cmd)) {
|
||||
return "Startup command must start with 'docker run'.";
|
||||
}
|
||||
if (/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/.test(cmd)) {
|
||||
return "Startup command contains unsupported control characters.";
|
||||
}
|
||||
|
||||
const allowedHostPorts = new Set(
|
||||
(Array.isArray(options.allowedHostPorts) ? options.allowedHostPorts : [])
|
||||
.map((entry) => parseStrictPort(entry))
|
||||
.filter((entry) => entry != null)
|
||||
);
|
||||
const reservedHostPorts = new Set(
|
||||
(Array.isArray(options.reservedHostPorts) ? options.reservedHostPorts : [])
|
||||
.map((entry) => parseStrictPort(entry))
|
||||
.filter((entry) => entry != null)
|
||||
);
|
||||
const expectedImageRef = cleanString(options.expectedImageRef);
|
||||
const args = parseShellArgs(cmd.slice("docker run".length).trim());
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const token = cleanString(args[i]);
|
||||
if (!token) continue;
|
||||
const tokenLower = token.toLowerCase();
|
||||
|
||||
if (!tokenLower.startsWith("-")) {
|
||||
if (expectedImageRef) {
|
||||
const normalizedExpected = normalizeDockerImage(expectedImageRef);
|
||||
const normalizedCommand = normalizeDockerImage(token);
|
||||
if (normalizedExpected && normalizedCommand && normalizedExpected !== normalizedCommand) {
|
||||
return `The Docker image in the startup command (${token}) does not match the configured image (${expectedImageRef}).`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
let flagName = tokenLower;
|
||||
let inlineValue = "";
|
||||
if (tokenLower.startsWith("--") && tokenLower.includes("=")) {
|
||||
const cutIdx = tokenLower.indexOf("=");
|
||||
flagName = tokenLower.slice(0, cutIdx);
|
||||
inlineValue = token.slice(cutIdx + 1);
|
||||
}
|
||||
|
||||
if (DOCKER_RUN_BLOCKED_FLAGS.has(flagName)) {
|
||||
return `Blocked dangerous Docker flag: ${flagName}`;
|
||||
}
|
||||
|
||||
if (flagName === "--mount") {
|
||||
const valueInfo = readDockerFlagValue(args, i, inlineValue);
|
||||
const mountValue = cleanString(valueInfo.value).toLowerCase();
|
||||
if (!mountValue) return "Docker flag --mount requires a value.";
|
||||
if (mountValue.includes("type=bind")) {
|
||||
return "Blocked dangerous Docker flag: --mount with bind";
|
||||
}
|
||||
i = valueInfo.nextIndex;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (flagName === "--tmpfs") {
|
||||
const valueInfo = readDockerFlagValue(args, i, inlineValue);
|
||||
const tmpfsValue = cleanString(valueInfo.value).toLowerCase();
|
||||
if (!tmpfsValue) return "Docker flag --tmpfs requires a value.";
|
||||
if (tmpfsValue.includes("exec")) {
|
||||
return "Blocked dangerous Docker flag: --tmpfs with exec";
|
||||
}
|
||||
i = valueInfo.nextIndex;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (DOCKER_RUN_HOST_NAMESPACE_FLAGS.has(flagName)) {
|
||||
const valueInfo = readDockerFlagValue(args, i, inlineValue);
|
||||
const nsMode = cleanString(valueInfo.value).toLowerCase();
|
||||
if (!nsMode) return `Docker flag ${flagName} requires a value.`;
|
||||
if (nsMode === "host") {
|
||||
return `Blocked dangerous Docker flag: ${flagName}=host`;
|
||||
}
|
||||
i = valueInfo.nextIndex;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (flagName === "-p" || flagName === "--publish" || flagName === "-p=" || flagName === "--publish=") {
|
||||
const valueInfo = readDockerFlagValue(args, i, inlineValue);
|
||||
const mapping = cleanString(valueInfo.value);
|
||||
if (!mapping) return "Docker publish flag is missing a port mapping.";
|
||||
if (!mapping.includes("{PORT}")) {
|
||||
const hostPort = extractHostPortFromMapping(mapping);
|
||||
if (!hostPort) return `Invalid Docker port mapping: ${mapping}`;
|
||||
if (!allowedHostPorts.has(hostPort)) {
|
||||
return 'Port config through docker edit command is not allowed. Add or remove a port through Port Management.';
|
||||
}
|
||||
if (reservedHostPorts.has(hostPort)) {
|
||||
return `Port ${hostPort} in the Docker command conflicts with a port forwarding rule.`;
|
||||
}
|
||||
}
|
||||
i = valueInfo.nextIndex;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isSafeShortDockerFlagCluster(flagName) || DOCKER_RUN_SAFE_STANDALONE_FLAGS.has(flagName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (DOCKER_RUN_FLAGS_WITH_VALUE.has(flagName)) {
|
||||
const valueInfo = readDockerFlagValue(args, i, inlineValue);
|
||||
if (!cleanString(valueInfo.value)) {
|
||||
return `Docker flag ${flagName} requires a value.`;
|
||||
}
|
||||
i = valueInfo.nextIndex;
|
||||
continue;
|
||||
}
|
||||
|
||||
return `Unsupported Docker flag in startup command: ${flagName}`;
|
||||
}
|
||||
|
||||
return "Startup command must include a Docker image.";
|
||||
}
|
||||
|
||||
function getDockerImageRef(docker) {
|
||||
const image = cleanString(docker?.image);
|
||||
if (!image) return "";
|
||||
const tag = cleanString(docker?.tag) || "latest";
|
||||
return `${image}:${tag}`;
|
||||
}
|
||||
|
||||
function resolveTemplateDockerConfig(source) {
|
||||
if (!source || typeof source !== "object") return null;
|
||||
|
||||
if (source.docker && typeof source.docker === "object") {
|
||||
return source.docker;
|
||||
}
|
||||
|
||||
const image = cleanString(source.image || source.dockerImage);
|
||||
const tag = cleanString(source.tag || source.dockerTag);
|
||||
const command = cleanString(source.command);
|
||||
const startupCommand = cleanString(source.startupCommand);
|
||||
const restart = cleanString(source.restart || source.restartPolicy);
|
||||
const ports = Array.isArray(source.ports) ? source.ports : [];
|
||||
const volumes = Array.isArray(source.volumes) ? source.volumes : [];
|
||||
const env = source.env && typeof source.env === "object" && !Array.isArray(source.env) ? source.env : {};
|
||||
|
||||
if (!image && !tag && !command && !startupCommand && !restart && !ports.length && !volumes.length && !Object.keys(env).length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
image,
|
||||
tag,
|
||||
command,
|
||||
startupCommand,
|
||||
restart,
|
||||
ports,
|
||||
volumes,
|
||||
env,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeStartupCommandForCreate(command, docker) {
|
||||
const cleanCommand = cleanString(command);
|
||||
if (!cleanCommand) return "";
|
||||
const imageRef = getDockerImageRef(resolveTemplateDockerConfig(docker) || docker);
|
||||
if (!imageRef) return cleanCommand;
|
||||
return cleanCommand.replace(/\{IMAGE\}/gi, imageRef).trim();
|
||||
}
|
||||
|
||||
function getDockerVolumes(docker, templateId) {
|
||||
const configuredVolumes = Array.isArray(docker?.volumes)
|
||||
? docker.volumes.map((entry) => cleanString(entry)).filter(Boolean)
|
||||
: [];
|
||||
if (configuredVolumes.length) {
|
||||
return configuredVolumes;
|
||||
}
|
||||
|
||||
const normalizedTemplateId = cleanString(templateId).toLowerCase();
|
||||
if (["nodejs", "discord-bot", "python", "runtime"].includes(normalizedTemplateId)) {
|
||||
return ["{DATA_DIR}:/app"];
|
||||
}
|
||||
return ["{DATA_DIR}:/data"];
|
||||
}
|
||||
|
||||
function getRuntimeCommand(templateId, docker, startFile) {
|
||||
const explicit = cleanString(docker?.command);
|
||||
if (explicit) return explicit;
|
||||
|
||||
const normalizedTemplateId = cleanString(templateId).toLowerCase();
|
||||
const resolvedStartFile = cleanString(startFile);
|
||||
if (normalizedTemplateId === "python") {
|
||||
return `python /app/${resolvedStartFile || "main.py"}`;
|
||||
}
|
||||
if (normalizedTemplateId === "nodejs" || normalizedTemplateId === "discord-bot") {
|
||||
return `cd /app && npm install && node /app/${resolvedStartFile || "index.js"}`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function getContainerPort(templateId, docker, hostPort) {
|
||||
const normalizedTemplateId = cleanString(templateId).toLowerCase();
|
||||
if (["nodejs", "discord-bot", "python", "runtime"].includes(normalizedTemplateId)) {
|
||||
return toPositiveNumber(hostPort);
|
||||
}
|
||||
|
||||
const ports = Array.isArray(docker?.ports) ? docker.ports : [];
|
||||
for (const entry of ports) {
|
||||
const port = toPositiveNumber(entry);
|
||||
if (port > 0) return port;
|
||||
}
|
||||
return toPositiveNumber(hostPort);
|
||||
}
|
||||
|
||||
function buildResourceArgs(resources) {
|
||||
const args = [];
|
||||
const ramMb = toPositiveNumber(resources?.ramMb);
|
||||
const cpuCores = toPositiveNumber(resources?.cpuCores);
|
||||
|
||||
if (ramMb > 0) {
|
||||
args.push("--memory", `${Math.floor(ramMb)}m`);
|
||||
args.push("--memory-reservation", `${Math.max(1, Math.floor((ramMb * 90) / 100))}m`);
|
||||
}
|
||||
|
||||
if (cpuCores > 0) {
|
||||
args.push("--cpus", String(cpuCores));
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
function buildDefaultStartupCommand({ name, templateId, docker, hostPort, resources, startFile }) {
|
||||
const normalizedTemplateId = cleanString(templateId).toLowerCase();
|
||||
if (!docker || typeof docker !== "object") return "";
|
||||
if (normalizedTemplateId === "minecraft") return "";
|
||||
|
||||
const imageRef = getDockerImageRef(docker);
|
||||
if (!imageRef) return "";
|
||||
|
||||
const serverName = cleanString(name) || "{SERVER_NAME}";
|
||||
const externalPort = toPositiveNumber(hostPort);
|
||||
const containerPort = getContainerPort(normalizedTemplateId, docker, hostPort);
|
||||
const parts = ["docker run -d -t", "--name", serverName, "--restart", cleanString(docker?.restart) || "unless-stopped"];
|
||||
|
||||
parts.push(...buildResourceArgs(resources));
|
||||
|
||||
if (externalPort > 0 && containerPort > 0) {
|
||||
parts.push("-p", `${externalPort}:${containerPort}`);
|
||||
}
|
||||
|
||||
for (const volume of getDockerVolumes(docker, normalizedTemplateId)) {
|
||||
parts.push("-v", volume);
|
||||
}
|
||||
|
||||
const env = docker?.env && typeof docker.env === "object" ? docker.env : {};
|
||||
for (const [key, value] of Object.entries(env)) {
|
||||
const envKey = cleanString(key);
|
||||
if (!envKey) continue;
|
||||
parts.push("-e", `${envKey}=${String(value ?? "")}`);
|
||||
}
|
||||
if (externalPort > 0) {
|
||||
parts.push("-e", `PORT=${externalPort}`);
|
||||
}
|
||||
|
||||
parts.push(imageRef);
|
||||
|
||||
const runtimeCommand = getRuntimeCommand(normalizedTemplateId, docker, startFile);
|
||||
if (runtimeCommand) {
|
||||
parts.push("sh", "-lc", JSON.stringify(runtimeCommand));
|
||||
}
|
||||
|
||||
return parts.join(" ").trim();
|
||||
}
|
||||
|
||||
function resolveStartupCommandForCreate({ requestedStartupCommand, template, templateId, name, hostPort, resources, startFile }) {
|
||||
const templateDocker = resolveTemplateDockerConfig(template);
|
||||
const requested = normalizeStartupCommandForCreate(requestedStartupCommand, templateDocker);
|
||||
if (requested) return requested;
|
||||
|
||||
const templateStartupCommand = normalizeStartupCommandForCreate(templateDocker?.startupCommand, templateDocker);
|
||||
if (templateStartupCommand) return templateStartupCommand;
|
||||
|
||||
return buildDefaultStartupCommand({
|
||||
name,
|
||||
templateId: templateId || template?.id || "",
|
||||
docker: templateDocker,
|
||||
hostPort,
|
||||
resources,
|
||||
startFile,
|
||||
});
|
||||
}
|
||||
|
||||
function extractStartupCommandFromNodeCreateResult(result) {
|
||||
if (!result || typeof result !== "object") return "";
|
||||
|
||||
const direct = cleanString(result.startupCommand);
|
||||
if (direct) return direct;
|
||||
|
||||
const metaStartup = cleanString(result.meta?.startupCommand);
|
||||
if (metaStartup) return metaStartup;
|
||||
|
||||
const runtimeStartup = cleanString(result.meta?.runtime?.startupCommand);
|
||||
if (runtimeStartup) return runtimeStartup;
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
function extractTechnicalServerNameFromNodeCreateResult(result, fallback = "") {
|
||||
const candidates = [
|
||||
result?.technicalName,
|
||||
result?.serverTechnicalName,
|
||||
result?.server?.technicalName,
|
||||
result?.meta?.technicalName,
|
||||
result?.meta?.serverTechnicalName,
|
||||
result?.meta?.server?.technicalName,
|
||||
result?.serverName,
|
||||
result?.server?.name,
|
||||
result?.name,
|
||||
result?.meta?.serverName,
|
||||
result?.meta?.server?.name,
|
||||
result?.meta?.name,
|
||||
result?.created?.technicalName,
|
||||
result?.created?.serverName,
|
||||
result?.created?.name,
|
||||
fallback,
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const sanitized = sanitizeServerToken(candidate);
|
||||
if (sanitized) return sanitized;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildDefaultStartupCommand,
|
||||
resolveStartupCommandForCreate,
|
||||
extractStartupCommandFromNodeCreateResult,
|
||||
extractTechnicalServerNameFromNodeCreateResult,
|
||||
validateDockerRunCommandSafety,
|
||||
};
|
||||
@@ -0,0 +1,149 @@
|
||||
"use strict";
|
||||
|
||||
function cleanString(value) {
|
||||
return String(value ?? "").trim();
|
||||
}
|
||||
|
||||
function cleanScript(value, maxLength = 262144) {
|
||||
return String(value ?? "")
|
||||
.replace(/\0/g, "")
|
||||
.replace(/\r\n?/g, "\n")
|
||||
.trim()
|
||||
.slice(0, maxLength);
|
||||
}
|
||||
|
||||
function toFiniteNumber(value) {
|
||||
const numeric = Number(value);
|
||||
return Number.isFinite(numeric) ? numeric : null;
|
||||
}
|
||||
|
||||
function cleanAbsoluteContainerPath(value, fallback = "") {
|
||||
let raw = cleanString(value).replace(/\0/g, "").replace(/\\/g, "/");
|
||||
if (!raw) return fallback;
|
||||
if (!raw.startsWith("/")) return fallback;
|
||||
raw = raw.replace(/\/+/g, "/");
|
||||
if (raw.length > 1) raw = raw.replace(/\/+$/, "");
|
||||
return raw || fallback;
|
||||
}
|
||||
|
||||
function sanitizeEnvPayload(env) {
|
||||
if (!env || typeof env !== "object" || Array.isArray(env)) return null;
|
||||
const out = {};
|
||||
for (const [key, value] of Object.entries(env)) {
|
||||
const envKey = cleanString(key);
|
||||
if (!envKey) continue;
|
||||
out[envKey] = String(value ?? "");
|
||||
}
|
||||
return Object.keys(out).length ? out : null;
|
||||
}
|
||||
|
||||
function sanitizeDockerInstallPayload(install) {
|
||||
if (!install || typeof install !== "object" || Array.isArray(install)) return null;
|
||||
|
||||
const script = cleanScript(install.script || install.installScript || install.install_script);
|
||||
if (!script) return null;
|
||||
|
||||
const image = cleanString(install.image || install.container) || "ghcr.io/pterodactyl/installers:debian";
|
||||
const entrypoint = cleanString(install.entrypoint) || "bash";
|
||||
const mountPath = cleanAbsoluteContainerPath(
|
||||
install.mountPath || install.containerPath || install.container_path || install.serverPath,
|
||||
"/mnt/server"
|
||||
);
|
||||
const runtimePath = cleanAbsoluteContainerPath(
|
||||
install.runtimePath || install.runtime_path || install.homePath || install.home_path,
|
||||
"/home/container"
|
||||
);
|
||||
|
||||
const timeoutRaw = toFiniteNumber(install.timeoutSeconds || install.timeout_seconds || install.timeout);
|
||||
const timeoutSeconds = timeoutRaw && timeoutRaw > 0
|
||||
? Math.max(60, Math.min(Math.trunc(timeoutRaw), 7200))
|
||||
: 1800;
|
||||
const minimumStorageRaw = toFiniteNumber(install.minimumStorageMb || install.minimum_storage_mb);
|
||||
const minimumStorageMb = minimumStorageRaw && minimumStorageRaw > 0
|
||||
? Math.max(1, Math.min(Math.trunc(minimumStorageRaw), 1024 * 1024))
|
||||
: 0;
|
||||
|
||||
const payload = {
|
||||
image,
|
||||
script,
|
||||
entrypoint,
|
||||
mountPath,
|
||||
runtimePath,
|
||||
timeoutSeconds,
|
||||
};
|
||||
if (minimumStorageMb > 0) payload.minimumStorageMb = minimumStorageMb;
|
||||
|
||||
const env = sanitizeEnvPayload(install.env);
|
||||
if (env) payload.env = env;
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
function sanitizeDockerTemplatePayload(docker) {
|
||||
if (!docker || typeof docker !== "object") return null;
|
||||
|
||||
const image = cleanString(docker.image);
|
||||
if (!image) return null;
|
||||
|
||||
const payload = {
|
||||
image,
|
||||
};
|
||||
|
||||
const tag = cleanString(docker.tag) || "latest";
|
||||
if (tag) payload.tag = tag;
|
||||
|
||||
const command = cleanString(docker.command);
|
||||
if (command) payload.command = command;
|
||||
|
||||
const workdir = cleanString(docker.workdir || docker.workingDir || docker.working_dir);
|
||||
if (workdir) payload.workdir = workdir;
|
||||
|
||||
const restart = cleanString(docker.restart);
|
||||
if (restart) payload.restart = restart;
|
||||
|
||||
const restartPolicy = cleanString(docker.restartPolicy);
|
||||
if (restartPolicy) payload.restartPolicy = restartPolicy;
|
||||
|
||||
const ports = Array.isArray(docker.ports)
|
||||
? docker.ports
|
||||
.map((entry) => {
|
||||
const port = toFiniteNumber(entry);
|
||||
return Number.isInteger(port) && port > 0 ? port : null;
|
||||
})
|
||||
.filter((entry) => entry != null)
|
||||
: [];
|
||||
if (ports.length) payload.ports = ports;
|
||||
|
||||
const volumes = Array.isArray(docker.volumes)
|
||||
? docker.volumes.map((entry) => cleanString(entry)).filter(Boolean)
|
||||
: [];
|
||||
if (volumes.length) payload.volumes = volumes;
|
||||
|
||||
const env = sanitizeEnvPayload(docker.env);
|
||||
if (env && Object.keys(env).length) payload.env = env;
|
||||
|
||||
const adpanelStartup = cleanScript(
|
||||
docker.adpanelStartup ||
|
||||
docker.adpanel_startup ||
|
||||
docker.pterodactylStartup ||
|
||||
docker.pterodactyl_startup ||
|
||||
docker.startup,
|
||||
32768
|
||||
);
|
||||
if (adpanelStartup) payload.adpanelStartup = adpanelStartup;
|
||||
|
||||
const install = sanitizeDockerInstallPayload(docker.install || docker.installation);
|
||||
if (install) payload.install = install;
|
||||
|
||||
if (docker.console !== undefined) {
|
||||
payload.console = docker.console;
|
||||
}
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
sanitizeDockerTemplatePayload,
|
||||
sanitizeDockerInstallPayload,
|
||||
sanitizeEnvPayload,
|
||||
};
|
||||
@@ -0,0 +1,114 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const crypto = require("crypto");
|
||||
|
||||
const STEALTH_CONFIG_PATH = path.join(__dirname, "..", "data", "stealth.json");
|
||||
const DEFAULT_COOKIE_NAME = "adpanel_gate";
|
||||
const DEFAULT_STEALTH_CONFIG = {
|
||||
enabled: true,
|
||||
cookieName: DEFAULT_COOKIE_NAME,
|
||||
cookieSecret: "",
|
||||
cookieTtlDays: 30,
|
||||
challengeSecret: "",
|
||||
htmlVariantSalt: "",
|
||||
createdAt: null,
|
||||
rotatedAt: null,
|
||||
};
|
||||
|
||||
function randomToken(bytes = 32) {
|
||||
return crypto.randomBytes(bytes).toString("base64url");
|
||||
}
|
||||
|
||||
function sanitizeCookieName(value) {
|
||||
const raw = String(value || "").trim();
|
||||
if (!raw) return DEFAULT_COOKIE_NAME;
|
||||
return /^[A-Za-z0-9._-]{3,64}$/.test(raw) ? raw : DEFAULT_COOKIE_NAME;
|
||||
}
|
||||
|
||||
function normalizeStealthConfig(input = {}) {
|
||||
const now = new Date().toISOString();
|
||||
const normalized = {
|
||||
...DEFAULT_STEALTH_CONFIG,
|
||||
...(input && typeof input === "object" ? input : {}),
|
||||
};
|
||||
|
||||
normalized.enabled = normalized.enabled !== false;
|
||||
normalized.cookieName = sanitizeCookieName(normalized.cookieName);
|
||||
normalized.cookieSecret = String(normalized.cookieSecret || "").trim() || randomToken(48);
|
||||
|
||||
const ttlDays = parseInt(String(normalized.cookieTtlDays || "").trim(), 10);
|
||||
normalized.cookieTtlDays = Number.isFinite(ttlDays) && ttlDays > 0 ? Math.min(ttlDays, 365) : 30;
|
||||
|
||||
normalized.challengeSecret = String(normalized.challengeSecret || "").trim() || randomToken(48);
|
||||
normalized.htmlVariantSalt = String(normalized.htmlVariantSalt || "").trim() || randomToken(24);
|
||||
normalized.createdAt = String(normalized.createdAt || "").trim() || now;
|
||||
normalized.rotatedAt = String(normalized.rotatedAt || "").trim() || normalized.createdAt;
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function readStealthConfigFile() {
|
||||
try {
|
||||
if (!fs.existsSync(STEALTH_CONFIG_PATH)) return null;
|
||||
const raw = fs.readFileSync(STEALTH_CONFIG_PATH, "utf8");
|
||||
return JSON.parse(raw);
|
||||
} catch (err) {
|
||||
console.warn("[stealth] Failed to read config:", err.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeStealthConfigFile(config) {
|
||||
const normalized = normalizeStealthConfig(config);
|
||||
const dir = path.dirname(STEALTH_CONFIG_PATH);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const tmpPath = `${STEALTH_CONFIG_PATH}.tmp`;
|
||||
fs.writeFileSync(tmpPath, JSON.stringify(normalized, null, 2), { mode: 0o600 });
|
||||
fs.renameSync(tmpPath, STEALTH_CONFIG_PATH);
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function loadStealthConfig() {
|
||||
const existing = readStealthConfigFile();
|
||||
if (!existing) {
|
||||
return writeStealthConfigFile(DEFAULT_STEALTH_CONFIG);
|
||||
}
|
||||
|
||||
const normalized = normalizeStealthConfig(existing);
|
||||
if (JSON.stringify(existing) !== JSON.stringify(normalized)) {
|
||||
return writeStealthConfigFile(normalized);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function saveStealthConfig(partial) {
|
||||
const current = loadStealthConfig();
|
||||
return writeStealthConfigFile({
|
||||
...current,
|
||||
...(partial && typeof partial === "object" ? partial : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function ensureStealthConfig(defaults = {}) {
|
||||
const current = loadStealthConfig();
|
||||
const merged = normalizeStealthConfig({
|
||||
...current,
|
||||
...(defaults && typeof defaults === "object" ? defaults : {}),
|
||||
});
|
||||
if (JSON.stringify(current) !== JSON.stringify(merged)) {
|
||||
return writeStealthConfigFile(merged);
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_COOKIE_NAME,
|
||||
DEFAULT_STEALTH_CONFIG,
|
||||
STEALTH_CONFIG_PATH,
|
||||
ensureStealthConfig,
|
||||
loadStealthConfig,
|
||||
saveStealthConfig,
|
||||
sanitizeCookieName,
|
||||
};
|
||||
Reference in new issue
Block a user