/* * Create-server inline wizard (Settings page). * Redesigned using the Create Node / Node Configure design system: * - Pure inline view (#serverCreateInlineView) switching with #serversOverviewView * - 6-step multi-step sidebar navigation with lock states and active indicators * - PanelInfo cards (.panelinfo-card-main, .panelinfo-row-item, .panelinfo-divider) * - Wizard navigation (.node-wizard-nav-bar) with Previous, Next, and Complete buttons * - Live capacity detection, port validation, startup auto-detection, and payload submission */ window.addEventListener('DOMContentLoaded', () => { // White-label brand name (set inline in page
via window.__BRANDING__); idempotent across scripts. window.__brandName = window.__brandName || (window.__BRANDING__ && window.__BRANDING__.appName) || "ADPanel"; function escapeHtml(s) { return String(s ?? '').replace(/[&<>"']/g, function (m) { return ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]); }); } // --- Views & Global Controls --- const serversOverviewView = document.getElementById('serversOverviewView'); const serverManageInlineView = document.getElementById('serverManageInlineView'); const serverCreateInlineView = document.getElementById('serverCreateInlineView'); const serverCreateBackBtn = document.getElementById('serverCreateBackBtn'); const serverCreateCategoriesNav = document.getElementById('serverCreateCategoriesNav'); const serverCreatePrevBtn = document.getElementById('serverCreatePrevBtn'); const serverCreateNextBtn = document.getElementById('serverCreateNextBtn'); const serverCreateCompleteBtn = document.getElementById('serverCreateCompleteBtn'); const createSpinner = document.getElementById('createSpinner'); const serversCreateWizardBtn = document.getElementById('serversCreateWizardBtn'); // --- Step 1: Configuration elements --- const serverNameEl = document.getElementById('serverName'); const templateGrid = document.getElementById('templateGrid'); const templateInfo = document.getElementById('templateInfo'); const templateInfo2 = document.getElementById('templateInfo2'); const serverCreateForkSection = document.getElementById('serverCreateForkSection'); const forkGrid = document.getElementById('forkGrid'); const forkInfo = document.getElementById('forkInfo'); const nodeGrid = document.getElementById('nodeGrid'); // --- Step 2: Networking elements --- const serverIpEl = document.getElementById('serverIp'); const serverPortEl = document.getElementById('serverPort'); const serverPortPreviewEl = document.getElementById('serverPortPreview'); const portDefaultValueEl = document.getElementById('portDefaultValue'); // --- Step 3: Startup elements --- const startupCommandEl = document.getElementById('startupCommand'); const startupCommandSourceEl = document.getElementById('startupCommandSource'); const startupCommandErrorEl = document.getElementById('startupCommandError'); const startupSpinner = document.getElementById('startupSpinner'); // --- Step 4: Import elements --- const importUrlEl = document.getElementById('importUrl'); const importProgressSection = document.getElementById('importProgressSection'); const importProgressContainer = document.getElementById('importProgressContainer'); const importProgressFill = document.getElementById('importProgressFill'); const importPercent = document.getElementById('importPercent'); const importDownloaded = document.getElementById('importDownloaded'); const importTotal = document.getElementById('importTotal'); // --- Step 5: Resources & Limits elements --- const nodeRamLimitEl = document.getElementById('nodeRamLimit'); const nodeCpuLimitEl = document.getElementById('nodeCpuLimit'); const nodeStorageLimitEl = document.getElementById('nodeStorageLimit'); const resourceRamEl = document.getElementById('resourceRam'); const resourceCpuCoresEl = document.getElementById('resourceCpuCores'); const resourceSwapEl = document.getElementById('resourceSwap'); const resourceStorageEl = document.getElementById('resourceStorage'); const resourceBackupsEl = document.getElementById('resourceBackups'); const resourceMaxSchedulesEl = document.getElementById('resourceMaxSchedules'); const resourceIoWeightEl = document.getElementById('resourceIoWeight'); const resourceCpuWeightEl = document.getElementById('resourceCpuWeight'); const resourcePidsLimitEl = document.getElementById('resourcePidsLimit'); const resourceFileLimitEl = document.getElementById('resourceFileLimit'); const resourceNetworkInboundLimitEl = document.getElementById('resourceNetworkInboundLimit'); const resourceNetworkOutboundLimitEl = document.getElementById('resourceNetworkOutboundLimit'); const resourceNetworkResetMinutesEl = document.getElementById('resourceNetworkResetMinutes'); const resourceDiskEl = document.getElementById('resourceDisk'); const resourceDiskHintEl = document.getElementById('resourceDiskHint'); // --- Step 6: Summary elements --- const summaryNameEl = document.getElementById('summaryServerName'); const summaryTemplateEl = document.getElementById('summaryTemplateName'); const summaryForkRow = document.getElementById('summaryForkRow'); const summaryForkName = document.getElementById('summaryForkName'); const summaryNodeEl = document.getElementById('summaryNodeName'); const summaryPort = document.getElementById('summaryPort'); const summaryRam = document.getElementById('summaryRam'); const summaryCpu = document.getElementById('summaryCpu'); const summaryStorage = document.getElementById('summaryStorage'); const summaryDisk = document.getElementById('summaryDisk'); // --- State Variables --- let createServerCurrentStep = 1; let createServerMaxStepReached = 1; let templates = []; let nodes = []; let selectedTemplateId = null; let selectedForkId = null; let selectedNodeId = ""; let selectedStartupCommand = ""; let selectedStartupCommandMode = ""; let selectedImportUrl = ""; const liveNodeCapacityCache = new Map(); const startupCommandCache = new Map(); const RESOURCE_NETWORK_LIMIT_MAX_MB = 1073741824; const RESOURCE_NETWORK_RESET_MAX_MINUTES = 43200; const MAX_SERVER_NAME_LENGTH = 40; const MC_VERSION = "1.21.8"; const MC_FORKS = [ { id: "paper", name: "Paper", desc: "Optimized performance with plugin support" }, { id: "pufferfish", name: "Pufferfish", desc: "TPS-focused optimizations" }, { id: "vanilla", name: "Vanilla", desc: "Standard Minecraft experience" }, { id: "purpur", name: "Purpur", desc: "Paper fork with extra settings" } ]; const ALLOWED_ARCHIVE_EXTENSIONS = ['.zip', '.rar', '.7z', '.tar.gz', '.tgz', '.tar.bz2', '.tbz2']; function sanitizeName(s) { s = (s || '').trim(); s = s.replace(/\s+/g, '-').replace(/[^a-zA-Z0-9\-_]/g, ''); return s.slice(0, MAX_SERVER_NAME_LENGTH) || ''; } function isValidArchiveUrl(url) { if (!url) return true; try { const parsedUrl = new URL(url); if (!['http:', 'https:'].includes(parsedUrl.protocol)) return false; const pathname = parsedUrl.pathname.toLowerCase(); return ALLOWED_ARCHIVE_EXTENSIONS.some(ext => pathname.endsWith(ext)); } catch { return false; } } function getTemplateMeta(t) { return { icon: 'fa-solid fa-cube', badge: t?.name || 'Template' }; } function autoResizeStartupCommand() { if (!startupCommandEl) return; startupCommandEl.style.height = 'auto'; startupCommandEl.style.height = Math.max(42, startupCommandEl.scrollHeight) + 'px'; } function getDefaultPortForTemplate(templateId) { const id = (templateId || '').toString().toLowerCase(); if (!id) return 25565; const configuredTemplate = (templates || []).find(t => String(t?.id || '').trim().toLowerCase() === id); const configuredPort = parseStrictPortValue( configuredTemplate?.defaultPort || configuredTemplate?.default_port || configuredTemplate?.docker?.ports?.[0] ); if (configuredPort) return configuredPort; if (id.includes('minecraft') || id === 'mc') return 25565; if (id.includes('node') || id.includes('discord')) return 3000; if (id.includes('http') || id.includes('web') || id.includes('proxy')) return 80; return 8080; } function parseStrictPortValue(value) { const str = String(value ?? '').trim(); if (!/^[1-9]\d{0,4}$/.test(str)) return null; const port = Number(str); if (!Number.isInteger(port) || port < 1 || port > 65535) return null; return port; } function sanitizePortInputValue(value) { return String(value ?? '').replace(/[^\d]/g, '').slice(0, 5); } function bindStrictPortInput(input) { if (!input) return; input.setAttribute('inputmode', 'numeric'); input.addEventListener('input', () => { const sanitized = sanitizePortInputValue(input.value); if (input.value !== sanitized) input.value = sanitized; if (serverPortPreviewEl) serverPortPreviewEl.textContent = sanitized || '25565'; }); } bindStrictPortInput(serverPortEl); function readCreateResourceValues() { const cpuCores = readOptionalResourceNumber(resourceCpuCoresEl, 'CPU cores'); if (cpuCores !== null && (cpuCores < 0 || cpuCores > Number.MAX_SAFE_INTEGER / 1e9)) { throw new Error('CPU cores must be within the supported range.'); } const maxResourceMb = Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024)); return { ramMb: readOptionalIntegerRange(resourceRamEl, 'RAM limit', 0, maxResourceMb), cpuCores, swapMb: readOptionalIntegerRange(resourceSwapEl, 'Swap limit', -1, maxResourceMb), storageMb: readOptionalIntegerRange(resourceStorageEl, 'Storage limit', 0, maxResourceMb), backupsMax: readOptionalIntegerRange(resourceBackupsEl, 'Max Backups', 0, Number.MAX_SAFE_INTEGER), maxSchedules: readOptionalIntegerRange(resourceMaxSchedulesEl, 'Max Schedules', 0, Number.MAX_SAFE_INTEGER), ioWeight: readOptionalIntegerRange(resourceIoWeightEl, 'I/O Priority', 10, 1000), cpuWeight: readOptionalIntegerRange(resourceCpuWeightEl, 'CPU Priority', 1, 1000), pidsLimit: readOptionalIntegerRange(resourcePidsLimitEl, 'Process Limit', 64, 4096), fileLimit: readOptionalIntegerRange(resourceFileLimitEl, 'File Limit', 1024, 1048576), networkInboundLimitMb: readOptionalIntegerRange(resourceNetworkInboundLimitEl, 'Inbound Limit', 1, RESOURCE_NETWORK_LIMIT_MAX_MB), networkOutboundLimitMb: readOptionalIntegerRange(resourceNetworkOutboundLimitEl, 'Outbound Limit', 1, RESOURCE_NETWORK_LIMIT_MAX_MB), networkResetMinutes: readOptionalIntegerRange(resourceNetworkResetMinutesEl, 'Reset Time', 1, RESOURCE_NETWORK_RESET_MAX_MINUTES) }; } function resolveNodeCacheKey(node) { return String(node?.id || node?.uuid || node?.name || '').trim(); } function configuredNodeCapacity(node) { return { ramMb: Math.max(0, Math.trunc(Number(node?.ram_mb || node?.buildConfig?.ram_mb || 0))), cpuCores: Math.max(0, Number(node?.cpu_cores || node?.buildConfig?.cpu_cores || node?.buildConfig?.cpuCores || 0)), diskGb: Math.max(0, Number(node?.disk_gb || node?.buildConfig?.disk_gb || node?.buildConfig?.diskGb || 0)) }; } function mergeNodeCapacityValue(configured, live, round, preferLive) { const cfg = Number(configured); const detected = Number(live); let value = 0; if (preferLive && Number.isFinite(detected) && detected > 0) value = detected; else if (Number.isFinite(cfg) && cfg > 0 && Number.isFinite(detected) && detected > 0) value = Math.min(cfg, detected); else if (Number.isFinite(detected) && detected > 0) value = detected; else if (Number.isFinite(cfg) && cfg > 0) value = cfg; return round ? Math.trunc(value) : value; } function resolveEffectiveNodeCapacity(node, liveCapacity) { const configured = configuredNodeCapacity(node); const live = (liveCapacity && typeof liveCapacity === 'object') ? liveCapacity : {}; return { ramMb: mergeNodeCapacityValue(configured.ramMb, live.ramMb, true, true), cpuCores: mergeNodeCapacityValue(configured.cpuCores, live.cpuCores, false), diskGb: mergeNodeCapacityValue(configured.diskGb, live.diskGb, false) }; } function applyNodeCapacity(capacity) { const ramMb = Number(capacity?.ramMb || 0); const cpuCores = Number(capacity?.cpuCores || 0); const diskGb = Number(capacity?.diskGb || 0); const diskMb = diskGb > 0 ? Math.trunc(diskGb * 1024) : 0; if (nodeRamLimitEl) nodeRamLimitEl.textContent = ramMb > 0 ? `${ramMb.toLocaleString()} MB` : 'Unlimited'; if (nodeCpuLimitEl) nodeCpuLimitEl.textContent = cpuCores > 0 ? `${cpuCores} cores` : 'Unlimited'; if (nodeStorageLimitEl) nodeStorageLimitEl.textContent = diskMb > 0 ? (diskMb >= 1010 ? `${(diskMb / 1024).toFixed(2).replace(/\.?0+$/, '')} GB` : `${diskMb.toLocaleString()} MB`) : 'Unlimited'; if (resourceRamEl) { if (ramMb > 0) resourceRamEl.max = ramMb; else resourceRamEl.removeAttribute('max'); } if (resourceCpuCoresEl) { if (cpuCores > 0) resourceCpuCoresEl.max = cpuCores; else resourceCpuCoresEl.removeAttribute('max'); } if (resourceStorageEl) { if (diskMb > 0) resourceStorageEl.max = diskMb; else resourceStorageEl.removeAttribute('max'); } } async function fetchLiveNodeCapacity(node) { const cacheKey = resolveNodeCacheKey(node); if (!cacheKey) return null; if (liveNodeCapacityCache.has(cacheKey)) return liveNodeCapacityCache.get(cacheKey); try { const res = await fetch(`/api/admin/nodes/${encodeURIComponent(cacheKey)}/stats`, { cache: 'no-store' }); const data = await res.json().catch(() => ({})); if (!res.ok || !data.ok || !data.online || !data.stats) return null; const liveCapacity = { ramMb: Math.max(0, Math.trunc(Number(data.stats?.ram?.totalMb || 0))), cpuCores: Math.max(0, Number(data.stats?.cpu?.cores || 0)), diskGb: Math.max(0, Number(data.stats?.disk?.totalGb || 0)) }; liveNodeCapacityCache.set(cacheKey, liveCapacity); return liveCapacity; } catch { return null; } } async function getEffectiveNodeCapacity(node) { const liveCapacity = await fetchLiveNodeCapacity(node); return resolveEffectiveNodeCapacity(node, liveCapacity); } function formatDiskOptionUsage(disk) { const used = Number(disk?.usedGb || 0); const limit = Number(disk?.limitGb || 0); const usedStr = (used >= 10 ? used.toFixed(0) : used.toFixed(1)).replace(/\.0$/, ''); return limit > 0 ? `${usedStr}/${limit} GB` : `${usedStr} GB used`; } async function populateNodeDiskOptions(node) { if (!resourceDiskEl) return; const primaryOpt = ''; resourceDiskEl.innerHTML = primaryOpt; resourceDiskEl.value = 'primary'; if (resourceDiskHintEl) resourceDiskHintEl.textContent = 'Server files are stored on the selected disk.'; const id = node && (node.id || node.uuid || node.name); if (!id) return; try { const res = await fetch(`/api/nodes/${encodeURIComponent(id)}/disks`, { cache: 'no-store' }); const data = await res.json().catch(() => ({})); if (!res.ok || !Array.isArray(data.disks)) return; const current = getSelectedNode(); if (!current || resolveNodeCacheKey(current) !== resolveNodeCacheKey(node)) return; const options = []; const additional = []; for (const d of data.disks) { const isPrimary = !!d.primary || String(d.id) === 'primary'; if (isPrimary) continue; additional.push(d); } options.push(primaryOpt); for (const d of additional) { const label = `${d.mountPath} (${formatDiskOptionUsage(d)})`; options.push(``); } resourceDiskEl.innerHTML = options.join(''); resourceDiskEl.value = 'primary'; if (resourceDiskHintEl) { resourceDiskHintEl.textContent = additional.length ? 'Primary is used by default. Select an additional disk to place this server elsewhere.' : 'This node has only the primary disk available.'; } } catch { // Leave primary } } function getSelectedNode() { if (!selectedNodeId) return null; return (nodes || []).find(x => (x.uuid === selectedNodeId) || (x.id === selectedNodeId) || (x.name === selectedNodeId) ) || null; } async function verifySelectedNodePortAvailable(portVal) { const node = getSelectedNode(); if (!node || !portVal) return true; try { const nodeId = encodeURIComponent(node.uuid || node.id || node.name || selectedNodeId); const res = await fetch(`/api/nodes/${nodeId}/ports/check?port=${encodeURIComponent(String(portVal))}`); const data = await res.json().catch(() => ({})); if (res.ok && data && data.available === false) { showCreateStepFeedback('feedback_server_create_networking', data.detail || data.error || `Port ${portVal} is already in use on this node.`); return false; } } catch (_) { } return true; } function findTemplateById(templateId) { const id = String(templateId || '').trim(); if (!id) return null; return (templates || []).find(t => String(t?.id || '').trim() === id) || null; } function buildDefaultStartupCommandForTemplate(template) { if (!template || !template.docker) return ''; // A projected (non-admin) template withholds the launch command; guessing // a per-id default here would be submitted as an override and replace the // template's own startup server-side. if (template.startupHidden) return ''; const explicit = String(template.docker?.command || '').trim(); if (explicit) return explicit; const templateId = String(template.id || '').trim().toLowerCase(); if (templateId === 'minecraft') { return `java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui`; } if (templateId === 'python') { return `python /app/main.py`; } if (templateId === 'nodejs' || templateId === 'discord-bot') { return `node /app/index.js`; } return ''; } function parseRuntimeProcessArgsInput(value) { const input = String(value || ''); const args = []; let current = ''; let quote = ''; let escape = false; for (let i = 0; i < input.length; i += 1) { const ch = input[i]; if (escape) { current += ch; escape = false; continue; } if (ch === '\\') { escape = true; continue; } if (quote) { if (ch === quote) quote = ''; else current += ch; continue; } if (ch === '"' || ch === "'") { quote = ch; continue; } if (/\s/.test(ch)) { if (current) { args.push(current); current = ''; } continue; } current += ch; } if (current) args.push(current); return args; } function validateRuntimeProcessCommandInput(value) { const command = String(value || '').trim(); if (!command) return null; if (command.length > 4000) return 'Process command is too long.'; if (command.includes('\n')) return 'Process command must be a single line.'; if (command.includes('`') || command.includes('$(')) { return 'Shell expansions are not allowed in process commands.'; } const args = parseRuntimeProcessArgsInput(command); if (!args.length) return 'Process command is empty.'; return null; } async function resolveStartupCommandForSelection(options = {}) { const templateId = String(options.templateId ?? selectedTemplateId ?? '').trim(); const nodeId = String(options.nodeId ?? selectedNodeId ?? 'none').trim() || 'none'; const forceRefresh = !!options.forceRefresh; const template = findTemplateById(templateId); if (!template) { selectedStartupCommand = ''; if (startupCommandEl) startupCommandEl.value = ''; if (startupCommandSourceEl) startupCommandSourceEl.textContent = 'No template selected yet.'; return ''; } if (template.startupHidden) { // The listing withheld this template's launch command (docker.command / // adpanelStartup are part of the audited leak surface), so there is // nothing to prefill and no guess may be submitted: yield the // no-command state so the create endpoint applies the template's own // startup. A deliberately typed override still submits (the input // listener clears the managed mode). selectedStartupCommand = ''; selectedStartupCommandMode = 'template-managed'; if (startupCommandEl) { startupCommandEl.value = ''; startupCommandEl.readOnly = true; } if (startupCommandSourceEl) startupCommandSourceEl.textContent = 'Startup is managed by the selected template.'; return ''; } const templateDefinedCommand = String(template?.docker?.command || '').trim(); const templateADPanelStartup = String( template?.docker?.adpanelStartup || template?.docker?.adpanel_startup || template?.docker?.pterodactylStartup || template?.docker?.pterodactyl_startup || '' ).trim(); if (startupCommandEl) startupCommandEl.readOnly = false; if (templateADPanelStartup) { selectedStartupCommand = templateADPanelStartup; selectedStartupCommandMode = 'adpanel-startup'; if (startupCommandEl) { startupCommandEl.value = selectedStartupCommand; startupCommandEl.readOnly = true; } if (startupCommandSourceEl) startupCommandSourceEl.textContent = 'Using the startup command defined by this template.'; return selectedStartupCommand; } selectedStartupCommandMode = ''; const fallbackCommand = buildDefaultStartupCommandForTemplate(template); const candidate = String(templateDefinedCommand || fallbackCommand || '').trim(); selectedStartupCommand = candidate; if (startupCommandEl) startupCommandEl.value = selectedStartupCommand; if (startupCommandSourceEl) { startupCommandSourceEl.textContent = templateDefinedCommand ? 'Using startup command defined in this template.' : 'Using default startup command for this template.'; } if (!templateDefinedCommand) { const cacheKey = `${String(templateId).toLowerCase()}::${String(nodeId).toLowerCase()}`; try { if (startupSpinner) startupSpinner.style.display = 'inline-block'; let detected = null; if (!forceRefresh && startupCommandCache.has(cacheKey)) { detected = startupCommandCache.get(cacheKey); } else { const response = await fetch('/api/templates/startup-command', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ templateId, nodeId }) }); const data = await response.json().catch(() => ({})); detected = { ok: response.ok && data?.ok, data }; startupCommandCache.set(cacheKey, detected); } if (detected?.ok && detected.data) { const data = detected.data; let detectedCommand = String(data.command || '').trim(); if (detectedCommand) { selectedStartupCommand = detectedCommand; if (startupCommandEl) startupCommandEl.value = selectedStartupCommand; if (startupCommandSourceEl) startupCommandSourceEl.textContent = 'Auto-detected process command from Docker image.'; } } } catch (_) { } finally { if (startupSpinner) startupSpinner.style.display = 'none'; } } if (startupCommandEl) { autoResizeStartupCommand(); } return selectedStartupCommand; } // --- Rendering Functions --- async function fetchTemplates() { try { const r = await fetch('/api/templates'); if (!r.ok) throw new Error('Failed to load templates'); const data = await r.json(); templates = (data && data.templates) || []; } catch { templates = [ { id: 'minecraft', name: 'Minecraft', description: 'Minecraft server with fork selection.' }, { id: 'nodejs', name: 'Node.js', description: 'Node.js runtime environment.' }, { id: 'python', name: 'Python', description: 'Python application runtime.' } ]; } renderTemplates(); } async function fetchNodes() { try { const r = await fetch('/api/nodes'); const data = await r.json(); nodes = (data && data.nodes) ? data.nodes : []; } catch { nodes = []; } renderNodes(); } function renderTemplates() { if (!templateGrid) return; templateGrid.innerHTML = ''; if (!templates.length) { templateGrid.innerHTML = '