/* * 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 = '
No templates available.
'; return; } templates.forEach(t => { const card = document.createElement('button'); card.type = 'button'; card.className = 'csw-template-item'; card.setAttribute('role', 'option'); card.setAttribute('aria-selected', 'false'); const meta = getTemplateMeta(t); card.innerHTML = `
${escapeHtml(t.name)}
`; card.addEventListener('click', () => { selectedTemplateId = t.id; selectedStartupCommand = buildDefaultStartupCommandForTemplate(t) || ''; [...templateGrid.children].forEach(c => { c.classList.remove('selected'); c.setAttribute('aria-selected', 'false'); }); card.classList.add('selected'); card.setAttribute('aria-selected', 'true'); // Dynamic Fork Section if (t.id === 'minecraft') { if (serverCreateForkSection) serverCreateForkSection.style.display = 'block'; renderForks(); } else { if (serverCreateForkSection) serverCreateForkSection.style.display = 'none'; selectedForkId = null; } // Port update const defPort = getDefaultPortForTemplate(t.id); if (serverPortEl) serverPortEl.value = String(defPort); if (portDefaultValueEl) portDefaultValueEl.textContent = String(defPort); if (serverPortPreviewEl) serverPortPreviewEl.textContent = String(defPort); void resolveStartupCommandForSelection({ templateId: selectedTemplateId, nodeId: selectedNodeId, forceRefresh: false }); }); if (selectedTemplateId && selectedTemplateId === t.id) { card.classList.add('selected'); card.setAttribute('aria-selected', 'true'); } templateGrid.appendChild(card); }); if (!selectedTemplateId && templates.length > 0) { const first = templateGrid.children[0]; if (first) first.click(); } } function renderForks() { if (!forkGrid) return; forkGrid.innerHTML = ''; MC_FORKS.forEach(f => { const card = document.createElement('button'); card.type = 'button'; card.className = 'csw-fork-item'; card.setAttribute('role', 'option'); card.setAttribute('aria-selected', 'false'); card.innerHTML = `
${escapeHtml(f.name)}
${escapeHtml(f.desc)}
`; card.addEventListener('click', () => { selectedForkId = f.id; [...forkGrid.children].forEach(c => { c.classList.remove('selected'); c.setAttribute('aria-selected', 'false'); }); card.classList.add('selected'); card.setAttribute('aria-selected', 'true'); if (forkInfo) forkInfo.textContent = `${f.name} selected.`; }); if (!selectedForkId && f.id === 'paper') { selectedForkId = 'paper'; card.classList.add('selected'); card.setAttribute('aria-selected', 'true'); if (forkInfo) forkInfo.textContent = `${f.name} selected.`; } else if (selectedForkId === f.id) { card.classList.add('selected'); card.setAttribute('aria-selected', 'true'); } forkGrid.appendChild(card); }); } function renderNodes() { if (!nodeGrid) return; nodeGrid.innerHTML = ''; if (!nodes.length) { nodeGrid.innerHTML = '
No nodes configured. Add a node before creating a server.
'; selectedNodeId = ''; return; } const autoNode = nodes.find(n => n && n.online) || nodes[0]; if (!selectedNodeId && autoNode) { selectedNodeId = autoNode.uuid || autoNode.id || autoNode.name || ''; } nodes.forEach(n => { const online = !!n.online; const nodeValue = n.uuid || n.id || n.name; const el = document.createElement('button'); el.type = 'button'; el.className = 'csw-node-item'; el.setAttribute('role', 'option'); el.setAttribute('aria-selected', 'false'); el.innerHTML = `
${escapeHtml(n.name || n.uuid)}
${online ? '● Online' : '○ Offline'} · ${escapeHtml(n.address || 'No address')}
`; el.addEventListener('click', () => { selectedNodeId = nodeValue; [...nodeGrid.children].forEach(c => { c.classList.remove('selected'); c.setAttribute('aria-selected', 'false'); }); el.classList.add('selected'); el.setAttribute('aria-selected', 'true'); if (serverIpEl) { serverIpEl.textContent = n.address || n.host || 'unknown'; } }); if (nodeValue && selectedNodeId === nodeValue) { el.classList.add('selected'); el.setAttribute('aria-selected', 'true'); if (serverIpEl) { serverIpEl.textContent = n.address || n.host || 'unknown'; } } nodeGrid.appendChild(el); }); } function renderCreateServerSummary() { const rawName = serverNameEl?.value?.trim() || 'My Server'; if (summaryNameEl) summaryNameEl.textContent = rawName; const t = findTemplateById(selectedTemplateId); if (summaryTemplateEl) summaryTemplateEl.textContent = t ? t.name : (selectedTemplateId || '—'); if (selectedTemplateId === 'minecraft') { if (summaryForkRow) summaryForkRow.style.display = 'flex'; const forkObj = MC_FORKS.find(f => f.id === selectedForkId); if (summaryForkName) summaryForkName.textContent = forkObj ? forkObj.name : (selectedForkId || 'Paper'); } else { if (summaryForkRow) summaryForkRow.style.display = 'none'; } const n = getSelectedNode(); if (summaryNodeEl) summaryNodeEl.textContent = n ? (n.name || n.uuid) : '—'; const portVal = serverPortEl?.value || '25565'; if (summaryPort) summaryPort.textContent = `${portVal} (${serverIpEl?.textContent || '0.0.0.0'})`; const ramVal = resourceRamEl?.value ? `${resourceRamEl.value} MB` : 'Node Default'; if (summaryRam) summaryRam.textContent = ramVal; const cpuVal = resourceCpuCoresEl?.value ? `${resourceCpuCoresEl.value} cores` : 'Node Default'; if (summaryCpu) summaryCpu.textContent = cpuVal; const storageVal = resourceStorageEl?.value ? `${resourceStorageEl.value} MB` : 'Node Default'; if (summaryStorage) summaryStorage.textContent = storageVal; const diskVal = resourceDiskEl?.value === 'primary' ? 'Primary (/var/lib/node)' : (resourceDiskEl?.options[resourceDiskEl.selectedIndex]?.text || 'Primary'); if (summaryDisk) summaryDisk.textContent = diskVal; } function showCreateStepFeedback(feedbackId, msg, isError = true) { const el = document.getElementById(feedbackId); if (!el) return; el.textContent = msg || ''; el.className = `panelinfo-update-status ${isError ? 'error' : 'success'}`; el.style.display = msg ? 'block' : 'none'; } // --- Step Validation --- async function validateCreateServerStep(step) { if (step === 1) { const rawName = serverNameEl?.value || ''; const name = sanitizeName(rawName); if (!name) { showCreateStepFeedback('feedback_server_create_config', 'Server Name is required (letters, numbers, dashes, underscores).'); if (serverNameEl) serverNameEl.focus(); return false; } if (!selectedTemplateId) { showCreateStepFeedback('feedback_server_create_config', 'Please select a template to continue.'); return false; } if (selectedTemplateId === 'minecraft' && !selectedForkId) { showCreateStepFeedback('feedback_server_create_config', 'Please select a Minecraft distribution/fork.'); return false; } const node = getSelectedNode(); if (!node) { showCreateStepFeedback('feedback_server_create_config', 'Please choose a target node.'); return false; } if (!node.online) { showCreateStepFeedback('feedback_server_create_config', 'The chosen node is currently offline. Please choose an online node.'); return false; } showCreateStepFeedback('feedback_server_create_config', '', false); return true; } if (step === 2) { const portVal = parseStrictPortValue(serverPortEl?.value); if (!portVal) { showCreateStepFeedback('feedback_server_create_networking', 'Invalid port. Please specify a valid port number between 1 and 65535.'); if (serverPortEl) serverPortEl.focus(); return false; } const node = getSelectedNode(); if (node && node.ports) { const alloc = node.ports; let allowed = true; if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) { allowed = portVal >= alloc.start && portVal < alloc.start + alloc.count; } else if (alloc.mode === 'list' && Array.isArray(alloc.ports) && alloc.ports.length > 0) { allowed = alloc.ports.includes(portVal); } if (!allowed) { let desc = alloc.mode === 'range' ? `${alloc.start}–${alloc.start + alloc.count - 1}` : alloc.ports.join(', '); showCreateStepFeedback('feedback_server_create_networking', `Port ${portVal} is not within node port allocation (${desc}).`); return false; } } const available = await verifySelectedNodePortAvailable(portVal); if (!available) return false; showCreateStepFeedback('feedback_server_create_networking', '', false); return true; } if (step === 3) { const cmd = startupCommandEl?.value || ''; const cmdErr = validateRuntimeProcessCommandInput(cmd); if (cmdErr) { showCreateStepFeedback('feedback_server_create_startup', cmdErr); return false; } showCreateStepFeedback('feedback_server_create_startup', '', false); return true; } if (step === 4) { const url = (importUrlEl?.value || '').trim(); if (url && !isValidArchiveUrl(url)) { showCreateStepFeedback('feedback_server_create_import', 'Invalid archive URL. Please provide a direct link ending in .zip, .rar, .7z, or .tar.gz'); return false; } selectedImportUrl = url; showCreateStepFeedback('feedback_server_create_import', '', false); return true; } if (step === 5) { const node = getSelectedNode(); if (!node) { showCreateStepFeedback('feedback_server_create_resources', 'Please select a node in Step 1.'); return false; } const effectiveCapacity = await getEffectiveNodeCapacity(node); const ramMb = effectiveCapacity.ramMb; const cpuCores = effectiveCapacity.cpuCores; const diskMb = effectiveCapacity.diskGb > 0 ? Math.trunc(effectiveCapacity.diskGb * 1024) : 0; let requested; try { requested = readCreateResourceValues(); } catch (err) { showCreateStepFeedback('feedback_server_create_resources', err.message); return false; } if (ramMb > 0 && requested.ramMb > ramMb) { showCreateStepFeedback('feedback_server_create_resources', `RAM limit cannot exceed node maximum (${ramMb.toLocaleString()} MB).`); return false; } if (cpuCores > 0 && requested.cpuCores > cpuCores) { showCreateStepFeedback('feedback_server_create_resources', `CPU cores cannot exceed node maximum (${cpuCores} cores).`); return false; } if (diskMb > 0 && requested.storageMb > diskMb) { showCreateStepFeedback('feedback_server_create_resources', `Storage limit cannot exceed node maximum (${diskMb.toLocaleString()} MB).`); return false; } showCreateStepFeedback('feedback_server_create_resources', '', false); return true; } return true; } // --- Step Navigation Functions --- function goToCreateServerStep(targetStep) { const step = Math.max(1, Math.min(6, parseInt(targetStep, 10) || 1)); createServerCurrentStep = step; if (step > createServerMaxStepReached) { createServerMaxStepReached = step; } if (serverCreateCategoriesNav) { serverCreateCategoriesNav.querySelectorAll('.server-category-btn').forEach(btn => { const s = parseInt(btn.getAttribute('data-step') || '1', 10); btn.classList.toggle('active', s === step); btn.classList.toggle('is-locked', s > createServerMaxStepReached); }); } const paneIds = [ 'pane_server_create_config', 'pane_server_create_networking', 'pane_server_create_startup', 'pane_server_create_import', 'pane_server_create_resources', 'pane_server_create_summary' ]; paneIds.forEach((pId, idx) => { const paneEl = document.getElementById(pId); if (paneEl) { paneEl.classList.toggle('active', idx + 1 === step); } }); if (serverCreatePrevBtn) { serverCreatePrevBtn.style.display = step > 1 ? 'inline-flex' : 'none'; } if (serverCreateNextBtn) { serverCreateNextBtn.style.display = step < 6 ? 'inline-flex' : 'none'; } if (serverCreateCompleteBtn) { serverCreateCompleteBtn.style.display = step === 6 ? 'inline-flex' : 'none'; } if (step === 2) { const node = getSelectedNode(); if (node && serverIpEl) { serverIpEl.textContent = node.address || node.host || 'unknown'; } if (serverPortPreviewEl && serverPortEl) { serverPortPreviewEl.textContent = serverPortEl.value || '25565'; } } else if (step === 3) { void resolveStartupCommandForSelection({ templateId: selectedTemplateId, nodeId: selectedNodeId, forceRefresh: false }).then(() => { autoResizeStartupCommand(); }); } else if (step === 5) { const node = getSelectedNode(); if (node) { applyNodeCapacity(resolveEffectiveNodeCapacity(node, null)); populateNodeDiskOptions(node); fetchLiveNodeCapacity(node).then(live => { if (live) applyNodeCapacity(resolveEffectiveNodeCapacity(node, live)); }); } } else if (step === 6) { renderCreateServerSummary(); } } function resetCreateServerWizard() { createServerCurrentStep = 1; createServerMaxStepReached = 1; selectedTemplateId = null; selectedForkId = null; selectedNodeId = ""; selectedStartupCommand = ""; selectedStartupCommandMode = ""; selectedImportUrl = ""; if (serverNameEl) serverNameEl.value = ''; if (serverPortEl) serverPortEl.value = ''; if (startupCommandEl) startupCommandEl.value = ''; if (importUrlEl) importUrlEl.value = ''; if (resourceRamEl) resourceRamEl.value = ''; if (resourceCpuCoresEl) resourceCpuCoresEl.value = ''; if (resourceSwapEl) resourceSwapEl.value = ''; if (resourceStorageEl) resourceStorageEl.value = ''; if (resourceBackupsEl) resourceBackupsEl.value = ''; if (resourceMaxSchedulesEl) resourceMaxSchedulesEl.value = ''; if (resourceIoWeightEl) resourceIoWeightEl.value = ''; if (resourceCpuWeightEl) resourceCpuWeightEl.value = ''; if (resourcePidsLimitEl) resourcePidsLimitEl.value = ''; if (resourceFileLimitEl) resourceFileLimitEl.value = ''; if (resourceNetworkInboundLimitEl) resourceNetworkInboundLimitEl.value = ''; if (resourceNetworkOutboundLimitEl) resourceNetworkOutboundLimitEl.value = ''; if (resourceNetworkResetMinutesEl) resourceNetworkResetMinutesEl.value = ''; ['feedback_server_create_config', 'feedback_server_create_networking', 'feedback_server_create_startup', 'feedback_server_create_import', 'feedback_server_create_resources', 'feedback_server_create_summary'].forEach(id => { const el = document.getElementById(id); if (el) { el.textContent = ''; el.style.display = 'none'; } }); if (serverCreateForkSection) serverCreateForkSection.style.display = 'none'; fetchTemplates(); fetchNodes(); goToCreateServerStep(1); } function showServerCreateView(show) { if (show) { if (serversOverviewView) serversOverviewView.style.display = 'none'; if (serverManageInlineView) serverManageInlineView.style.display = 'none'; if (serverCreateInlineView) serverCreateInlineView.style.display = 'flex'; resetCreateServerWizard(); } else { if (serverCreateInlineView) serverCreateInlineView.style.display = 'none'; if (serversOverviewView) serversOverviewView.style.display = 'block'; } } // --- Event Listeners --- if (serversCreateWizardBtn) { serversCreateWizardBtn.addEventListener('click', (e) => { e.preventDefault(); showServerCreateView(true); }); } if (serverCreateBackBtn) { serverCreateBackBtn.addEventListener('click', () => { showServerCreateView(false); }); } if (startupCommandEl) { startupCommandEl.addEventListener('input', autoResizeStartupCommand); } if (serverCreateNextBtn) { serverCreateNextBtn.addEventListener('click', async () => { const ok = await validateCreateServerStep(createServerCurrentStep); if (ok) { goToCreateServerStep(createServerCurrentStep + 1); } }); } if (serverCreatePrevBtn) { serverCreatePrevBtn.addEventListener('click', () => { if (createServerCurrentStep > 1) { goToCreateServerStep(createServerCurrentStep - 1); } }); } if (serverCreateCategoriesNav) { serverCreateCategoriesNav.addEventListener('click', async (e) => { const btn = e.target.closest('.server-category-btn'); if (!btn) return; const targetStep = parseInt(btn.getAttribute('data-step') || '1', 10); if (targetStep === createServerCurrentStep) return; if (targetStep < createServerCurrentStep) { goToCreateServerStep(targetStep); } else { const ok = await validateCreateServerStep(createServerCurrentStep); if (ok) { goToCreateServerStep(targetStep); } } }); } // Complete / Deploy Button if (serverCreateCompleteBtn) { serverCreateCompleteBtn.addEventListener('click', async () => { const ok = await validateCreateServerStep(5); if (!ok) { goToCreateServerStep(5); return; } const raw = serverNameEl?.value || ''; const name = sanitizeName(raw); const node = getSelectedNode(); const portVal = parseStrictPortValue(serverPortEl?.value); if (!name || !selectedTemplateId || !node || !portVal) { showCreateStepFeedback('feedback_server_create_summary', 'Incomplete server configuration. Please check all steps.'); return; } try { if (createSpinner) createSpinner.style.display = 'inline-block'; serverCreateCompleteBtn.disabled = true; const displayName = raw.trim().replace(/[^a-zA-Z0-9 \-_.]/g, '').replace(/\s+/g, ' ').slice(0, 120); const payload = { name, displayName: displayName || name, templateId: selectedTemplateId, nodeId: selectedNodeId, hostPort: portVal }; const selectedDiskId = resourceDiskEl ? String(resourceDiskEl.value || '').trim() : ''; if (selectedDiskId && selectedDiskId !== 'primary') { payload.diskId = selectedDiskId; } const cmd = startupCommandEl?.value?.trim() || ''; if (cmd && selectedStartupCommandMode !== 'adpanel-startup' && selectedStartupCommandMode !== 'image-default' && selectedStartupCommandMode !== 'template-managed') { payload.command = cmd; } if (selectedTemplateId === 'minecraft') { payload.mcFork = selectedForkId || 'paper'; payload.mcVersion = MC_VERSION; } if (selectedImportUrl) { payload.importUrl = selectedImportUrl; } payload.resources = readCreateResourceValues(); // F1: server create is step-up gated server-side. The first attempt // rides the panel's grace window (no prompt when a live grant exists); // on a 403 challenge the shared settings.js modal collects a fresh // credential and retries in place. settings.js always loads before // this file on the settings page. let r; let j; if (typeof window.sendGuardedRequestWithStepUp === 'function') { const guarded = await window.sendGuardedRequestWithStepUp('/api/servers/create', 'POST', payload, { subtitle: `Create server "${name}"`, reason: 'Creating a server provisions a new container on a node. Verify your identity to continue.', confirmText: 'Verify & Create', cancelledMessage: 'Verification cancelled — the server was not created.', }); r = guarded.res; j = guarded.data; } else { r = await fetch('/api/servers/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); j = await r.json().catch(() => ({})); if (r.status === 403 && ['password-required', '2fa-required'].includes(String(j?.code || ''))) { throw new Error('Identity verification is required to create a server. Reload the page and try again.'); } } if (!r.ok || !j.ok) { throw new Error( (j && (j.detail || j.message || j.error)) ? (j.detail || j.message || j.error) : 'Server creation failed.' ); } window.location.href = `/server/${encodeURIComponent(name)}`; } catch (err) { showCreateStepFeedback('feedback_server_create_summary', err.message || 'Server creation failed.'); serverCreateCompleteBtn.disabled = false; if (createSpinner) createSpinner.style.display = 'none'; } }); } // Export for backward compatibility / assistant triggers window.ADPanelDashboardCreate = { openCreateModal() { showServerCreateView(true); return true; }, closeCreateModal() { showServerCreateView(false); return true; } }; // Auto-open server create wizard if requested via URL query params or hash try { const urlParams = new URLSearchParams(window.location.search || ''); const createParam = (urlParams.get('create') || urlParams.get('action') || urlParams.get('wizard') || '').toLowerCase(); const hashVal = (window.location.hash || '').toLowerCase(); if ( createParam === 'server' || createParam === 'create' || createParam === 'true' || createParam === '1' || createParam === 'create-server' || hashVal === '#create' || hashVal === '#create-server' || hashVal === '#createserver' ) { showServerCreateView(true); } } catch (_) {} });