No servers found.
`;
return;
}
serversListEl.innerHTML = '';
serversListEl._deleteTokensByName = new Map();
serversListEl._suspensionTokensByName = new Map();
serversListEl._templateTokensByName = new Map();
serversListEl._transferTokensByName = new Map();
_cachedServersList.forEach(item => {
const name = String(item.name || String(item) || '').trim();
if (name && item && typeof item === 'object') {
_cacheResourcesData(name, {
name,
displayName: item.displayName || name,
template: item.template,
hostPort: item.port,
ip: item.ip || item.nodeAddress || '',
serverIp: item.ip || item.nodeAddress || '',
nodeAddress: item.nodeAddress || item.ip || '',
nodePorts: Array.isArray(item.nodePorts) ? item.nodePorts : [],
nodeAllocations: Array.isArray(item.nodeAllocations) ? item.nodeAllocations : [],
resources: item.resources || {},
command: item.command || '',
effectiveCommand: item.effectiveCommand || item.command || '',
javaVersion: item.javaVersion || '',
stats: item.stats || null
});
}
const visibleName = item.displayName || name;
const isLocal = (item && typeof item.isLocal === 'boolean') ? item.isLocal : (!item.nodeId);
const chipText = isLocal ? 'ID: localhost' : `ID: ${item.nodeId}`;
const templateLabel = displayTemplateName(item?.template);
const deleteToken = String(item?.deleteToken || '').trim();
const suspensionToken = String(item?.suspensionToken || '').trim();
const templateToken = String(item?.templateChangeToken || '').trim();
const transferToken = String(item?.transferToken || '').trim();
const isDeletingServer = item?.deleting === true;
const isSuspendedServer = item?.suspended === true || item?.suspended === 1 || String(item?.suspended || '').toLowerCase() === 'true';
if (name && deleteToken) {
serversListEl._deleteTokensByName.set(name, deleteToken);
serversListEl._deleteTokensByName.set(name.toLowerCase(), deleteToken);
}
if (name && suspensionToken) {
serversListEl._suspensionTokensByName.set(name, suspensionToken);
serversListEl._suspensionTokensByName.set(name.toLowerCase(), suspensionToken);
}
if (name && templateToken) {
serversListEl._templateTokensByName.set(name, templateToken);
serversListEl._templateTokensByName.set(name.toLowerCase(), templateToken);
}
if (name && transferToken) {
serversListEl._transferTokensByName.set(name, transferToken);
serversListEl._transferTokensByName.set(name.toLowerCase(), transferToken);
}
const row = document.createElement('div');
row.className = `server-row${isDeletingServer ? '' : ' clickable-card'}${isSuspendedServer ? ' server-row-suspended' : ''}`;
row.dataset.name = name;
row.dataset.targetId = String(item?.targetId ?? '');
row.dataset.template = item?.template || '';
row.dataset.nodeId = item?.nodeId ? String(item.nodeId) : '';
row.dataset.suspended = isSuspendedServer ? '1' : '0';
row.innerHTML = `
No templates found. Create one to get started.
`;
return;
}
templatesListEl.innerHTML = '';
list.forEach(tpl => {
// Keyed by the RAW id (trimmed/lowercased), NOT the alias-normalized id:
// with a legacy alias pair ("py" + "python") a normalized key made the
// two cards overwrite each other here, so edit pre-fill and export
// resolved to the wrong template of the pair. The card buttons below
// carry this same raw id (data-id), so key and lookup agree exactly.
const rawTemplateId = String(tpl?.id || '').trim().toLowerCase();
if (rawTemplateId) {
templateExportMap.set(rawTemplateId, tpl);
}
const encodedTemplateId = encodeURIComponent(tpl.id || '');
const encodedTemplateName = encodeURIComponent(tpl.name || tpl.id || '');
const row = document.createElement('div');
row.className = 'template-card clickable-card';
row.innerHTML = `
${escapeHtml(tpl.name || tpl.id)}
ID: ${escapeHtml(tpl.id || '—')}
${escapeHtml(tpl.description || 'No description')}
${escapeHtml((tpl.docker && tpl.docker.image) ? tpl.docker.image : 'Custom image')}
${escapeHtml((tpl.docker && tpl.docker.tag) ? tpl.docker.tag : 'latest')}
`;
templatesListEl.appendChild(row);
});
}
function renderTemplatesPagination(currentPage, totalPages, total) {
const el = document.getElementById('templatesPagination');
if (!el) return;
if (totalPages <= 1) { el.innerHTML = ''; return; }
const startItem = (currentPage - 1) * _templatesLimit + 1;
const endItem = Math.min(currentPage * _templatesLimit, total);
el.innerHTML = `
`;
el.querySelectorAll('button[data-tpl-page]').forEach(btn => {
btn.addEventListener('click', () => {
const p = parseInt(btn.dataset.tplPage, 10);
if (p >= 1 && p <= totalPages) loadTemplates(p);
});
});
}
const TEMPLATE_STORE_API = '/api/settings/template-store';
const TEMPLATE_STORE_CATEGORIES = [
{ id: 'games', label: 'Games' },
{ id: 'communication', label: 'Communication' },
{ id: 'development', label: 'Development' },
{ id: 'hosting', label: 'Hosting' },
{ id: 'media', label: 'Media' },
];
const templateStoreCategoryCache = new Map();
const templateStoreFileCache = new Map();
const templateStoreItemCache = new Map();
const templateStoreState = {
activeCategory: 'games',
query: '',
renderToken: 0,
searchTimer: null,
closeTimer: null,
installedTemplateIds: new Set(),
};
function getTemplateStoreCategory(categoryId) {
return TEMPLATE_STORE_CATEGORIES.find(category => category.id === categoryId) || TEMPLATE_STORE_CATEGORIES[0];
}
function getTemplateStoreCategoryCache(categoryId) {
if (!templateStoreCategoryCache.has(categoryId)) {
templateStoreCategoryCache.set(categoryId, { items: null, promise: null, error: null });
}
return templateStoreCategoryCache.get(categoryId);
}
// Drops the in-memory listing for one category (and the per-file cache) so the
// next open of the store re-fetches fresh content + hashes. Used after a
// hash-drift rejection: the cached copy is provably stale at that point.
function invalidateTemplateStoreCategoryCache(categoryId) {
if (categoryId) templateStoreCategoryCache.delete(categoryId);
templateStoreFileCache.clear();
}
function setTemplateStoreFeedback(message, type = '') {
if (!templateStoreFeedback) return;
templateStoreFeedback.textContent = message || '';
templateStoreFeedback.classList.toggle('is-error', type === 'error');
templateStoreFeedback.classList.toggle('is-success', type === 'success');
}
function renderTemplateStoreLoading(message) {
if (!templateStoreGrid) return;
templateStoreGrid.innerHTML = `
/*.json) and its image, ' +
'environment variables and install script have not been vetted by the store. Install it only if ' +
'you personally placed that file there.\n\nInstall this local override anyway?'
);
if (!proceed) {
setTemplateStoreFeedback('Install cancelled — local override was not installed.');
return;
}
}
// Nothing is sent until the admin has seen every submitted field. The
// dialog resolves false on cancel/close/Escape — fail closed even if the
// dialog markup is missing entirely.
const reviewed = await openStoreTemplateReviewDialog(item);
if (!reviewed) {
setTemplateStoreFeedback('Install cancelled — nothing was installed.');
return;
}
if (!item.sha256) {
setTemplateStoreFeedback('Store metadata is missing an integrity hash. Reopen the store and try again.', 'error');
return;
}
const originalHtml = button ? button.innerHTML : '';
try {
if (button) {
button.disabled = true;
button.innerHTML = ' Installing';
}
setTemplateStoreFeedback('');
// Reference only (category + file + entry index + content hash). The panel
// resolves the template from its own store cache and pins it to this hash,
// so the content persisted is byte-for-byte the content just reviewed —
// the page never gets to submit template fields itself.
const reference = {
category: item.categoryId,
fileName: item.fileName,
entryIndex: Number.isInteger(item.payloadIndex) ? item.payloadIndex : 0,
sha256: item.sha256,
};
const { res, data } = await sendGuardedRequestWithStepUp('/api/settings/templates/store-install', 'POST', reference, {
subtitle: item.untrusted
? 'Verify your identity to install this LOCAL OVERRIDE template'
: 'Verify your identity to install this template',
reason: item.untrusted
? 'WARNING: this template comes from a local override on the panel host, not the upstream store. Installing stores the container image, volumes, environment variables, startup and install script you just reviewed, and servers will execute them. Step-up verification confirms you personally reviewed and trust this file.'
: 'Installing stores the container image, volumes, environment variables, startup and install script you just reviewed; servers will execute them. The panel installs the store copy pinned to the hash you reviewed. Step-up verification confirms this action was requested by you.',
confirmText: item.untrusted ? 'Confirm & Install Local Override' : 'Confirm & Install Template',
cancelledMessage: 'Verification cancelled — the template was not installed.'
});
if (!res.ok) {
const alreadyExists = String(data.error || '').toLowerCase().includes('already exists');
if (data.code === 'store-template-changed') {
// The server refused because the store content no longer matches the
// hash that was reviewed. The cached listing is stale by definition —
// drop it and re-render so the next click reviews the new content.
invalidateTemplateStoreCategoryCache(item.categoryId);
setTemplateStoreFeedback(data.error || 'This store template changed since it was reviewed. Review it again, then install.', 'error');
loadTemplateStoreView();
return;
}
if (alreadyExists && button) {
button.classList.add('is-installed');
button.disabled = true;
button.innerHTML = ' Installed';
const normalizedId = normalizeTemplateIdClient(item?.id);
if (normalizedId) templateStoreState.installedTemplateIds.add(normalizedId);
setTemplateStoreFeedback('');
} else if (button) {
button.disabled = false;
button.innerHTML = originalHtml;
setTemplateStoreFeedback(data.error || 'Failed to install template.', 'error');
}
return;
}
if (button) {
button.classList.add('is-installed');
button.disabled = true;
button.innerHTML = ' Installed';
}
const normalizedId = normalizeTemplateIdClient(data.template?.id || item?.id);
if (normalizedId) templateStoreState.installedTemplateIds.add(normalizedId);
setTemplateStoreFeedback('');
_templatesPage = 1;
_templatesSearch = '';
const localTemplatesSearchInput = document.getElementById('templatesSearchInput');
if (localTemplatesSearchInput) localTemplatesSearchInput.value = '';
loadTemplates(1, '');
} catch (err) {
console.error(err);
if (button) {
button.disabled = false;
button.innerHTML = originalHtml;
}
setTemplateStoreFeedback(err?.message || 'Network error while installing template.', 'error');
}
}
if (openTemplateStoreBtn) {
openTemplateStoreBtn.addEventListener('click', openTemplateStoreModal);
}
if (templateStoreClose) {
templateStoreClose.addEventListener('click', closeTemplateStoreModal);
}
// Click outside disabled — user must use close/cancel button
// if (templateStoreOverlay) {
// templateStoreOverlay.addEventListener('click', (e) => {
// if (e.target === templateStoreOverlay) closeTemplateStoreModal();
// });
// }
document.querySelectorAll('.template-store-tab').forEach(tab => {
tab.addEventListener('click', () => {
setTemplateStoreActiveCategory(tab.dataset.storeCategory || 'games');
templateStoreState.query = '';
if (templateStoreSearch) templateStoreSearch.value = '';
loadTemplateStoreView();
});
});
if (templateStoreSearch) {
templateStoreSearch.addEventListener('input', () => {
clearTimeout(templateStoreState.searchTimer);
templateStoreState.searchTimer = setTimeout(() => {
templateStoreState.query = templateStoreSearch.value.trim();
loadTemplateStoreView();
}, 220);
});
}
if (templateStoreGrid) {
templateStoreGrid.addEventListener('click', (e) => {
const button = e.target.closest('.template-store-install');
if (!button) return;
const item = templateStoreItemCache.get(button.dataset.storeKey || '');
installTemplateStoreItem(item, button);
});
}
function openTemplateModal() {
createTemplateOverlay.classList.add('show');
createTemplateModal.classList.add('show');
createTemplateFeedback.textContent = '';
}
function closeTemplateModal() {
createTemplateOverlay.classList.remove('show');
createTemplateModal.classList.remove('show');
createTemplateFeedback.textContent = '';
if (templateEditorState.mode === 'edit') setTemplateModalMode('create');
}
function setTemplateModalMode(mode, template = null) {
const nextMode = mode === 'edit' ? 'edit' : 'create';
const modalStartup = getTemplateEditorStartup(template);
templateEditorState.mode = nextMode;
templateEditorState.editTemplateId = nextMode === 'edit' ? String(template?.id || '').trim() : '';
templateEditorState.startupSource = modalStartup.source;
templateEditorState.startupValue = modalStartup.value;
// Leaving edit mode drops any import-carried container config so a stale
// one from a previous modal session can never ride into a later save. Same
// for the parked install extras: nothing between here and the next modal
// open repopulates them.
if (nextMode === 'create') {
templateEditorState.containerConfig = null;
templateEditorState.installExtras = {};
}
if (createTemplateModal) createTemplateModal.dataset.mode = nextMode;
if (nextMode === 'edit') {
if (createTemplateModalTitle) createTemplateModalTitle.textContent = 'Edit Template';
if (createTemplateModalSubtitle) createTemplateModalSubtitle.textContent = 'Update this template and save your changes.';
if (createTemplateSave) createTemplateSave.innerHTML = ' Save Template';
if (ct_id) {
ct_id.readOnly = true;
ct_id.title = 'Template ID cannot be changed after creation.';
}
return;
}
if (createTemplateModalTitle) createTemplateModalTitle.textContent = 'New Template';
if (createTemplateModalSubtitle) createTemplateModalSubtitle.textContent = 'Set up a reusable Docker template.';
if (createTemplateSave) createTemplateSave.innerHTML = ' Create Template';
if (ct_id) {
ct_id.readOnly = false;
ct_id.title = '';
}
}
function getTemplateManagedStartup(template) {
return String(
template?.docker?.adpanelStartup ||
template?.docker?.adpanel_startup ||
template?.docker?.pterodactylStartup ||
template?.docker?.pterodactyl_startup ||
''
).trim();
}
function getTemplateEditorStartup(template) {
const managedStartup = getTemplateManagedStartup(template);
if (managedStartup) return { value: managedStartup, source: 'managed' };
return {
value: String(template?.docker?.command || '').trim(),
source: ''
};
}
function startupCommandNeedsManagedRuntime(command) {
const value = String(command || '').trim();
if (!value) return false;
if (value.includes('\n')) return true;
if (value.includes('`') || value.includes('$')) return true;
const args = parseRuntimeProcessArgsInput(value);
if (args.length && isRuntimeEnvAssignmentTokenInput(args[0])) return true;
const { execName: resolvedExecName, index: execIndex } = resolveRuntimeProcessExecutableArgsInput(args);
if (validateRuntimeContainerLauncherInput(args)) return false;
if (isBlockedRuntimeShellExecutableInput(resolvedExecName || args[0]) && isRuntimeShellWrapperArgsInput(args, execIndex)) {
return true;
}
return args.some(arg => RUNTIME_PROCESS_BLOCKED_TOKENS.has(String(arg || '').trim()));
}
function clearTemplateForm() {
if (ct_name) ct_name.value = '';
if (ct_id) ct_id.value = '';
if (ct_description) ct_description.value = '';
if (ct_template_image) ct_template_image.value = '';
if (ct_default_port) ct_default_port.value = '';
if (ct_image) ct_image.value = '';
if (ct_tag) ct_tag.value = 'latest';
if (ct_startup_command) ct_startup_command.value = '';
if (ct_workdir) ct_workdir.value = '';
if (ct_env_json) ct_env_json.value = '';
templateEditorState.startupSource = '';
templateEditorState.startupValue = '';
templateEditorState.containerConfig = null;
if (ct_advanced_settings) ct_advanced_settings.open = false;
populateTemplateInstallForm(null);
if (ct_import_json) ct_import_json.value = '';
}
function populateTemplateForm(template) {
if (!template || typeof template !== 'object') return;
if (ct_name) ct_name.value = String(template.name || template.id || '').trim();
if (ct_id) ct_id.value = String(template.id || '').trim();
if (ct_description) ct_description.value = String(template.description || '').trim();
if (ct_template_image) ct_template_image.value = String(template.templateImage || template.template_image || '').trim();
if (ct_default_port) ct_default_port.value = String(template.defaultPort || template.default_port || '').trim();
if (ct_image) ct_image.value = String(template?.docker?.image || '').trim();
if (ct_tag) ct_tag.value = String(template?.docker?.tag || 'latest').trim() || 'latest';
const startup = getTemplateEditorStartup(template);
templateEditorState.startupSource = startup.source;
templateEditorState.startupValue = startup.value;
if (ct_startup_command) ct_startup_command.value = startup.value;
if (ct_workdir) ct_workdir.value = String(template?.docker?.workdir || '').trim();
if (ct_env_json) {
const env = template?.docker?.env && typeof template.docker.env === 'object' && !Array.isArray(template.docker.env)
? template.docker.env
: {};
ct_env_json.value = Object.keys(env).length ? JSON.stringify(env, null, 2) : '';
}
populateTemplateInstallForm(template?.docker?.install || null);
if (ct_import_json) ct_import_json.value = '';
}
function findTemplateForEditor(templateId) {
// Raw-id lookup — must mirror the templateExportMap keying in
// renderTemplates (alias normalization here resolved legacy alias pairs to
// the wrong entry).
const rawId = String(templateId || '').trim().toLowerCase();
if (!rawId) return null;
return templateExportMap.get(rawId) || null;
}
function openTemplateEditModal(templateId) {
const selected = findTemplateForEditor(templateId);
if (!selected) {
if (templatesFeedbackEl) templatesFeedbackEl.textContent = 'Template data not available for editing. Please refresh the list.';
return;
}
// A pure form edit must not forward ports/volumes/portProtocols — omitting
// the fields is what keeps the update endpoint's stored fallback (and its
// workdir auto-align) in charge, so drop any import-carried config first.
templateEditorState.containerConfig = null;
populateTemplateForm(selected);
setTemplateModalMode('edit', selected);
if (createTemplateFeedback) createTemplateFeedback.textContent = '';
openTemplateModal();
}
function sanitizeTemplateWorkdirInput(value) {
let workdir = String(value || '').trim();
if (!workdir) return '';
workdir = workdir.replace(/\\/g, '/').replace(/\/+/g, '/');
if (workdir.length > 1) workdir = workdir.replace(/\/+$/, '');
return workdir;
}
function validateTemplateWorkdirInput(value) {
const workdir = sanitizeTemplateWorkdirInput(value);
if (!workdir) return '';
if (!workdir.startsWith('/')) return 'Workdir must be an absolute Linux path (example: /app).';
if (workdir.includes('..')) return 'Workdir must not include path traversal segments.';
if (!/^\/[A-Za-z0-9._\-/]+$/.test(workdir)) {
return 'Workdir may only include letters, numbers, "/", ".", "_" and "-".';
}
return '';
}
function validateTemplateDockerTagInput(value) {
// Client mirror of the server's docker-tag boundary (utils/
// template-store-trust.js validateDockerTagInput — keep this regex and
// message in sync with it), the same way parseTemplateEnvJsonInput mirrors
// validateTemplateEnvPayload: fail closed in the form so a malformed tag
// is named before the save ever spends a step-up prompt on a 400. Empty is
// INVALID here, like on the server — callers skip empty so the server's
// default (create: "latest", edit: the stored tag) still applies.
const tag = String(value || '').trim();
if (!/^[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}$/.test(tag)) {
const shown = tag.length > 120 ? `${tag.slice(0, 120)}…` : tag;
return `Invalid docker tag "${shown}" — tags must start with a letter, digit or underscore, may only contain letters, digits, ".", "_" and "-" and are limited to 128 characters.`;
}
return '';
}
function parseTemplateEnvJsonInput(value) {
const raw = String(value || '').trim();
if (!raw) return {};
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('Environment JSON must be an object.');
}
const out = {};
Object.entries(parsed).forEach(([key, val]) => {
const envKey = String(key || '').trim();
// Fail closed like the server's env boundary
// (utils/server-template-payload.js validateTemplateEnvPayload — keep
// this mirror in sync with it) instead of silently shrinking what the
// admin reviewed: an empty key is skipped no more, and a literal
// "__proto__" key must be rejected here — assigning it would trigger the
// inherited setter and swallow the entry, so it could never reach the
// server's 400. Object/array values are likewise rejected before the
// String() coercion below, which would otherwise survive them as
// "[object Object]" (arrays as "1,2") — garbage no admin reviewed, and
// exactly what the server boundary refuses.
if (!envKey) {
throw new Error('Environment JSON contains an entry with an empty key.');
}
if (envKey === '__proto__') {
throw new Error('Environment JSON contains the reserved key "__proto__".');
}
if (val !== null && val !== undefined && typeof val === 'object') {
throw new Error(`Environment JSON value for "${envKey}" must be a string, number, boolean or null.`);
}
out[envKey] = String(val ?? '');
});
return out;
}
function parseTemplateDefaultPort(value) {
const raw = String(value || '').trim();
if (!raw) return null;
const port = Number.parseInt(raw, 10);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('Default port must be between 1 and 65535.');
}
return port;
}
function slugifyTemplateId(value) {
return String(value || 'custom')
.trim()
.toLowerCase()
.replace(/[^a-z0-9_-]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 60) || 'custom';
}
function splitDockerImageAndTag(ref) {
const raw = String(ref || '').trim();
if (!raw) return { image: '', tag: 'latest' };
const slash = raw.lastIndexOf('/');
const colon = raw.lastIndexOf(':');
if (colon > slash) {
return { image: raw.slice(0, colon), tag: raw.slice(colon + 1) || 'latest' };
}
return { image: raw, tag: 'latest' };
}
// Extract the installer settings the install form cannot represent. Only
// present-and-type-valid keys are carried; no clamping or validation happens
// here — the server re-sanitizes the whole install on save
// (sanitizeDockerInstallPayload), so duplicating that logic would only drift.
function installExtrasFromInstall(install) {
const cfg = install && typeof install === 'object' && !Array.isArray(install) ? install : {};
const extras = {};
if (cfg.env && typeof cfg.env === 'object' && !Array.isArray(cfg.env)) {
// Deep-cloned so the editor state never aliases the template listing
// cache the edit modal populates from.
extras.env = cloneImportedContainerValue(cfg.env);
}
if (typeof cfg.timeoutSeconds === 'number' && Number.isFinite(cfg.timeoutSeconds)) {
extras.timeoutSeconds = cfg.timeoutSeconds;
}
if (typeof cfg.minimumStorageMb === 'number' && Number.isFinite(cfg.minimumStorageMb)) {
extras.minimumStorageMb = cfg.minimumStorageMb;
}
if (cfg.allowEmpty === true) extras.allowEmpty = true;
return extras;
}
function buildTemplateInstallFromForm() {
const script = String(ct_install_script?.value || '').trim();
if (!script) return null;
const install = {
image: String(ct_install_image?.value || '').trim() || 'ghcr.io/pterodactyl/installers:debian',
script,
mountPath: sanitizeTemplateWorkdirInput(ct_install_mount?.value || '/mnt/server') || '/mnt/server',
runtimePath: sanitizeTemplateWorkdirInput(ct_install_runtime?.value || '/home/container') || '/home/container',
};
const mountError = validateTemplateWorkdirInput(install.mountPath);
if (mountError) throw new Error(`Install mount path: ${mountError}`);
const runtimeError = validateTemplateWorkdirInput(install.runtimePath);
if (runtimeError) throw new Error(`Install runtime path: ${runtimeError}`);
// The stash goes UNDER the form fields: it only re-supplies what the form
// cannot represent, so it can never override an admin-visible edit. An
// empty script returns null above — clearing the script is how an admin
// removes the installer.
return { ...templateEditorState.installExtras, ...install };
}
function populateTemplateInstallForm(install) {
const cfg = install && typeof install === 'object' ? install : {};
// Park the installer settings this form has no fields for so a save can
// send them back instead of silently dropping them. A null install
// (clearTemplateForm, installer-less template or import) resets the stash.
templateEditorState.installExtras = installExtrasFromInstall(cfg);
if (ct_install_image) ct_install_image.value = String(cfg.image || cfg.container || '').trim();
if (ct_install_mount) ct_install_mount.value = String(cfg.mountPath || cfg.containerPath || '/mnt/server').trim();
if (ct_install_runtime) ct_install_runtime.value = String(cfg.runtimePath || '/home/container').trim();
if (ct_install_script) ct_install_script.value = String(cfg.script || '').trim();
}
function adpanelEggToTemplatePayload(payload) {
// In the egg format docker_images maps image ref -> display label, so the
// key carries the reference the panel needs; values may be friendly aliases.
const dockerImageEntries = payload.docker_images && typeof payload.docker_images === 'object' && !Array.isArray(payload.docker_images)
? Object.entries(payload.docker_images)
: [];
const firstImageEntry = dockerImageEntries[0] || [];
const dockerRef = String(firstImageEntry[0] || firstImageEntry[1] || payload.docker_image || '').trim();
const { image, tag } = splitDockerImageAndTag(dockerRef);
const installation = payload.scripts && payload.scripts.installation && typeof payload.scripts.installation === 'object'
? payload.scripts.installation
: null;
const env = {};
(Array.isArray(payload.variables) ? payload.variables : []).forEach(variable => {
const key = String(variable?.env_variable || '').trim();
if (!key) return;
// The egg format defines default_value as a string, so an object/array
// there is malformed input — String() would survive it as
// "[object Object]" ("1,2" for arrays), the same garbage the server's
// env boundary (utils/server-template-payload.js
// validateTemplateEnvPayload) refuses. Fail closed at import instead of
// feeding the editor an env the save would have to reject.
const defaultValue = variable?.default_value;
if (defaultValue !== null && defaultValue !== undefined && typeof defaultValue === 'object') {
throw new Error(`Egg variable "${key}" has an invalid default_value — it must be a string, number, boolean or null.`);
}
env[key] = String(defaultValue ?? '');
});
const startup = String(payload.startup || '').trim();
if (startup) env.STARTUP = startup;
const portCandidate = Number.parseInt(env.SERVER_PORT || env.PORT || env.SRCDS_PORT || '', 10);
const defaultPort = Number.isInteger(portCandidate) && portCandidate > 0 && portCandidate <= 65535
? portCandidate
: (startup.includes('27015') || env.SRCDS_APPID ? 27015 : 8080);
return {
template_name: String(payload.name || '').trim(),
template_id: slugifyTemplateId(payload.name || payload.id || 'custom-template'),
description: String(payload.description || '').trim(),
docker_image: image,
docker_tag: tag,
startup,
workdir: '/home/container',
defaultPort,
env,
install: installation ? {
image: String(installation.container || installation.image || '').trim() || 'ghcr.io/pterodactyl/installers:debian',
script: String(installation.script || '').trim(),
mountPath: '/mnt/server',
runtimePath: '/home/container',
} : null,
};
}
// Export downloads the canonical stored template shape (id/name/docker.*),
// while this importer historically only understood Pterodactyl egg files and
// the flat editor payload — so an exported file could never be re-imported.
// The detector below recognizes the stored shape and the converter maps it
// onto the flat payload the rest of the importer expects.
//
// Fields the editor form cannot represent get explicit handling so an
// exported file truly round-trips: ports, portProtocols and volumes are
// hoisted onto the flat payload and parked in
// templateEditorState.containerConfig (see
// templateContainerConfigFromImportPayload), and the save request forwards
// them — the server's fail-closed ingestion boundary
// (validatePortListInput / validateTemplateVolumeListPayload) rejects invalid
// specs by name instead of storing a template whose mounts silently never
// exist. Console config stays intentionally excluded: the create endpoint
// rebuilds it from the image default, and only the update endpoint preserves
// a stored console.
function looksLikeStoredAdpanelTemplate(payload) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return false;
if (Object.prototype.hasOwnProperty.call(payload, 'template_name')) return false;
// Egg markers — the same condition applyTemplateJsonImport dispatches on —
// so this detector stays accurate when called on its own.
if (payload.meta?.version || payload.scripts?.installation || payload.docker_images) return false;
const docker = payload.docker;
return !!docker && typeof docker === 'object' && !Array.isArray(docker);
}
function cloneImportedContainerValue(value) {
try {
return JSON.parse(JSON.stringify(value));
} catch {
return value;
}
}
// Park the container-mount surface an import carries (ports/portProtocols/
// volumes — fields the editor form cannot represent) in the editor state the
// save request forwards. Field resolution mirrors the server's ingestion
// chains: ports/volumes pass through the shapes constructTemplateDefinition
// already accepts (arrays, comma strings, single specs), and portProtocols
// mirrors the body-level `portProtocols || port_protocols` fallback. Values
// are deep-cloned so the editor state never aliases the template listing
// cache. Returns null when the payload carries none of the fields — plain
// form saves must omit them so the update endpoint's stored fallback keeps
// preserving them for pure edits.
function templateContainerConfigFromImportPayload(payload) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null;
const config = {};
let present = false;
const park = (key, value) => {
if (value === undefined || value === null) return;
config[key] = cloneImportedContainerValue(value);
present = true;
};
if (Object.prototype.hasOwnProperty.call(payload, 'ports')) park('ports', payload.ports);
const protocols = payload.portProtocols || payload.port_protocols;
if (protocols !== undefined && protocols !== null) park('portProtocols', protocols);
if (Object.prototype.hasOwnProperty.call(payload, 'volumes')) park('volumes', payload.volumes);
return present ? config : null;
}
function adpanelStoredTemplateToTemplatePayload(template) {
const docker = template.docker && typeof template.docker === 'object' && !Array.isArray(template.docker)
? template.docker
: {};
const managedStartup = String(
docker.adpanelStartup ||
docker.adpanel_startup ||
docker.pterodactylStartup ||
docker.pterodactyl_startup ||
''
).trim();
const payload = {
template_name: String(template.name || template.id || '').trim(),
template_id: String(template.id || '').trim(),
description: String(template.description || '').trim(),
docker_image: String(docker.image || '').trim(),
docker_tag: String(docker.tag || '').trim(),
startup: managedStartup || String(docker.command || '').trim(),
image: String(template.templateImage || template.template_image || '').trim(),
workdir: String(docker.workdir || '').trim(),
defaultPort: template.defaultPort || template.default_port || '',
env: docker.env && typeof docker.env === 'object' && !Array.isArray(docker.env) ? docker.env : {},
// Whole-install passthrough is load-bearing: it carries the installer
// settings the form cannot represent (env/timeoutSeconds/minimumStorageMb/
// allowEmpty) to populateTemplateInstallForm, which parks the type-valid
// ones in templateEditorState.installExtras — remapping field-by-field
// here would silently break the export→import→save round-trip again.
install: docker.install && typeof docker.install === 'object' && !Array.isArray(docker.install) ? docker.install : null,
};
// Round trip: hoist the container-mount fields the form cannot represent
// (same alias chain the server reads) so
// templateContainerConfigFromImportPayload can park them for the save
// request instead of silently dropping them.
if (docker.ports !== undefined && docker.ports !== null) {
payload.ports = cloneImportedContainerValue(docker.ports);
}
const rawPortProtocols = docker.portProtocols || docker.port_protocols || docker.protocols;
if (rawPortProtocols !== undefined && rawPortProtocols !== null) {
payload.portProtocols = cloneImportedContainerValue(rawPortProtocols);
}
if (docker.volumes !== undefined && docker.volumes !== null) {
payload.volumes = cloneImportedContainerValue(docker.volumes);
}
return payload;
}
function applyTemplateJsonImport(payload) {
// Older exports (and hand-merged backups) wrap the template in an array.
// The editor form holds exactly one template, so unwrap a single-element
// array and reject anything else with a clear message.
if (Array.isArray(payload)) {
if (payload.length !== 1) {
throw new Error(payload.length === 0
? 'This file contains no template.'
: `This file contains ${payload.length} templates. Import one template file at a time.`);
}
payload = payload[0];
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
throw new Error('Invalid JSON format.');
}
if (payload.meta?.version || payload.scripts?.installation || payload.docker_images) {
payload = adpanelEggToTemplatePayload(payload);
} else if (looksLikeStoredAdpanelTemplate(payload)) {
payload = adpanelStoredTemplateToTemplatePayload(payload);
}
const requiredKeys = [
'template_name',
'template_id',
'docker_image'
];
for (const key of requiredKeys) {
if (!Object.prototype.hasOwnProperty.call(payload, key)) {
throw new Error(`Missing required field in JSON: ${key}`);
}
}
const templateName = String(payload.template_name || '').trim();
const templateId = String(payload.template_id || '').trim();
const description = String(payload.description || '').trim();
const dockerImage = String(payload.docker_image || '').trim();
const dockerTag = String(payload.docker_tag || 'latest').trim() || 'latest';
const startup = String(
payload.startup ||
payload.adpanelStartup ||
payload.adpanel_startup ||
payload.pterodactylStartup ||
payload.pterodactyl_startup ||
''
).trim();
const templateImage = String(payload.image || '').trim();
const workdir = sanitizeTemplateWorkdirInput(payload.workdir);
const defaultPort = payload.defaultPort || payload.default_port || '';
const env = payload.env && typeof payload.env === 'object' && !Array.isArray(payload.env) ? payload.env : {};
const install = payload.install || payload.installation || null;
if (!templateName || !templateId || !dockerImage) {
throw new Error('JSON must include non-empty template_name, template_id and docker_image.');
}
const startupCommandError = startupCommandNeedsManagedRuntime(startup)
? null
: validateRuntimeProcessCommandInput(startup);
if (startupCommandError) {
throw new Error(startupCommandError);
}
const workdirError = validateTemplateWorkdirInput(workdir);
if (workdirError) {
throw new Error(workdirError);
}
if (ct_name) ct_name.value = templateName;
if (ct_id) {
if (templateEditorState.mode === 'edit' && templateEditorState.editTemplateId) {
ct_id.value = templateEditorState.editTemplateId;
} else {
ct_id.value = templateId;
}
}
if (ct_description) ct_description.value = description;
if (ct_image) ct_image.value = dockerImage;
if (ct_tag) ct_tag.value = dockerTag;
if (ct_startup_command) ct_startup_command.value = startup;
templateEditorState.startupSource = startupCommandNeedsManagedRuntime(startup) ? 'managed' : '';
templateEditorState.startupValue = startup;
if (ct_template_image) ct_template_image.value = templateImage;
if (ct_workdir) ct_workdir.value = workdir;
if (ct_default_port) ct_default_port.value = defaultPort ? String(defaultPort) : '';
if (ct_env_json) ct_env_json.value = Object.keys(env).length ? JSON.stringify(env, null, 2) : '';
populateTemplateInstallForm(install);
// Set last, after every validation above passed, so a failed import can
// never leave a half-carried container config behind.
templateEditorState.containerConfig = templateContainerConfigFromImportPayload(payload);
}
[createTemplateCancel, createTemplateClose].forEach(el => {
if (!el) return;
el.addEventListener('click', (e) => {
if (e.target === el || el === createTemplateCancel || el === createTemplateClose) {
closeTemplateModal();
}
});
});
// Click outside disabled — user must use close/cancel button
// if (createTemplateOverlay) {
// createTemplateOverlay.addEventListener('click', (e) => {
// if (e.target === createTemplateOverlay) closeTemplateModal();
// });
// }
if (openCreateTemplateBtn) {
openCreateTemplateBtn.addEventListener('click', () => {
setTemplateModalMode('create');
clearTemplateForm();
openTemplateModal();
});
}
if (createTemplateImportBtn && ct_import_json) {
createTemplateImportBtn.addEventListener('click', () => {
ct_import_json.click();
});
ct_import_json.addEventListener('change', async () => {
const file = ct_import_json.files && ct_import_json.files[0] ? ct_import_json.files[0] : null;
if (!file) return;
try {
if (!String(file.name || '').toLowerCase().endsWith('.json')) {
throw new Error('Only .json files are accepted.');
}
const raw = await file.text();
const parsed = JSON.parse(raw);
applyTemplateJsonImport(parsed);
const actionWord = templateEditorState.mode === 'edit' ? 'Save' : 'Create';
const carriedNote = templateEditorState.containerConfig
? ' Ports, port protocols and volume mounts were carried over — they are not editable in this form.'
: '';
createTemplateFeedback.textContent = `Template JSON imported successfully.${carriedNote} Review and click ${actionWord}.`;
} catch (err) {
createTemplateFeedback.textContent = err?.message || 'Invalid template JSON.';
} finally {
ct_import_json.value = '';
}
});
}
if (createTemplateSave) {
createTemplateSave.addEventListener('click', async () => {
const isEditMode = templateEditorState.mode === 'edit';
const id = (ct_id.value || '').trim();
const name = (ct_name.value || '').trim();
const description = (ct_description.value || '').trim();
const templateImage = (ct_template_image.value || '').trim();
const defaultPortInput = ct_default_port?.value || '';
const image = (ct_image.value || '').trim();
const tag = (ct_tag.value || '').trim();
const startupCommand = (ct_startup_command?.value || '').trim();
const workdirInput = ct_workdir?.value || '';
const workdir = sanitizeTemplateWorkdirInput(workdirInput);
const preserveManagedStartup = templateEditorState.startupSource === 'managed'
&& startupCommand
&& startupCommand === templateEditorState.startupValue;
const storeStartupAsManaged = !!startupCommand && (
preserveManagedStartup ||
startupCommandNeedsManagedRuntime(startupCommand)
);
let defaultPort = null;
let env = {};
let install = null;
if (isEditMode && !templateEditorState.editTemplateId) {
createTemplateFeedback.textContent = 'Missing template reference for edit mode. Reopen the edit popup.';
return;
}
if (!name || !id || !image) {
createTemplateFeedback.textContent = 'Please fill out name, id and docker image.';
return;
}
const startupCommandError = storeStartupAsManaged
? null
: validateRuntimeProcessCommandInput(startupCommand);
if (startupCommandError) {
createTemplateFeedback.textContent = startupCommandError;
return;
}
const workdirError = validateTemplateWorkdirInput(workdirInput);
if (workdirError) {
createTemplateFeedback.textContent = workdirError;
return;
}
// Empty stays empty so the server falls back (create: "latest", edit:
// the stored tag); anything else must match the grammar the server
// enforces. Egg imports land here too — splitDockerImageAndTag already
// split their refs into image + tag inside this field.
const tagError = tag ? validateTemplateDockerTagInput(tag) : '';
if (tagError) {
createTemplateFeedback.textContent = tagError;
return;
}
try {
defaultPort = parseTemplateDefaultPort(defaultPortInput);
env = parseTemplateEnvJsonInput(ct_env_json?.value || '');
install = buildTemplateInstallFromForm();
} catch (err) {
createTemplateFeedback.textContent = err?.message || 'Invalid template advanced settings.';
return;
}
try {
createTemplateSave.disabled = true;
createTemplateFeedback.textContent = isEditMode ? 'Updating template…' : 'Saving template…';
const endpoint = isEditMode
? `/api/settings/templates/${encodeURIComponent(templateEditorState.editTemplateId)}`
: '/api/settings/templates';
const method = isEditMode ? 'PUT' : 'POST';
const requestBody = {
id,
name,
description,
dockerImage: image,
dockerTag: tag,
templateImage,
defaultPort,
command: storeStartupAsManaged ? '' : startupCommand,
dockerWorkdir: workdir,
env,
adpanelStartup: storeStartupAsManaged ? startupCommand : '',
install,
};
// Round trip: forward the container-mount surface an import carried so
// a cloned template keeps its ports and mounts. Plain form edits leave
// this null — omitting the fields is what lets the update endpoint's
// stored fallback (and its workdir auto-align) preserve the template.
if (templateEditorState.containerConfig) {
Object.assign(requestBody, templateEditorState.containerConfig);
}
const { res, data } = await sendGuardedRequestWithStepUp(endpoint, method, requestBody, {
subtitle: isEditMode ? 'Verify your identity to update this template' : 'Verify your identity to create this template',
reason: 'Templates define the container image, startup command and install script that servers execute. Step-up verification confirms this action was requested by you.',
confirmText: 'Confirm & Save Template',
cancelledMessage: isEditMode ? 'Verification cancelled — the template was not updated.' : 'Verification cancelled — the template was not created.'
});
if (!res.ok) {
createTemplateFeedback.textContent = data.error || 'Failed to save template';
createTemplateSave.disabled = false;
return;
}
createTemplateFeedback.textContent = isEditMode ? 'Template updated!' : 'Template created!';
setTimeout(() => {
closeTemplateModal();
setTemplateModalMode('create');
}, 400);
loadTemplates(_templatesPage, _templatesSearch);
} catch (e) {
console.error(e);
createTemplateFeedback.textContent = e?.message || 'Network error while saving template';
} finally {
createTemplateSave.disabled = false;
}
});
}
async function deleteTemplate(templateId, templateName, btn) {
if (!templateId) return;
if (!confirm(`Delete template "${templateName || templateId}"? It cannot be undone.`)) return;
try {
if (btn) {
btn.disabled = true;
btn.innerHTML = ' ';
}
const { res, data } = await sendGuardedRequestWithStepUp(
`/api/settings/templates/${encodeURIComponent(templateId)}`,
'DELETE',
{},
{
subtitle: 'Verify your identity to delete this template',
reason: 'Deleting a template removes the launch configuration servers start from. Step-up verification confirms this action was requested by you.',
confirmText: 'Confirm & Delete Template',
cancelledMessage: 'Verification cancelled — the template was not deleted.'
}
);
if (!res.ok) {
const serversMsg = Array.isArray(data.servers) && data.servers.length ? ` In use by: ${data.servers.join(', ')}` : '';
if (templatesFeedbackEl) templatesFeedbackEl.textContent = (data.error || 'Failed to delete template.') + serversMsg;
return;
}
if (templatesFeedbackEl) templatesFeedbackEl.textContent = `Template "${templateName || templateId}" deleted.`;
loadTemplates();
} catch (err) {
console.error(err);
if (templatesFeedbackEl) templatesFeedbackEl.textContent = err?.message || 'Network error while deleting template.';
} finally {
if (btn) {
btn.disabled = false;
btn.innerHTML = ' ';
}
}
}
function sanitizeExportFilenamePart(value) {
const raw = String(value || '').trim().toLowerCase();
const sanitized = raw.replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
return sanitized || 'template';
}
function getTemplateExportFilename(templateId, templateName) {
const basename = sanitizeExportFilenamePart(templateId || templateName || 'template');
return `${basename}.json`;
}
function cloneTemplateForExport(template) {
if (!template || typeof template !== 'object') return null;
try {
return JSON.parse(JSON.stringify(template));
} catch {
return { ...template };
}
}
// Export the canonical stored template shape as a single JSON object so the
// file round-trips through "Import JSON" on the templates page. The importer
// also accepts the array-wrapped files older builds produced.
function buildTemplateExportJson(template) {
return `${JSON.stringify(template, null, 2)}\n`;
}
function triggerJsonDownload(filename, content) {
const blob = new Blob([content], { type: 'application/json;charset=utf-8' });
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
URL.revokeObjectURL(url);
}
function exportTemplate(templateId, templateName, btn) {
// Raw-id lookup — must mirror the templateExportMap keying in
// renderTemplates (alias normalization here resolved legacy alias pairs to
// the wrong entry).
const rawId = String(templateId || '').trim().toLowerCase();
if (!rawId) {
if (templatesFeedbackEl) templatesFeedbackEl.textContent = 'Invalid template id for export.';
return;
}
const selected = templateExportMap.get(rawId);
const template = cloneTemplateForExport(selected);
if (!template) {
if (templatesFeedbackEl) templatesFeedbackEl.textContent = 'Template data not available for export.';
return;
}
const originalHtml = btn ? btn.innerHTML : '';
try {
if (btn) {
btn.disabled = true;
btn.innerHTML = ' ';
}
const filename = getTemplateExportFilename(templateId, templateName);
const jsonContent = buildTemplateExportJson(template);
triggerJsonDownload(filename, jsonContent);
if (templatesFeedbackEl) {
templatesFeedbackEl.textContent = `Template "${templateName || templateId}" exported successfully.`;
}
} catch (err) {
console.error(err);
if (templatesFeedbackEl) templatesFeedbackEl.textContent = 'Failed to export template JSON.';
} finally {
if (btn) {
btn.disabled = false;
btn.innerHTML = originalHtml || ' ';
}
}
}
if (templatesListEl) {
templatesListEl.addEventListener('click', (e) => {
const editBtn = e.target.closest('.edit-template');
if (editBtn) {
const id = decodeURIComponent(editBtn.dataset.id || '');
openTemplateEditModal(id);
return;
}
const exportBtn = e.target.closest('.export-template');
if (exportBtn) {
const id = decodeURIComponent(exportBtn.dataset.id || '');
const name = decodeURIComponent(exportBtn.dataset.name || '') || id;
exportTemplate(id, name, exportBtn);
return;
}
const btn = e.target.closest('.delete-template');
if (!btn) return;
const id = decodeURIComponent(btn.dataset.id || '');
const name = decodeURIComponent(btn.dataset.name || '') || id;
deleteTemplate(id, name, btn);
});
}
function closeServerTemplateModal() {
if (serverTemplateOverlay) serverTemplateOverlay.classList.remove('show');
if (serverTemplateModal) serverTemplateModal.classList.remove('show');
templatePickerState.selected = '';
templatePickerState.selectedNorm = '';
templatePickerState.server = '';
templatePickerState.originalTemplate = '';
if (serverTemplateModal) {
serverTemplateModal.dataset.server = '';
serverTemplateModal.dataset.selected = '';
}
if (serverTemplateList) serverTemplateList.innerHTML = '';
if (serverTemplateFeedback) serverTemplateFeedback.textContent = '';
}
function selectServerTemplate(id) {
const normalized = normalizeTemplateIdClient(id);
if (!normalized) return;
templatePickerState.selected = id;
templatePickerState.selectedNorm = normalized;
if (serverTemplateModal) serverTemplateModal.dataset.selected = id;
Array.from(serverTemplateList.querySelectorAll('.template-option-card')).forEach(card => {
const normCard = normalizeTemplateIdClient(card.dataset.id);
card.classList.toggle('active', normCard === normalized);
});
renderServerTemplateAction();
}
function renderServerTemplateAction() {
if (!serverTemplateDone) return;
const { selectedNorm, originalTemplate, submitting, completed } = templatePickerState;
const label = serverTemplateDone.querySelector('#serverTemplateActionLabel');
const icon = serverTemplateDone.querySelector('i');
if (label) label.textContent = completed ? 'Done' : submitting ? 'Reinstalling...' : selectedNorm && selectedNorm === originalTemplate ? 'Reapply Latest Template' : 'Apply Template';
if (icon) icon.className = submitting ? 'fa-solid fa-spinner fa-spin' : 'fa-solid fa-check';
serverTemplateDone.disabled = submitting || (!selectedNorm && !completed);
}
function renderServerTemplateOptions(list, currentTemplate) {
if (!serverTemplateList) return;
const seen = new Set();
const unique = [];
(Array.isArray(list) ? list : []).forEach(tpl => {
const norm = normalizeTemplateIdClient(tpl?.id);
if (!norm || seen.has(norm)) return;
seen.add(norm);
const canonicalId = tpl?.id || norm;
unique.push({ ...tpl, _norm: norm, _id: canonicalId });
});
if (unique.length === 0) {
serverTemplateList.innerHTML = `No templates available.
`;
return;
}
serverTemplateList.innerHTML = '';
unique.forEach(tpl => {
const card = document.createElement('div');
card.className = 'template-option-card';
card.dataset.id = tpl._id;
const templateImage = tpl.template_image || tpl.templateImage || '';
if (templateImage) {
card.style.setProperty('--template-bg', `url(${templateImage})`);
card.innerHTML = `
${escapeHtml(tpl.name || tpl.id)}
${escapeHtml(tpl.description || 'No description')}
${escapeHtml((tpl.docker && tpl.docker.image) ? tpl.docker.image : 'Custom image')}
`;
card.style.cssText = `--bg-image: url('${templateImage.replace(/'/g, "\\'")}')`;
} else {
card.innerHTML = `
${escapeHtml(tpl.name || tpl.id)}
${escapeHtml(tpl.description || 'No description')}
${escapeHtml((tpl.docker && tpl.docker.image) ? tpl.docker.image : 'Custom image')}
`;
}
if (tpl._norm === normalizeTemplateIdClient(currentTemplate || templatePickerState.selected)) {
card.classList.add('active');
templatePickerState.selected = tpl._id;
templatePickerState.selectedNorm = tpl._norm;
if (serverTemplateModal) serverTemplateModal.dataset.selected = tpl._id;
}
serverTemplateList.appendChild(card);
});
if (!templatePickerState.selected && unique[0]) {
selectServerTemplate(unique[0]._id);
}
renderServerTemplateAction();
}
// Stale-response guard: reopening the picker must let the newest fetch win.
let _serverTemplateModalRenderToken = 0;
async function openServerTemplateModal(serverName, currentTemplate, expectedTargetId) {
if (!serverTemplateOverlay || !serverTemplateModal) return;
const renderToken = ++_serverTemplateModalRenderToken;
const isStale = () => renderToken !== _serverTemplateModalRenderToken;
templatePickerState.server = serverName;
templatePickerState.expectedTargetId = expectedTargetId;
templatePickerState.selected = '';
templatePickerState.selectedNorm = '';
templatePickerState.originalTemplate = normalizeTemplateIdClient(currentTemplate);
templatePickerState.completed = false;
renderServerTemplateAction();
serverTemplateModal.dataset.server = serverName;
serverTemplateModal.dataset.selected = templatePickerState.selected || '';
serverTemplateTitle.textContent = `Change template for ${serverName}`;
serverTemplateSubtitle.textContent = currentTemplate
? `Current template: ${displayTemplateName(currentTemplate)}`
: 'Select a template to apply to this server.';
serverTemplateOverlay.classList.add('show');
serverTemplateModal.classList.add('show');
if (serverTemplateList) serverTemplateList.innerHTML = `Loading templates…
`;
if (serverTemplateFeedback) serverTemplateFeedback.textContent = '';
try {
const collected = [];
let page = 1;
let totalPages = 1;
do {
let res;
try {
const params = new URLSearchParams({ page: String(page), limit: '200' });
res = await fetch('/api/settings/templates?' + params.toString());
} catch (err) {
if (isStale()) return;
if (page === 1) throw err;
console.warn('[template-picker] Network error on page ' + page + ', rendering the ' + collected.length + ' templates loaded so far.', err);
break;
}
if (isStale()) return;
const data = await res.json().catch(() => ({ templates: [] }));
if (isStale()) return;
if (!res.ok) {
if (page === 1) {
if (serverTemplateFeedback) serverTemplateFeedback.textContent = data.error || 'Failed to load templates.';
return;
}
console.warn('[template-picker] Failed to load page ' + page + ', rendering the ' + collected.length + ' templates loaded so far.', data.error || 'Failed to load templates.');
break;
}
(Array.isArray(data.templates) ? data.templates : []).forEach(tpl => collected.push(tpl));
totalPages = Math.max(1, Number(data.totalPages || 1));
page += 1;
} while (page <= totalPages && page <= 10);
updateTemplateNameMap(collected);
renderServerTemplateOptions(collected, currentTemplate);
} catch (err) {
console.error(err);
if (isStale()) return;
if (serverTemplateFeedback) serverTemplateFeedback.textContent = 'Network error while loading templates.';
}
}
if (serverTemplateList) {
serverTemplateList.addEventListener('click', (e) => {
const card = e.target.closest('.template-option-card');
if (!card) return;
selectServerTemplate(card.dataset.id);
});
}
if (serverTemplateCancel) {
serverTemplateCancel.addEventListener('click', closeServerTemplateModal);
}
if (serverTemplateClose) {
serverTemplateClose.addEventListener('click', closeServerTemplateModal);
}
// Click outside disabled — user must use close/cancel button
// if (serverTemplateOverlay) {
// serverTemplateOverlay.addEventListener('click', (e) => {
// if (e.target === serverTemplateOverlay) closeServerTemplateModal();
// });
// }
if (serverTemplateDone) {
serverTemplateDone.addEventListener('click', async () => {
const server = serverTemplateModal?.dataset?.server || '';
const selected = templatePickerState.selected || serverTemplateModal?.dataset?.selected || '';
const originalTemplate = templatePickerState.originalTemplate || '';
if (templatePickerState.submitting) return;
if (!server || templatePickerState.completed) {
closeServerTemplateModal();
return;
}
if (!selected) {
if (serverTemplateFeedback) serverTemplateFeedback.textContent = 'Select a template first.';
return;
}
const selectedNorm = normalizeTemplateIdClient(selected);
const reapply = selectedNorm === originalTemplate;
const templateAction = reapply ? 'Reapplying the latest template' : 'Changing the template';
const confirmMsg = `${templateAction} will REINSTALL the server "${server}". That means:\n\n` +
` - All server files will be permanently deleted.\n\n` +
` Are you sure you want to continue?`;
if (!confirm(confirmMsg)) return;
const unconfirmedMessage = 'The reinstall result could not be confirmed. It may still be running or may have completed. Check the server state before retrying.';
try {
templatePickerState.submitting = true;
renderServerTemplateAction();
if (serverTemplateCancel) serverTemplateCancel.disabled = true;
if (serverTemplateClose) serverTemplateClose.style.pointerEvents = 'none';
if (serverTemplateFeedback) {
serverTemplateFeedback.textContent = 'Stopping server and deleting files… This may take a few minutes.';
serverTemplateFeedback.style.color = 'var(--warning, #f0ad4e)';
}
const { res, data } = await sendServerRowActionWithGuards(
`/api/settings/servers/${encodeURIComponent(server)}/template`,
'POST',
{ templateId: selected, expectedTargetId: templatePickerState.expectedTargetId, ...(reapply ? { reapply: true } : {}) },
{
getToken: () => getServerTemplateChangeToken(server),
refreshToken: () => refreshServerTemplateChangeToken(server),
copy: {
subtitle: `${reapply ? 'Reapply' : 'Change'} template of "${server}"`,
reason: `${templateAction} reinstalls the server and permanently deletes all of its files. Verify your identity to continue.`,
confirmText: 'Verify & Reinstall',
cancelledMessage: 'Verification cancelled — the template was not changed.',
unconfirmedMessage,
},
}
);
if (!res.ok || data?.ok !== true) {
const unconfirmed = res.ok || res.status === 0 || data?.code === 'reinstall-result-unconfirmed' || (res.status >= 500 && !data?.error);
if (serverTemplateFeedback) {
serverTemplateFeedback.textContent = data?.error || (unconfirmed ? unconfirmedMessage : 'Failed to change template.');
serverTemplateFeedback.style.color = 'var(--danger, #d9534f)';
}
return;
}
templatePickerState.originalTemplate = selectedNorm;
templatePickerState.completed = true;
if (serverTemplateFeedback) {
serverTemplateFeedback.textContent = data.eulaRequired === true
? 'Server files replaced. Accept the Minecraft EULA in the console before starting the server.'
: reapply ? 'Latest template reapplied and server files replaced.' : 'Template changed and server files replaced.';
serverTemplateFeedback.style.color = 'var(--success, #5cb85c)';
}
const row = findServerRowByName(server);
if (row) {
row.dataset.template = selected;
const chip = row.querySelector('.template-chip');
if (chip) chip.textContent = `Template: ${displayTemplateName(selected)}`;
}
if (data.eulaRequired !== true) setTimeout(() => { closeServerTemplateModal(); }, 1200);
} catch (err) {
console.error(err);
if (serverTemplateFeedback) {
serverTemplateFeedback.textContent = err?.message || unconfirmedMessage;
serverTemplateFeedback.style.color = 'var(--danger, #d9534f)';
}
} finally {
templatePickerState.submitting = false;
renderServerTemplateAction();
if (serverTemplateCancel) serverTemplateCancel.disabled = false;
if (serverTemplateClose) serverTemplateClose.style.pointerEvents = '';
}
});
}
// F1 follow-up: the legacy quick-creator was removed — it POSTed to
// /api/settings/servers, a route that no longer exists (404), and real server
// creation is the wizard's step-up-gated POST /api/servers/create.
serversListEl.addEventListener('mouseover', (e) => {
const resourceBtn = e.target.closest('.manage-resources');
if (!resourceBtn) return;
const row = resourceBtn.closest('.server-row');
const serverName = row?.dataset?.name || (resourceBtn.dataset.name ? decodeURIComponent(resourceBtn.dataset.name) : '');
if (serverName) _prefetchResources(serverName);
});
serversListEl.addEventListener('click', async (e) => {
const resourceBtn = e.target.closest('.manage-resources');
if (resourceBtn) {
const row = resourceBtn.closest('.server-row');
const serverName = row?.dataset?.name || (resourceBtn.dataset.name ? decodeURIComponent(resourceBtn.dataset.name) : '');
if (serverName) openResourcesModal(serverName);
return;
}
const transferBtn = e.target.closest('.transfer-server');
if (transferBtn) {
const row = transferBtn.closest('.server-row');
const serverName = row?.dataset?.name || (transferBtn.dataset.name ? decodeURIComponent(transferBtn.dataset.name) : '');
const currentNodeId = row?.dataset?.nodeId ? String(row.dataset.nodeId) : '';
if (serverName) openTransferModal(serverName, currentNodeId, Number(row?.dataset?.targetId));
return;
}
const changeBtn = e.target.closest('.change-template');
if (changeBtn) {
const row = changeBtn.closest('.server-row');
const serverName = row?.dataset?.name || (changeBtn.dataset.name ? decodeURIComponent(changeBtn.dataset.name) : '');
const currentTemplate = row?.dataset?.template || '';
if (serverName) openServerTemplateModal(serverName, currentTemplate, Number(row?.dataset?.targetId));
return;
}
const suspendBtn = e.target.closest('.server-suspension-action, .suspend-server');
if (suspendBtn) {
if (suspendBtn.disabled) return;
const row = suspendBtn.closest('.server-row');
const encName = suspendBtn.dataset.name;
const serverName = row?.dataset?.name || (encName ? decodeURIComponent(encName) : '');
if (!serverName) return;
const nextSuspended = String(suspendBtn.dataset.nextSuspended || 'true').toLowerCase() !== 'false';
if (typeof window.openServerSuspensionVerificationModal === 'function') {
window.openServerSuspensionVerificationModal(serverName, nextSuspended, suspendBtn);
} else {
alert('Security confirmation is still loading. Please try again.');
}
return;
}
const btn = e.target.closest('.delete-server');
if (!btn) return;
const encName = btn.dataset.name;
if (!encName) return;
const name = decodeURIComponent(encName);
if (typeof window.openServerDeleteVerificationModal === 'function') {
window.openServerDeleteVerificationModal(name, btn);
} else {
alert('Security confirmation is still loading. Please try again.');
}
});
const transferModalOverlay = document.getElementById('transferModalOverlay');
const transferModal = document.getElementById('transferModal');
const transferModalTitle = document.getElementById('transferModalTitle');
const transferModalSubtitle = document.getElementById('transferModalSubtitle');
const transferModalClose = document.getElementById('transferModalClose');
const transferCancel = document.getElementById('transferCancel');
const transferFeedback = document.getElementById('transferFeedback');
const transferNodeList = document.getElementById('transferNodeList');
const transferProgress = document.getElementById('transferProgress');
const transferProgressFill = document.getElementById('transferProgressFill');
const transferProgressText = document.getElementById('transferProgressText');
let transferPollTimer = null;
let transferPollRetryAt = 0;
let transferViewVersion = 0;
function setTransferFeedback(msg, isError = false) {
if (!transferFeedback) return;
transferFeedback.textContent = msg || '';
transferFeedback.className = 'node-feedback' + (isError ? ' error' : '');
}
function setTransferProgress(job) {
if (!transferProgress || !transferProgressFill || !transferProgressText) return;
if (!job) {
transferProgress.style.display = 'none';
transferProgressFill.style.width = '0%';
transferProgressText.textContent = '';
return;
}
transferProgress.style.display = 'block';
const pct = Math.max(0, Math.min(100, Number(job.percent || 0)));
transferProgressFill.style.width = `${pct}%`;
const status = job.status ? String(job.status) : 'running';
transferProgressText.textContent = `${status}${job.message ? ' — ' + job.message : ''}`;
}
function showTransferModal(show) {
if (!transferModalOverlay) return;
if (show) {
transferModalOverlay.setAttribute('aria-hidden', 'false');
transferModalOverlay.classList.add('show');
} else {
transferModalOverlay.setAttribute('aria-hidden', 'true');
transferModalOverlay.classList.remove('show');
transferViewVersion += 1;
setTransferFeedback('');
setTransferProgress(null);
if (transferNodeList) transferNodeList.innerHTML = '';
if (transferPollTimer) {
clearInterval(transferPollTimer);
transferPollTimer = null;
}
}
}
async function fetchTransferJob(serverName) {
if (Date.now() < transferPollRetryAt) return undefined;
const res = await fetch(`/api/settings/servers/${encodeURIComponent(serverName)}/transfer`, { cache: 'no-store' });
if (res.status === 429 || res.status >= 500) {
const retryAfter = Number(res.headers.get('retry-after'));
transferPollRetryAt = Date.now() + (Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : 5000);
return undefined;
}
if (!res.ok) return null;
const data = await res.json().catch(() => null);
if (data?.job === null) return null;
if (data?.job && typeof data.job === 'object') return data.job;
transferPollRetryAt = Date.now() + 5000;
return undefined;
}
async function pollTransfer(serverName, viewVersion) {
const timer = transferPollTimer;
try {
const job = await fetchTransferJob(serverName);
if (viewVersion !== transferViewVersion || timer !== transferPollTimer || job === undefined) return;
if (job) {
setTransferProgress(job);
if (job.status === 'error') setTransferFeedback(job.error || job.message || 'Transfer failed', true);
if (job.finishedAt) {
if (job.status === 'done') setTransferFeedback(job.message || 'Transfer complete.', false);
clearInterval(transferPollTimer);
transferPollTimer = null;
loadServers();
}
} else {
if (transferPollTimer) {
clearInterval(transferPollTimer);
transferPollTimer = null;
}
loadServers();
}
} catch { }
}
async function loadTransferNodes(serverName, currentNodeId, viewVersion, expectedTargetId) {
if (!transferNodeList) return;
transferNodeList.innerHTML = `Loading nodes…
`;
try {
const res = await fetch('/api/nodes', { cache: 'no-store' });
const data = await res.json().catch(() => ({ nodes: [] }));
if (viewVersion !== transferViewVersion) return;
if (!res.ok) throw new Error(data.error || 'Failed to load nodes');
const nodes = Array.isArray(data.nodes) ? data.nodes : [];
transferNodeList.innerHTML = '';
const filtered = nodes.filter(n => {
const id = String(n.id || '').trim();
const uuid = String(n.uuid || '').trim();
const name = String(n.name || '').trim();
const anyId = String(id || uuid || name || '').trim();
if (!anyId) return false;
if (currentNodeId && (String(currentNodeId) === id || String(currentNodeId) === uuid || String(currentNodeId) === name)) return false;
if (n.online !== true) return false;
return true;
});
if (!filtered.length) {
transferNodeList.innerHTML = `No nodes available.
`;
return;
}
filtered.forEach(n => {
const id = n.uuid || n.id || n.name;
const item = document.createElement('div');
item.className = 'transfer-node-item';
item.dataset.id = id;
item.innerHTML = `
Transfer
`;
item.querySelector('button')?.addEventListener('click', async (ev) => {
ev.stopPropagation();
await startTransfer(serverName, id, viewVersion, expectedTargetId);
});
item.addEventListener('click', async () => {
await startTransfer(serverName, id, viewVersion, expectedTargetId);
});
transferNodeList.appendChild(item);
});
} catch (e) {
if (viewVersion !== transferViewVersion) return;
console.error(e);
transferNodeList.innerHTML = `Failed to load nodes.
`;
}
}
async function startTransfer(serverName, targetNodeId, viewVersion, expectedTargetId) {
if (viewVersion !== transferViewVersion) return;
try {
setTransferFeedback('Starting transfer…');
setTransferProgress({ status: 'preparing', percent: 0, message: 'Starting…' });
const { res, data } = await sendServerRowActionWithGuards(
`/api/settings/servers/${encodeURIComponent(serverName)}/transfer`,
'POST',
{ targetNodeId, expectedTargetId },
{
getToken: () => getServerTransferToken(serverName),
refreshToken: () => refreshServerTransferToken(serverName),
copy: {
subtitle: `Transfer "${serverName}" to another node`,
reason: 'Transferring moves the server to another node: it will be stopped, copied over, and restarted there. Verify your identity to continue.',
confirmText: 'Verify & Transfer',
cancelledMessage: 'Verification cancelled — the transfer was not started.',
},
}
);
if (viewVersion !== transferViewVersion) return;
if (!res.ok) throw new Error(data?.error || 'Failed to start transfer');
if (data.job) setTransferProgress(data.job);
setTransferFeedback('Transfer in progress…');
if (!transferPollTimer) {
transferPollTimer = setInterval(() => pollTransfer(serverName, viewVersion), 1500);
}
} catch (e) {
if (viewVersion !== transferViewVersion) return;
console.error(e);
setTransferFeedback(e?.message || 'Failed to start transfer', true);
setTransferProgress(null);
}
}
async function openTransferModal(serverName, currentNodeId = '', expectedTargetId) {
const viewVersion = ++transferViewVersion;
if (transferPollTimer) clearInterval(transferPollTimer);
transferPollTimer = null;
if (transferModalTitle) transferModalTitle.textContent = `Transfer: ${serverName}`;
if (transferModalSubtitle) transferModalSubtitle.textContent = 'Pick a destination node.';
setTransferFeedback('');
setTransferProgress(null);
showTransferModal(true);
await loadTransferNodes(serverName, currentNodeId, viewVersion, expectedTargetId);
if (viewVersion !== transferViewVersion || transferPollTimer) return;
try {
const existing = await fetchTransferJob(serverName);
if (viewVersion !== transferViewVersion || transferPollTimer) return;
if (existing) setTransferProgress(existing);
if (existing === undefined || (existing && !existing.finishedAt)) {
transferPollTimer = setInterval(() => pollTransfer(serverName, viewVersion), 1500);
}
} catch {
if (viewVersion === transferViewVersion && !transferPollTimer) setTransferFeedback('Could not load transfer status.', true);
}
}
if (transferModalClose) transferModalClose.addEventListener('click', () => showTransferModal(false));
if (transferCancel) transferCancel.addEventListener('click', () => showTransferModal(false));
// Click outside disabled — user must use close/cancel button
// if (transferModalOverlay) {
// transferModalOverlay.addEventListener('click', (e) => {
// if (e.target === transferModalOverlay) showTransferModal(false);
// });
// }
const serversOverviewView = document.getElementById('serversOverviewView');
const serverManageInlineView = document.getElementById('serverManageInlineView');
const serverManageTitle = document.getElementById('serverManageTitle');
const serverManageSubtitle = document.getElementById('serverManageSubtitle');
const serverManageBackBtn = document.getElementById('serverManageBackBtn');
const serverManageCategoriesNav = document.getElementById('serverManageCategoriesNav');
// Category save buttons
const saveResourcesCategoryBtn = document.getElementById('saveResourcesCategoryBtn');
const saveLimitsCategoryBtn = document.getElementById('saveLimitsCategoryBtn');
const saveBandwidthCategoryBtn = document.getElementById('saveBandwidthCategoryBtn');
const savePortsCategoryBtn = document.getElementById('savePortsCategoryBtn');
const saveStartupCategoryBtn = document.getElementById('saveStartupCategoryBtn');
// Category feedback elements
const feedbackServer = document.getElementById('feedback_server');
const feedbackResources = document.getElementById('feedback_resources');
const feedbackLimits = document.getElementById('feedback_limits');
const feedbackBandwidth = document.getElementById('feedback_bandwidth');
const feedbackPorts = document.getElementById('feedback_ports');
const feedbackStartup = document.getElementById('feedback_startup');
const resJavaVersionDivider = document.getElementById('res_javaVersionDivider');
// Legacy modal element references kept safe for fallback
const resourcesModalOverlay = document.getElementById('resourcesModalOverlay');
const resourcesModal = document.getElementById('resourcesModal');
const resourcesModalTitle = document.getElementById('resourcesModalTitle');
const resourcesModalSubtitle = document.getElementById('resourcesModalSubtitle');
const resourcesModalClose = document.getElementById('resourcesModalClose');
const resourcesCancel = document.getElementById('resourcesCancel');
const resourcesSave = document.getElementById('resourcesSave');
const resourcesFeedback = document.getElementById('resourcesFeedback');
const resServerNameInput = document.getElementById('res_serverName');
const resRenameServerBtn = document.getElementById('res_renameServer');
const resRamMb = document.getElementById('res_ramMb');
const resCpuCores = document.getElementById('res_cpuCores');
const resStorageMb = document.getElementById('res_storageMb');
const resSwapMb = document.getElementById('res_swapMb');
const resBackupsMax = document.getElementById('res_backupsMax');
const resMaxSchedules = document.getElementById('res_maxSchedules');
const resIoWeight = document.getElementById('res_ioWeight');
const resCpuWeight = document.getElementById('res_cpuWeight');
const resPidsLimit = document.getElementById('res_pidsLimit');
const resFileLimit = document.getElementById('res_fileLimit');
const resNetworkInboundLimitMb = document.getElementById('res_networkInboundLimitMb');
const resNetworkOutboundLimitMb = document.getElementById('res_networkOutboundLimitMb');
const resNetworkResetMinutes = document.getElementById('res_networkResetMinutes');
const resUsageBar = document.getElementById('res_usageBar');
const resUsageText = document.getElementById('res_usageText');
const resPortsList = document.getElementById('res_portsList');
const resPortDropdown = document.getElementById('res_portDropdown');
const resPortDropdownTrigger = document.getElementById('res_portDropdownTrigger');
const resPortDropdownMenu = document.getElementById('res_portDropdownMenu');
const resPortDropdownSelectedText = document.getElementById('res_portDropdownSelectedText');
const resPortSelect = document.getElementById('res_portSelect');
const resNewPort = document.getElementById('res_newPort');
const resAddPort = document.getElementById('res_addPort');
const resStartupCommand = document.getElementById('res_startupCommand');
const resStartupSection = document.getElementById('res_startupSection');
const resStartupPreview = document.getElementById('res_startupPreview');
const resCopyStartupCmd = document.getElementById('res_copyStartupCmd');
const resStartupCommandHelp = document.getElementById('res_startupCommandHelp');
const resJavaVersionField = document.getElementById('res_javaVersionField');
const resJavaVersion = document.getElementById('res_javaVersion');
const resJavaVersionHint = document.getElementById('res_javaVersionHint');
const resJavaDropdown = document.getElementById('res_javaDropdown');
const resJavaDropdownTrigger = document.getElementById('res_javaDropdownTrigger');
const resJavaDropdownMenu = document.getElementById('res_javaDropdownMenu');
const resJavaDropdownSelectedText = document.getElementById('res_javaDropdownSelectedText');
if (resAddPort) resAddPort.setAttribute('data-unsaved-action', 'true');
const RESOURCE_NETWORK_LIMIT_MAX_MB = 1073741824;
const RESOURCE_NETWORK_RESET_MAX_MINUTES = 43200;
const MINECRAFT_JAVA_MIN_VERSION = 8;
const MINECRAFT_JAVA_MAX_VERSION = 30;
const DEFAULT_MINECRAFT_JAVA_OPTIONS = Object.freeze(['8', '11', '17', '21', '22', '23', '24', '25', '26']);
let _measureCanvas = null;
function getExactTextWidth(text, font) {
if (!_measureCanvas) _measureCanvas = document.createElement('canvas');
const ctx = _measureCanvas.getContext('2d');
ctx.font = font || '13px Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
return ctx.measureText(text).width;
}
function autoResizeInput(input) {
if (!input) return;
if (input.id === 'nm_disk_mount' || input.id === 'nm_cmd' || input.id === 'res_startupCommand') return;
const val = String(input.value || input.placeholder || '');
if (!val) {
input.style.width = '24px';
return;
}
if (window.CSS && CSS.supports && CSS.supports('field-sizing', 'content')) {
input.style.width = '';
return;
}
const font = window.getComputedStyle(input).font || '13px Inter, sans-serif';
const width = Math.ceil(getExactTextWidth(val, font)) + 2;
input.style.width = `${width}px`;
}
function triggerAutoResizeInputs() {
document.querySelectorAll('.panelinfo-input, .panelinfo-input-wrap .panelinfo-input').forEach(input => {
autoResizeInput(input);
});
}
document.addEventListener('input', (e) => {
if (e.target && e.target.matches && (e.target.matches('.panelinfo-input') || e.target.matches('.panelinfo-input-wrap .panelinfo-input'))) {
autoResizeInput(e.target);
}
});
document.addEventListener('click', (e) => {
const wrap = e.target.closest && e.target.closest('.panelinfo-input-wrap');
if (wrap) {
const input = wrap.querySelector('.panelinfo-input');
if (input) {
input.focus();
}
}
});
function formatStorageMb(mb) {
if (mb == null || isNaN(mb) || mb <= 0) return '';
if (mb >= 1010) return (mb / 1024).toFixed(2).replace(/\.?0+$/, '') + ' GB';
return Math.round(mb) + ' MB';
}
function readOptionalResourceNumber(input, label) {
if (input?.validity.badInput || (input?.value && !Number.isFinite(input.valueAsNumber))) {
throw new Error(`${label} must be a number.`);
}
return input?.value ? input.valueAsNumber : null;
}
function readOptionalIntegerRange(input, label, min, max) {
const value = readOptionalResourceNumber(input, label);
if (value === null) return null;
if (!Number.isSafeInteger(value)) throw new Error(`${label} must be a whole number.`);
if (value < min || value > max) {
throw new Error(`${label} must be between ${min} and ${max}.`);
}
return value;
}
if (resStorageMb) {
resStorageMb.addEventListener('input', () => {
const hint = resStorageMb.closest('.node-form-field')?.querySelector('.resource-hint');
if (!hint) return;
const val = parseInt(resStorageMb.value, 10);
if (!isNaN(val) && val > 0) {
const display = formatStorageMb(val);
hint.textContent = `Disk space limit: ${display}`;
} else {
hint.textContent = 'Disk space limit for server files (e.g. 500 = 500 MB, 50000 = ~48.83 GB)';
}
});
}
let currentResourcesServer = '';
let currentResourcesRenameToken = '';
let resourcesViewVersion = 0;
let currentResourcesTargetId = null;
let originalServerDisplayName = '';
let currentServerIp = '';
let currentServerPortIps = {};
let currentNodePorts = [];
let currentNodeAllocations = [];
let currentNodeAddress = '';
let currentServerPorts = [];
let originalServerPorts = [];
let currentServerMainPort = null;
let originalServerMainPort = null;
let currentServerTemplate = '';
let originalStartupCommand = '';
let originalStartupCommandSource = '';
let currentMinecraftJavaEnabled = false;
let originalMinecraftJavaVersion = '';
const serverResourceEditorInputs = {
ramMb: resRamMb, cpuCores: resCpuCores, storageMb: resStorageMb, swapMb: resSwapMb,
backupsMax: resBackupsMax, maxSchedules: resMaxSchedules, ioWeight: resIoWeight,
cpuWeight: resCpuWeight, pidsLimit: resPidsLimit, fileLimit: resFileLimit,
networkInboundLimitMb: resNetworkInboundLimitMb, networkOutboundLimitMb: resNetworkOutboundLimitMb,
networkResetMinutes: resNetworkResetMinutes
};
let savedServerResourceValues = {};
registerModalCustomStateReader('resourcesModalOverlay', () => ({
server: currentResourcesServer || '',
mainPort: currentServerMainPort ?? null,
ports: currentServerPorts.slice().map(Number).filter(Number.isFinite).sort((a, b) => a - b),
javaVersion: currentMinecraftJavaEnabled ? String(resJavaVersion?.value || '').trim() : ''
}));
function showCategoryFeedback(cat, msg, isError = false) {
const elMap = {
server: feedbackServer,
resources: feedbackResources,
limits: feedbackLimits,
bandwidth: feedbackBandwidth,
ports: feedbackPorts,
startup: feedbackStartup,
'node-config': document.getElementById('feedback_node_config'),
'node-resources': document.getElementById('feedback_node_resources'),
'node-ports': document.getElementById('feedback_node_ports'),
'node-disks': document.getElementById('feedback_node_disks'),
'node-linking': document.getElementById('feedback_node_linking'),
'node-danger': document.getElementById('feedback_node_danger'),
node_config: document.getElementById('feedback_node_config'),
node_resources: document.getElementById('feedback_node_resources'),
node_ports: document.getElementById('feedback_node_ports'),
node_disks: document.getElementById('feedback_node_disks'),
node_linking: document.getElementById('feedback_node_linking'),
node_danger: document.getElementById('feedback_node_danger')
};
const el = elMap[cat] || resourcesFeedback;
if (el) {
if (el._feedbackTimer) {
clearTimeout(el._feedbackTimer);
el._feedbackTimer = null;
}
el.textContent = msg;
el.className = 'panelinfo-update-status ' + (isError ? 'error' : 'success');
el.style.display = msg ? 'block' : 'none';
if (msg && !isError) {
el._feedbackTimer = setTimeout(() => {
el.style.display = 'none';
el.textContent = '';
el._feedbackTimer = null;
}, 3000);
}
}
}
function clearAllCategoryFeedback() {
[
feedbackServer, feedbackResources, feedbackLimits, feedbackBandwidth, feedbackPorts, feedbackStartup, resourcesFeedback,
document.getElementById('feedback_node_config'),
document.getElementById('feedback_node_resources'),
document.getElementById('feedback_node_ports'),
document.getElementById('feedback_node_disks'),
document.getElementById('feedback_node_linking'),
document.getElementById('feedback_node_danger')
].forEach((el) => {
if (el) {
el.textContent = '';
el.style.display = 'none';
}
});
}
function switchServerCategory(catName) {
const targetCat = catName || 'server';
const btns = serverManageCategoriesNav ? serverManageCategoriesNav.querySelectorAll('.server-category-btn') : [];
btns.forEach((btn) => {
if (btn.dataset.cat === targetCat) {
btn.classList.add('active');
} else {
btn.classList.remove('active');
}
});
const panes = serverManageInlineView ? serverManageInlineView.querySelectorAll('.server-category-pane') : [];
panes.forEach((pane) => {
if (pane.id === `pane_${targetCat}`) {
pane.classList.add('active');
} else {
pane.classList.remove('active');
}
});
renderPortsList();
renderPortDropdown();
triggerAutoResizeInputs();
}
if (serverManageCategoriesNav) {
serverManageCategoriesNav.addEventListener('click', (e) => {
const btn = e.target.closest('.server-category-btn');
if (btn && btn.dataset.cat) {
switchServerCategory(btn.dataset.cat);
}
});
}
function showResourcesFeedback(msg, isError = false) {
const activePane = serverManageInlineView?.querySelector('.server-category-pane.active');
const cat = activePane ? activePane.id.replace('pane_', '') : 'resources';
showCategoryFeedback(cat, msg, isError);
if (resourcesFeedback) {
resourcesFeedback.textContent = msg;
resourcesFeedback.className = 'panelinfo-update-status ' + (isError ? 'error' : 'success');
resourcesFeedback.style.display = msg ? 'block' : 'none';
}
}
function clearResourcesFeedback() {
clearAllCategoryFeedback();
}
function renderStartupCommandPreview(command) {
if (!resStartupPreview) return;
const value = String(command || '').trim();
if (!value) {
resStartupPreview.innerHTML = 'No startup command configured';
return;
}
const escaped = value.replace(/&/g, '&').replace(//g, '>');
resStartupPreview.innerHTML = '' + escaped + '';
}
function adjustStartupCommandHeight() {
if (!resStartupCommand) return;
resStartupCommand.style.height = '20px';
const scrollH = resStartupCommand.scrollHeight;
if (scrollH > 28) {
resStartupCommand.style.height = Math.min(scrollH, 140) + 'px';
} else {
resStartupCommand.style.height = '20px';
}
}
function renderStartupCommandEditorState(command) {
const source = String(originalStartupCommandSource || '').trim().toLowerCase();
if (source === 'adpanel-startup' || source === 'image-default' || source === 'image-inspect') {
if (resStartupCommand) {
resStartupCommand.setAttribute('aria-invalid', 'false');
resStartupCommand.readOnly = true;
}
if (resStartupCommandHelp) {
resStartupCommandHelp.textContent = 'Default command set by image';
resStartupCommandHelp.style.display = 'block';
resStartupCommandHelp.style.color = 'rgba(255, 255, 255, 0.45)';
}
adjustStartupCommandHeight();
return '';
}
const error = validateRuntimeProcessCommandInput(command);
if (resStartupCommand) {
resStartupCommand.setAttribute('aria-invalid', error ? 'true' : 'false');
resStartupCommand.readOnly = false;
}
if (resStartupCommandHelp) {
if (error) {
resStartupCommandHelp.textContent = error;
resStartupCommandHelp.style.display = 'block';
resStartupCommandHelp.style.color = '#ef4444';
} else {
resStartupCommandHelp.textContent = '';
resStartupCommandHelp.style.display = 'none';
}
}
adjustStartupCommandHeight();
return error;
}
function normalizeMinecraftJavaVersionClient(value) {
const raw = String(value ?? '').trim().toLowerCase();
if (!raw) return '';
const match = raw.match(/^(\d{1,2})(?:\D.*)?$/);
if (!match) return '';
const version = Number(match[1]);
if (!Number.isInteger(version) || version < MINECRAFT_JAVA_MIN_VERSION || version > MINECRAFT_JAVA_MAX_VERSION) return '';
return String(version);
}
function isMinecraftTemplateLikeClient(templateId, templateName) {
const normalizedTemplateId = normalizeTemplateIdClient(templateId);
if (normalizedTemplateId === 'minecraft') return true;
if (normalizedTemplateId.includes('minecraft')) return true;
return String(templateName || '').trim().toLowerCase().includes('minecraft');
}
function resetMinecraftJavaSelector() {
currentMinecraftJavaEnabled = false;
originalMinecraftJavaVersion = '';
if (resJavaVersion) {
resJavaVersion.innerHTML = '';
resJavaVersion.value = '';
resJavaVersion.disabled = true;
}
if (resJavaDropdownSelectedText) {
resJavaDropdownSelectedText.textContent = 'Select Java...';
}
if (resJavaDropdownMenu) {
resJavaDropdownMenu.innerHTML = '';
resJavaDropdownMenu.hidden = true;
}
if (resJavaDropdown) {
resJavaDropdown.classList.remove('is-open');
}
if (resJavaVersionField) {
resJavaVersionField.hidden = true;
resJavaVersionField.style.display = 'none';
}
if (resJavaVersionDivider) {
resJavaVersionDivider.style.display = 'none';
}
if (resJavaVersionHint) resJavaVersionHint.textContent = '';
}
function renderMinecraftJavaSelector(data) {
resetMinecraftJavaSelector();
if (!isMinecraftTemplateLikeClient(data?.template, data?.templateName)) return;
const javaPayload = data?.minecraftJava && typeof data.minecraftJava === 'object' ? data.minecraftJava : null;
const rawOptions = Array.isArray(javaPayload?.options) && javaPayload.options.length
? javaPayload.options
: DEFAULT_MINECRAFT_JAVA_OPTIONS.map((version) => ({ version, tag: `${version}-jre`, label: `Java ${version}` }));
const options = rawOptions
.map((option) => {
const version = normalizeMinecraftJavaVersionClient(option?.version || option?.value || option);
if (!version) return null;
return {
version,
tag: String(option?.tag || `${version}-jre`).trim(),
label: String(option?.label || `Java ${version}`).trim(),
};
})
.filter(Boolean);
if (!options.length) return;
const seen = new Set();
const uniqueOptions = [];
if (resJavaVersion) resJavaVersion.innerHTML = '';
for (const option of options) {
if (seen.has(option.version)) continue;
seen.add(option.version);
uniqueOptions.push(option);
if (resJavaVersion) {
const opt = document.createElement('option');
opt.value = option.version;
opt.textContent = `${option.label} (${option.tag})`;
resJavaVersion.appendChild(opt);
}
}
const selected = normalizeMinecraftJavaVersionClient(data?.javaVersion || javaPayload?.selected) ||
normalizeMinecraftJavaVersionClient(options.find((option) => option.version === '21')?.version) ||
options[0].version;
if (resJavaVersion) {
resJavaVersion.value = selected;
resJavaVersion.disabled = false;
}
originalMinecraftJavaVersion = selected;
currentMinecraftJavaEnabled = true;
const selectedOpt = uniqueOptions.find(o => o.version === selected) || uniqueOptions[0];
if (resJavaDropdownSelectedText && selectedOpt) {
resJavaDropdownSelectedText.textContent = `${selectedOpt.label} (${selectedOpt.tag})`;
}
if (resJavaDropdownMenu) {
let html = '';
uniqueOptions.forEach((opt, idx) => {
if (idx > 0) {
html += '
';
}
const isCurrent = opt.version === selected;
html += `
${escapeHtml(opt.label)} (${escapeHtml(opt.tag)})
`;
});
resJavaDropdownMenu.innerHTML = html;
resJavaDropdownMenu.querySelectorAll('.dashboard-assistant-dropdown-item[data-version]').forEach(item => {
item.addEventListener('click', (e) => {
e.stopPropagation();
const v = item.getAttribute('data-version');
const lbl = item.getAttribute('data-label');
if (resJavaVersion) resJavaVersion.value = v;
if (resJavaDropdownSelectedText) resJavaDropdownSelectedText.textContent = lbl;
resJavaDropdownMenu.querySelectorAll('.dashboard-assistant-dropdown-item').forEach(i => i.classList.remove('active'));
item.classList.add('active');
if (resJavaDropdown) resJavaDropdown.classList.remove('is-open');
if (resJavaDropdownMenu) resJavaDropdownMenu.hidden = true;
});
});
}
if (resJavaVersionField) {
resJavaVersionField.hidden = false;
resJavaVersionField.style.display = 'flex';
}
if (resJavaVersionDivider) {
resJavaVersionDivider.style.display = 'block';
}
if (resJavaVersionHint) {
resJavaVersionHint.textContent = '';
}
}
function sanitizePortInputValue(value) {
return String(value ?? '').replace(/[^\d]/g, '').slice(0, 5);
}
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;
}
const RUNTIME_PROCESS_BLOCKED_EXECUTABLES = new Set([
'sh', '/bin/sh', 'bash', '/bin/bash', 'ash', '/bin/ash', 'dash', '/bin/dash', 'zsh', '/bin/zsh', 'ksh', '/bin/ksh',
]);
const RUNTIME_PROCESS_BLOCKED_CONTAINER_EXECUTABLES = new Set([
'docker', 'docker-compose', 'podman', 'podman-compose', 'nerdctl', 'ctr',
]);
const RUNTIME_PROCESS_ENV_WRAPPERS = new Set(['env']);
const RUNTIME_PROCESS_BLOCKED_TOKENS = new Set([
'&&', '||', '|', ';', '&', '>', '>>', '<', '<<', '2>', '2>>', '2>&1', '|&',
]);
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;
}
// The exact-token blocklist only catches operators as standalone arguments;
// parseRuntimeProcessArgsInput keeps "app.js;curl" as one literal argv token.
// Reject any operator character a shell would interpret outside quotes so the
// command carries no shell syntax at all; quoted operators are literal data
// and stay allowed (a bare quoted ";" still fails the exact-token check).
// Quote/escape handling mirrors parseRuntimeProcessArgsInput exactly.
function findUnquotedRuntimeShellOperatorInput(command) {
const input = String(command || '');
let quote = '';
let escape = false;
for (let i = 0; i < input.length; i += 1) {
const ch = input[i];
if (escape) {
escape = false;
continue;
}
if (ch === '\\') {
escape = true;
continue;
}
if (quote) {
if (ch === quote) quote = '';
continue;
}
if (ch === '"' || ch === "'") {
quote = ch;
continue;
}
if (ch === ';' || ch === '&' || ch === '|' || ch === '<' || ch === '>') {
return ch;
}
}
return '';
}
function getRuntimeProcessExecutableBaseNameInput(value) {
const raw = String(value || '').trim();
if (!raw) return '';
let candidate = raw;
if (/\s/.test(candidate)) {
const nestedArgs = parseRuntimeProcessArgsInput(candidate);
if (nestedArgs.length) candidate = String(nestedArgs[0] || '').trim();
}
const normalized = candidate.toLowerCase().replace(/\\/g, '/');
const parts = normalized.split('/').filter(Boolean);
return parts.pop() || normalized;
}
function isRuntimeEnvAssignmentTokenInput(value) {
const token = String(value || '').trim();
if (!token || token.startsWith('-')) return false;
const eqIdx = token.indexOf('=');
if (eqIdx <= 0) return false;
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(token.slice(0, eqIdx));
}
function resolveRuntimeProcessExecutableArgsInput(args) {
const parts = Array.isArray(args) ? args : [];
if (!parts.length) return { execName: '', index: -1 };
let index = 0;
while (index < parts.length) {
const token = String(parts[index] || '').trim();
if (!token) {
index += 1;
continue;
}
const execName = getRuntimeProcessExecutableBaseNameInput(token);
if (RUNTIME_PROCESS_ENV_WRAPPERS.has(execName)) {
index += 1;
while (index < parts.length) {
const envToken = String(parts[index] || '').trim();
if (!envToken) {
index += 1;
continue;
}
if (envToken === '--') {
index += 1;
break;
}
if (envToken.startsWith('-') || isRuntimeEnvAssignmentTokenInput(envToken)) {
index += 1;
continue;
}
break;
}
continue;
}
return { execName, index };
}
return { execName: '', index: -1 };
}
function validateRuntimeContainerLauncherInput(args) {
const { execName } = resolveRuntimeProcessExecutableArgsInput(args);
if (RUNTIME_PROCESS_BLOCKED_CONTAINER_EXECUTABLES.has(execName)) {
return 'Container runtime CLI commands like "docker run" are not allowed here. Configure image, ports, volumes, env, and the in-container process separately.';
}
return null;
}
function isBlockedRuntimeShellExecutableInput(value) {
const execName = getRuntimeProcessExecutableBaseNameInput(value);
return RUNTIME_PROCESS_BLOCKED_EXECUTABLES.has(execName);
}
function isRuntimeShellWrapperArgsInput(args, execIndex) {
if (!Array.isArray(args) || execIndex < 0 || execIndex >= args.length) return false;
if (!isBlockedRuntimeShellExecutableInput(args[execIndex])) return false;
const flags = String(args[execIndex + 1] || '').trim().toLowerCase();
return flags.startsWith('-') && flags.includes('c');
}
// adpanel:surrogate-safe-cut — mirror of utils/safe-truncate.js, the
// canonical implementation: keep this in exact lockstep with it, including
// the trailing-lone-high drop (a cap cut that would split an astral
// character ends one character earlier instead of storing a lone half,
// which encodes as U+FFFD). The frontend bundle cannot require the Node
// helper, so the drop is inlined here with the same while-loop form; the
// parity pin (tests/runtime-process-command.test.js) evaluates both copies
// and asserts they cut identically at the astral boundary.
function isHighSurrogate(unit) {
return unit >= 0xd800 && unit <= 0xdbff;
}
function sanitizeRuntimeCommandInput(value) {
const text = String(value ?? '').replace(/\r\n?/g, '\n').trim();
let cut = text.length <= 4000 ? text : text.slice(0, 4000);
while (cut.length > 0 && isHighSurrogate(cut.charCodeAt(cut.length - 1))) {
cut = cut.slice(0, -1);
}
return cut;
}
function validateRuntimeProcessCommandInput(value) {
const command = sanitizeRuntimeCommandInput(value);
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.';
const { execName: resolvedExecName, index: execIndex } = resolveRuntimeProcessExecutableArgsInput(args);
const containerRuntimeError = validateRuntimeContainerLauncherInput(args);
if (containerRuntimeError) return containerRuntimeError;
if (isBlockedRuntimeShellExecutableInput(resolvedExecName || args[0]) && isRuntimeShellWrapperArgsInput(args, execIndex)) {
return 'Shell wrappers like sh -c or bash -lc are not allowed. Provide the executable and arguments directly.';
}
for (const arg of args) {
const token = String(arg || '').trim();
if (RUNTIME_PROCESS_BLOCKED_TOKENS.has(token)) {
return `Shell control operator "${token}" is not allowed in process commands.`;
}
}
const unquotedOperator = findUnquotedRuntimeShellOperatorInput(command);
if (unquotedOperator) {
return `Shell control operator "${unquotedOperator}" is not allowed in unquoted process command arguments. Quote the argument if it is meant literally.`;
}
return null;
}
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;
});
}
async function submitResourcesRename() {
if (!currentResourcesServer || !resServerNameInput) return;
const serverName = currentResourcesServer;
const viewVersion = resourcesViewVersion;
const requestedName = (resServerNameInput.value || '').trim();
if (!requestedName) {
showCategoryFeedback('server', 'Enter a server name', true);
resServerNameInput.focus();
return;
}
if (requestedName === originalServerDisplayName) {
showCategoryFeedback('server', 'Server name is already up to date.', false);
return;
}
if (!currentResourcesRenameToken) {
showCategoryFeedback('server', 'Rename token missing. Please refresh and try again.', true);
return;
}
const previousButtonHtml = resRenameServerBtn ? resRenameServerBtn.innerHTML : '';
try {
if (resServerNameInput) resServerNameInput.disabled = true;
if (resRenameServerBtn) {
resRenameServerBtn.disabled = true;
resRenameServerBtn.innerHTML = ' Renaming...';
}
showCategoryFeedback('server', 'Renaming server…', false);
const res = await fetch(`/api/settings/servers/${encodeURIComponent(serverName)}/rename`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': currentResourcesRenameToken
},
body: JSON.stringify({ newName: requestedName, expectedTargetId: currentResourcesTargetId })
});
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
if (!res.ok) {
throw new Error(data.error || 'Failed to rename server');
}
const nextDisplay = data?.displayName || requestedName;
_resourcesCache.delete(serverName.toLowerCase());
if (viewVersion !== resourcesViewVersion) return;
originalServerDisplayName = nextDisplay;
if (serverManageTitle) serverManageTitle.textContent = nextDisplay;
if (resServerNameInput) resServerNameInput.value = nextDisplay;
if (data?.renameActionToken) currentResourcesRenameToken = data.renameActionToken;
await loadServers(_serversPage, _serversSearch);
if (viewVersion === resourcesViewVersion) showCategoryFeedback('server', `Server renamed to ${nextDisplay}.`, false);
} catch (err) {
if (viewVersion !== resourcesViewVersion) return;
console.error('[resources-rename]', err);
showCategoryFeedback('server', err.message || 'Rename failed', true);
if (resServerNameInput) {
resServerNameInput.disabled = false;
resServerNameInput.focus();
resServerNameInput.select();
}
} finally {
if (viewVersion === resourcesViewVersion && resServerNameInput) {
resServerNameInput.disabled = false;
}
if (viewVersion === resourcesViewVersion && resRenameServerBtn) {
resRenameServerBtn.disabled = false;
resRenameServerBtn.innerHTML = previousButtonHtml || ' Save Server Name';
}
}
}
function getServerPortIp(port) {
const p = Number(port);
if (currentServerPortIps[p]) return currentServerPortIps[p];
const found = currentNodeAllocations.find(a => Number(a.port) === p);
if (found && found.ip) return String(found.ip).trim();
if (currentServerIp) return currentServerIp;
return currentNodeAddress || '0.0.0.0';
}
function updatePortsWarningState() {
if (currentServerMainPort == null) {
showCategoryFeedback('ports', 'A primary port is required to apply changes and restart the server.', true);
} else {
const fb = feedbackPorts;
if (fb && fb.classList.contains('error') && fb.textContent.includes('primary port is required')) {
fb.style.display = 'none';
fb.textContent = '';
}
}
}
function renderPortsList() {
if (!resPortsList) return;
resPortsList.innerHTML = '';
const hasPrimary = currentServerMainPort != null;
if (hasPrimary) {
const mainItem = document.createElement('div');
mainItem.className = 'port-item port-item-primary';
const mainIp = getServerPortIp(currentServerMainPort);
const ipPrefix = `${escapeHtml(mainIp)}: `;
mainItem.innerHTML = `${ipPrefix} Primary `;
resPortsList.appendChild(mainItem);
const input = mainItem.querySelector('.port-edit-input');
bindStrictPortInput(input);
input.addEventListener('change', () => {
const val = parseStrictPortValue(input.value);
if (!val) {
showCategoryFeedback('ports', 'Main port must be between 1 and 65535', true);
input.value = currentServerMainPort;
return;
}
if (currentNodePorts.length > 0 && !currentNodePorts.includes(val)) {
showCategoryFeedback('ports', `Port ${val} is not in this node's allocated ports`, true);
input.value = currentServerMainPort;
return;
}
if (currentServerPorts.includes(val)) {
showCategoryFeedback('ports', `Port ${val} is already used as an additional port`, true);
input.value = currentServerMainPort;
return;
}
clearAllCategoryFeedback();
currentServerMainPort = val;
const assignedIp = getServerPortIp(val);
if (assignedIp) currentServerIp = assignedIp;
renderPortsList();
renderPortDropdown();
updatePortsWarningState();
});
const removePrimaryBtn = mainItem.querySelector('.port-remove-primary');
if (removePrimaryBtn) {
removePrimaryBtn.addEventListener('click', (e) => {
e.stopPropagation();
currentServerMainPort = null;
renderPortsList();
renderPortDropdown();
updatePortsWarningState();
});
}
}
currentServerPorts.forEach((port, index) => {
const item = document.createElement('div');
item.className = 'port-item';
const portIp = getServerPortIp(port);
const ipPrefix = `${escapeHtml(portIp)}: `;
let makePrimaryBtnHtml = '';
if (!hasPrimary) {
makePrimaryBtnHtml = ` Set Primary `;
}
item.innerHTML = `${ipPrefix}${port} ${makePrimaryBtnHtml} `;
resPortsList.appendChild(item);
if (!hasPrimary) {
const setPrimaryBtn = item.querySelector('.port-set-primary-btn');
if (setPrimaryBtn) {
setPrimaryBtn.addEventListener('click', (e) => {
e.stopPropagation();
currentServerPorts.splice(index, 1);
currentServerMainPort = port;
const assignedIp = getServerPortIp(port);
if (assignedIp) currentServerIp = assignedIp;
clearAllCategoryFeedback();
renderPortsList();
renderPortDropdown();
updatePortsWarningState();
});
}
}
});
if (!hasPrimary && currentServerPorts.length === 0) {
const emptyNotice = document.createElement('div');
emptyNotice.className = 'port-list-empty-notice';
emptyNotice.style.cssText = 'font-size: 12.5px; color: rgba(255, 255, 255, 0.4); padding: 4px 0; font-family: Inter, sans-serif;';
emptyNotice.textContent = 'No ports configured. Select a port from the dropdown below.';
resPortsList.appendChild(emptyNotice);
}
updatePortsWarningState();
}
function renderPortDropdown() {
if (!resPortDropdownMenu) return;
const assignedKeys = new Set();
if (currentServerMainPort != null) {
const mainIp = getServerPortIp(currentServerMainPort);
assignedKeys.add(`${mainIp}:${Number(currentServerMainPort)}`);
}
currentServerPorts.forEach(p => {
const portIp = getServerPortIp(p);
assignedKeys.add(`${portIp}:${Number(p)}`);
});
let availableAllocations = [];
if (currentNodeAllocations.length > 0) {
const seen = new Set();
availableAllocations = currentNodeAllocations.filter(a => {
const p = Number(a.port);
const ip = String(a.ip || currentNodeAddress || currentServerIp || '0.0.0.0').trim();
const key = `${ip}:${p}`;
if (assignedKeys.has(key) || seen.has(key)) return false;
seen.add(key);
return true;
});
} else {
availableAllocations = currentNodePorts
.map(p => ({ ip: currentNodeAddress || currentServerIp || '0.0.0.0', port: Number(p) }))
.filter(a => !assignedKeys.has(`${a.ip}:${a.port}`));
}
if (resPortDropdownSelectedText) {
resPortDropdownSelectedText.textContent = availableAllocations.length > 0 ? 'Select port...' : 'No available ports';
}
if (resPortSelect) {
resPortSelect.innerHTML = 'Select port... ' +
availableAllocations.map(a => `${escapeHtml(a.ip)}:${a.port} `).join('');
resPortSelect.value = '';
}
if (availableAllocations.length === 0) {
resPortDropdownMenu.innerHTML = `
No available ports on node
`;
return;
}
let html = '';
availableAllocations.forEach((a, idx) => {
if (idx > 0) {
html += '
';
}
const label = `${escapeHtml(a.ip)}:${a.port}`;
html += `
${label}
`;
});
resPortDropdownMenu.innerHTML = html;
resPortDropdownMenu.querySelectorAll('.dashboard-assistant-dropdown-item[data-port]').forEach(item => {
item.addEventListener('click', (e) => {
e.stopPropagation();
const port = parseStrictPortValue(item.getAttribute('data-port'));
const ip = item.getAttribute('data-ip') || currentServerIp || currentNodeAddress || '0.0.0.0';
if (!port) return;
if (currentNodePorts.length > 0 && !currentNodePorts.includes(port)) {
showCategoryFeedback('ports', `Port ${port} is not in this node's allocated ports`, true);
return;
}
if (currentServerMainPort != null && port === currentServerMainPort && getServerPortIp(currentServerMainPort) === ip) {
showCategoryFeedback('ports', `Port ${ip}:${port} is already the primary server port`, true);
return;
}
if (currentServerPorts.includes(port) && currentServerPortIps[port] === ip) {
showCategoryFeedback('ports', `Port ${ip}:${port} is already in the list`, true);
return;
}
currentServerPortIps[port] = ip;
if (currentServerMainPort == null && currentServerPorts.length === 0) {
currentServerMainPort = port;
currentServerIp = ip;
} else {
if (!currentServerPorts.includes(port)) {
currentServerPorts.push(port);
}
}
clearAllCategoryFeedback();
renderPortsList();
renderPortDropdown();
updatePortsWarningState();
if (resPortDropdown) resPortDropdown.classList.remove('is-open');
if (resPortDropdownMenu) resPortDropdownMenu.hidden = true;
});
});
}
function removePort(index) {
if (index >= 0 && index < currentServerPorts.length) {
clearAllCategoryFeedback();
currentServerPorts.splice(index, 1);
renderPortsList();
renderPortDropdown();
updatePortsWarningState();
}
}
function syncPortsToStartupCommand() {
renderStartupCommandEditorState(resStartupCommand?.value || '');
}
function parseDockerArgs(argsStr) {
const args = [];
let current = '';
let inQuote = '';
for (let i = 0; i < argsStr.length; i++) {
const ch = argsStr[i];
if (inQuote) {
if (ch === inQuote) { inQuote = ''; continue; }
current += ch;
} else if (ch === '"' || ch === "'") {
inQuote = ch;
} else if (ch === ' ' || ch === '\t') {
if (current) { args.push(current); current = ''; }
} else {
current += ch;
}
}
if (current) args.push(current);
return args;
}
if (resPortDropdownTrigger) {
resPortDropdownTrigger.addEventListener('click', (e) => {
e.stopPropagation();
if (resJavaDropdown) {
resJavaDropdown.classList.remove('is-open');
if (resJavaDropdownMenu) resJavaDropdownMenu.hidden = true;
}
if (!resPortDropdown) return;
const isOpen = resPortDropdown.classList.contains('is-open');
if (isOpen) {
resPortDropdown.classList.remove('is-open');
if (resPortDropdownMenu) resPortDropdownMenu.hidden = true;
} else {
resPortDropdown.classList.add('is-open');
if (resPortDropdownMenu) resPortDropdownMenu.hidden = false;
}
});
}
if (resJavaDropdownTrigger) {
resJavaDropdownTrigger.addEventListener('click', (e) => {
e.stopPropagation();
if (resPortDropdown) {
resPortDropdown.classList.remove('is-open');
if (resPortDropdownMenu) resPortDropdownMenu.hidden = true;
}
if (!resJavaDropdown) return;
const isOpen = resJavaDropdown.classList.contains('is-open');
if (isOpen) {
resJavaDropdown.classList.remove('is-open');
if (resJavaDropdownMenu) resJavaDropdownMenu.hidden = true;
} else {
resJavaDropdown.classList.add('is-open');
if (resJavaDropdownMenu) resJavaDropdownMenu.hidden = false;
}
});
}
if (nm_port_ip_dropdown_trigger) {
nm_port_ip_dropdown_trigger.addEventListener('click', (e) => {
e.stopPropagation();
if (!nm_port_ip_dropdown) return;
const isOpen = nm_port_ip_dropdown.classList.contains('is-open');
if (isOpen) {
nm_port_ip_dropdown.classList.remove('is-open');
if (nm_port_ip_dropdown_menu) nm_port_ip_dropdown_menu.hidden = true;
} else {
nm_port_ip_dropdown.classList.add('is-open');
if (nm_port_ip_dropdown_menu) nm_port_ip_dropdown_menu.hidden = false;
}
});
}
if (cn_port_ip_dropdown_trigger) {
cn_port_ip_dropdown_trigger.addEventListener('click', (e) => {
e.stopPropagation();
if (!cn_port_ip_dropdown) return;
const isOpen = cn_port_ip_dropdown.classList.contains('is-open');
if (isOpen) {
cn_port_ip_dropdown.classList.remove('is-open');
if (cn_port_ip_dropdown_menu) cn_port_ip_dropdown_menu.hidden = true;
} else {
cn_port_ip_dropdown.classList.add('is-open');
if (cn_port_ip_dropdown_menu) cn_port_ip_dropdown_menu.hidden = false;
}
});
}
document.addEventListener('click', (e) => {
if (resPortDropdown && !resPortDropdown.contains(e.target)) {
resPortDropdown.classList.remove('is-open');
if (resPortDropdownMenu) resPortDropdownMenu.hidden = true;
}
if (resJavaDropdown && !resJavaDropdown.contains(e.target)) {
resJavaDropdown.classList.remove('is-open');
if (resJavaDropdownMenu) resJavaDropdownMenu.hidden = true;
}
if (nm_port_ip_dropdown && !nm_port_ip_dropdown.contains(e.target)) {
nm_port_ip_dropdown.classList.remove('is-open');
if (nm_port_ip_dropdown_menu) nm_port_ip_dropdown_menu.hidden = true;
}
if (cn_port_ip_dropdown && !cn_port_ip_dropdown.contains(e.target)) {
cn_port_ip_dropdown.classList.remove('is-open');
if (cn_port_ip_dropdown_menu) cn_port_ip_dropdown_menu.hidden = true;
}
});
if (resPortsList) {
resPortsList.addEventListener('click', (e) => {
const removeBtn = e.target.closest('.port-remove');
if (removeBtn) {
const index = parseInt(removeBtn.dataset.index, 10);
removePort(index);
}
});
}
function _applyResourcesFormData(data, serverName) {
if (!data && !serverName) return;
currentResourcesRenameToken = data?.renameActionToken || currentResourcesRenameToken || '';
const r = data?.resources || {};
const stats = data?.stats || {};
currentServerTemplate = data?.template || currentServerTemplate || '';
currentServerPortIps = {};
if (data?.resources?.portAllocations && typeof data.resources.portAllocations === 'object') {
if (Array.isArray(data.resources.portAllocations)) {
data.resources.portAllocations.forEach(a => {
if (a && a.port) currentServerPortIps[Number(a.port)] = String(a.ip || '').trim();
});
} else {
Object.entries(data.resources.portAllocations).forEach(([p, ip]) => {
currentServerPortIps[Number(p)] = String(ip || '').trim();
});
}
}
if (Array.isArray(data?.nodeAllocations)) {
currentNodeAllocations = data.nodeAllocations.filter(a => a && Number.isInteger(Number(a.port)));
} else {
currentNodeAllocations = [];
}
if (data?.nodeAddress) {
currentNodeAddress = String(data.nodeAddress).trim();
}
if (Array.isArray(data?.nodePorts) && data.nodePorts.length > 0) {
currentNodePorts = data.nodePorts.slice().map(Number).filter(p => Number.isInteger(p) && p >= 1 && p <= 65535);
} else if (currentNodeAllocations.length > 0) {
currentNodePorts = currentNodeAllocations.map(a => Number(a.port));
}
const incomingIp = String(data?.ip || data?.serverIp || '').trim();
if (incomingIp) {
currentServerIp = incomingIp;
} else if (!currentServerIp) {
const row = findServerItemByName(currentResourcesServer);
if (row?.ip || row?.serverIp) {
currentServerIp = String(row.ip || row.serverIp).trim();
} else if (data?.nodeAddress) {
currentServerIp = String(data.nodeAddress).trim();
}
}
if (serverManageTitle) serverManageTitle.textContent = currentResourcesServer;
if (serverManageSubtitle) serverManageSubtitle.textContent = 'Configure settings and resource limits';
if (resourcesModalTitle) resourcesModalTitle.textContent = `Resources: ${currentResourcesServer}`;
if (resourcesModalSubtitle) resourcesModalSubtitle.textContent = 'Set limits for this server.';
originalServerDisplayName = data?.displayName || currentResourcesServer;
if (resServerNameInput) resServerNameInput.value = originalServerDisplayName;
if (resRenameServerBtn) resRenameServerBtn.disabled = !currentResourcesRenameToken;
if (resRamMb) resRamMb.value = r.ramMb ?? '';
if (resCpuCores) resCpuCores.value = r.cpuCores ?? '';
if (resStorageMb) resStorageMb.value = r.storageMb ?? (r.storageGb != null ? Math.round(r.storageGb * 1024) : '');
if (resSwapMb) resSwapMb.value = r.swapMb != null ? String(r.swapMb) : '-1';
if (resBackupsMax) resBackupsMax.value = r.backupsMax ?? '';
if (resMaxSchedules) resMaxSchedules.value = r.maxSchedules ?? '';
if (resIoWeight) resIoWeight.value = r.ioWeight ?? '';
if (resCpuWeight) resCpuWeight.value = r.cpuWeight ?? '';
if (resPidsLimit) resPidsLimit.value = r.pidsLimit ?? '';
if (resFileLimit) resFileLimit.value = r.fileLimit ?? '';
if (resNetworkInboundLimitMb) resNetworkInboundLimitMb.value = r.networkInboundLimitMb ?? '';
if (resNetworkOutboundLimitMb) resNetworkOutboundLimitMb.value = r.networkOutboundLimitMb ?? '';
if (resNetworkResetMinutes) resNetworkResetMinutes.value = r.networkResetMinutes ?? '';
savedServerResourceValues = Object.fromEntries(Object.entries(serverResourceEditorInputs).map(([key, input]) => [
key, readServerResourceEditorValue(key, input)
]));
const hostPort = data?.hostPort != null ? Number(data.hostPort) : (data?.port != null ? Number(data.port) : null);
currentServerMainPort = hostPort != null && Number.isInteger(hostPort) ? hostPort : null;
originalServerMainPort = currentServerMainPort;
if (Array.isArray(r.ports)) currentServerPorts = r.ports.slice().map(Number).filter(p => Number.isInteger(p) && p >= 1 && p <= 65535);
else currentServerPorts = [];
originalServerPorts = currentServerPorts.slice();
const cmd = String(data?.effectiveCommand || data?.command || data?.imageDefaultCommand || '').trim();
originalStartupCommand = cmd;
originalStartupCommandSource = String(data?.commandSource || '').trim();
if (resStartupCommand) {
resStartupCommand.value = cmd;
const src = originalStartupCommandSource.toLowerCase();
resStartupCommand.readOnly = src === 'adpanel-startup' || src === 'image-default' || src === 'image-inspect';
}
if (stats?.memory) {
const used = stats.memory.usedMb || 0;
const limit = stats.memory.limitMb || r.ramMb || 0;
const pct = limit > 0 ? Math.min(100, (used / limit) * 100) : 0;
if (resUsageBar) {
resUsageBar.style.width = `${pct}%`;
resUsageBar.className = 'resource-usage-fill' + (pct > 80 ? ' warning' : '');
}
if (resUsageText) {
resUsageText.textContent = limit > 0 ? `${Math.round(used)} MB / ${Math.round(limit)} MB (${pct.toFixed(1)}%)` : 'No limit set';
}
} else {
if (resUsageBar) resUsageBar.style.width = '0%';
if (resUsageText) resUsageText.textContent = r.ramMb ? `0 MB / ${r.ramMb} MB (server stopped)` : 'No usage data';
}
renderStartupCommandEditorState(cmd);
renderMinecraftJavaSelector(data);
renderPortsList();
renderPortDropdown();
triggerAutoResizeInputs();
}
function _prefetchResources(serverName) {
if (!serverName) return;
if (_resourcesPrefetch && _resourcesPrefetch.key === serverName.toLowerCase()) return;
if (_getCachedResourcesData(serverName)) return;
const key = serverName.toLowerCase();
const promise = _fetchResourcesData(serverName)
.catch(() => null)
.finally(() => {
if (_resourcesPrefetch?.promise === promise) _resourcesPrefetch = null;
});
_resourcesPrefetch = { key, promise };
}
async function _fetchResourcesData(serverName) {
const res = await fetch(`/api/settings/servers/${encodeURIComponent(serverName)}/resources`, {
signal: AbortSignal.timeout(30_000)
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw { status: res.status, error: data?.error || `HTTP ${res.status}` };
}
const data = await res.json();
_cacheResourcesData(serverName, data);
return data;
}
async function openResourcesModal(serverName, initialCategory = 'server') {
const viewVersion = ++resourcesViewVersion;
const content = serverManageInlineView?.querySelector('.server-manage-content');
if (content) {
content.inert = true;
content.setAttribute('aria-busy', 'true');
}
currentResourcesServer = serverName;
currentResourcesTargetId = null;
currentResourcesRenameToken = '';
originalServerDisplayName = serverName;
if (resServerNameInput) resServerNameInput.value = serverName;
currentServerIp = '';
currentNodeAddress = '';
currentNodePorts = [];
currentServerPorts = [];
currentServerMainPort = null;
originalServerMainPort = null;
currentServerTemplate = '';
clearAllCategoryFeedback();
resetMinecraftJavaSelector();
// Prepopulate from client-side cached list immediately for instant UI response
const rowData = findServerItemByName(serverName);
if (rowData) {
_applyResourcesFormData({
name: rowData.name || serverName,
displayName: rowData.displayName || rowData.name || serverName,
template: rowData.template,
hostPort: rowData.port,
ip: rowData.ip || rowData.nodeAddress || '',
serverIp: rowData.ip || rowData.nodeAddress || '',
nodeAddress: rowData.nodeAddress || rowData.ip || '',
nodePorts: Array.isArray(rowData.nodePorts) ? rowData.nodePorts : [],
nodeAllocations: Array.isArray(rowData.nodeAllocations) ? rowData.nodeAllocations : [],
resources: rowData.resources || {},
command: rowData.command || '',
effectiveCommand: rowData.effectiveCommand || rowData.command || '',
javaVersion: rowData.javaVersion || '',
stats: rowData.stats || null
}, serverName);
}
const cached = _getCachedResourcesData(serverName);
if (cached) {
_applyResourcesFormData(cached, serverName);
}
renderPortsList();
renderPortDropdown();
if (serversOverviewView) serversOverviewView.style.display = 'none';
const serverCreateInlineView = document.getElementById('serverCreateInlineView');
if (serverCreateInlineView) serverCreateInlineView.style.display = 'none';
if (serverManageInlineView) serverManageInlineView.style.display = 'flex';
if (serverManageTitle) serverManageTitle.textContent = serverName;
if (serverManageSubtitle) serverManageSubtitle.textContent = 'Loading server settings...';
if (resourcesModalSubtitle) resourcesModalSubtitle.textContent = 'Set limits for this server.';
if (resServerNameInput) {
resServerNameInput.disabled = false;
}
if (resRenameServerBtn) {
resRenameServerBtn.disabled = !currentResourcesRenameToken;
resRenameServerBtn.innerHTML = ' Save Server Name';
}
if (resourcesSave) resourcesSave.disabled = false;
if (resNewPort) resNewPort.value = '';
if (resStartupSection) resStartupSection.style.display = '';
switchServerCategory(initialCategory || 'server');
try {
const prefetch = _resourcesPrefetch;
const data = await (prefetch?.key === serverName.toLowerCase() ? prefetch.promise : _fetchResourcesData(serverName));
if (viewVersion !== resourcesViewVersion) return;
if (!data) throw new Error('Failed to load server settings');
_applyResourcesFormData(data, serverName);
currentResourcesTargetId = data.targetId;
if (content) content.inert = false;
if (serverManageSubtitle) serverManageSubtitle.textContent = 'Configure settings and resource limits';
} catch (err) {
if (viewVersion !== resourcesViewVersion) return;
console.error('[resources] Failed to load:', err);
if (serverManageSubtitle) serverManageSubtitle.textContent = err?.error || 'Failed to load server settings. Go back and try again.';
} finally {
if (viewVersion === resourcesViewVersion && content) content.removeAttribute('aria-busy');
}
}
function readServerResourceEditorValue(key, input) {
if (input?.validity?.badInput) return NaN;
return input?.value ? Number(input.value) : (key.startsWith('network') ? 0 : null);
}
function hasServerManageUnsavedChanges() {
if (!currentResourcesServer || currentResourcesTargetId == null) return false;
if (resServerNameInput && resServerNameInput.value.trim() !== originalServerDisplayName) return true;
if (resStartupCommand && !resStartupCommand.readOnly && resStartupCommand.value.trim() !== originalStartupCommand) return true;
if (currentMinecraftJavaEnabled && resJavaVersion?.value !== originalMinecraftJavaVersion) return true;
if (Object.entries(serverResourceEditorInputs).some(([key, input]) =>
input && readServerResourceEditorValue(key, input) !== savedServerResourceValues[key]
)) return true;
if (currentServerMainPort !== originalServerMainPort) return true;
const curPortsSorted = currentServerPorts.slice().map(Number).sort((a, b) => a - b);
const origPortsSorted = (originalServerPorts || []).slice().map(Number).sort((a, b) => a - b);
if (curPortsSorted.length !== origPortsSorted.length) return true;
for (let i = 0; i < curPortsSorted.length; i++) {
if (curPortsSorted[i] !== origPortsSorted[i]) return true;
}
return false;
}
function closeResourcesModal(force = false) {
if (force !== true && hasServerManageUnsavedChanges()) {
const ok = window.confirm(`${UNSAVED_MODAL_MESSAGE}\n\nClose without saving?`);
if (!ok) return false;
}
resourcesViewVersion += 1;
const serverCreateInlineView = document.getElementById('serverCreateInlineView');
if (serverCreateInlineView) serverCreateInlineView.style.display = 'none';
if (serverManageInlineView) serverManageInlineView.style.display = 'none';
if (serversOverviewView) serversOverviewView.style.display = 'block';
if (resourcesModalOverlay) {
resourcesModalOverlay.setAttribute('aria-hidden', 'true');
resourcesModalOverlay.classList.remove('show');
}
currentResourcesServer = '';
currentResourcesTargetId = null;
currentResourcesRenameToken = '';
currentServerMainPort = null;
originalServerMainPort = null;
originalServerPorts = [];
originalStartupCommand = '';
originalStartupCommandSource = '';
if (resStartupCommand) resStartupCommand.readOnly = false;
resetMinecraftJavaSelector();
clearAllCategoryFeedback();
return true;
}
async function patchResourcesForEditor(serverName, viewVersion, body) {
if (body.resources) {
const resources = Object.fromEntries(Object.entries(body.resources).filter(([key, value]) => savedServerResourceValues[key] !== value));
if (!Object.keys(resources).length && Object.keys(body).length === 1) {
return { ok: true, data: { restarted: false } };
}
body = { ...body, resources };
}
try {
const res = await fetch(`/api/settings/servers/${encodeURIComponent(serverName)}/resources`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...body, expectedTargetId: currentResourcesTargetId })
});
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
if (viewVersion !== resourcesViewVersion) return null;
const ok = res.ok && data?.ok === true;
if (ok && body.resources) {
for (const key of Object.keys(savedServerResourceValues)) {
if (Object.hasOwn(body.resources, key)) savedServerResourceValues[key] = body.resources[key];
}
}
return { ok, data };
} finally {
_resourcesCache.delete(serverName.toLowerCase());
}
}
function readHardwareResourceEdits() {
const resources = {};
for (const [key, input, label] of [
['ramMb', resRamMb, 'RAM limit'], ['cpuCores', resCpuCores, 'CPU cores'], ['storageMb', resStorageMb, 'Storage limit']
]) {
const value = readOptionalResourceNumber(input, label);
if (value !== null) resources[key] = value;
}
if (resSwapMb?.value) resources.swapMb = Number(resSwapMb.value);
return resources;
}
async function saveResourcesCategory() {
if (!currentResourcesServer) return;
const serverName = currentResourcesServer;
const viewVersion = resourcesViewVersion;
let resources;
try {
resources = readHardwareResourceEdits();
} catch (err) {
showCategoryFeedback('resources', err.message, true);
return;
}
const btn = saveResourcesCategoryBtn || resourcesSave;
const prevHtml = btn ? btn.innerHTML : '';
if (btn) {
btn.disabled = true;
btn.innerHTML = ' Applying...';
}
try {
const result = await patchResourcesForEditor(serverName, viewVersion, { resources });
if (!result || viewVersion !== resourcesViewVersion) return;
if (!result.ok) {
showCategoryFeedback('resources', result.data?.error || 'Failed to update resources', true);
return;
}
showCategoryFeedback('resources', result.data.restarted === false ? 'Resources updated.' : 'Resources updated. Restart confirmed.', false);
} catch (err) {
if (viewVersion !== resourcesViewVersion) return;
console.error('[resources] Save error:', err);
showCategoryFeedback('resources', 'Network error while saving resources', true);
} finally {
if (btn) {
btn.disabled = false;
btn.innerHTML = prevHtml || ' Apply & Restart';
}
}
}
function readOperationalResourceEdits() {
const resources = {};
for (const [key, input, label, min, max] of [
['backupsMax', resBackupsMax, 'Max Backups', 0, Number.MAX_SAFE_INTEGER],
['maxSchedules', resMaxSchedules, 'Max Schedules', 0, Number.MAX_SAFE_INTEGER],
['ioWeight', resIoWeight, 'I/O Priority', 10, 1000],
['cpuWeight', resCpuWeight, 'CPU Priority', 1, 1000],
['pidsLimit', resPidsLimit, 'Process Limit', 64, 4096],
['fileLimit', resFileLimit, 'File Limit', 1024, 1048576]
]) {
const value = readOptionalIntegerRange(input, label, min, max);
if (value !== null) resources[key] = value;
}
return resources;
}
async function saveLimitsCategory() {
if (!currentResourcesServer) return;
const serverName = currentResourcesServer;
const viewVersion = resourcesViewVersion;
let resources;
try {
resources = readOperationalResourceEdits();
} catch (err) {
showCategoryFeedback('limits', err.message || 'Invalid limit value', true);
return;
}
const btn = saveLimitsCategoryBtn;
const prevHtml = btn ? btn.innerHTML : '';
if (btn) {
btn.disabled = true;
btn.innerHTML = ' Applying...';
}
try {
const result = await patchResourcesForEditor(serverName, viewVersion, { resources });
if (!result || viewVersion !== resourcesViewVersion) return;
if (!result.ok) {
showCategoryFeedback('limits', result.data?.error || 'Failed to update limits', true);
return;
}
showCategoryFeedback('limits', result.data.restarted === false ? 'Limits updated.' : 'Limits updated. Restart confirmed.', false);
} catch (err) {
if (viewVersion !== resourcesViewVersion) return;
console.error('[limits] Save error:', err);
showCategoryFeedback('limits', 'Network error while saving limits', true);
} finally {
if (btn) {
btn.disabled = false;
btn.innerHTML = prevHtml || ' Apply & Restart';
}
}
}
async function saveBandwidthCategory() {
if (!currentResourcesServer) return;
const serverName = currentResourcesServer;
const viewVersion = resourcesViewVersion;
const resources = {};
try {
const networkInboundLimitMb = readOptionalIntegerRange(resNetworkInboundLimitMb, 'Inbound Limit', 1, RESOURCE_NETWORK_LIMIT_MAX_MB);
const networkOutboundLimitMb = readOptionalIntegerRange(resNetworkOutboundLimitMb, 'Outbound Limit', 1, RESOURCE_NETWORK_LIMIT_MAX_MB);
const networkResetMinutesValue = readOptionalIntegerRange(resNetworkResetMinutes, 'Reset Time', 1, RESOURCE_NETWORK_RESET_MAX_MINUTES);
if (networkInboundLimitMb != null) resources.networkInboundLimitMb = networkInboundLimitMb;
else if (resNetworkInboundLimitMb) resources.networkInboundLimitMb = 0;
if (networkOutboundLimitMb != null) resources.networkOutboundLimitMb = networkOutboundLimitMb;
else if (resNetworkOutboundLimitMb) resources.networkOutboundLimitMb = 0;
if (networkResetMinutesValue != null) resources.networkResetMinutes = networkResetMinutesValue;
else if (resNetworkResetMinutes) resources.networkResetMinutes = 0;
} catch (err) {
showCategoryFeedback('bandwidth', err.message || 'Invalid bandwidth value', true);
return;
}
const btn = saveBandwidthCategoryBtn;
const prevHtml = btn ? btn.innerHTML : '';
if (btn) {
btn.disabled = true;
btn.innerHTML = ' Saving...';
}
try {
const result = await patchResourcesForEditor(serverName, viewVersion, { resources });
if (!result || viewVersion !== resourcesViewVersion) return;
if (!result.ok) {
showCategoryFeedback('bandwidth', result.data?.error || 'Failed to update bandwidth limits', true);
return;
}
showCategoryFeedback('bandwidth', 'Bandwidth limits updated successfully!', false);
} catch (err) {
if (viewVersion !== resourcesViewVersion) return;
console.error('[bandwidth] Save error:', err);
showCategoryFeedback('bandwidth', 'Network error while saving bandwidth limits', true);
} finally {
if (btn) {
btn.disabled = false;
btn.innerHTML = prevHtml || ' Save Bandwidth';
}
}
}
async function savePortsCategory() {
if (!currentResourcesServer) return;
const serverName = currentResourcesServer;
const viewVersion = resourcesViewVersion;
if (currentServerMainPort == null) {
showCategoryFeedback('ports', 'A primary port is required to apply changes and restart the server.', true);
return;
}
const primaryIp = getServerPortIp(currentServerMainPort);
if (primaryIp) {
currentServerIp = primaryIp;
}
const portAllocations = [];
if (currentServerMainPort != null) {
portAllocations.push({ port: currentServerMainPort, ip: getServerPortIp(currentServerMainPort) });
}
currentServerPorts.forEach(p => {
portAllocations.push({ port: p, ip: getServerPortIp(p) });
});
const resources = {
ports: currentServerPorts.slice(),
portAllocations
};
const requestBody = { resources };
if (currentServerMainPort != null) {
requestBody.mainPort = currentServerMainPort;
}
if (currentServerIp) {
requestBody.ip = currentServerIp;
}
const btn = savePortsCategoryBtn;
const prevHtml = btn ? btn.innerHTML : '';
if (btn) {
btn.disabled = true;
btn.innerHTML = ' Applying...';
}
try {
const result = await patchResourcesForEditor(serverName, viewVersion, requestBody);
if (!result || viewVersion !== resourcesViewVersion) return;
if (!result.ok) {
showCategoryFeedback('ports', result.data?.error || 'Failed to update ports', true);
return;
}
originalServerPorts = resources.ports;
originalServerMainPort = requestBody.mainPort;
showCategoryFeedback('ports', 'Ports updated. Restart confirmed.', false);
} catch (err) {
if (viewVersion !== resourcesViewVersion) return;
console.error('[ports] Save error:', err);
showCategoryFeedback('ports', 'Network error while saving ports', true);
} finally {
if (btn) {
btn.disabled = false;
btn.innerHTML = prevHtml || ' Apply & Restart';
}
}
}
async function saveStartupCategory() {
if (!currentResourcesServer) return;
const serverName = currentResourcesServer;
const viewVersion = resourcesViewVersion;
const requestBody = {};
const startupCommand = String(resStartupCommand?.value || '').trim();
const startupCommandError = renderStartupCommandEditorState(startupCommand);
if (startupCommandError) {
showCategoryFeedback('startup', startupCommandError, true);
resStartupCommand?.focus();
return;
}
const startupSource = String(originalStartupCommandSource || '').trim().toLowerCase();
if (!['adpanel-startup', 'image-default', 'image-inspect'].includes(startupSource) && startupCommand !== originalStartupCommand) {
requestBody.command = startupCommand;
}
if (currentMinecraftJavaEnabled) {
const selectedJavaVersion = normalizeMinecraftJavaVersionClient(resJavaVersion?.value);
if (!selectedJavaVersion) {
showCategoryFeedback('startup', 'Unsupported Minecraft Java version.', true);
resJavaVersion?.focus();
return;
}
if (selectedJavaVersion !== originalMinecraftJavaVersion) {
requestBody.javaVersion = selectedJavaVersion;
}
}
const btn = saveStartupCategoryBtn;
const prevHtml = btn ? btn.innerHTML : '';
if (btn) {
btn.disabled = true;
btn.innerHTML = ' Applying...';
}
try {
const result = await patchResourcesForEditor(serverName, viewVersion, requestBody);
if (!result || viewVersion !== resourcesViewVersion) return;
if (!result.ok) {
showCategoryFeedback('startup', result.data?.error || 'Failed to update startup command', true);
return;
}
originalStartupCommand = startupCommand;
if (requestBody.javaVersion) originalMinecraftJavaVersion = requestBody.javaVersion;
showCategoryFeedback('startup', result.data.restarted === false ? 'Startup settings unchanged.' : 'Startup settings updated. Restart confirmed.', false);
} catch (err) {
if (viewVersion !== resourcesViewVersion) return;
console.error('[startup] Save error:', err);
showCategoryFeedback('startup', 'Network error while saving startup command', true);
} finally {
if (btn) {
btn.disabled = false;
btn.innerHTML = prevHtml || ' Apply & Restart';
}
}
}
async function saveResources() {
if (!currentResourcesServer) return;
const serverName = currentResourcesServer;
const viewVersion = resourcesViewVersion;
let resources;
try {
resources = { ...readHardwareResourceEdits(), ...readOperationalResourceEdits() };
const networkInboundLimitMb = readOptionalIntegerRange(resNetworkInboundLimitMb, 'Inbound Limit', 1, RESOURCE_NETWORK_LIMIT_MAX_MB);
const networkOutboundLimitMb = readOptionalIntegerRange(resNetworkOutboundLimitMb, 'Outbound Limit', 1, RESOURCE_NETWORK_LIMIT_MAX_MB);
const networkResetMinutesValue = readOptionalIntegerRange(resNetworkResetMinutes, 'Reset Time', 1, RESOURCE_NETWORK_RESET_MAX_MINUTES);
if (networkInboundLimitMb != null) resources.networkInboundLimitMb = networkInboundLimitMb;
else if (resNetworkInboundLimitMb) resources.networkInboundLimitMb = 0;
if (networkOutboundLimitMb != null) resources.networkOutboundLimitMb = networkOutboundLimitMb;
else if (resNetworkOutboundLimitMb) resources.networkOutboundLimitMb = 0;
if (networkResetMinutesValue != null) resources.networkResetMinutes = networkResetMinutesValue;
else if (resNetworkResetMinutes) resources.networkResetMinutes = 0;
} catch (err) {
showResourcesFeedback(err.message || 'Invalid resource value', true);
return;
}
resources.ports = currentServerPorts.slice();
const requestBody = { resources };
const startupCommand = String(resStartupCommand?.value || '').trim();
const startupCommandError = renderStartupCommandEditorState(startupCommand);
if (startupCommandError) {
showResourcesFeedback(startupCommandError, true);
resStartupCommand?.focus();
return;
}
const startupSource = String(originalStartupCommandSource || '').trim().toLowerCase();
if (!['adpanel-startup', 'image-default', 'image-inspect'].includes(startupSource) && startupCommand !== originalStartupCommand) {
requestBody.command = startupCommand;
}
if (currentMinecraftJavaEnabled) {
const selectedJavaVersion = normalizeMinecraftJavaVersionClient(resJavaVersion?.value);
if (!selectedJavaVersion) {
showResourcesFeedback('Unsupported Minecraft Java version.', true);
resJavaVersion?.focus();
return;
}
if (selectedJavaVersion !== originalMinecraftJavaVersion) {
requestBody.javaVersion = selectedJavaVersion;
}
}
if (currentServerMainPort != null && currentServerMainPort !== originalServerMainPort) {
requestBody.mainPort = currentServerMainPort;
}
if (resourcesSave) {
resourcesSave.disabled = true;
resourcesSave.innerHTML = ' Applying...';
}
try {
const result = await patchResourcesForEditor(serverName, viewVersion, requestBody);
if (!result || viewVersion !== resourcesViewVersion) return;
if (!result.ok) {
showResourcesFeedback(result.data?.error || 'Failed to update resources', true);
return;
}
showResourcesFeedback(result.data.restarted === false ? 'Resources updated.' : 'Resources updated. Restart confirmed.', false);
} catch (err) {
if (viewVersion !== resourcesViewVersion) return;
console.error('[resources] Save error:', err);
showResourcesFeedback('Network error while saving resources', true);
} finally {
if (resourcesSave) {
resourcesSave.disabled = false;
resourcesSave.innerHTML = ' Apply & Restart';
}
}
}
if (serverManageBackBtn) serverManageBackBtn.addEventListener('click', closeResourcesModal);
if (resourcesModalClose) resourcesModalClose.addEventListener('click', closeResourcesModal);
if (resourcesCancel) resourcesCancel.addEventListener('click', closeResourcesModal);
if (resourcesSave) resourcesSave.addEventListener('click', saveResources);
if (saveResourcesCategoryBtn) saveResourcesCategoryBtn.addEventListener('click', saveResourcesCategory);
if (saveLimitsCategoryBtn) saveLimitsCategoryBtn.addEventListener('click', saveLimitsCategory);
if (saveBandwidthCategoryBtn) saveBandwidthCategoryBtn.addEventListener('click', saveBandwidthCategory);
if (savePortsCategoryBtn) savePortsCategoryBtn.addEventListener('click', savePortsCategory);
if (saveStartupCategoryBtn) saveStartupCategoryBtn.addEventListener('click', saveStartupCategory);
if (resRenameServerBtn) resRenameServerBtn.addEventListener('click', submitResourcesRename);
if (resJavaVersion) {
resJavaVersion.addEventListener('change', () => {
// Removed dynamic hint update
});
}
if (resServerNameInput) {
resServerNameInput.addEventListener('keydown', async (e) => {
if (e.key === 'Enter') {
e.preventDefault();
await submitResourcesRename();
}
});
}
if (resCopyStartupCmd) {
resCopyStartupCmd.addEventListener('click', () => {
const cmd = resStartupCommand?.value?.trim() || resStartupPreview?.textContent?.trim() || '';
if (cmd && cmd !== 'No startup command configured' && cmd !== 'Loading...') {
copyToClipboard(cmd).then(() => {
const icon = resCopyStartupCmd.querySelector('i');
if (icon) {
icon.className = 'fa-solid fa-check';
setTimeout(() => { icon.className = 'fa-solid fa-copy'; }, 1500);
}
}).catch(() => { });
}
});
}
if (resStartupCommand) {
resStartupCommand.addEventListener('input', () => {
if (['adpanel-startup', 'image-default', 'image-inspect'].includes(String(originalStartupCommandSource || '').trim().toLowerCase())) return;
renderStartupCommandEditorState(resStartupCommand.value);
});
}
async function loadAccounts() {
// Section only renders for admins; every other caller no-ops instead of
// firing a request the server will 403.
if (!accountsListEl) return;
accountsListEl.innerHTML = `Loading accounts…
`;
try {
const res = await fetch('/api/settings/accounts');
if (!res.ok) {
const err = await res.json().catch(() => ({ error: 'failed' }));
accountsListEl.innerHTML = `Failed to load accounts
`;
console.warn(err);
return;
}
const data = await res.json();
accountsListEl._accounts = data.accounts || [];
window.ADPanelAccountTargets.update(accountsListEl._accounts);
accountsListEl._bots = data.bots || [];
accountsListEl._actionTokens = data.actionTokens || {};
try {
window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
} catch (_) { }
accountsListEl.dataset.agentEnabled = String(data.agentEnabled === true);
renderAccounts(accountsListEl._accounts, accountsListEl._bots);
} catch (e) {
console.error(e);
accountsListEl.innerHTML = `Network error
`;
}
}
function renderAccounts(accounts, bots, searchQuery = '') {
if (!accountsListEl) return;
accountsListEl.innerHTML = '';
accountsListEl._deleteTokensByEmail = new Map();
accountsListEl._suspensionTokensByEmail = new Map();
accountsListEl._accountFlagsByEmail = new Map();
let filtered = Array.isArray(accounts) ? [...accounts] : [];
if (searchQuery && searchQuery.trim()) {
const q = searchQuery.trim().toLowerCase();
filtered = filtered.filter(acc =>
acc.email && acc.email.toLowerCase().includes(q)
);
}
filtered.sort((a, b) => {
const aAdmin = !!a?.admin;
const bAdmin = !!b?.admin;
if (aAdmin !== bAdmin) return aAdmin ? -1 : 1;
return String(a?.email || '').localeCompare(String(b?.email || ''));
});
if (!Array.isArray(filtered) || filtered.length === 0) {
if (searchQuery && searchQuery.trim()) {
accountsListEl.innerHTML = ` No accounts matching "${escapeHtml(searchQuery)}"
`;
} else {
accountsListEl.innerHTML = ` No accounts found
`;
}
return;
}
filtered.forEach(acc => {
const div = document.createElement('div');
const isSuspendedAccount = !!acc.suspended;
div.className = `account-row${isSuspendedAccount ? ' account-row-suspended' : ''}`;
const isAdminAccount = !!acc.admin;
const twoFactorActionLabel = acc.has2FA ? 'Reset 2FA' : 'Setup 2FA';
const email = String(acc.email || '').trim();
const deleteToken = String(acc.deleteToken || '').trim();
const suspensionToken = String(acc.suspensionToken || '').trim();
if (email && deleteToken) {
accountsListEl._deleteTokensByEmail.set(email, deleteToken);
accountsListEl._deleteTokensByEmail.set(email.toLowerCase(), deleteToken);
}
if (email && suspensionToken) {
accountsListEl._suspensionTokensByEmail.set(email, suspensionToken);
accountsListEl._suspensionTokensByEmail.set(email.toLowerCase(), suspensionToken);
}
if (email) {
const flags = { admin: !!acc.admin, has2FA: !!acc.has2FA };
accountsListEl._accountFlagsByEmail.set(email, flags);
accountsListEl._accountFlagsByEmail.set(email.toLowerCase(), flags);
}
const accessLabel = isAdminAccount
? 'admin account'
: (isSuspendedAccount ? 'suspended' : ((Array.isArray(acc.servers) && acc.servers.length > 0) ? `${acc.servers.length} access` : 'no access'));
const statusBadges = [
isAdminAccount ? 'admin ' : 'user ',
isSuspendedAccount ? 'suspended ' : ''
].filter(Boolean).join('');
const agentAccessToggle = accountsListEl.dataset.agentEnabled !== 'true' ? '' : `
Agent
`;
const accessControls = isAdminAccount ? '' : `
${agentAccessToggle}
`;
const suspensionButton = isAdminAccount ? '' : `
`;
div.innerHTML = `
${escapeHtml(email)} ${statusBadges}
${escapeHtml(accessLabel)}
${accessControls}
${suspensionButton}
`;
// Action tokens stay in the JS Maps above (same handling model as the
// webhook tokens) — never in DOM attributes, which any script or extension
// with DOM access can read.
accountsListEl.appendChild(div);
});
}
function getAccountDeleteToken(email) {
const normalizedEmail = String(email || '').trim();
if (!normalizedEmail) return '';
const tokens = accountsListEl?._deleteTokensByEmail;
if (tokens && typeof tokens.get === 'function') {
return String(tokens.get(normalizedEmail) || tokens.get(normalizedEmail.toLowerCase()) || '').trim();
}
return '';
}
// Per-account delete/suspension tokens are single-use: when a step-up
// challenge burns the presented token, the server re-mints a fresh one in the
// failure response and the flow stores it here so the retry from the still
// open modal cannot die on "invalid or missing action token".
function storeAccountDeleteToken(email, token) {
const normalizedEmail = String(email || '').trim();
const clean = String(token || '').trim();
if (!normalizedEmail || !clean) return;
const tokens = accountsListEl?._deleteTokensByEmail;
if (tokens && typeof tokens.set === 'function') {
tokens.set(normalizedEmail, clean);
tokens.set(normalizedEmail.toLowerCase(), clean);
}
}
function storeAccountSuspensionToken(email, token) {
const normalizedEmail = String(email || '').trim();
const clean = String(token || '').trim();
if (!normalizedEmail || !clean) return;
const tokens = accountsListEl?._suspensionTokensByEmail;
if (tokens && typeof tokens.set === 'function') {
tokens.set(normalizedEmail, clean);
tokens.set(normalizedEmail.toLowerCase(), clean);
}
}
async function refreshAccountDeleteToken(email) {
const normalizedEmail = String(email || '').trim();
if (!normalizedEmail) return '';
await loadAccounts();
return getAccountDeleteToken(normalizedEmail);
}
function getAccountSuspensionToken(email) {
const normalizedEmail = String(email || '').trim();
if (!normalizedEmail) return '';
const tokens = accountsListEl?._suspensionTokensByEmail;
if (tokens && typeof tokens.get === 'function') {
return String(tokens.get(normalizedEmail) || tokens.get(normalizedEmail.toLowerCase()) || '').trim();
}
return '';
}
async function refreshAccountSuspensionToken(email) {
const normalizedEmail = String(email || '').trim();
if (!normalizedEmail) return '';
await loadAccounts();
return getAccountSuspensionToken(normalizedEmail);
}
// accountsListEl._accountFlagsByEmail (admin / has2FA per listed account) is
// still maintained by the accounts renderer below; the peer-admin target
// proof lookups that consumed it were removed — account actions now step up
// with the acting admin's own password/TOTP only.
if (accountsSearchInput) {
accountsSearchInput.addEventListener('input', (e) => {
const query = e.target.value;
const accounts = accountsListEl._accounts || [];
const bots = accountsListEl._bots || [];
renderAccounts(accounts, bots, query);
});
}
// Both handlers live in the admin-only accounts section; skip registration
// entirely when that section is not rendered.
if (accountsListEl) {
accountsListEl.addEventListener('click', async (e) => {
const manageBtn = e.target.closest('.manage-access');
if (manageBtn) {
const enc = manageBtn.dataset.email;
if (!enc) return;
const email = decodeURIComponent(enc);
openManageAccessModal(email);
return;
}
const changePassBtn = e.target.closest('.change-password-btn');
if (changePassBtn) {
const enc = changePassBtn.dataset.email;
if (!enc) return;
const email = decodeURIComponent(enc);
openAdminChangePasswordModal(email);
return;
}
const suspensionBtn = e.target.closest('.account-suspension-btn');
if (suspensionBtn) {
const enc = suspensionBtn.dataset.email;
if (!enc) return;
const email = decodeURIComponent(enc);
const currentlySuspended = suspensionBtn.dataset.suspended === '1';
if (typeof window.openAccountSuspensionVerificationModal === 'function') {
window.openAccountSuspensionVerificationModal(email, !currentlySuspended, suspensionBtn);
} else {
alert('Security confirmation is still loading. Please try again.');
}
return;
}
const deleteBtn = e.target.closest('.delete-user-btn');
if (deleteBtn) {
const enc = deleteBtn.dataset.email;
if (!enc) return;
const email = decodeURIComponent(enc);
if (typeof window.openAccountDeleteVerificationModal === 'function') {
window.openAccountDeleteVerificationModal(email, deleteBtn);
} else {
alert('Security confirmation is still loading. Please try again.');
}
return;
}
});
accountsListEl.addEventListener('change', async (e) => {
const toggle = e.target.closest('.agent-access-toggle');
if (!toggle) return;
const enc = toggle.dataset.email;
if (!enc) return;
const email = decodeURIComponent(enc);
const enabled = toggle.checked;
// Agent access is step-up protected server-side: the verification flow
// owns the toggle state (reverts it on challenge/failure, sets it on
// success) and shows the shared security modal when a credential is
// required.
if (typeof window.setAgentAccessWithVerification === 'function') {
window.setAgentAccessWithVerification(email, enabled, '', toggle);
return;
}
toggle.checked = !enabled;
alert('Security confirmation is still loading. Please try again.');
});
}
async function openManageAccessModal(email) {
accountModal._accountTarget = window.ADPanelAccountTargets.select(email);
accountModalTitle.textContent = `Manage access for ${email}`;
accountModalBody.innerHTML = ``;
accountModalOverlay.classList.add('show');
accountModal.classList.add('show');
try {
const res = await fetch('/api/settings/accounts');
if (!res.ok) {
const err = await res.json().catch(() => ({ error: 'failed' }));
accountModalBody.innerHTML = ``;
console.warn(err);
return;
}
const data = await res.json();
const accounts = data.accounts || [];
const bots = data.bots || [];
const rec = accounts.find(a => String(a.email).toLowerCase() === String(email).toLowerCase());
if (Number(rec?.id) !== accountModal._accountTarget.id) throw new Error('Account state changed. Reload accounts and select it again.');
const userServers = rec ? (Array.isArray(rec.servers) ? rec.servers : []) : [];
if (!Array.isArray(bots) || bots.length === 0) {
accountModalBody.innerHTML = ``;
return;
}
const list = document.createElement('div');
list.className = 'access-list';
bots.forEach(b => {
const row = document.createElement('div');
row.className = 'access-server-row';
const left = document.createElement('div');
left.className = 'access-server-left';
left.innerHTML = `
${escapeHtml(b)}
`;
let hasAccess = userServers.includes(b) || userServers.includes('all');
const actions = document.createElement('div');
actions.className = 'access-server-actions';
if (hasAccess) {
const editBtn = document.createElement('button');
editBtn.className = 'access-btn access-btn-edit';
editBtn.title = `Edit permissions for ${email} on ${b}`;
editBtn.innerHTML = ` Edit`;
editBtn.addEventListener('click', () => {
const existing = getSavedPerms(email, b);
openPermsModal(email, b, () => openManageAccessModal(email), existing);
});
const revokeBtn = document.createElement('button');
revokeBtn.className = 'access-btn access-btn-revoke';
revokeBtn.title = `Revoke access for ${email} on ${b}`;
revokeBtn.textContent = 'Revoke';
revokeBtn.addEventListener('click', () => {
// Revocation is step-up protected server-side like the permission
// grant: route through the shared security verification modal, which
// refreshes this dialog with the updated rows on success.
if (typeof window.openRevokeAccessVerificationModal === 'function') {
window.openRevokeAccessVerificationModal(email, b, revokeBtn);
return;
}
alert('Security confirmation is still loading. Please try again.');
});
actions.appendChild(editBtn);
actions.appendChild(revokeBtn);
} else {
const addBtn = document.createElement('button');
addBtn.className = 'access-btn access-btn-add';
addBtn.innerHTML = ' Grant';
addBtn.addEventListener('click', () => {
const remembered = getSavedPerms(email, b);
openPermsModal(email, b, () => openManageAccessModal(email), remembered);
});
actions.appendChild(addBtn);
}
row.appendChild(left);
row.appendChild(actions);
list.appendChild(row);
});
accountModalBody.innerHTML = '';
accountModalBody.appendChild(list);
} catch (e) {
console.error(e);
accountModalBody.innerHTML = ``;
}
}
accountModalClose.addEventListener('click', () => {
accountModalOverlay.classList.remove('show');
accountModal.classList.remove('show');
});
// Click outside disabled — user must use close/cancel button
// accountModalOverlay.addEventListener('click', (e) => {
// if (e.target === accountModalOverlay) {
// accountModalOverlay.classList.remove('show');
// accountModal.classList.remove('show');
// }
// });
async function openPermsModal(email, server, onSaved, existingPerms) {
const accountTarget = accountModal._accountTarget || window.ADPanelAccountTargets.select(email);
let serverPerms = null;
try {
const resp = await fetch(`/api/settings/accounts/${encodeURIComponent(email)}/perms?server=${encodeURIComponent(server)}`);
if (resp.ok) {
const data = await resp.json();
if (data.ok && data.permissions) {
serverPerms = data.permissions;
}
}
} catch (e) {
console.error('Failed to fetch permissions from server:', e);
}
const permsToUse = serverPerms || existingPerms;
const isEdit = !!permsToUse && Object.keys(permsToUse).some(k => permsToUse[k]);
permModalTitle.textContent = isEdit
? `Edit permissions for ${email} on ${server}`
: `Grant permissions for ${email} on ${server}`;
permModalBody.innerHTML = buildPermsFormHtml(permsToUse, !!serverPerms);
permModalOverlay.classList.add('show');
permModal.classList.add('show');
permModal.dataset.email = email;
permModal.dataset.server = server;
permModal.dataset.mode = isEdit ? 'edit' : 'add';
permModal._onSaved = typeof onSaved === 'function' ? onSaved : null;
permModal._existingPerms = permsToUse || null;
permModal._accountTarget = accountTarget;
const selAll = document.getElementById('perm_all');
const permInputs = Array.from(permModalBody.querySelectorAll('input[type="checkbox"].perm'));
selAll.checked = permInputs.length > 0 && permInputs.every(cb => cb.checked);
selAll.addEventListener('change', () => {
permInputs.forEach(cb => { cb.checked = selAll.checked; });
});
permInputs.forEach(cb => {
cb.addEventListener('change', () => {
selAll.checked = permInputs.length > 0 && permInputs.every(x => x.checked);
});
});
}
function closePermsModal() {
permModalOverlay.classList.remove('show');
permModal.classList.remove('show');
permModal.dataset.email = '';
permModal.dataset.server = '';
permModal.dataset.mode = '';
permModal._onSaved = null;
permModal._existingPerms = null;
}
function buildPermsFormHtml(existing, fromServer) {
const currentSummary = existing ? summarizePerms(existing) : null;
const permLabels = {
files_read: { label: 'Read files', icon: 'fa-file' },
files_write: { label: 'Edit existing files', icon: 'fa-file-pen' },
files_delete: { label: 'Delete files', icon: 'fa-trash' },
files_rename: { label: 'Rename files', icon: 'fa-pen' },
files_archive: { label: 'Create archives', icon: 'fa-file-zipper' },
console_read: { label: 'Read console', icon: 'fa-terminal' },
console_write: { label: 'Console commands (shell access)', icon: 'fa-terminal', danger: true, note: 'Runs arbitrary shell commands inside the server container — full in-container code execution (files, secrets, network).' },
server_stop: { label: 'Stop server', icon: 'fa-stop' },
server_start: { label: 'Start server', icon: 'fa-play' },
files_upload: { label: 'Upload files', icon: 'fa-upload' },
files_create: { label: 'Create files/folders', icon: 'fa-folder-plus' },
activity_logs: { label: 'View activity logs', icon: 'fa-clock-rotate-left' },
backups_view: { label: 'View backups', icon: 'fa-box-archive' },
backups_create: { label: 'Create and restore backups', icon: 'fa-box-archive', danger: true, note: 'Restoring can stop the server and replace its current files.' },
backups_delete: { label: 'Delete backups', icon: 'fa-trash-can' },
scheduler_access: { label: 'Access scheduler', icon: 'fa-calendar-days' },
scheduler_create: { label: 'Create schedules', icon: 'fa-calendar-plus' },
scheduler_delete: { label: 'Delete schedules', icon: 'fa-calendar-xmark' },
store_access: { label: 'Access store', icon: 'fa-store' },
server_reinstall: { label: 'Reinstall server', icon: 'fa-rotate' },
planner_access: { label: 'Planner access', icon: 'fa-list-check' }
};
const rows = PERM_KEYS.map((key) => {
const checked = existing ? !!existing[key] : (key === 'files_read');
const perm = permLabels[key] || { label: key, icon: 'fa-circle' };
return `
${perm.label}
${perm.note ? `${perm.note} ` : ''}
`;
}).join('');
const info = fromServer
? `
Current permissions: ${escapeHtml(currentSummary || 'None assigned')}
`
: existing
? `
Cached: ${escapeHtml(currentSummary)}. Toggle as needed.
`
: `
Select the permissions you want to grant to this user.
`;
return `
${info}
Select all permissions
${rows}
`;
}
permCancel.addEventListener('click', closePermsModal);
if (permCancelBtn) permCancelBtn.addEventListener('click', closePermsModal);
// Click outside disabled — user must use close/cancel button
// permModalOverlay.addEventListener('click', (e) => { if (e.target === permModalOverlay) closePermsModal(); });
permSave.addEventListener('click', async () => {
const email = permModal.dataset.email || '';
const server = permModal.dataset.server || '';
if (!email || !server) { closePermsModal(); return; }
const permInputs = Array.from(permModalBody.querySelectorAll('input[type="checkbox"].perm'));
const selected = {};
PERM_KEYS.forEach(k => selected[k] = false);
permInputs.forEach(cb => {
const key = cb.dataset.key;
selected[key] = !!cb.checked;
});
const finalPerms = selected;
const existing = permModal._existingPerms || getSavedPerms(email, server);
if (finalPerms.console_write && !(existing && existing.console_write)) {
const warned = window.confirm('Granting "Console commands (shell access)" lets this user run arbitrary shell commands inside the server container (full in-container code execution: files, secrets, network). Continue?');
if (!warned) return;
}
// Permission grants are step-up protected server-side (console_write /
// files_write equal code execution on the server): route the save through
// the shared security verification modal, which prompts for the acting
// admin's password/2FA when no verified grace window is active.
if (typeof window.openPermsGrantVerificationModal === 'function') {
window.openPermsGrantVerificationModal(email, server, finalPerms, {
accountTarget: permModal._accountTarget,
onSaved: () => { if (typeof permModal._onSaved === 'function') permModal._onSaved(); },
});
return;
}
alert('Security confirmation is still loading. Please try again.');
});
document.addEventListener('DOMContentLoaded', () => {
const WAIT_INTERVAL = 100;
const WAIT_TIMEOUT = 3000;
const sidebarSelector = '#sidebarNav';
const pathnameDefaults = [
{ match: /^\/servers(?:\/|$)/i, panel: 'servers' },
{ match: /^\/settings(?:\/|$)/i, panel: 'customization' }
];
function getExplicitRequestedPanel() {
const params = new URLSearchParams(location.search);
const p = params.get('panel');
if (p) return p;
if (location.hash && location.hash.length > 1) return location.hash.slice(1);
return null;
}
function getRequestedPanel() {
const explicitPanel = getExplicitRequestedPanel();
if (isValidSettingsPanel(explicitPanel)) return explicitPanel;
const savedPanel = getSavedSettingsPanel();
if (savedPanel) return savedPanel;
const path = location.pathname || '/';
for (const r of pathnameDefaults) {
if (r.match.test(path)) return r.panel;
}
return null;
}
function tryOpenPanel(panel) {
if (!panel) return false;
const safePanel = escapeSettingsPanelSelectorValue(panel);
const btn = document.querySelector(`${sidebarSelector} button[data-panel="${safePanel}"]`);
if (btn) {
activateSettingsPanel(panel, { force: true, instant: true });
console.log(`[openPanel] opened panel: ${panel}`);
return true;
}
return false;
}
async function waitForSidebarAndOpen() {
const panel = getRequestedPanel();
if (!panel) { console.log('[openPanel] no panel requested'); return; }
const activeSec = document.getElementById(panel);
const activeBtn = document.querySelector(`${sidebarSelector} button[data-panel="${escapeSettingsPanelSelectorValue(panel)}"]`);
if (activeSec && activeSec.classList.contains('active') && activeBtn && activeBtn.classList.contains('active')) {
activateSettingsPanel(panel, { force: true, instant: true });
return;
}
const start = Date.now();
if (document.querySelector(sidebarSelector)) { if (tryOpenPanel(panel)) return; }
while (Date.now() - start < WAIT_TIMEOUT) {
const side = document.querySelector(sidebarSelector);
if (side) { if (tryOpenPanel(panel)) return; }
await new Promise(r => setTimeout(r, WAIT_INTERVAL));
}
console.warn(`[openPanel] failed to open panel "${panel}"`);
const directPanelEl = document.getElementById(panel);
if (directPanelEl) {
activateSettingsPanel(panel, { force: true, instant: true });
console.log(`[openPanel] opened panel by id: ${panel}`);
}
}
async function maybeOpenAssistantRequestedAction() {
const action = getRequestedAssistantSettingsAction();
if (!action) return;
await new Promise(resolve => setTimeout(resolve, 180));
const handled = tryOpenRequestedAssistantSettingsAction(action);
if (!handled) {
console.warn(`[assistantSettings] failed to open action "${action}"`);
return;
}
clearRequestedAssistantSettingsAction();
}
(async () => {
// DOMContentLoaded handlers registered after this one still wire panel
// loaders (the webhooks UI block assigns window._loadWebhooks). Yield to
// a macrotask so all wiring completes before the initial panel opens,
// otherwise landing directly on that panel (saved panel / ?panel= /
// #hash) skips its data load and leaves the action tokens unminted.
await new Promise(resolve => setTimeout(resolve, 0));
await waitForSidebarAndOpen();
await maybeOpenAssistantRequestedAction();
})();
});
async function fetchWithTimeout(url, opts = {}, ms = 2500) {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), ms);
try {
const res = await fetch(url, { ...opts, signal: ctrl.signal });
clearTimeout(t);
return res;
} catch (e) {
clearTimeout(t);
throw e;
}
}
function setNodeStatus(row, cls, label) {
const dot = row.querySelector('.status-dot');
if (!dot) return;
dot.classList.remove('green', 'red', 'gray');
dot.classList.add(cls);
if (label) dot.title = label;
}
// --- Create Node Wizard State & Functions ---
let createNodeCurrentStep = 1;
let createNodeMaxStepReached = 1;
let createNodeCreatedId = null;
let createNodeCreatedNode = null;
let createNodeDraftSave = null;
let createNodeAllocatedPorts = [];
let createNodeDisks = [];
let createNodeHealthPollingInterval = null;
let createNodeHealthRun = null;
let createNodeVerifiedStreak = 0;
function showNodeCreateView(show) {
if (show) {
showNodeManageView(false);
if (nodesMainView) nodesMainView.style.display = 'none';
if (nodeCreateInlineView) nodeCreateInlineView.style.display = 'flex';
resetCreateNodeWizard();
} else {
createNodeDraftSave = null;
stopCreateNodeHealthCheck();
lockNodeSecret('cn', 'config');
lockNodeSecret('cn', 'command');
if (nodeCreateInlineView) nodeCreateInlineView.style.display = 'none';
if (nodesMainView) nodesMainView.style.display = 'block';
}
}
function showCreateNodeModal(show) {
showNodeCreateView(show);
}
function resetCreateNodeWizard() {
createNodeCurrentStep = 1;
createNodeMaxStepReached = 1;
createNodeCreatedId = null;
createNodeCreatedNode = null;
createNodeDraftSave = null;
createNodeDisks = [];
createNodeAllocatedPorts = [];
stopCreateNodeHealthCheck();
lockNodeSecret('cn', 'config');
lockNodeSecret('cn', 'command');
if (cn_name) cn_name.value = '';
if (cn_address) cn_address.value = '';
if (cn_additional_ips_container) cn_additional_ips_container.innerHTML = '';
if (cn_port_ip_select) cn_port_ip_select.innerHTML = 'Select IP... ';
if (cn_port_ip_selected_text) cn_port_ip_selected_text.textContent = 'Select IP...';
if (cn_port_ip_dropdown_menu) cn_port_ip_dropdown_menu.innerHTML = '';
if (cn_daemon_port) cn_daemon_port.value = '';
if (cn_max_upload_mb) cn_max_upload_mb.value = '';
if (cn_cpu_cores) cn_cpu_cores.value = '';
if (cn_ram_gb) cn_ram_gb.value = '';
if (cn_disk_gb) cn_disk_gb.value = '';
if (cn_ssl_enabled) cn_ssl_enabled.checked = false;
if (cn_under_cloudflare) cn_under_cloudflare.checked = false;
if (cn_disk_mount) cn_disk_mount.value = '';
if (cn_disk_limit) cn_disk_limit.value = '';
if (cn_port_start) cn_port_start.value = '';
if (cn_port_count) cn_port_count.value = '';
if (cn_port_list) cn_port_list.value = '';
['feedback_create_config', 'feedback_create_resources', 'feedback_create_ports', 'feedback_create_disks', 'feedback_create_linking', 'feedback_create_summary'].forEach(id => {
const el = document.getElementById(id);
if (el) { el.textContent = ''; el.style.display = 'none'; }
});
const completeBtn = document.getElementById('nodeCreateCompleteBtn');
if (completeBtn) completeBtn.disabled = true;
updateCreateNodeConnectionMode({ preferPanelHttps: true });
goToCreateNodeStep(1);
}
function goToCreateNodeStep(targetStep) {
if (createNodeDraftSave?.pending) return;
let step = Math.max(1, Math.min(6, parseInt(targetStep, 10) || 1));
if (step === 6 && !createNodeDraftSave?.saved) step = 5;
for (let previous = createNodeCurrentStep; previous < step; previous++) {
if (!validateCreateNodeStep(previous)) {
if (previous !== createNodeCurrentStep) goToCreateNodeStep(previous);
return;
}
}
if (step < 5) createNodeDraftSave = null;
createNodeCurrentStep = step;
if (step > createNodeMaxStepReached) {
createNodeMaxStepReached = step;
}
if (nodeCreateCategoriesNav) {
nodeCreateCategoriesNav.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 > createNodeMaxStepReached);
});
}
const paneIds = [
'pane_create_config',
'pane_create_resources',
'pane_create_ports',
'pane_create_disks',
'pane_create_linking',
'pane_create_summary'
];
paneIds.forEach((pId, idx) => {
const paneEl = document.getElementById(pId);
if (paneEl) {
paneEl.classList.toggle('active', idx + 1 === step);
}
});
if (nodeCreatePrevBtn) {
nodeCreatePrevBtn.style.display = step > 1 ? 'inline-flex' : 'none';
}
if (nodeCreateNextBtn) {
nodeCreateNextBtn.style.display = step < 6 ? 'inline-flex' : 'none';
nodeCreateNextBtn.disabled = false;
}
if (nodeCreateCompleteBtn) {
nodeCreateCompleteBtn.style.display = step === 6 ? 'inline-flex' : 'none';
}
if (step !== 6) stopCreateNodeHealthCheck();
if (step === 3) {
populateCreateNodePortsIpDropdown();
renderCreateNodePortsList();
} else if (step === 4) {
renderCreateNodeDisksList();
} else if (step === 5) {
renderCreateNodeLinking();
} else if (step === 6) {
renderCreateNodeSummary();
startCreateNodeHealthCheck();
}
autoFitPanelInputs();
triggerAutoResizeInputs();
}
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';
}
function validateCreateNodeStep(step) {
if (step === 1) {
const name = (cn_name?.value || '').trim();
const address = (cn_address?.value || '').trim();
if (!name) {
showCreateStepFeedback('feedback_create_config', 'Node Name is required.');
return false;
}
if (!address) {
showCreateStepFeedback('feedback_create_config', 'Address (IP or FQDN) is required.');
return false;
}
const daemonPort = parseInt(cn_daemon_port?.value || '8080', 10);
if (!Number.isFinite(daemonPort) || daemonPort < 1 || daemonPort > 65535) {
showCreateStepFeedback('feedback_create_config', 'Daemon port must be between 1 and 65535.');
return false;
}
const uploadLimit = parseInt(cn_max_upload_mb?.value || '10240', 10);
if (!Number.isFinite(uploadLimit) || uploadLimit < 1 || uploadLimit > 100000) {
showCreateStepFeedback('feedback_create_config', 'Max upload size must be between 1 and 100000 MB.');
return false;
}
const ssl_enabled = !!(cn_ssl_enabled && cn_ssl_enabled.checked && canUseHttpsForNodeAddress(address));
const under_cloudflare = !!(ssl_enabled && cn_under_cloudflare && cn_under_cloudflare.checked);
if (under_cloudflare && !isCloudflareHttpsPort(daemonPort)) {
showCreateStepFeedback('feedback_create_config', 'Under Cloudflare requires daemon port 443, 2053, 2083, 2087, 2096, or 8443.');
return false;
}
showCreateStepFeedback('feedback_create_config', '', false);
return true;
}
if (step === 2) {
const cpu = parseInt(cn_cpu_cores?.value || '', 10);
const ram = parseInt(cn_ram_gb?.value || '', 10);
const disk = parseInt(cn_disk_gb?.value || '', 10);
if (!Number.isFinite(cpu) || cpu < 1) {
showCreateStepFeedback('feedback_create_resources', 'Total CPU Cores is required (must be at least 1).');
return false;
}
if (!Number.isFinite(ram) || ram < 1) {
showCreateStepFeedback('feedback_create_resources', 'Total Memory (RAM) is required (must be at least 1 GB).');
return false;
}
if (ram > 2097151) {
showCreateStepFeedback('feedback_create_resources', 'Total Memory (RAM) must not exceed 2097151 GB.');
return false;
}
if (!Number.isFinite(disk) || disk < 10) {
showCreateStepFeedback('feedback_create_resources', 'Primary Disk Size is required (must be at least 10 GB).');
return false;
}
if (disk > 2147483647) {
showCreateStepFeedback('feedback_create_resources', 'Primary Disk Size must not exceed 2147483647 GB.');
return false;
}
showCreateStepFeedback('feedback_create_resources', '', false);
return true;
}
if (step === 3) {
if (createNodeAllocatedPorts.length === 0) {
showCreateStepFeedback('feedback_create_ports', 'Please add at least one port allocation to the pool using the form above.');
return false;
}
const addresses = new Set(getCreateNodePortAddresses());
const stale = createNodeAllocatedPorts.find(allocation => !addresses.has(allocation.ip));
if (stale) {
showCreateStepFeedback('feedback_create_ports', `Port ${stale.port} uses ${stale.ip}, which is no longer an eligible address. Remove it and allocate it again.`);
return false;
}
showCreateStepFeedback('feedback_create_ports', '', false);
return true;
}
if (step === 4) {
showCreateStepFeedback('feedback_create_disks', '', false);
return true;
}
if (step === 5) {
showCreateStepFeedback('feedback_create_linking', '', false);
return true;
}
return true;
}
function renderCreateNodePortsList() {
const container = document.getElementById('cn_allocated_ports_container');
const subtitle = document.getElementById('cn_allocated_ports_subtitle');
if (!container) return;
if (subtitle) {
subtitle.textContent = `${createNodeAllocatedPorts.length} ports staged in pool`;
}
if (createNodeAllocatedPorts.length === 0) {
container.innerHTML = `No ports staged. Use the form above to add ports.
`;
return;
}
container.innerHTML = createNodeAllocatedPorts.map((item, idx) => {
const label = `${item.ip || '0.0.0.0'}:${item.port}`;
return `
${escapeHtml(label)}
`;
}).join('');
container.querySelectorAll('.node-port-remove-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const idx = parseInt(btn.getAttribute('data-idx'), 10);
if (!Number.isNaN(idx)) {
createNodeAllocatedPorts.splice(idx, 1);
renderCreateNodePortsList();
}
});
});
}
function renderCreateNodeDisksList() {
const listEl = document.getElementById('cn_disks_list');
const countEl = document.getElementById('cn_disks_count');
if (!listEl) return;
const totalDisks = 1 + createNodeDisks.length;
if (countEl) countEl.textContent = `${totalDisks} volume${totalDisks === 1 ? '' : 's'} configured`;
let html = `
/var/lib/node PRIMARY
Primary data storage partition (${cn_disk_gb?.value || 100} GB)
`;
createNodeDisks.forEach((d, idx) => {
html += `
${escapeHtml(d.mount)}
Mounted disk (${d.limit} GB)
Remove
`;
});
listEl.innerHTML = html;
listEl.querySelectorAll('.cn-disk-remove-btn').forEach(btn => {
btn.addEventListener('click', () => {
const idx = parseInt(btn.getAttribute('data-idx'), 10);
if (!Number.isNaN(idx)) {
createNodeDisks.splice(idx, 1);
renderCreateNodeDisksList();
}
});
});
}
async function registerCreateNodeDraft() {
const name = (cn_name?.value || '').trim();
const address = (cn_address?.value || '').trim();
const additional_ips = getAdditionalIpsFromContainer(cn_additional_ips_container, 'cn');
const cpu_cores = parseInt(cn_cpu_cores?.value || '1', 10);
const ram_gb = parseInt(cn_ram_gb?.value || '1', 10);
const disk_gb = parseInt(cn_disk_gb?.value || '10', 10);
if (!Number.isFinite(cpu_cores) || cpu_cores < 1) throw new Error('CPU cores must be a whole number of at least 1');
if (!Number.isFinite(ram_gb) || ram_gb < 1) throw new Error('RAM must be a whole number of at least 1 GB');
if (!Number.isFinite(disk_gb) || disk_gb < 10) throw new Error('Disk size must be a whole number of at least 10 GB');
const max_upload_mb = parseInt(cn_max_upload_mb?.value || '10240', 10);
const api_port = parseInt(cn_daemon_port?.value || '8080', 10);
const ssl_enabled = !!(cn_ssl_enabled && cn_ssl_enabled.checked && canUseHttpsForNodeAddress(address));
const under_cloudflare = !!(ssl_enabled && cn_under_cloudflare && cn_under_cloudflare.checked);
const payload = {
name,
address,
additional_ips,
cpu_cores,
ram_mb: ram_gb * 1024,
disk_gb,
ports: {
mode: 'list',
ports: createNodeAllocatedPorts.map(a => a.port),
allocations: createNodeAllocatedPorts
},
max_upload_mb,
api_port,
ssl_enabled,
under_cloudflare,
disks: createNodeDisks
};
if (!createNodeCreatedId) {
const { res, data } = await sendNodeWriteWithStepUp('/api/nodes', 'POST', payload, {
subtitle: 'Verify your identity to register this node',
reason: 'Registering a node provisions a daemon access token. Step-up verification confirms this action was requested by you.',
cancelledMessage: 'Verification cancelled — the node was not registered.'
});
if (!res.ok) {
throw new Error(data.error || 'Failed to register node');
}
return data;
} else {
const { res, data } = await sendNodeWriteWithStepUp(`/api/nodes/${encodeURIComponent(createNodeCreatedId)}`, 'PATCH', {
...payload,
ports_revision: createNodeCreatedNode?.ports_revision,
}, {
subtitle: 'Verify your identity to update this node',
reason: 'Updating this node can change where the panel connects to it. Step-up verification confirms this action was requested by you.',
cancelledMessage: 'Verification cancelled — the node was not updated.'
});
if (!res.ok) {
throw new Error(data.error || 'Failed to update node');
}
return data;
}
}
async function renderCreateNodeLinking() {
// Both surfaces stay locked: the config and the setup command only cross
// the wire after identity verification (Receive / Generate Command).
lockNodeSecret('cn', 'config');
lockNodeSecret('cn', 'command');
if (createNodeDraftSave?.saved) return;
const save = { pending: true, saved: false };
createNodeDraftSave = save;
if (nodeCreateNextBtn) nodeCreateNextBtn.disabled = true;
try {
// Register/refresh the node draft so the health beacon can poll, but the
// config/command stay locked until the admin verifies their identity.
const node = await registerCreateNodeDraft();
if (createNodeDraftSave !== save) return;
createNodeCreatedId = node.id || node.uuid;
createNodeCreatedNode = node;
save.saved = true;
showCreateStepFeedback('feedback_create_linking', '', false);
} catch (err) {
if (createNodeDraftSave === save) showCreateStepFeedback('feedback_create_linking', err.message, true);
} finally {
if (createNodeDraftSave === save) {
save.pending = false;
if (nodeCreateNextBtn) nodeCreateNextBtn.disabled = false;
}
}
}
function renderCreateNodeSummary() {
const sName = document.getElementById('cn_sum_name');
const sAddr = document.getElementById('cn_sum_address');
const sPort = document.getElementById('cn_sum_port');
const sCpu = document.getElementById('cn_sum_cpu');
const sRam = document.getElementById('cn_sum_ram');
const sDisk = document.getElementById('cn_sum_disk');
const sPorts = document.getElementById('cn_sum_ports');
if (sName) sName.textContent = cn_name?.value?.trim() || '-';
if (sAddr) {
const addrs = [cn_address?.value?.trim(), ...getAdditionalIpsFromContainer(cn_additional_ips_container, 'cn')].filter(Boolean);
sAddr.textContent = addrs.length > 0 ? addrs.join(', ') : '-';
}
if (sPort) sPort.textContent = cn_daemon_port?.value?.trim() || '8080';
if (sCpu) sCpu.textContent = `${cn_cpu_cores?.value?.trim() || '-'} cores`;
if (sRam) sRam.textContent = `${cn_ram_gb?.value?.trim() || '-'} GB`;
if (sDisk) sDisk.textContent = `${cn_disk_gb?.value?.trim() || '-'} GB`;
if (sPorts) sPorts.textContent = `${createNodeAllocatedPorts.length} ports allocated`;
}
function startCreateNodeHealthCheck() {
stopCreateNodeHealthCheck();
createNodeHealthRun = { controller: new AbortController(), inFlight: false };
checkCreateNodeHealth();
createNodeHealthPollingInterval = setInterval(checkCreateNodeHealth, 5000);
}
function stopCreateNodeHealthCheck() {
createNodeHealthRun?.controller.abort();
createNodeHealthRun = null;
if (createNodeHealthPollingInterval) {
clearInterval(createNodeHealthPollingInterval);
createNodeHealthPollingInterval = null;
}
createNodeVerifiedStreak = 0;
if (nodeCreateCompleteBtn) nodeCreateCompleteBtn.disabled = true;
}
async function checkCreateNodeHealth() {
const run = createNodeHealthRun;
const nodeId = createNodeCreatedId;
if (!run || run.inFlight || !nodeId) return;
run.inFlight = true;
const beaconDot = document.getElementById('cn_beacon_dot');
const beaconStatus = document.getElementById('cn_beacon_status');
const beaconHint = document.getElementById('cn_beacon_hint');
const completeBtn = document.getElementById('nodeCreateCompleteBtn');
try {
const res = await fetch(`/api/admin/nodes/${encodeURIComponent(nodeId)}/stats`, { cache: 'no-store', signal: run.controller.signal });
const data = await res.json().catch(() => ({}));
if (createNodeHealthRun !== run || createNodeCreatedId !== nodeId) return;
const online = !!(res.ok && data.online);
const verified = data.verified === true;
if (online && verified) {
createNodeVerifiedStreak++;
if (createNodeVerifiedStreak >= 2) {
if (beaconDot) {
beaconDot.className = 'node-status-beacon online';
}
if (beaconStatus) {
beaconStatus.textContent = 'Node is Online & Identity Verified';
beaconStatus.style.color = '#86efac';
}
if (beaconHint) {
beaconHint.textContent = 'The node daemon connected and cryptographically proved its identity. Click Complete to finish.';
}
if (completeBtn) {
completeBtn.disabled = false;
}
} else {
if (beaconDot) {
beaconDot.className = 'node-status-beacon online';
}
if (beaconStatus) {
beaconStatus.textContent = 'Node online — verifying identity (1/2)…';
beaconStatus.style.color = '#86efac';
}
if (beaconHint) {
beaconHint.textContent = 'Waiting for a second consecutive verified sample before enabling Complete.';
}
if (completeBtn) {
completeBtn.disabled = true;
}
}
} else if (online && !verified) {
createNodeVerifiedStreak = 0;
if (beaconDot) {
beaconDot.className = 'node-status-beacon online';
}
if (beaconStatus) {
beaconStatus.textContent = 'Node responded — identity NOT verified';
beaconStatus.style.color = '#fbbf24';
}
if (beaconHint) {
beaconHint.textContent = 'Something answered at the node address but could not prove it holds this node\'s credentials (outdated daemon or untrusted responder). Update/redeploy the node daemon and wait.';
}
if (completeBtn) {
completeBtn.disabled = true;
}
} else {
createNodeVerifiedStreak = 0;
if (beaconDot) {
beaconDot.className = 'node-status-beacon offline';
}
if (beaconStatus) {
beaconStatus.textContent = 'Waiting for node connection...';
beaconStatus.style.color = '#ffffff';
}
if (beaconHint) {
beaconHint.textContent = 'Paste the configuration file or execute the setup command on your node machine.';
}
if (completeBtn) {
completeBtn.disabled = true;
}
}
} catch (err) {
if (createNodeHealthRun !== run || createNodeCreatedId !== nodeId) return;
createNodeVerifiedStreak = 0;
if (beaconDot) beaconDot.className = 'node-status-beacon offline';
if (completeBtn) completeBtn.disabled = true;
} finally {
run.inFlight = false;
}
}
if (openCreateNodeBtn) {
openCreateNodeBtn.addEventListener('click', () => showNodeCreateView(true));
}
if (nodeCreateBackBtn) {
nodeCreateBackBtn.addEventListener('click', () => showNodeCreateView(false));
}
if (createNodeClose) {
createNodeClose.addEventListener('click', () => showNodeCreateView(false));
}
if (createNodeCancel) {
createNodeCancel.addEventListener('click', () => showNodeCreateView(false));
}
if (nodeCreatePrevBtn) {
nodeCreatePrevBtn.addEventListener('click', () => {
if (createNodeCurrentStep > 1) {
goToCreateNodeStep(createNodeCurrentStep - 1);
}
});
}
if (nodeCreateNextBtn) {
nodeCreateNextBtn.addEventListener('click', () => {
goToCreateNodeStep(createNodeCurrentStep + 1);
});
}
if (nodeCreateCompleteBtn) {
nodeCreateCompleteBtn.addEventListener('click', async () => {
stopCreateNodeHealthCheck();
showNodeCreateView(false);
await loadNodes(1, '');
});
}
if (nodeCreateCategoriesNav) {
nodeCreateCategoriesNav.querySelectorAll('.server-category-btn').forEach(btn => {
btn.addEventListener('click', () => {
const step = parseInt(btn.getAttribute('data-step') || '1', 10);
if (step <= createNodeMaxStepReached) {
goToCreateNodeStep(step);
}
});
});
}
document.querySelectorAll('input[name="cn_ports_mode"]').forEach(r => {
r.addEventListener('change', () => {
const mode = document.querySelector('input[name="cn_ports_mode"]:checked')?.value || 'range';
const rangeStartRow = document.getElementById('cn_ports_range_start_row');
const rangeCountDivider = document.getElementById('cn_ports_range_count_divider');
const rangeCountRow = document.getElementById('cn_ports_range_count_row');
const listRow = document.getElementById('cn_ports_list_row');
if (rangeStartRow) rangeStartRow.style.display = (mode === 'range') ? 'flex' : 'none';
if (rangeCountDivider) rangeCountDivider.style.display = (mode === 'range') ? 'block' : 'none';
if (rangeCountRow) rangeCountRow.style.display = (mode === 'range') ? 'flex' : 'none';
if (listRow) listRow.style.display = (mode === 'list') ? 'flex' : 'none';
});
});
const cnPortsAddBtn = document.getElementById('cn_ports_add_btn');
if (cnPortsAddBtn) {
cnPortsAddBtn.addEventListener('click', () => {
try {
const mode = document.querySelector('input[name="cn_ports_mode"]:checked')?.value || 'range';
const parsed = parsePortsInput(mode, cn_port_start, cn_port_count, cn_port_list);
const selectedIp = cn_port_ip_select?.value;
if (!selectedIp) throw new Error('Add and select a node IP address before allocating ports.');
const existingKeySet = new Set(createNodeAllocatedPorts.map(a => `${a.ip || selectedIp}:${a.port}`));
if (parsed.mode === 'range') {
for (let i = 0; i < parsed.count; i++) {
const p = parsed.start + i;
const key = `${selectedIp}:${p}`;
if (!existingKeySet.has(key)) {
createNodeAllocatedPorts.push({ ip: selectedIp, port: p });
existingKeySet.add(key);
}
}
} else if (Array.isArray(parsed.ports)) {
parsed.ports.forEach(p => {
const key = `${selectedIp}:${p}`;
if (!existingKeySet.has(key)) {
createNodeAllocatedPorts.push({ ip: selectedIp, port: p });
existingKeySet.add(key);
}
});
}
createNodeAllocatedPorts.sort((a, b) => a.port - b.port);
renderCreateNodePortsList();
showCreateStepFeedback('feedback_create_ports', '', false);
} catch (err) {
showCreateStepFeedback('feedback_create_ports', err.message);
}
});
}
const cnPortsClearAllBtn = document.getElementById('cn_ports_clear_all');
if (cnPortsClearAllBtn) {
cnPortsClearAllBtn.addEventListener('click', () => {
createNodeAllocatedPorts = [];
renderCreateNodePortsList();
});
}
const cnDiskAddBtn = document.getElementById('cn_disk_add');
if (cnDiskAddBtn) {
cnDiskAddBtn.addEventListener('click', () => {
const mount = (cn_disk_mount?.value || '').trim();
const limit = parseInt(cn_disk_limit?.value || '0', 10);
if (!mount || !mount.startsWith('/')) {
showCreateStepFeedback('feedback_create_disks', 'Mount path must start with / (e.g. /mnt/disk1)');
return;
}
if (!Number.isFinite(limit) || limit < 1) {
showCreateStepFeedback('feedback_create_disks', 'Disk limit must be at least 1 GB');
return;
}
createNodeDisks.push({ mount, limit });
if (cn_disk_mount) cn_disk_mount.value = '';
if (cn_disk_limit) cn_disk_limit.value = '';
renderCreateNodeDisksList();
showCreateStepFeedback('feedback_create_disks', '', false);
});
}
const cnCopyConfigBtn = document.getElementById('cn_copyConfig');
if (cnCopyConfigBtn) {
cnCopyConfigBtn.addEventListener('click', async () => {
const box = document.getElementById('cn_configYml');
if (!isNodeSecretRevealed('cn', 'config')) return;
const text = box?.value || '';
if (!text) return;
try {
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(text);
} else {
await legacyCopyToClipboard(text);
}
const orig = cnCopyConfigBtn.innerHTML;
cnCopyConfigBtn.innerHTML = ' Copied!';
setTimeout(() => { cnCopyConfigBtn.innerHTML = orig; }, 1800);
} catch (err) {
alert('Failed to copy configuration');
}
});
}
const cnDownloadConfigBtn = document.getElementById('cn_downloadConfig');
if (cnDownloadConfigBtn) {
cnDownloadConfigBtn.addEventListener('click', () => {
if (!isNodeSecretRevealed('cn', 'config')) return;
const box = document.getElementById('cn_configYml');
const text = box?.value || '';
if (!text) return;
const blob = new Blob([text], { type: 'text/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'config.yml';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
}
const cnShowCmdBtn = document.getElementById('cn_showCmd');
if (cnShowCmdBtn) {
cnShowCmdBtn.addEventListener('click', async () => {
if (!createNodeCreatedId && !cn_name?.value?.trim()) return;
openNodeSecretModal('cn', 'command');
});
}
const cnCopyCmdBtn = document.getElementById('cn_copyCmd');
if (cnCopyCmdBtn) {
cnCopyCmdBtn.addEventListener('click', async () => {
const cmdInput = document.getElementById('cn_cmd');
const text = cmdInput?.value || '';
if (!text) return;
try {
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(text);
} else {
await legacyCopyToClipboard(text);
}
const orig = cnCopyCmdBtn.innerHTML;
cnCopyCmdBtn.innerHTML = ' Copied!';
setTimeout(() => { cnCopyCmdBtn.innerHTML = orig; }, 1800);
} catch (err) {
alert('Failed to copy command');
}
});
}
function parsePortsInput(mode, startEl, countEl, listEl) {
const wholeNumber = (value) => /^\d+$/.test(value) ? Number(value) : NaN;
if (mode === 'range') {
const start = wholeNumber(String(startEl?.value || '').trim());
const count = wholeNumber(String(countEl?.value || '').trim());
if (!Number.isFinite(start) || start < 1024 || start > 65535) {
if (Number.isFinite(start) && start < 1024) throw new Error('Ports below 1024 cannot be allocated.');
throw new Error('Invalid start port (must be 1024-65535)');
}
if (!Number.isFinite(count) || count < 1 || count > 1000) throw new Error('Invalid count');
if (start + count - 1 > 65535) throw new Error('Port range exceeds 65535');
return { mode: 'range', start, count };
} else {
const raw = (listEl?.value || '').trim();
if (!raw) throw new Error('Provide at least one port');
const parts = raw.split(',').map(value => wholeNumber(value.trim()));
if (parts.some(port => !Number.isFinite(port))) throw new Error('Every list entry must be a whole port number.');
const uniq = Array.from(new Set(parts));
if (uniq.length === 0) throw new Error('No valid ports');
if (uniq.length > 1000) throw new Error('Too many ports (max 1000)');
if (uniq.some(p => p < 1024)) throw new Error('Ports below 1024 cannot be allocated.');
if (uniq.some(p => p > 65535)) throw new Error('Ports cannot exceed 65535.');
return { mode: 'list', ports: uniq };
}
}
function countPorts(alloc) {
if (!alloc) return 0;
if (alloc.mode === 'range') return Math.max(0, parseInt(alloc.count || 0, 10));
if (alloc.mode === 'list' && Array.isArray(alloc.ports)) return alloc.ports.length;
return 0;
}
function portsSummary(alloc) {
if (!alloc) return '—';
if (alloc.mode === 'range') return `range ${alloc.start}..${alloc.start + alloc.count - 1} (${alloc.count})`;
if (alloc.mode === 'list') return `${alloc.ports.length} ports`;
return '—';
}
async function loadNodes(page, search) {
if (typeof page === 'undefined') page = _nodesPage;
if (typeof search === 'undefined') search = _nodesSearch;
const request = ++_nodesLoadRequest;
_nodesPage = page;
_nodesSearch = search;
const isFirstLoad = !nodesListEl.querySelector('.node-row');
if (isFirstLoad) {
nodesListEl.innerHTML = `Loading…
`;
}
try {
const params = new URLSearchParams({ page: String(page), limit: String(_nodesLimit) });
if (search) params.set('search', search);
const res = await fetch('/api/nodes?' + params.toString());
if (request !== _nodesLoadRequest) return;
if (!res.ok) {
nodesListEl.innerHTML = `Failed to load nodes
`;
return;
}
const data = await res.json().catch(() => ({ nodes: [], total: 0, page: 1, totalPages: 1 }));
if (request !== _nodesLoadRequest) return;
const nodes = Array.isArray(data.nodes) ? data.nodes : [];
const total = Number(data.total || nodes.length);
const totalPages = Math.max(1, Number(data.totalPages) || 1);
const currentPage = clampServedPage(data.page, page, totalPages);
_nodesPage = currentPage;
renderNodes(nodes);
renderNodesPagination(currentPage, totalPages, total);
} catch (e) {
if (request !== _nodesLoadRequest) return;
console.error(e);
nodesListEl.innerHTML = `Network error
`;
}
}
let _nodesLoadRequest = 0;
let _nodesPage = 1;
let _nodesSearch = '';
const _nodesLimit = 50;
let _serversPage = 1;
let _serversSearch = '';
const _serversLimit = 50;
let _serversSearchTimer;
let _templatesPage = 1;
let _templatesSearch = '';
const _templatesLimit = 50;
let _templatesSearchTimer;
let _nodesTimer;
let _nodesSearchTimer;
const nodesSearchInput = document.getElementById('nodesSearchInput');
const nodesPaginationEl = document.getElementById('nodesPagination');
function stopNodesPolling() { clearInterval(_nodesTimer); _nodesTimer = null; }
function startNodesPolling() {
stopNodesPolling();
_nodesTimer = setInterval(() => loadNodes(), 30000);
}
function leaveNodesPanel() {
// adpanel:node-secret-view - credentials must not survive in a hidden settings tab.
stopNodesPolling();
clearTimeout(_nodesSearchTimer);
_nodesLoadRequest++;
stopCreateNodeHealthCheck();
lockNodeSecret('cn', 'config');
lockNodeSecret('cn', 'command');
lockNodeSecret('nm', 'config');
lockNodeSecret('nm', 'command');
resetNodeDangerZone();
}
if (nodesSearchInput) {
nodesSearchInput.addEventListener('input', () => {
clearTimeout(_nodesSearchTimer);
_nodesSearchTimer = setTimeout(() => {
_nodesPage = 1;
loadNodes(1, nodesSearchInput.value.trim());
}, 300);
});
}
const serversSearchInput = document.getElementById('serversSearchInput');
if (serversSearchInput) {
serversSearchInput.addEventListener('input', () => {
clearTimeout(_serversSearchTimer);
_serversSearchTimer = setTimeout(() => {
_serversPage = 1;
loadServers(1, serversSearchInput.value.trim());
}, 300);
});
}
const templatesSearchInput = document.getElementById('templatesSearchInput');
if (templatesSearchInput) {
templatesSearchInput.addEventListener('input', () => {
clearTimeout(_templatesSearchTimer);
_templatesSearchTimer = setTimeout(() => {
_templatesPage = 1;
loadTemplates(1, templatesSearchInput.value.trim());
}, 300);
});
}
function renderNodesPagination(currentPage, totalPages, total) {
if (!nodesPaginationEl) return;
if (totalPages <= 1) { nodesPaginationEl.innerHTML = ''; return; }
const startItem = (currentPage - 1) * _nodesLimit + 1;
const endItem = Math.min(currentPage * _nodesLimit, total);
nodesPaginationEl.innerHTML = `
`;
nodesPaginationEl.querySelectorAll('button[data-page]').forEach(btn => {
btn.addEventListener('click', () => {
const p = parseInt(btn.dataset.page, 10);
if (p >= 1 && p <= totalPages) loadNodes(p);
});
});
}
function renderNodes(nodes) {
if (!nodes || nodes.length === 0) {
nodesListEl.innerHTML = `
${_nodesSearch ? 'No nodes match your search.' : "You haven't created any node yet."}
${!_nodesSearch ? '
Create node' : ''}
`;
const emptyCreateBtn = nodesListEl.querySelector('[data-open-create-node]');
if (emptyCreateBtn && openCreateNodeBtn) {
emptyCreateBtn.addEventListener('click', () => openCreateNodeBtn.click());
}
return;
}
const frag = document.createDocumentFragment();
const now = Date.now();
for (let i = 0; i < nodes.length; i++) {
const n = nodes[i];
const row = document.createElement('div');
row.className = 'node-row';
const nodeId = n.id || n.uuid || '';
row.dataset.id = nodeId;
row.dataset.uuid = n.uuid || '';
const lastSeen = Number(n.last_seen || n.lastSeen || n.lastHeartbeat || 0);
const fresh = lastSeen > 0 && (now - lastSeen) < 120000;
let statusClass = 'gray';
let statusLabel = 'No recent heartbeat';
if (n.online === false) {
statusClass = 'red';
statusLabel = 'Offline';
}
if (fresh || n.online === true) {
if (n.port_ok === false) {
statusClass = 'red';
statusLabel = 'Heartbeat ok, port unreachable';
} else if (n.online === true) {
statusClass = 'green';
statusLabel = 'Online';
} else if (n.port_ok == null) {
statusClass = 'gray';
statusLabel = 'Checking…';
}
}
const portCount = countPorts(n.ports);
const rotateRequired = !!n.token_rotate_required;
row.innerHTML = `
${escapeHtml(n.name || 'unnamed')}${rotateRequired ? ' Rotate required ' : ''}
${escapeHtml(n.address || '0.0.0.0')} • API ${Number(n.api_port || 8080)} • RAM ${Number(n.ram_mb || 0) / 1024 | 0} GB • Disk ${Number(n.disk_gb || 0)} GB • Ports ${portCount}
ID: ${escapeHtml(nodeId.toString())}
Update
Statistics
Configure
`;
row.querySelector('.open-node-update').addEventListener('click', (ev) => {
ev.stopPropagation();
if (typeof window.openNodeUpdateModal === 'function') window.openNodeUpdateModal(nodeId);
});
row.querySelector('.open-stats').addEventListener('click', (ev) => { ev.stopPropagation(); openNodeStatsModal(nodeId, n.name); });
row.querySelector('.open-node').addEventListener('click', (ev) => { ev.stopPropagation(); openNodeModal(nodeId); });
row.addEventListener('click', () => openNodeModal(nodeId));
frag.appendChild(row);
}
nodesListEl.innerHTML = '';
nodesListEl.appendChild(frag);
}
if (typeof window.io === 'function') {
try {
const _nodeStatusSocket = window.io();
_nodeStatusSocket.on('node:status', (data) => {
if (!data || !data.id || !nodesListEl) return;
// data.id is untrusted socket payload — never interpolate it into a
// selector string; a crafted id could throw or match an unintended row.
const targetId = String(data.id);
const rows = Array.from(nodesListEl.querySelectorAll('.node-row'));
const row = rows.find(el => el.dataset.uuid === targetId) || rows.find(el => el.dataset.id === targetId);
if (!row) return;
if (data.online) {
setNodeStatus(row, 'green', 'Online');
} else {
setNodeStatus(row, 'red', 'Offline / unreachable');
}
});
const subscribe = () => _nodeStatusSocket.emit('dashboard:subscribe', []);
_nodeStatusSocket.on('connect', subscribe);
if (_nodeStatusSocket.connected) subscribe();
} catch { }
}
function isIPAddress(addr) {
if (!addr) return true;
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(addr)) return true;
if (/^\[?[0-9a-fA-F:]+\]?$/.test(addr)) return true;
return false;
}
function extractHostname(value) {
const raw = String(value || '').trim();
if (!raw) return '';
if (/^https?:\/\//i.test(raw)) {
try {
return new URL(raw).hostname;
} catch {
return '';
}
}
const withoutPath = raw.split(/[/?#]/)[0];
if (withoutPath.startsWith('[')) {
const end = withoutPath.indexOf(']');
return end > 0 ? withoutPath.slice(1, end) : withoutPath;
}
const colonCount = (withoutPath.match(/:/g) || []).length;
if (colonCount === 1) return withoutPath.split(':')[0];
return withoutPath;
}
function isLoopbackHostname(hostname) {
const host = String(hostname || '').trim().toLowerCase();
return host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]';
}
function canUseHttpsForNodeAddress(address) {
const host = extractHostname(address);
return !!host && !isIPAddress(host) && !isLoopbackHostname(host);
}
function isNodeUnderCloudflare(node) {
const buildConfig = node && typeof node.buildConfig === 'object' ? node.buildConfig : {};
return !!(node?.under_cloudflare || node?.cloudflare_proxy || buildConfig.under_cloudflare || buildConfig.cloudflare_proxy);
}
const CLOUDFLARE_HTTPS_EDGE_PORTS = new Set([443, 2053, 2083, 2087, 2096, 8443]);
function isCloudflareHttpsPort(port) {
const value = Number(port);
return Number.isInteger(value) && CLOUDFLARE_HTTPS_EDGE_PORTS.has(value);
}
function preferCloudflareDaemonPort(input) {
if (!input) return;
const current = parseInt(input.value || '8080', 10);
if (!isCloudflareHttpsPort(current)) input.value = '8443';
}
function defaultNodeTlsPaths(node) {
if (!node || !node.ssl_enabled) return { cert: '', key: '' };
const host = extractHostname(node.address || '');
if (!canUseHttpsForNodeAddress(host) || !/^[a-z0-9.-]+$/i.test(host)) return { cert: '', key: '' };
return {
cert: `/etc/letsencrypt/live/${host.toLowerCase()}/fullchain.pem`,
key: `/etc/letsencrypt/live/${host.toLowerCase()}/privkey.pem`,
};
}
function isPanelOnHttpsDomain() {
const host = String(window.location.hostname || '').trim();
return window.location.protocol === 'https:' && !!host && !isIPAddress(host) && !isLoopbackHostname(host);
}
function updateNodeConnectionCopy(checkbox, label, help, cloudflareToggle = null) {
const httpsEnabled = !!(checkbox && checkbox.checked);
const underCloudflare = !!(cloudflareToggle && cloudflareToggle.checked);
if (label) label.textContent = httpsEnabled ? 'HTTPS Connection' : 'HTTP Connection';
if (help) {
if (!httpsEnabled) {
help.textContent = 'Communicate with this node over HTTP.';
} else if (underCloudflare) {
help.textContent = 'Communicate with this node through Cloudflare over HTTPS.';
} else {
help.textContent = "Communicate with this node over HTTPS (requires Let's Encrypt or custom SSL certificate on the node).";
}
}
}
function updateCloudflareToggle(sslCheckbox, row, toggle) {
const show = !!(sslCheckbox && sslCheckbox.checked);
if (row) row.style.display = show ? '' : 'none';
if (!show && toggle) toggle.checked = false;
}
let createNodeConnectionTouched = false;
let createNodeDraft = null;
function getCheckedRadioValue(name, root = document) {
return root.querySelector(`input[name="${name}"]:checked`)?.value || '';
}
function setCheckedRadioValue(name, value, root = document) {
const el = root.querySelector(`input[name="${name}"][value="${value}"]`);
if (el) {
el.checked = true;
el.dispatchEvent(new Event('change'));
}
}
function captureCreateNodeDraft() {
createNodeDraft = {
name: cn_name?.value || '',
address: cn_address?.value || '',
cpu_cores: cn_cpu_cores?.value || '',
ram_gb: cn_ram_gb?.value || '',
disk_gb: cn_disk_gb?.value || '',
ports_mode: getCheckedRadioValue('cn_ports_mode'),
port_start: cn_port_start?.value || '',
port_count: cn_port_count?.value || '',
port_list: cn_port_list?.value || '',
max_upload_mb: cn_max_upload_mb?.value || '',
daemon_port: cn_daemon_port?.value || '',
ssl_enabled: !!(cn_ssl_enabled && cn_ssl_enabled.checked),
under_cloudflare: !!(cn_under_cloudflare && cn_under_cloudflare.checked),
connectionTouched: createNodeConnectionTouched,
};
}
function restoreCreateNodeDraft() {
if (!createNodeDraft) return false;
if (cn_name) cn_name.value = createNodeDraft.name;
if (cn_address) cn_address.value = createNodeDraft.address;
if (cn_cpu_cores) cn_cpu_cores.value = createNodeDraft.cpu_cores;
if (cn_ram_gb) cn_ram_gb.value = createNodeDraft.ram_gb;
if (cn_disk_gb) cn_disk_gb.value = createNodeDraft.disk_gb;
if (createNodeDraft.ports_mode) setCheckedRadioValue('cn_ports_mode', createNodeDraft.ports_mode);
if (cn_port_start) cn_port_start.value = createNodeDraft.port_start;
if (cn_port_count) cn_port_count.value = createNodeDraft.port_count;
if (cn_port_list) cn_port_list.value = createNodeDraft.port_list;
if (cn_max_upload_mb) cn_max_upload_mb.value = createNodeDraft.max_upload_mb;
if (cn_daemon_port) cn_daemon_port.value = createNodeDraft.daemon_port;
if (cn_ssl_enabled) cn_ssl_enabled.checked = !!createNodeDraft.ssl_enabled;
if (cn_under_cloudflare) cn_under_cloudflare.checked = !!createNodeDraft.under_cloudflare;
createNodeConnectionTouched = !!createNodeDraft.connectionTouched;
return true;
}
function resetCreateNodeForm() {
if (cn_name) cn_name.value = '';
if (cn_address) cn_address.value = '';
if (cn_cpu_cores) cn_cpu_cores.value = '';
if (cn_ram_gb) cn_ram_gb.value = '';
if (cn_disk_gb) cn_disk_gb.value = '';
setCheckedRadioValue('cn_ports_mode', 'range');
if (cn_port_start) cn_port_start.value = '';
if (cn_port_count) cn_port_count.value = '';
if (cn_port_list) cn_port_list.value = '';
if (cn_max_upload_mb) cn_max_upload_mb.value = '100';
if (cn_daemon_port) cn_daemon_port.value = '8080';
if (cn_ssl_enabled) cn_ssl_enabled.checked = false;
if (cn_under_cloudflare) cn_under_cloudflare.checked = false;
createNodeConnectionTouched = false;
updateCreateNodeConnectionMode({ preferPanelHttps: true });
}
function updateCreateNodeConnectionMode(options = {}) {
if (!cn_ssl_row) return;
const address = String(cn_address?.value || '').trim();
const addressAllowsHttps = canUseHttpsForNodeAddress(address);
const panelHttpsDomain = isPanelOnHttpsDomain();
const shouldShow = addressAllowsHttps || (panelHttpsDomain && !address);
if (!shouldShow) {
cn_ssl_row.style.display = 'none';
if (cn_ssl_enabled) cn_ssl_enabled.checked = false;
updateNodeConnectionCopy(cn_ssl_enabled, cn_connection_label, cn_connection_help, cn_under_cloudflare);
updateCloudflareToggle(cn_ssl_enabled, cn_under_cloudflare_row, cn_under_cloudflare);
return;
}
cn_ssl_row.style.display = '';
if (options.preferPanelHttps && panelHttpsDomain && !createNodeConnectionTouched) {
if (cn_ssl_enabled) cn_ssl_enabled.checked = true;
}
updateNodeConnectionCopy(cn_ssl_enabled, cn_connection_label, cn_connection_help, cn_under_cloudflare);
updateCloudflareToggle(cn_ssl_enabled, cn_under_cloudflare_row, cn_under_cloudflare);
}
if (cn_ssl_enabled) {
cn_ssl_enabled.addEventListener('change', () => {
createNodeConnectionTouched = true;
updateNodeConnectionCopy(cn_ssl_enabled, cn_connection_label, cn_connection_help, cn_under_cloudflare);
updateCloudflareToggle(cn_ssl_enabled, cn_under_cloudflare_row, cn_under_cloudflare);
});
}
if (cn_under_cloudflare) {
cn_under_cloudflare.addEventListener('change', () => {
if (cn_under_cloudflare.checked) preferCloudflareDaemonPort(cn_daemon_port);
updateNodeConnectionCopy(cn_ssl_enabled, cn_connection_label, cn_connection_help, cn_under_cloudflare);
});
}
if (cn_address && cn_ssl_row) {
cn_address.addEventListener('input', () => updateCreateNodeConnectionMode({ preferPanelHttps: true }));
}
function showNodeManageView(show) {
if (show) {
if (nodesMainView) nodesMainView.style.display = 'none';
if (nodeManageInlineView) nodeManageInlineView.style.display = 'flex';
} else {
// Leaving the node view wipes any revealed config/command from the DOM.
nodeManageRequest++;
CURRENT_NODE = null;
lockNodeSecret('nm', 'config');
lockNodeSecret('nm', 'command');
if (nodeManageInlineView) nodeManageInlineView.style.display = 'none';
if (nodesMainView) nodesMainView.style.display = 'block';
}
}
function showNodeModal(show) {
showNodeManageView(show);
return true;
}
if (nodeManageBackBtn) {
nodeManageBackBtn.addEventListener('click', () => {
showNodeManageView(false);
loadNodes();
});
}
function switchNodeCategory(targetCat) {
const cat = String(targetCat || 'node-config').trim();
if (nodeManageCategoriesNav) {
nodeManageCategoriesNav.querySelectorAll('.server-category-btn').forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('data-cat') === cat);
});
}
const paneId = `pane_${cat.replace(/-/g, '_')}`;
if (nodeManageInlineView) {
nodeManageInlineView.querySelectorAll('.server-category-pane').forEach(p => {
p.classList.toggle('active', p.id === paneId);
});
}
autoFitPanelInputs();
triggerAutoResizeInputs();
}
if (nodeManageCategoriesNav) {
nodeManageCategoriesNav.querySelectorAll('.server-category-btn').forEach(btn => {
btn.addEventListener('click', () => {
const cat = btn.getAttribute('data-cat');
switchNodeCategory(cat);
});
});
}
let CURRENT_NODE = null;
let nodeManageRequest = 0;
async function openNodeModal(id, focusLinking = false) {
const request = ++nodeManageRequest;
try {
const res = await fetch(`/api/nodes/${encodeURIComponent(id)}`);
const node = await res.json();
if (request !== nodeManageRequest) return;
if (!res.ok) throw new Error(node.error || 'Failed to load node');
CURRENT_NODE = node;
fillNodeModal(node, focusLinking);
showNodeManageView(true);
} catch (e) {
if (request === nodeManageRequest) alert(e.message || 'Failed to open node');
}
}
function setRadio(name, value) {
const el = document.querySelector(`input[name="${name}"][value="${value}"]`);
if (el) { el.checked = true; el.dispatchEvent(new Event('change')); }
}
function updateEditNodeConnectionMode() {
const addr = (nm_address?.value || '').trim();
const hasTlsHostname = canUseHttpsForNodeAddress(addr);
const showTls = hasTlsHostname || !!CURRENT_NODE?.ssl_enabled || !!nm_ssl_enabled?.checked;
if (nm_ssl_row) nm_ssl_row.style.display = showTls ? 'flex' : 'none';
if (nm_ssl_divider) nm_ssl_divider.style.display = showTls ? 'block' : 'none';
const showCf = hasTlsHostname && !!nm_ssl_enabled?.checked;
if (nm_under_cloudflare_row) nm_under_cloudflare_row.style.display = showCf ? 'flex' : 'none';
if (nm_under_cloudflare_divider) nm_under_cloudflare_divider.style.display = showCf ? 'block' : 'none';
updateNodeConnectionCopy(nm_ssl_enabled, nm_connection_label, nm_connection_help, showCf ? nm_under_cloudflare : null);
}
let currentNodeInUsePorts = {};
async function loadNodeInUsePorts(node) {
if (!node || CURRENT_NODE !== node) return;
currentNodeInUsePorts = {};
if (nm_allocated_ports_container) {
nm_allocated_ports_container.textContent = 'Loading ports...';
updateAllocatedPortsSelectionUI();
}
const id = node.id || node.uuid;
if (!id) return;
let inUse = {};
try {
const res = await fetch(`/api/nodes/${encodeURIComponent(id)}/ports/in-use`);
if (res.ok) {
const data = await res.json();
inUse = data.inUse || {};
}
} catch (err) {
console.warn('Failed to load in-use ports:', err);
}
if (CURRENT_NODE !== node) return;
currentNodeInUsePorts = inUse;
renderNodeAllocatedPorts(node);
}
function renderAdditionalIpRows(container, ips = [], prefix = 'nm') {
if (!container) return;
container.innerHTML = '';
ips.forEach(ip => {
addAdditionalIpRow(container, ip, prefix);
});
}
function addAdditionalIpRow(container, initialValue = '', prefix = 'nm') {
if (!container) return;
const rowWrapper = document.createElement('div');
rowWrapper.className = `${prefix}-additional-ip-item-wrap`;
rowWrapper.innerHTML = `
`;
const removeBtn = rowWrapper.querySelector(`.${prefix}-remove-ip-btn`);
if (removeBtn) {
removeBtn.addEventListener('click', () => {
rowWrapper.remove();
if (prefix === 'cn') populateCreateNodePortsIpDropdown();
});
}
const input = rowWrapper.querySelector(`.${prefix}-additional-ip-input`);
if (input && prefix === 'cn') {
input.addEventListener('input', populateCreateNodePortsIpDropdown);
}
container.appendChild(rowWrapper);
autoFitPanelInputs();
if (!initialValue && input) {
input.focus();
}
}
function getAdditionalIpsFromContainer(container, prefix = 'nm') {
if (!container) return [];
const inputs = container.querySelectorAll(`.${prefix}-additional-ip-input`);
const ips = [];
inputs.forEach(inp => {
const val = String(inp.value || '').trim();
if (val) ips.push(val);
});
return Array.from(new Set(ips));
}
function nodePortAddresses(primary, additional, underCloudflare) {
const addresses = new Set([primary, ...additional].filter(Boolean));
if (underCloudflare) addresses.delete(primary);
return Array.from(addresses);
}
function getCreateNodePortAddresses() {
const primary = String(cn_address?.value || '').trim();
return nodePortAddresses(primary, getAdditionalIpsFromContainer(cn_additional_ips_container, 'cn'), cn_under_cloudflare?.checked);
}
function populateNodePortsIpDropdown(node) {
if (!nm_port_ip_dropdown_menu || !nm_port_ip_select) return;
const primaryIp = String(node?.address || '').trim();
const allIps = nodePortAddresses(primaryIp, node?.additional_ips || node?.ips || [], isNodeUnderCloudflare(node));
const currentVal = nm_port_ip_select.value;
const selectedIp = allIps.includes(currentVal) ? currentVal : (allIps[0] || '');
if (nm_port_ip_selected_text) {
nm_port_ip_selected_text.textContent = selectedIp || 'No eligible address';
}
nm_port_ip_select.innerHTML = allIps.map(ip => `${escapeHtml(ip)} `).join('');
nm_port_ip_select.value = selectedIp;
nm_port_ip_dropdown_menu.innerHTML = allIps.map((ip, idx) => {
const isPrimary = ip === primaryIp;
const divider = idx > 0 ? '
' : '';
return `${divider}
${escapeHtml(ip)}
${isPrimary ? 'PRIMARY ' : ''}
`;
}).join('');
nm_port_ip_dropdown_menu.querySelectorAll('.dashboard-assistant-dropdown-item[data-ip]').forEach(item => {
item.addEventListener('click', (e) => {
e.stopPropagation();
const ip = item.getAttribute('data-ip');
if (!ip) return;
nm_port_ip_select.value = ip;
if (nm_port_ip_selected_text) nm_port_ip_selected_text.textContent = ip;
nm_port_ip_dropdown_menu.querySelectorAll('.dashboard-assistant-dropdown-item').forEach(el => el.classList.remove('is-active'));
item.classList.add('is-active');
if (nm_port_ip_dropdown) nm_port_ip_dropdown.classList.remove('is-open');
if (nm_port_ip_dropdown_menu) nm_port_ip_dropdown_menu.hidden = true;
});
});
}
function populateCreateNodePortsIpDropdown() {
if (!cn_port_ip_dropdown_menu || !cn_port_ip_select) return;
const primaryIp = String(cn_address?.value || '').trim();
const allIps = getCreateNodePortAddresses();
const currentVal = cn_port_ip_select.value;
const selectedIp = allIps.includes(currentVal) ? currentVal : (allIps[0] || '');
if (cn_port_ip_selected_text) {
cn_port_ip_selected_text.textContent = selectedIp || 'No eligible address';
}
cn_port_ip_select.innerHTML = allIps.map(ip => `${escapeHtml(ip)} `).join('');
cn_port_ip_select.value = selectedIp;
cn_port_ip_dropdown_menu.innerHTML = allIps.map((ip, idx) => {
const isPrimary = ip === primaryIp;
const divider = idx > 0 ? '
' : '';
return `${divider}
${escapeHtml(ip)}
${isPrimary ? 'PRIMARY ' : ''}
`;
}).join('');
cn_port_ip_dropdown_menu.querySelectorAll('.dashboard-assistant-dropdown-item[data-ip]').forEach(item => {
item.addEventListener('click', (e) => {
e.stopPropagation();
const ip = item.getAttribute('data-ip');
if (!ip) return;
cn_port_ip_select.value = ip;
if (cn_port_ip_selected_text) cn_port_ip_selected_text.textContent = ip;
cn_port_ip_dropdown_menu.querySelectorAll('.dashboard-assistant-dropdown-item').forEach(el => el.classList.remove('is-active'));
item.classList.add('is-active');
if (cn_port_ip_dropdown) cn_port_ip_dropdown.classList.remove('is-open');
if (cn_port_ip_dropdown_menu) cn_port_ip_dropdown_menu.hidden = true;
});
});
}
if (nm_add_ip_btn) {
nm_add_ip_btn.addEventListener('click', () => {
addAdditionalIpRow(nm_additional_ips_container, '', 'nm');
});
}
if (cn_add_ip_btn) {
cn_add_ip_btn.addEventListener('click', () => {
addAdditionalIpRow(cn_additional_ips_container, '', 'cn');
populateCreateNodePortsIpDropdown();
});
}
function getNodeAllocations(node) {
if (!node) return [];
const portsObj = node.ports || {};
if (Array.isArray(portsObj.allocations) && portsObj.allocations.length > 0) {
return portsObj.allocations.map(a => ({
ip: String(a.ip || node.address || '0.0.0.0').trim(),
port: Number(a.port)
})).filter(a => a.port >= 1 && a.port <= 65535);
}
const defaultIp = node.address || '0.0.0.0';
if (portsObj.mode === 'range') {
const start = Number(portsObj.start || 25565);
const count = Number(portsObj.count || 10);
const list = [];
for (let i = 0; i < count; i++) {
const p = start + i;
if (p >= 1 && p <= 65535) list.push({ ip: defaultIp, port: p });
}
return list;
}
if (Array.isArray(portsObj.ports)) {
return portsObj.ports.map(p => ({ ip: defaultIp, port: Number(p) })).filter(a => a.port >= 1 && a.port <= 65535);
}
return [];
}
function updatePortsConfirmButtonState() {
if (!nm_ports_confirm_btn) return;
const mode = document.querySelector('input[name="nm_ports_mode"]:checked')?.value || 'range';
try {
parsePortsInput(mode, nm_port_start, nm_port_count, nm_port_list);
nm_ports_confirm_btn.disabled = false;
} catch {
nm_ports_confirm_btn.disabled = true;
}
}
function updateAllocatedPortsSelectionUI() {
if (!nm_allocated_ports_container) return;
const availableCheckboxes = nm_allocated_ports_container.querySelectorAll('.node-port-checkbox:not(:disabled)');
const checkedBoxes = nm_allocated_ports_container.querySelectorAll('.node-port-checkbox:not(:disabled):checked');
const count = checkedBoxes.length;
const total = availableCheckboxes.length;
if (nm_ports_selected_count) nm_ports_selected_count.textContent = String(count);
if (nm_ports_delete_selected) {
nm_ports_delete_selected.style.display = count > 0 ? 'inline-flex' : 'none';
}
if (nm_ports_select_all) {
if (total === 0) {
nm_ports_select_all.disabled = true;
nm_ports_select_all.innerHTML = ' Select All';
} else {
nm_ports_select_all.disabled = false;
if (count === total) {
nm_ports_select_all.innerHTML = ' Deselect All';
} else {
nm_ports_select_all.innerHTML = ' Select All';
}
}
}
}
function renderNodeAllocatedPorts(node) {
if (!nm_allocated_ports_container) return;
const allocations = getNodeAllocations(node);
if (nm_allocated_ports_subtitle) {
nm_allocated_ports_subtitle.textContent = `${allocations.length} port${allocations.length === 1 ? '' : 's'} available in pool`;
}
if (allocations.length === 0) {
nm_allocated_ports_container.innerHTML = 'No ports allocated yet. Use the form above to allocate port ranges or lists.
';
if (nm_ports_select_all) {
nm_ports_select_all.disabled = true;
nm_ports_select_all.innerHTML = ' Select All';
}
updateAllocatedPortsSelectionUI();
return;
}
if (nm_ports_select_all) nm_ports_select_all.disabled = false;
nm_allocated_ports_container.innerHTML = '';
allocations.forEach(alloc => {
const ip = alloc.ip || (node && node.address) || '0.0.0.0';
const port = Number(alloc.port);
const key = `${ip}:${port}`;
const inUseServers = currentNodeInUsePorts[port] || currentNodeInUsePorts[String(port)];
const isInUse = Array.isArray(inUseServers) && inUseServers.length > 0;
const chip = document.createElement('div');
chip.className = 'node-port-item' + (isInUse ? ' in-use is-occupied' : '');
chip.dataset.key = key;
chip.dataset.ip = ip;
chip.dataset.port = String(port);
const chk = document.createElement('input');
chk.type = 'checkbox';
chk.className = 'node-port-checkbox';
const label = document.createElement('span');
label.className = 'node-port-label';
label.textContent = `${ip}:${port}`;
chip.appendChild(chk);
chip.appendChild(label);
if (isInUse) {
chip.title = `Occupied by server(s): ${inUseServers.join(', ')} (Locked)`;
chk.disabled = true;
chk.tabIndex = -1;
const lockIcon = document.createElement('i');
lockIcon.className = 'fa-solid fa-lock node-port-occupied-icon';
lockIcon.title = `In use by ${inUseServers.join(', ')}`;
chip.appendChild(lockIcon);
} else {
const delBtn = document.createElement('button');
delBtn.type = 'button';
delBtn.className = 'node-port-delete-btn';
delBtn.title = `Delete port ${port}`;
delBtn.setAttribute('aria-label', `Delete port ${port}`);
delBtn.innerHTML = ' ';
chip.appendChild(delBtn);
chip.addEventListener('click', (e) => {
if (e.target === delBtn || delBtn.contains(e.target)) return;
if (e.target !== chk) {
chk.checked = !chk.checked;
}
chip.classList.toggle('selected', chk.checked);
updateAllocatedPortsSelectionUI();
});
chk.addEventListener('change', () => {
chip.classList.toggle('selected', chk.checked);
updateAllocatedPortsSelectionUI();
});
delBtn.addEventListener('click', async (e) => {
e.stopPropagation();
await deleteSingleNodePortAllocation(key);
});
}
nm_allocated_ports_container.appendChild(chip);
});
updateAllocatedPortsSelectionUI();
}
async function saveUpdatedNodeAllocations(updatedAllocations) {
const node = CURRENT_NODE;
if (!node) return false;
try {
showCategoryFeedback('node-ports', '');
const payload = {
ports_revision: node.ports_revision,
ports: {
mode: 'list',
allocations: updatedAllocations,
ports: Array.from(new Set(updatedAllocations.map(a => Number(a.port)))).sort((a, b) => a - b)
}
};
const { res, data } = await sendNodeWriteWithStepUp(`/api/nodes/${encodeURIComponent(node.id || node.uuid)}`, 'PATCH', payload, {
subtitle: 'Verify your identity to update port allocations',
reason: 'Port allocation changes affect where servers on this node are reachable.',
cancelledMessage: 'Verification cancelled — allocations were not saved.'
});
if (CURRENT_NODE !== node) return false;
if (!res.ok) throw new Error([data.error || 'Failed to update port allocations', data.detail || ''].filter(Boolean).join('\n'));
const saved = CURRENT_NODE = Object.assign({}, node, data);
await loadNodeInUsePorts(saved);
if (CURRENT_NODE !== saved) return false;
await refreshRevealedNodeSecret('nm', 'config');
await loadNodes();
return CURRENT_NODE === saved;
} catch (err) {
if (CURRENT_NODE === node) showCategoryFeedback('node-ports', err.message || 'Error updating allocations', true);
return false;
}
}
async function deleteSingleNodePortAllocation(targetKey) {
if (!CURRENT_NODE) return;
const portNum = parseInt(targetKey.split(':').pop(), 10);
const usedBy = currentNodeInUsePorts[portNum] || currentNodeInUsePorts[String(portNum)];
if (usedBy && usedBy.length > 0) {
showCategoryFeedback('node-ports', `Cannot delete port ${portNum} — it is currently in use by server: "${usedBy.join(', ')}".`, true);
return;
}
const currentAllocations = getNodeAllocations(CURRENT_NODE);
const updated = currentAllocations.filter(a => `${a.ip || CURRENT_NODE.address || '0.0.0.0'}:${a.port}` !== targetKey);
const ok = await saveUpdatedNodeAllocations(updated);
if (ok) {
showCategoryFeedback('node-ports', `Port allocation ${targetKey} deleted successfully!`, false);
}
}
let portsRadiosBound = false;
function bindEditPortsRadios() {
if (portsRadiosBound) return;
portsRadiosBound = true;
document.querySelectorAll('input[name="nm_ports_mode"]').forEach(r => {
r.addEventListener('change', () => {
const mode = document.querySelector('input[name="nm_ports_mode"]:checked')?.value || 'range';
const rangeRows = [nm_ports_range_start_row, nm_ports_range_count_divider, nm_ports_range_count_row];
if (mode === 'list') {
rangeRows.forEach(el => { if (el) el.style.display = 'none'; });
if (nm_ports_list_row) nm_ports_list_row.style.display = 'flex';
} else {
rangeRows.forEach(el => { if (el) el.style.display = el.classList.contains('panelinfo-divider') ? 'block' : 'flex'; });
if (nm_ports_list_row) nm_ports_list_row.style.display = 'none';
}
updatePortsConfirmButtonState();
triggerAutoResizeInputs();
});
});
if (nm_port_start) nm_port_start.addEventListener('input', updatePortsConfirmButtonState);
if (nm_port_count) nm_port_count.addEventListener('input', updatePortsConfirmButtonState);
if (nm_port_list) nm_port_list.addEventListener('input', updatePortsConfirmButtonState);
if (nm_ports_confirm_btn) {
nm_ports_confirm_btn.addEventListener('click', async () => {
if (!CURRENT_NODE) return;
const mode = document.querySelector('input[name="nm_ports_mode"]:checked')?.value || 'range';
const selectedIp = nm_port_ip_select?.value;
if (!selectedIp) {
showCategoryFeedback('node-ports', 'Save a node IP address in Configuration before allocating ports.', true);
return;
}
let parsed;
try {
parsed = parsePortsInput(mode, nm_port_start, nm_port_count, nm_port_list);
} catch (err) {
showCategoryFeedback('node-ports', err.message, true);
return;
}
const newPorts = parsed.ports || Array.from({ length: parsed.count }, (_, index) => parsed.start + index);
const currentAllocations = getNodeAllocations(CURRENT_NODE);
const uniqueMap = new Map();
currentAllocations.forEach(a => {
const ip = a.ip || CURRENT_NODE.address || '0.0.0.0';
uniqueMap.set(`${ip}:${a.port}`, { ip: ip, port: Number(a.port) });
});
let addedCount = 0;
newPorts.forEach(p => {
const key = `${selectedIp}:${p}`;
if (!uniqueMap.has(key)) {
uniqueMap.set(key, { ip: selectedIp, port: p });
addedCount++;
}
});
const updatedAllocations = Array.from(uniqueMap.values()).sort((a, b) => a.port - b.port);
nm_ports_confirm_btn.disabled = true;
nm_ports_confirm_btn.innerHTML = ' Allocating…';
const ok = await saveUpdatedNodeAllocations(updatedAllocations);
nm_ports_confirm_btn.disabled = false;
nm_ports_confirm_btn.innerHTML = ' Confirm';
if (ok) {
showCategoryFeedback('node-ports', `Successfully allocated ${addedCount} new port(s)!`, false);
if (mode === 'range') {
if (nm_port_count) nm_port_count.value = '';
} else {
if (nm_port_list) nm_port_list.value = '';
}
updatePortsConfirmButtonState();
triggerAutoResizeInputs();
}
});
}
if (nm_ports_select_all) {
nm_ports_select_all.addEventListener('click', () => {
if (!nm_allocated_ports_container) return;
const availableCheckboxes = nm_allocated_ports_container.querySelectorAll('.node-port-checkbox:not(:disabled)');
const checkedBoxes = nm_allocated_ports_container.querySelectorAll('.node-port-checkbox:not(:disabled):checked');
const allSelected = availableCheckboxes.length > 0 && checkedBoxes.length === availableCheckboxes.length;
availableCheckboxes.forEach(chk => {
chk.checked = !allSelected;
const chip = chk.closest('.node-port-item');
if (chip) chip.classList.toggle('selected', !allSelected);
});
updateAllocatedPortsSelectionUI();
});
}
if (nm_ports_delete_selected) {
nm_ports_delete_selected.addEventListener('click', async () => {
if (!CURRENT_NODE || !nm_allocated_ports_container) return;
const checkedBoxes = nm_allocated_ports_container.querySelectorAll('.node-port-checkbox:not(:disabled):checked');
if (checkedBoxes.length === 0) return;
const keysToDelete = new Set();
checkedBoxes.forEach(chk => {
const chip = chk.closest('.node-port-item');
if (chip?.dataset?.key) {
keysToDelete.add(chip.dataset.key);
}
});
if (keysToDelete.size === 0) return;
const ok = confirm(`Delete ${keysToDelete.size} selected port allocation(s)?`);
if (!ok) return;
const currentAllocations = getNodeAllocations(CURRENT_NODE);
const updated = currentAllocations.filter(a => !keysToDelete.has(`${a.ip || CURRENT_NODE.address || '0.0.0.0'}:${a.port}`));
const saved = await saveUpdatedNodeAllocations(updated);
if (saved) {
showCategoryFeedback('node-ports', `Deleted ${keysToDelete.size} port(s) from allocation pool!`, false);
}
});
}
}
function fillNodeModal(node, focusLinking = false) {
if (nodeManageTitle) nodeManageTitle.textContent = node.name || 'Node';
if (nodeManageSubtitle) {
// textContent is HTML-inert, so the raw address renders verbatim — running
// escapeHtml() here would double-encode &<> into visible entities.
nodeManageSubtitle.textContent = `${node.address || '0.0.0.0'} • ${Number(node.cpu_cores || 0)} cores • ${(Number(node.ram_mb || 0) / 1024 | 0)} GB RAM`;
}
if (nm_name) nm_name.value = node.name || '';
if (nm_address) nm_address.value = node.address || '';
renderAdditionalIpRows(nm_additional_ips_container, node.additional_ips || node.buildConfig?.ips || [], 'nm');
populateNodePortsIpDropdown(node);
if (nm_cpu_cores) nm_cpu_cores.value = Number(node.cpu_cores || 0) || '';
if (nm_ram_gb) nm_ram_gb.value = (Number(node.ram_mb || 0) / 1024 | 0);
if (nm_disk_gb) nm_disk_gb.value = Number(node.disk_gb || 0);
if (nm_max_upload_mb) nm_max_upload_mb.value = Number(node.max_upload_mb || 10240);
if (nm_daemon_port) nm_daemon_port.value = Number(node.api_port || 8080);
if (nm_ssl_enabled) nm_ssl_enabled.checked = !!node.ssl_enabled;
if (nm_under_cloudflare) nm_under_cloudflare.checked = !!node.under_cloudflare;
updateEditNodeConnectionMode();
updateNodeRotateWarning(node);
setRadio('nm_ports_mode', 'range');
if (nm_ports_range_start_row) nm_ports_range_start_row.style.display = 'flex';
if (nm_ports_range_count_divider) nm_ports_range_count_divider.style.display = 'block';
if (nm_ports_range_count_row) nm_ports_range_count_row.style.display = 'flex';
if (nm_ports_list_row) nm_ports_list_row.style.display = 'none';
if (nm_port_start) nm_port_start.value = '25565';
if (nm_port_count) nm_port_count.value = '10';
if (nm_port_list) nm_port_list.value = '';
bindEditPortsRadios();
loadNodeInUsePorts(node);
updatePortsConfirmButtonState();
lockNodeSecret('nm', 'config');
lockNodeSecret('nm', 'command');
resetNodeDangerZone();
['node-config', 'node-resources', 'node-ports', 'node-disks', 'node-linking', 'node-danger'].forEach(c => showCategoryFeedback(c, ''));
switchNodeCategory(focusLinking ? 'node-linking' : 'node-config');
loadNodeDisks();
autoFitPanelInputs();
}
// Reflects the startup token-integrity state (nodes.token_status) in the node
// modal: a persistent warning in the Linking tab plus a badge next to the
// rotate action. The flag comes from the admin API as token_rotate_required.
function updateNodeRotateWarning(node) {
const flagged = !!(node && node.token_rotate_required);
if (nm_rotate_warning) {
nm_rotate_warning.classList.remove('node-rotate-warning-info');
nm_rotate_warning.style.display = flagged ? 'flex' : 'none';
if (flagged && nm_rotate_warning_text) {
nm_rotate_warning_text.textContent = !node.token_invalidated
? 'The credential for this node pre-dates encryption at rest and must be rotated. Rotate the token below — a reachable, up-to-date daemon adopts it automatically.'
: 'The stored credential for this node failed verification (legacy plaintext value or undecryptable token) and was invalidated. Rotate the token below, then re-deploy config.yml / the setup command from this tab to restore the node connection.';
}
}
if (nm_rotate_state) nm_rotate_state.style.display = flagged ? 'inline-flex' : 'none';
}
// Shown after rotating an invalidated credential: the flag has cleared, but
// the daemon still runs the retired token until the admin re-deploys config.
function showNodeRedeployGuidance() {
if (!nm_rotate_warning) return;
nm_rotate_warning.classList.add('node-rotate-warning-info');
nm_rotate_warning.style.display = 'flex';
if (nm_rotate_warning_text) {
nm_rotate_warning_text.textContent = 'Token rotated. The daemon could not be updated directly (its previous credential was invalidated), so re-deploy config.yml or the setup command below to install the new token. The node will come back online once the new configuration is applied.';
}
}
function resetNodeDangerZone() { if (nm_delete_security_divider) nm_delete_security_divider.style.display = 'none';
if (nm_delete_security_row) nm_delete_security_row.style.display = 'none';
if (nm_deleteCredential) nm_deleteCredential.value = '';
if (nm_delete) {
nm_delete.disabled = false;
nm_delete.innerHTML = ' Delete Node';
}
}
function autoFitPanelInputs() {
triggerAutoResizeInputs();
}
// --- Node secret reveal (config.yml / setup command) --------------------------
// The node config embeds the daemon's bearer credential, so it is never built
// in the browser and never present in ordinary API responses. It crosses the
// wire only through the step-up verified POST reveal endpoints, and the
// plaintext is wiped from the DOM when the surface re-locks (view change or
// inactivity timeout).
const NODE_SECRET_REVEAL_TTL_MS = 5 * 60 * 1000;
const nodeSecretRevealState = { context: null, kind: null, action: null, customRequest: null, onCancel: null, confirmText: null, forceCredential: false };
const nodeSecretTimers = {};
const nodeSecretModalOverlay = document.getElementById('nodeSecretModalOverlay');
const nodeSecretModalClose = document.getElementById('nodeSecretModalClose');
const nodeSecretModalCancel = document.getElementById('nodeSecretModalCancel');
const nodeSecretModalConfirm = document.getElementById('nodeSecretModalConfirm');
const nodeSecretCredential = document.getElementById('nodeSecretCredential');
const nodeSecretCredentialLabel = document.getElementById('nodeSecretCredentialLabel');
const nodeSecretCredentialHint = document.getElementById('nodeSecretCredentialHint');
const nodeSecretModalError = document.getElementById('nodeSecretModalError');
const nodeSecretModalSubtitle = document.getElementById('nodeSecretModalSubtitle');
const nodeSecretModalReason = document.getElementById('nodeSecretModalReason');
function nodeSecretElementsFor(context, kind) {
const prefix = context === 'cn' ? 'cn' : 'nm';
if (kind === 'config') {
return {
box: document.getElementById(`${prefix}_configYml`),
lock: document.getElementById(`${prefix}_configLock`),
buttons: [document.getElementById(`${prefix}_copyConfig`), document.getElementById(`${prefix}_downloadConfig`)]
};
}
return {
box: document.getElementById(`${prefix}_cmd`),
lock: document.getElementById(`${prefix}_cmdLock`),
buttons: [document.getElementById(`${prefix}_copyCmd`)]
};
}
function isNodeSecretRevealed(context, kind) {
const els = nodeSecretElementsFor(context, kind);
return !!(els.lock && els.lock.style.display === 'none');
}
function lockNodeSecret(context, kind) {
if (nodeSecretRevealState.context === context && nodeSecretRevealState.kind === kind) closeNodeSecretModal();
const els = nodeSecretElementsFor(context, kind);
if (!els.lock) return;
els.lock.style.display = 'flex';
if (els.box) {
els.box.value = '';
try { els.box.blur(); } catch { }
}
(els.buttons || []).forEach(b => { if (b) b.disabled = true; });
const key = `${context}:${kind}`;
if (nodeSecretTimers[key]) {
window.clearTimeout(nodeSecretTimers[key]);
delete nodeSecretTimers[key];
}
}
function revealNodeSecretSurface(context, kind, value) {
const els = nodeSecretElementsFor(context, kind);
if (!els.lock || !els.box) return;
els.lock.style.display = 'none';
els.box.value = value;
(els.buttons || []).forEach(b => { if (b) b.disabled = false; });
const key = `${context}:${kind}`;
if (nodeSecretTimers[key]) window.clearTimeout(nodeSecretTimers[key]);
nodeSecretTimers[key] = window.setTimeout(() => {
lockNodeSecret(context, kind);
}, NODE_SECRET_REVEAL_TTL_MS);
}
// Re-fetch a currently revealed secret after its source data changed. When the
// step-up grace window has expired the server rejects the refresh and the
// surface re-locks — the credential is never left on screen stale.
async function refreshRevealedNodeSecret(context, kind) {
if (!isNodeSecretRevealed(context, kind)) return;
const key = `${context}:${kind}`;
const revealTimer = nodeSecretTimers[key];
try {
const credential = isStepUpGraceActive() ? STEP_UP_GRACE_CREDENTIAL : '';
const result = await requestNodeSecret(context, kind, credential);
if (nodeSecretTimers[key] === revealTimer) revealNodeSecretSurface(context, kind, result.value);
} catch {
if (nodeSecretTimers[key] === revealTimer) lockNodeSecret(context, kind);
}
}
function setNodeSecretModalError(msg) {
if (!nodeSecretModalError) return;
if (msg) {
nodeSecretModalError.textContent = msg;
nodeSecretModalError.style.display = 'block';
} else {
nodeSecretModalError.textContent = '';
nodeSecretModalError.style.display = 'none';
}
}
function openNodeSecretModal(context, kind, onVerified, options = {}) {
if (!nodeSecretModalOverlay || !nodeSecretCredential) return;
nodeSecretRevealState.request = Symbol();
nodeSecretRevealState.context = context;
nodeSecretRevealState.kind = kind;
nodeSecretRevealState.action = typeof onVerified === 'function' ? onVerified : null;
nodeSecretRevealState.customRequest = typeof options.customRequest === 'function' ? options.customRequest : null;
nodeSecretRevealState.onCancel = typeof options.onCancel === 'function' ? options.onCancel : null;
nodeSecretRevealState.confirmText = options.confirmText || null;
nodeSecretRevealState.keepOpenWhileVerifying = options.keepOpenWhileVerifying === true;
const forceCredential = !!(options.forceCredential || kind === 'custom');
nodeSecretRevealState.forceCredential = forceCredential;
const modalCopy = {
config: {
subtitle: 'Verify your identity to receive the node configuration',
reason: "The node configuration file contains the node daemon's authentication secrets. It is only revealed after identity verification.",
confirmText: 'Verify & Receive'
},
command: {
subtitle: 'Verify your identity to receive the node setup command',
reason: 'The setup command contains no secrets. It carries a single-use link your node uses to fetch its configuration from the panel over HTTPS — the link expires after 10 minutes and works exactly once, so run the command promptly after generating it.',
confirmText: 'Verify & Receive'
},
rotate: {
subtitle: 'Verify your identity to rotate the node token',
reason: 'Rotating replaces the bearer credential the daemon authenticates with. A reachable, up-to-date daemon adopts the new token automatically; otherwise re-deploy config.yml from the Linking tab afterwards.',
confirmText: 'Verify & Rotate'
},
custom: {
subtitle: 'Verify your identity to continue',
reason: 'This action is protected with step-up verification. Confirm your credentials to continue.',
confirmText: 'Confirm & Continue'
}
};
const copy = { ...(modalCopy[kind] || modalCopy.config) };
if (options.subtitle) copy.subtitle = options.subtitle;
if (options.reason) copy.reason = options.reason;
if (options.confirmText) copy.confirmText = options.confirmText;
if (nodeSecretModalSubtitle) {
nodeSecretModalSubtitle.textContent = copy.subtitle;
}
if (nodeSecretModalReason) {
nodeSecretModalReason.textContent = copy.reason;
}
if (nodeSecretModalConfirm) {
nodeSecretModalConfirm.disabled = false;
nodeSecretModalConfirm.textContent = copy.confirmText || 'Confirm & Continue';
}
configureStepUpCredentialField(nodeSecretCredential, nodeSecretCredentialLabel, nodeSecretCredentialHint, { force: forceCredential });
bindStepUpCredentialInput(nodeSecretCredential);
setNodeSecretModalError('');
nodeSecretModalOverlay.classList.add('show');
nodeSecretModalOverlay.setAttribute('aria-hidden', 'false');
if (forceCredential || !isStepUpGraceActive()) {
setTimeout(() => { try { nodeSecretCredential.focus(); } catch { } }, 60);
}
}
function closeNodeSecretModal() {
if (!nodeSecretModalOverlay) return;
if (nodeSecretRevealState.keepOpenWhileVerifying && nodeSecretRevealState.onCancel && nodeSecretModalConfirm?.disabled) return;
nodeSecretRevealState.request = null;
if (nodeSecretModalConfirm) nodeSecretModalConfirm.disabled = false;
nodeSecretModalOverlay.classList.remove('show');
nodeSecretModalOverlay.setAttribute('aria-hidden', 'true');
if (nodeSecretCredential) nodeSecretCredential.value = '';
setNodeSecretModalError('');
const onCancel = nodeSecretRevealState.onCancel;
nodeSecretRevealState.context = null;
nodeSecretRevealState.kind = null;
nodeSecretRevealState.action = null;
nodeSecretRevealState.customRequest = null;
nodeSecretRevealState.onCancel = null;
nodeSecretRevealState.confirmText = null;
nodeSecretRevealState.keepOpenWhileVerifying = false;
nodeSecretRevealState.forceCredential = false;
// Fired on every dismissal path (cancel, close, Escape). A pending step-up
// prompt resolves as cancelled; after a successful confirm the awaiting
// promise is already settled, so this is a harmless no-op there.
if (onCancel) {
try { onCancel(); } catch { }
}
}
async function requestNodeSecret(context, kind, credential) {
// 'custom' flows perform their own guarded request inside customRequest (see
// sendNodeWriteWithStepUp) — there is no fixed endpoint to call here.
if (kind === 'custom') {
const customRequest = nodeSecretRevealState.customRequest;
if (typeof customRequest !== 'function') throw new Error('Nothing to verify.');
return customRequest(credential);
}
const nodeId = await resolveNodeSecretNodeId(context);
if (kind === 'rotate') {
const body = {};
appendStepUpCredentialPayload(body, credential);
const res = await fetch(`/api/nodes/${encodeURIComponent(nodeId)}/rotate-token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
cache: 'no-store'
});
const data = await res.json().catch(() => ({}));
if (data.revokeSecurity) applyGlobalStepUpSecurityFromPayload(data.revokeSecurity);
if (!res.ok) {
if (res.status === 403 && (data.code === '2fa-required' || data.code === 'password-required')) {
configureStepUpCredentialField(nodeSecretCredential, nodeSecretCredentialLabel, nodeSecretCredentialHint);
}
throw new Error(data.error || 'Verification failed');
}
return {
ok: true,
value: '',
rotate: data,
security: data.graceExpiresAt ? { graceExpiresAt: data.graceExpiresAt } : null
};
}
const path = kind === 'config' ? 'config.yml' : 'one-time-command';
const body = {};
appendStepUpCredentialPayload(body, credential);
const res = await fetch(`/api/nodes/${encodeURIComponent(nodeId)}/${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
cache: 'no-store'
});
const data = await res.json().catch(() => ({}));
if (data.revokeSecurity) applyGlobalStepUpSecurityFromPayload(data.revokeSecurity);
if (!res.ok) {
if (res.status === 403 && (data.code === '2fa-required' || data.code === 'password-required')) {
configureStepUpCredentialField(nodeSecretCredential, nodeSecretCredentialLabel, nodeSecretCredentialHint);
}
throw new Error(data.error || 'Verification failed');
}
return {
ok: true,
value: kind === 'config' ? String(data.configYml || '') : String(data.command || ''),
security: data.graceExpiresAt ? { graceExpiresAt: data.graceExpiresAt } : null
};
}
async function resolveNodeSecretNodeId(context) {
if (context === 'nm') {
if (!CURRENT_NODE) throw new Error('Open a node first.');
return String(CURRENT_NODE.id || CURRENT_NODE.uuid || '');
}
if (!createNodeDraftSave?.saved || !createNodeCreatedId) {
throw new Error('Save the current node configuration before revealing credentials.');
}
return String(createNodeCreatedId);
}
async function confirmNodeSecretReveal() {
const { context, kind, action, confirmText, forceCredential, request } = nodeSecretRevealState;
if (!kind || nodeSecretModalConfirm?.disabled || (kind !== 'custom' && !context)) return;
const credential = validateStepUpCredential(nodeSecretCredential, (msg) => setNodeSecretModalError(msg), { force: forceCredential || kind === 'custom' });
if (!credential) return;
if (nodeSecretModalConfirm) {
nodeSecretModalConfirm.disabled = true;
nodeSecretModalConfirm.innerHTML = ' Verifying…';
}
try {
const verified = await requestNodeSecret(context, kind, credential);
if (nodeSecretRevealState.request !== request) return;
if (verified.security) applyGlobalStepUpSecurityFromPayload(verified.security);
nodeSecretRevealState.onCancel = null;
closeNodeSecretModal();
if (kind === 'custom') return;
if (kind === 'rotate') {
// Nothing to reveal: rotation only refreshes node state. The onVerified
// callback re-opens the node (re-locking any revealed config/setup
// surfaces — they embedded the now-retired token) and reports the result.
if (action) {
try { action(verified.rotate); } catch { }
}
return;
}
revealNodeSecretSurface(context, kind, verified.value);
if (action) {
try { action(verified.value); } catch { }
}
} catch (err) {
if (nodeSecretRevealState.request !== request) return;
setNodeSecretModalError(err?.message || 'Verification failed. Please try again.');
if (nodeSecretCredential && !isStepUpGraceActive()) {
nodeSecretCredential.value = '';
try { nodeSecretCredential.focus(); } catch { }
}
} finally {
if (nodeSecretModalConfirm && nodeSecretRevealState.request === request) {
nodeSecretModalConfirm.disabled = false;
const defaultLabel = kind === 'custom' ? 'Confirm & Continue' : (kind === 'rotate' ? 'Verify & Rotate' : 'Verify & Receive');
nodeSecretModalConfirm.textContent = confirmText || defaultLabel;
}
}
}
// Post-rotation refresh: re-open the node so the rotate-required badge and
// warning reflect the new state, wipe any revealed config/setup surfaces
// (they embedded the retired token), refresh the node list, and report the
// outcome in the Linking tab.
async function onNodeTokenRotated(rotate) {
if (CURRENT_NODE) {
const id = CURRENT_NODE.id || CURRENT_NODE.uuid;
if (id) {
try { await openNodeModal(id, true); } catch { }
}
}
try { loadNodes(); } catch { }
const reconfigureRequired = !!(rotate && rotate.reconfigureRequired);
if (reconfigureRequired) {
showNodeRedeployGuidance();
} else {
showCategoryFeedback('node-linking', 'Token rotated — the daemon adopted the new credential automatically.', false);
}
}
function bindNodeSecretTrigger(el, context, kind) { if (!el || el.dataset.nodeSecretBound === 'true') return;
el.dataset.nodeSecretBound = 'true';
const open = (e) => {
if (e && typeof e.preventDefault === 'function') e.preventDefault();
if (e && typeof e.stopPropagation === 'function') e.stopPropagation();
openNodeSecretModal(context, kind);
};
el.addEventListener('click', open);
el.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') open(e);
});
}
bindNodeSecretTrigger(document.getElementById('nm_receiveConfig'), 'nm', 'config');
bindNodeSecretTrigger(document.getElementById('nm_configLock'), 'nm', 'config');
bindNodeSecretTrigger(document.getElementById('cn_receiveConfig'), 'cn', 'config');
bindNodeSecretTrigger(document.getElementById('cn_configLock'), 'cn', 'config');
bindNodeSecretTrigger(document.getElementById('nm_cmdLock'), 'nm', 'command');
bindNodeSecretTrigger(document.getElementById('cn_cmdLock'), 'cn', 'command');
if (nm_rotateToken) nm_rotateToken.addEventListener('click', (e) => {
e.stopPropagation();
if (!CURRENT_NODE) return;
openNodeSecretModal('nm', 'rotate', onNodeTokenRotated);
});
if (nodeSecretModalConfirm) nodeSecretModalConfirm.addEventListener('click', () => { confirmNodeSecretReveal(); });
if (nodeSecretModalCancel) nodeSecretModalCancel.addEventListener('click', closeNodeSecretModal);
if (nodeSecretModalClose) nodeSecretModalClose.addEventListener('click', closeNodeSecretModal);
if (nodeSecretModalOverlay) {
nodeSecretModalOverlay.addEventListener('keydown', (e) => {
if (e.key === 'Escape') closeNodeSecretModal();
if (e.key === 'Enter' && document.activeElement === nodeSecretCredential) confirmNodeSecretReveal();
});
}
if (nodeSecretCredential) bindStepUpCredentialInput(nodeSecretCredential);
function legacyCopyToClipboard(text) {
return new Promise((resolve, reject) => {
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "fixed";
textArea.style.left = "-9999px";
textArea.style.top = "0";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const successful = document.execCommand('copy');
if (successful) resolve();
else reject(new Error('Copy failed'));
} catch (err) {
reject(err);
} finally {
document.body.removeChild(textArea);
}
});
}
function copyToClipboard(text) {
const value = String(text == null ? '' : text);
if (navigator.clipboard && navigator.clipboard.writeText) {
return navigator.clipboard.writeText(value).catch(() => legacyCopyToClipboard(value));
}
return legacyCopyToClipboard(value);
}
if (nm_copyConfig) {
nm_copyConfig.addEventListener('click', () => {
if (!isNodeSecretRevealed('nm', 'config')) return;
copyToClipboard(nm_configYml?.value || '').then(() => {
nm_copyConfig.innerHTML = ' Copied';
setTimeout(() => nm_copyConfig.innerHTML = ' Copy File', 1500);
});
});
}
if (nm_downloadConfig) {
nm_downloadConfig.addEventListener('click', () => {
if (!isNodeSecretRevealed('nm', 'config')) return;
const blob = new Blob([nm_configYml?.value || ''], { type: 'text/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = 'config.yml'; a.click();
URL.revokeObjectURL(url);
});
}
if (nm_showCmd) {
nm_showCmd.addEventListener('click', () => {
if (!CURRENT_NODE) return;
openNodeSecretModal('nm', 'command');
});
}
if (nm_copyCmd) {
nm_copyCmd.addEventListener('click', () => {
const val = (nm_cmd?.value || '').trim();
if (!val || val.startsWith('Click Generate') || val.startsWith('Generating')) return;
copyToClipboard(val).then(() => {
nm_copyCmd.innerHTML = ' Copied';
setTimeout(() => nm_copyCmd.innerHTML = ' Copy Command', 1500);
});
});
}
if (nm_address) {
nm_address.addEventListener('input', updateEditNodeConnectionMode);
}
if (nm_ssl_enabled) {
nm_ssl_enabled.addEventListener('change', () => {
updateNodeConnectionCopy(nm_ssl_enabled, nm_connection_label, nm_connection_help, nm_under_cloudflare);
updateCloudflareToggle(nm_ssl_enabled, nm_under_cloudflare_row, nm_under_cloudflare);
updateEditNodeConnectionMode();
});
}
if (nm_under_cloudflare) {
nm_under_cloudflare.addEventListener('change', () => {
if (nm_under_cloudflare.checked) preferCloudflareDaemonPort(nm_daemon_port);
updateNodeConnectionCopy(nm_ssl_enabled, nm_connection_label, nm_connection_help, nm_under_cloudflare);
});
}
function nodeApiId() {
return CURRENT_NODE ? (CURRENT_NODE.id || CURRENT_NODE.uuid) : '';
}
function formatDiskUsage(disk) {
const used = Number(disk?.usedGb || 0);
const limit = Number(disk?.limitGb || 0);
const usedStr = used >= 0 ? used.toFixed(used >= 10 ? 0 : 1).replace(/\.0$/, '') : '0';
if (limit > 0) {
const pct = Math.min(100, Math.round((used / limit) * 100));
return `${usedStr} / ${limit} GB (${pct}%)`;
}
return `${usedStr} GB used`;
}
function renderNodeDisks(disks) {
if (!nm_disks_list) return;
const list = Array.isArray(disks) ? disks.slice() : [];
list.sort((a, b) => (b.primary ? 1 : 0) - (a.primary ? 1 : 0));
if (nm_disks_count) nm_disks_count.textContent = `${list.length} volume${list.length === 1 ? '' : 's'}`;
if (!list.length) {
nm_disks_list.innerHTML = 'No disks reported.
';
return;
}
nm_disks_list.innerHTML = list.map((d) => {
const isPrimary = !!d.primary || String(d.id) === 'primary';
const mount = escapeHtml(d.mountPath || (isPrimary ? '/var/lib/node' : ''));
const usage = escapeHtml(formatDiskUsage(d));
const badge = isPrimary
? 'Primary '
: '';
const removeBtn = isPrimary
? ''
: ` `;
return `
${mount}
${badge}
${usage}
${removeBtn}
`;
}).join('');
nm_disks_list.querySelectorAll('.node-disk-remove').forEach((btn) => {
btn.addEventListener('click', () => removeNodeDisk(btn.getAttribute('data-disk-id')));
});
}
async function loadNodeDisks() {
if (!nm_disks_list) return;
const request = nodeManageRequest;
const id = nodeApiId();
if (!id) return;
nm_disks_list.innerHTML = 'Loading disks…
';
showCategoryFeedback('node-disks', '');
try {
const res = await fetch(`/api/nodes/${encodeURIComponent(id)}/disks`, { cache: 'no-store' });
const data = await res.json().catch(() => ({}));
if (request !== nodeManageRequest) return;
if (!res.ok) throw new Error(data.error || 'Failed to load disks');
renderNodeDisks(data.disks || []);
} catch (e) {
if (request !== nodeManageRequest) return;
nm_disks_list.innerHTML = '';
showCategoryFeedback('node-disks', e.message || 'Failed to load disks', true);
}
}
async function addNodeDisk() {
const id = nodeApiId();
if (!id) return;
const mountPath = (nm_disk_mount?.value || '').trim();
const limitGb = parseInt(nm_disk_limit?.value || '', 10);
if (!mountPath) { showCategoryFeedback('node-disks', 'Mount path required', true); return; }
if (!Number.isFinite(limitGb) || limitGb <= 0) { showCategoryFeedback('node-disks', 'Limit must be a positive number of GB', true); return; }
try {
if (nm_disk_add) nm_disk_add.disabled = true;
showCategoryFeedback('node-disks', '');
// Disk add changes where server storage lives — node-write class, so it
// rides the shared step-up modal (grace window avoids repeat prompts).
const { res, data } = await sendNodeWriteWithStepUp(
`/api/nodes/${encodeURIComponent(id)}/disks`,
'POST',
{ mountPath, limitGb },
{
subtitle: `Add disk to node`,
reason: 'Adding a disk changes where server storage lives on this node. Verify your identity to continue.',
confirmText: 'Verify & Add Disk',
cancelledMessage: 'Verification cancelled — no disk was added.',
}
);
if (!res.ok) throw new Error(data?.error || 'Failed to add disk');
if (nm_disk_mount) nm_disk_mount.value = '';
if (nm_disk_limit) nm_disk_limit.value = '';
showCategoryFeedback('node-disks', 'Disk added successfully!', false);
await loadNodeDisks();
} catch (e) {
showCategoryFeedback('node-disks', e?.message || 'Failed to add disk', true);
} finally {
if (nm_disk_add) nm_disk_add.disabled = false;
}
}
async function removeNodeDisk(diskId) {
const id = nodeApiId();
if (!id || !diskId) return;
if (!confirm('Remove this disk? It must have no servers assigned.')) return;
try {
showCategoryFeedback('node-disks', '');
const { res, data } = await sendNodeWriteWithStepUp(
`/api/nodes/${encodeURIComponent(id)}/disks/${encodeURIComponent(diskId)}`,
'DELETE',
{},
{
subtitle: 'Remove disk from node',
reason: 'Removing a disk deletes this node\'s storage configuration for it. Verify your identity to continue.',
confirmText: 'Verify & Remove Disk',
cancelledMessage: 'Verification cancelled — no disk was removed.',
}
);
if (!res.ok) throw new Error(data?.error || 'Failed to remove disk');
showCategoryFeedback('node-disks', 'Disk removed successfully!', false);
await loadNodeDisks();
} catch (e) {
showCategoryFeedback('node-disks', e?.message || 'Failed to remove disk', true);
}
}
if (nm_disk_add) nm_disk_add.addEventListener('click', addNodeDisk);
async function saveNodeCategory(cat) {
const node = CURRENT_NODE;
if (!node) return;
const request = nodeManageRequest;
const btnMap = {
'node-config': nm_save_config_btn,
'node-resources': nm_save_resources_btn
};
const btn = btnMap[cat];
const origHtml = btn ? btn.innerHTML : '';
showCategoryFeedback(cat, '');
try {
if (btn) { btn.disabled = true; btn.innerHTML = ' Saving…'; }
const name = nm_name ? nm_name.value.trim() : CURRENT_NODE.name;
const address = nm_address ? nm_address.value.trim() : CURRENT_NODE.address;
const cpu_cores = nm_cpu_cores ? parseInt(nm_cpu_cores.value, 10) : (CURRENT_NODE.cpu_cores || 0);
const ram_gb = nm_ram_gb ? parseInt(nm_ram_gb.value, 10) : (Number(CURRENT_NODE.ram_mb || 0) / 1024 | 0);
const disk_gb = nm_disk_gb ? parseInt(nm_disk_gb.value, 10) : Number(CURRENT_NODE.disk_gb || 0);
let payload;
if (cat === 'node-config') {
if (!name) throw new Error('Name required');
if (!address) throw new Error('Address required');
const additional_ips = getAdditionalIpsFromContainer(nm_additional_ips_container, 'nm');
const max_upload_mb = parseInt(nm_max_upload_mb?.value || '10240', 10);
if (!Number.isFinite(max_upload_mb) || max_upload_mb < 1 || max_upload_mb > 100000) throw new Error('Upload limit must be between 1 and 100000 MB');
const api_port = parseInt(nm_daemon_port?.value || '8080', 10);
if (!Number.isFinite(api_port) || api_port < 1 || api_port > 65535) throw new Error('Daemon port must be between 1 and 65535');
const ssl_enabled = !!(nm_ssl_enabled?.checked ?? node.ssl_enabled);
const under_cloudflare = !!(ssl_enabled && nm_under_cloudflare?.checked && canUseHttpsForNodeAddress(address));
if (under_cloudflare && !isCloudflareHttpsPort(api_port)) {
throw new Error('Under Cloudflare requires daemon port 443, 2053, 2083, 2087, 2096, or 8443');
}
payload = { name, address, additional_ips, max_upload_mb, api_port, ssl_enabled, under_cloudflare };
} else if (cat === 'node-resources') {
if (!Number.isFinite(cpu_cores) || cpu_cores < 1) throw new Error('Invalid CPU cores (min 1)');
if (!Number.isFinite(ram_gb) || ram_gb < 1) throw new Error('Invalid RAM limit');
if (ram_gb > 2097151) throw new Error('Invalid RAM limit (must not exceed 2097151 GB)');
if (!Number.isFinite(disk_gb) || disk_gb < 10) throw new Error('Invalid Disk size (min 10 GB)');
if (disk_gb > 2147483647) throw new Error('Invalid Disk size (must not exceed 2147483647 GB)');
payload = { cpu_cores, ram_mb: ram_gb * 1024, disk_gb };
} else {
if (!name) throw new Error('Name required');
if (!address) throw new Error('Address required');
if (!Number.isFinite(cpu_cores) || cpu_cores < 1) throw new Error('Invalid CPU cores (min 1)');
if (!Number.isFinite(ram_gb) || ram_gb < 1) throw new Error('Invalid RAM limit');
if (ram_gb > 2097151) throw new Error('Invalid RAM limit (must not exceed 2097151 GB)');
if (!Number.isFinite(disk_gb) || disk_gb < 10) throw new Error('Invalid Disk size (min 10 GB)');
if (disk_gb > 2147483647) throw new Error('Invalid Disk size (must not exceed 2147483647 GB)');
payload = { name, address, cpu_cores, ram_mb: ram_gb * 1024, disk_gb };
}
const { res, data } = await sendNodeWriteWithStepUp(`/api/nodes/${encodeURIComponent(node.id || node.uuid)}`, 'PATCH', payload, {
subtitle: 'Verify your identity to save node changes',
reason: 'Saving can change where the panel connects to this node. Step-up verification confirms this action was requested by you.',
cancelledMessage: 'Verification cancelled — nothing was saved.'
});
if (request !== nodeManageRequest) return;
if (!res.ok) throw new Error([data.error || 'Failed to save', data.detail || ''].filter(Boolean).join('\n'));
const saved = CURRENT_NODE = Object.assign({}, node, data);
if (cat === 'node-config') populateNodePortsIpDropdown(saved);
await loadNodeInUsePorts(saved);
if (CURRENT_NODE !== saved) return;
if (nodeManageTitle) nodeManageTitle.textContent = CURRENT_NODE.name || 'Node';
if (nodeManageSubtitle) {
nodeManageSubtitle.textContent = `${CURRENT_NODE.address || '0.0.0.0'} • ${Number(CURRENT_NODE.cpu_cores || 0)} cores • ${(Number(CURRENT_NODE.ram_mb || 0) / 1024 | 0)} GB RAM`;
}
showCategoryFeedback(cat, 'Saved successfully!', false);
await refreshRevealedNodeSecret('nm', 'config');
await loadNodes();
} catch (e) {
if (request === nodeManageRequest) showCategoryFeedback(cat, e.message || 'Error saving node', true);
} finally {
if (btn) { btn.disabled = false; btn.innerHTML = origHtml; }
}
}
if (nm_save_config_btn) nm_save_config_btn.addEventListener('click', () => saveNodeCategory('node-config'));
if (nm_save_resources_btn) nm_save_resources_btn.addEventListener('click', () => saveNodeCategory('node-resources'));
function revealNodeDeleteSecurityField() {
if (nm_delete_security_divider) nm_delete_security_divider.style.display = 'block';
if (nm_delete_security_row) nm_delete_security_row.style.display = 'flex';
configureStepUpCredentialField(nm_deleteCredential, nm_deleteCredentialLabel, nm_deleteCredentialHint);
bindStepUpCredentialInput(nm_deleteCredential);
if (nm_deleteCredential) {
nm_deleteCredential.focus();
triggerAutoResizeInputs();
}
}
async function executeNodeDeletion(credentialValue = '') {
if (!CURRENT_NODE) return;
try {
if (nm_delete) nm_delete.disabled = true;
if (nm_delete_confirm_btn) {
nm_delete_confirm_btn.disabled = true;
nm_delete_confirm_btn.innerHTML = ' Deleting…';
}
showCategoryFeedback('node-danger', '');
const payload = {};
if (credentialValue) {
appendStepUpCredentialPayload(payload, credentialValue);
}
const res = await fetch(`/api/nodes/${encodeURIComponent(CURRENT_NODE.id || CURRENT_NODE.uuid)}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const data = await res.json().catch(() => ({}));
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (!res.ok) {
const code = String(data.code || '').toLowerCase();
const err = String(data.error || '');
const isSecurityRequired = res.status === 403 && (code.includes('2fa') || code.includes('password') || err.toLowerCase().includes('2fa') || err.toLowerCase().includes('password') || err.toLowerCase().includes('code'));
if (isSecurityRequired) {
revealNodeDeleteSecurityField();
showCategoryFeedback('node-danger', err || 'Security verification code is required', true);
return;
}
throw new Error(err || 'Failed to delete node');
}
showCategoryFeedback('node-danger', 'Node deleted successfully!', false);
resetNodeDangerZone();
setTimeout(() => {
showNodeManageView(false);
loadNodes();
}, 700);
} catch (e) {
showCategoryFeedback('node-danger', e.message || 'Error deleting node', true);
} finally {
if (nm_delete) nm_delete.disabled = false;
if (nm_delete_confirm_btn) {
nm_delete_confirm_btn.disabled = false;
nm_delete_confirm_btn.innerHTML = ' Confirm Deletion';
}
}
}
if (nm_delete) {
nm_delete.addEventListener('click', async () => {
if (!CURRENT_NODE) return;
const isSecurityVisible = nm_delete_security_row && nm_delete_security_row.style.display !== 'none';
if (isSecurityVisible) {
const cred = validateStepUpCredential(nm_deleteCredential, (msg, isErr) => {
showCategoryFeedback('node-danger', msg || '', isErr);
});
if (!cred) {
nm_deleteCredential?.focus();
return;
}
const ok = confirm(`Delete node "${CURRENT_NODE.name}"? This action is permanent.`);
if (!ok) return;
return executeNodeDeletion(cred);
}
const hasActiveGrace = isStepUpGraceActive();
const has2FA = !!(stepUpSecurityState?.twoFactorEnabled ?? currentUserHas2FA);
if (!hasActiveGrace) {
revealNodeDeleteSecurityField();
showCategoryFeedback('node-danger', '');
return;
}
const ok = confirm(`Delete node "${CURRENT_NODE.name}"? This action is permanent.`);
if (!ok) return;
executeNodeDeletion('');
});
}
if (nm_delete_confirm_btn) {
nm_delete_confirm_btn.addEventListener('click', async () => {
if (!CURRENT_NODE) return;
const cred = validateStepUpCredential(nm_deleteCredential, (msg, isErr) => {
showCategoryFeedback('node-danger', msg || '', isErr);
});
if (!cred) {
nm_deleteCredential?.focus();
return;
}
const ok = confirm(`Delete node "${CURRENT_NODE.name}"? This action is permanent.`);
if (!ok) return;
executeNodeDeletion(cred);
});
}
if (nm_deleteCredential) {
nm_deleteCredential.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
if (nm_delete_confirm_btn && nm_delete_security_row && nm_delete_security_row.style.display !== 'none') {
nm_delete_confirm_btn.click();
} else if (nm_delete) {
nm_delete.click();
}
}
});
}
document.querySelectorAll('.toggle-pass').forEach(btn => {
const input = btn.parentElement.querySelector('input');
const icon = btn.querySelector('i');
btn.addEventListener('click', () => {
const isPassword = input.type === 'password';
input.type = isPassword ? 'text' : 'password';
icon.classList.toggle('fa-eye', !isPassword);
icon.classList.toggle('fa-eye-slash', isPassword);
});
});
(function () {
const rateLimiterCard = document.getElementById('rateLimiterCard');
const rateLimiterToggle = document.getElementById('rateLimiterToggle');
const rateLimiterDetails = document.getElementById('rateLimiterDetails');
const rateLimiterLimit = document.getElementById('rateLimiterLimit');
const rateLimiterWindow = document.getElementById('rateLimiterWindow');
const rateLimiterSave = document.getElementById('rateLimiterSave');
const rateLimiterFeedback = document.getElementById('rateLimiterFeedback');
const rateLimiterSummary = document.getElementById('rateLimiterSummary');
const rateLimiterCredentialInput = document.getElementById('rateLimiterCredentialInput');
const rateLimiterCredentialLabel = document.getElementById('rateLimiterCredentialLabel');
const rateLimiterCredentialHint = document.getElementById('rateLimiterCredentialHint');
if (!rateLimiterCard) return;
const rateLimiterSwitchLabel = rateLimiterCard.querySelector('.switch');
if (rateLimiterSwitchLabel) {
rateLimiterSwitchLabel.addEventListener('click', (e) => e.stopPropagation());
}
let detailsOpen = false;
function updateSummary() {
const limit = parseInt(rateLimiterLimit.value, 10) || 5;
const window = parseInt(rateLimiterWindow.value, 10) || 120;
rateLimiterSummary.textContent = `${limit} requests per ${window} seconds`;
}
function showFeedback(msg, isError = false) {
rateLimiterFeedback.textContent = msg;
rateLimiterFeedback.style.color = isError ? '#ef4444' : '#22c55e';
setTimeout(() => { rateLimiterFeedback.textContent = ''; }, 3000);
}
let securityActionTokens = {};
// adpanel:settings-token-registry — loadSecuritySettings() reassigns this
// binding on every fetch, so the refresher writes through a live view.
registerSettingsActionTokenRegistry(createSettingsActionTokenView(() => securityActionTokens));
async function loadSecuritySettings() {
try {
const res = await fetch('/api/settings/security');
if (!res.ok) return;
const data = await res.json();
rateLimiterToggle.checked = !!data.rate_limiting;
rateLimiterLimit.value = data.limit || 5;
rateLimiterWindow.value = data.window_seconds || 120;
securityActionTokens = data.actionTokens || {};
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
configureStepUpCredentialField(rateLimiterCredentialInput, rateLimiterCredentialLabel, rateLimiterCredentialHint);
bindStepUpCredentialInput(rateLimiterCredentialInput);
updateSummary();
} catch (e) {
console.error('Failed to load security settings:', e);
}
}
async function saveSecuritySettings() {
const rate_limiting = rateLimiterToggle.checked;
const limit = parseInt(rateLimiterLimit.value, 10);
const window_seconds = parseInt(rateLimiterWindow.value, 10);
if (!limit || limit < 1 || limit > 10000) {
showFeedback('Limit must be between 1 and 10000', true);
return;
}
if (!window_seconds || window_seconds < 1 || window_seconds > 86400) {
showFeedback('Window must be between 1 and 86400 seconds', true);
return;
}
// Changing the rate limiter (disabling it, loosening its bounds) weakens
// the panel's brute-force defense, so the server requires a step-up
// credential. Reveal the credential field and stop before sending when it
// is still empty — the request would only be rejected.
configureStepUpCredentialField(rateLimiterCredentialInput, rateLimiterCredentialLabel, rateLimiterCredentialHint);
const credential = validateStepUpCredential(rateLimiterCredentialInput, (msg, isErr) => {
showFeedback(msg, isErr);
});
if (!credential) {
detailsOpen = true;
rateLimiterDetails.style.display = 'block';
rateLimiterCredentialInput?.focus();
return;
}
rateLimiterSave.disabled = true;
try {
const body = { rate_limiting, limit, window_seconds };
appendStepUpCredentialPayload(body, credential);
const res = await fetch('/api/settings/security', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': securityActionTokens.updateSecurity || ''
},
body: JSON.stringify(body)
});
const data = await res.json();
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (!res.ok) {
showFeedback(data.error || 'Failed to save', true);
// Re-sync the toggle with the server state (the save did not apply).
await loadSecuritySettings();
} else {
showFeedback('Settings saved successfully!');
if (rateLimiterCredentialInput) rateLimiterCredentialInput.value = '';
await loadSecuritySettings();
}
} catch (e) {
showFeedback('Network error', true);
} finally {
rateLimiterSave.disabled = false;
}
}
rateLimiterCard.addEventListener('click', (e) => {
if (e.target.closest('.switch') || e.target.closest('input') || e.target.closest('button')) return;
detailsOpen = !detailsOpen;
rateLimiterDetails.style.display = detailsOpen ? 'block' : 'none';
});
rateLimiterToggle.addEventListener('change', async () => {
await saveSecuritySettings();
});
rateLimiterLimit.addEventListener('input', updateSummary);
rateLimiterWindow.addEventListener('input', updateSummary);
rateLimiterSave.addEventListener('click', (e) => {
e.stopPropagation();
saveSecuritySettings();
});
[rateLimiterLimit, rateLimiterWindow].forEach(el => {
el.addEventListener('click', (e) => e.stopPropagation());
});
loadSecuritySettings();
document.querySelector('button[data-panel="security"]')?.addEventListener('click', loadSecuritySettings);
})();
(function () {
const captchaCard = document.getElementById('captchaCard');
if (!captchaCard) return;
const captchaToggle = document.getElementById('captchaToggle');
const captchaDetails = document.getElementById('captchaDetails');
const captchaModalOverlay = document.getElementById('captchaModalOverlay');
const captchaModal = document.getElementById('captchaModal');
const captchaSiteKey = document.getElementById('captchaSiteKey');
const captchaSecretKey = document.getElementById('captchaSecretKey');
const captchaSecretToggle = document.getElementById('captchaSecretToggle');
const captchaModalClose = document.getElementById('captchaModalClose');
const captchaModalCancel = document.getElementById('captchaModalCancel');
const captchaModalSave = document.getElementById('captchaModalSave');
const captchaModalFeedback = document.getElementById('captchaModalFeedback');
const captchaCredentialInput = document.getElementById('captchaCredentialInput');
const captchaCredentialLabel = document.getElementById('captchaCredentialLabel');
const captchaCredentialHint = document.getElementById('captchaCredentialHint');
const captchaDisableModalOverlay = document.getElementById('captchaDisableModalOverlay');
const captchaDisableModal = document.getElementById('captchaDisableModal');
const captchaDisableModalClose = document.getElementById('captchaDisableModalClose');
const captchaDisableModalCancel = document.getElementById('captchaDisableModalCancel');
const captchaDisableModalConfirm = document.getElementById('captchaDisableModalConfirm');
const captchaDisableModalFeedback = document.getElementById('captchaDisableModalFeedback');
const captchaDisableCredentialInput = document.getElementById('captchaDisableCredentialInput');
const captchaDisableCredentialLabel = document.getElementById('captchaDisableCredentialLabel');
const captchaDisableCredentialHint = document.getElementById('captchaDisableCredentialHint');
const captchaSwitchLabel = captchaCard.querySelector('.switch');
if (captchaSwitchLabel) {
captchaSwitchLabel.addEventListener('click', (e) => e.stopPropagation());
}
let captchaEnabled = false;
let isLoading = false;
let detailsOpen = false;
let pendingToggleState = null;
function showFeedback(msg, isError = false) {
if (!captchaModalFeedback) return;
captchaModalFeedback.textContent = msg;
captchaModalFeedback.style.color = isError ? '#ef4444' : '#22c55e';
if (msg) {
setTimeout(() => {
if (captchaModalFeedback) captchaModalFeedback.textContent = '';
}, 4000);
}
}
function openModal() {
if (!captchaModalOverlay || !captchaModal) return;
captchaSiteKey.value = '';
captchaSecretKey.value = '';
captchaSecretKey.type = 'password';
if (captchaSecretToggle) {
const icon = captchaSecretToggle.querySelector('i');
if (icon) icon.className = 'fa-solid fa-eye';
}
configureStepUpCredentialField(captchaCredentialInput, captchaCredentialLabel, captchaCredentialHint);
bindStepUpCredentialInput(captchaCredentialInput);
if (captchaCredentialInput) captchaCredentialInput.value = '';
showFeedback('');
captchaModalOverlay.setAttribute('aria-hidden', 'false');
captchaModalOverlay.style.display = 'flex';
captchaModalOverlay.classList.add('show');
void captchaModal.offsetWidth;
captchaModal.classList.add('show');
setTimeout(() => captchaSiteKey.focus(), 100);
}
document.addEventListener(ASSISTANT_SETTINGS_ACTION_EVENT, (event) => {
if (event?.detail?.action === 'captcha') {
openModal();
}
});
function closeModal(revertToggle = false) {
if (!captchaModalOverlay) return;
const focusTarget = captchaToggle || document.body;
focusTarget.focus();
setTimeout(() => {
captchaModalOverlay.setAttribute('aria-hidden', 'true');
captchaModalOverlay.classList.remove('show');
if (captchaModal) captchaModal.classList.remove('show');
captchaModalOverlay.style.display = 'none';
}, 10);
if (captchaCredentialInput) captchaCredentialInput.value = '';
if (revertToggle && pendingToggleState !== null) {
captchaToggle.checked = !pendingToggleState;
}
pendingToggleState = null;
}
function openDisableModal() {
if (!captchaDisableModalOverlay || !captchaDisableModal) return;
configureStepUpCredentialField(captchaDisableCredentialInput, captchaDisableCredentialLabel, captchaDisableCredentialHint);
bindStepUpCredentialInput(captchaDisableCredentialInput);
if (captchaDisableCredentialInput) captchaDisableCredentialInput.value = '';
if (captchaDisableModalFeedback) captchaDisableModalFeedback.textContent = '';
captchaDisableModalOverlay.setAttribute('aria-hidden', 'false');
captchaDisableModalOverlay.style.display = 'flex';
captchaDisableModalOverlay.classList.add('show');
void captchaDisableModal.offsetWidth;
captchaDisableModal.classList.add('show');
setTimeout(() => captchaDisableCredentialInput?.focus(), 100);
}
function closeDisableModal(revertToggle = false) {
if (!captchaDisableModalOverlay) return;
captchaDisableModalOverlay.setAttribute('aria-hidden', 'true');
captchaDisableModalOverlay.classList.remove('show');
if (captchaDisableModal) captchaDisableModal.classList.remove('show');
captchaDisableModalOverlay.style.display = 'none';
if (captchaDisableCredentialInput) captchaDisableCredentialInput.value = '';
if (revertToggle && pendingToggleState !== null) {
captchaToggle.checked = !pendingToggleState;
}
pendingToggleState = null;
}
function showDisableFeedback(msg, isError = false) {
if (!captchaDisableModalFeedback) return;
captchaDisableModalFeedback.textContent = msg;
captchaDisableModalFeedback.style.color = isError ? '#ef4444' : '#22c55e';
if (msg) {
setTimeout(() => {
if (captchaDisableModalFeedback) captchaDisableModalFeedback.textContent = '';
}, 4000);
}
}
function updateUI() {
if (captchaToggle) captchaToggle.checked = captchaEnabled;
if (captchaDetails) captchaDetails.style.display = captchaEnabled ? 'block' : 'none';
}
async function loadCaptchaStatus() {
if (isLoading) return;
isLoading = true;
try {
const res = await fetch('/api/settings/security');
if (!res.ok) return;
const data = await res.json();
captchaEnabled = !!data.captcha_enabled;
if (data.actionTokens) securityActionTokens = data.actionTokens;
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
configureStepUpCredentialField(captchaCredentialInput, captchaCredentialLabel, captchaCredentialHint);
configureStepUpCredentialField(captchaDisableCredentialInput, captchaDisableCredentialLabel, captchaDisableCredentialHint);
updateUI();
} catch (e) {
console.error('Failed to load captcha status:', e);
} finally {
isLoading = false;
}
}
captchaToggle.addEventListener('change', async () => {
const newState = captchaToggle.checked;
pendingToggleState = newState;
if (newState) {
openModal();
} else {
// Disabling wipes the configured keys and strips the login page's bot
// protection, so it now goes through a confirmation modal that also
// collects the step-up credential the server requires.
openDisableModal();
}
});
captchaCard.addEventListener('click', (e) => {
if (e.target.closest('.switch') || e.target.closest('input') || e.target.closest('button')) return;
if (!captchaEnabled) return;
detailsOpen = !detailsOpen;
if (captchaDetails) captchaDetails.style.display = detailsOpen ? 'block' : 'none';
});
captchaModalCancel.addEventListener('click', () => closeModal(true));
if (captchaModalClose) captchaModalClose.addEventListener('click', () => closeModal(true));
captchaModalOverlay.addEventListener('click', (e) => {
if (e.target === captchaModalOverlay) closeModal(true);
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && captchaModalOverlay.style.display === 'flex') {
closeModal(true);
}
});
if (captchaDisableModalCancel) captchaDisableModalCancel.addEventListener('click', () => closeDisableModal(true));
if (captchaDisableModalClose) captchaDisableModalClose.addEventListener('click', () => closeDisableModal(true));
if (captchaDisableModalOverlay) {
captchaDisableModalOverlay.addEventListener('click', (e) => {
if (e.target === captchaDisableModalOverlay) closeDisableModal(true);
});
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && captchaDisableModalOverlay && captchaDisableModalOverlay.style.display === 'flex') {
closeDisableModal(true);
}
});
if (captchaDisableModalConfirm) {
captchaDisableModalConfirm.addEventListener('click', async () => {
configureStepUpCredentialField(captchaDisableCredentialInput, captchaDisableCredentialLabel, captchaDisableCredentialHint);
const credential = validateStepUpCredential(captchaDisableCredentialInput, showDisableFeedback);
if (!credential) return;
captchaDisableModalConfirm.disabled = true;
showDisableFeedback('Disabling captcha...');
try {
const body = { enabled: false };
appendStepUpCredentialPayload(body, credential);
const res = await fetch('/api/settings/captcha', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': securityActionTokens.updateCaptcha || ''
},
body: JSON.stringify(body)
});
const data = await res.json();
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (!res.ok) {
showDisableFeedback(data.error || 'Failed to disable captcha', true);
} else {
captchaEnabled = false;
closeDisableModal(false);
updateUI();
await loadCaptchaStatus();
}
} catch (e) {
showDisableFeedback('Network error', true);
} finally {
captchaDisableModalConfirm.disabled = false;
}
});
}
if (captchaSecretToggle) {
captchaSecretToggle.addEventListener('click', () => {
const isPassword = captchaSecretKey.type === 'password';
captchaSecretKey.type = isPassword ? 'text' : 'password';
const icon = captchaSecretToggle.querySelector('i');
if (icon) icon.className = isPassword ? 'fa-solid fa-eye-slash' : 'fa-solid fa-eye';
});
}
captchaModalSave.addEventListener('click', async () => {
const siteKey = captchaSiteKey.value.trim();
const secretKey = captchaSecretKey.value.trim();
if (!siteKey) {
showFeedback('Please enter your Site Key', true);
captchaSiteKey.focus();
return;
}
if (siteKey.length < 10) {
showFeedback('Site Key appears to be invalid (too short)', true);
captchaSiteKey.focus();
return;
}
if (!secretKey) {
showFeedback('Please enter your Secret Key', true);
captchaSecretKey.focus();
return;
}
if (secretKey.length < 10) {
showFeedback('Secret Key appears to be invalid (too short)', true);
captchaSecretKey.focus();
return;
}
// Saving the keys requires a step-up credential on the server (a key
// replacement swaps login verification to operator-chosen key material).
configureStepUpCredentialField(captchaCredentialInput, captchaCredentialLabel, captchaCredentialHint);
const credential = validateStepUpCredential(captchaCredentialInput, showFeedback);
if (!credential) return;
captchaModalSave.disabled = true;
showFeedback('Saving...');
try {
const body = { site_key: siteKey, secret_key: secretKey, enabled: true };
appendStepUpCredentialPayload(body, credential);
const res = await fetch('/api/settings/captcha', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': securityActionTokens.updateCaptcha || ''
},
body: JSON.stringify(body)
});
const data = await res.json();
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (!res.ok) {
showFeedback(data.error || 'Failed to save', true);
} else {
captchaEnabled = true;
updateUI();
closeModal(false);
await loadCaptchaStatus();
}
} catch (e) {
showFeedback('Network error', true);
} finally {
captchaModalSave.disabled = false;
}
});
const securityBtn = document.querySelector('button[data-panel="security"]');
if (securityBtn) {
securityBtn.addEventListener('click', loadCaptchaStatus);
}
const securityPanel = document.getElementById('security');
if (securityPanel && securityPanel.classList.contains('active')) {
loadCaptchaStatus();
}
})();
(function () {
const maintenanceCard = document.getElementById('maintenanceCard');
if (!maintenanceCard) return;
const maintenanceToggle = document.getElementById('maintenanceToggle');
const maintenanceDetails = document.getElementById('maintenanceDetails');
const maintenanceActiveBox = document.getElementById('maintenanceActiveBox');
const maintenanceActiveText = document.getElementById('maintenanceActiveText');
const maintenanceScheduledBox = document.getElementById('maintenanceScheduledBox');
const maintenanceScheduledText = document.getElementById('maintenanceScheduledText');
const maintenanceModalOverlay = document.getElementById('maintenanceModalOverlay');
const maintenanceModal = document.getElementById('maintenanceModal');
const maintenanceModalClose = document.getElementById('maintenanceModalClose');
const maintenanceModalCancel = document.getElementById('maintenanceModalCancel');
const maintenanceModalSave = document.getElementById('maintenanceModalSave');
const maintenanceModalFeedback = document.getElementById('maintenanceModalFeedback');
const maintenanceImmediate = document.getElementById('maintenanceImmediate');
const maintenanceScheduledRadio = document.getElementById('maintenanceScheduled');
const maintenanceScheduleGroup = document.getElementById('maintenanceScheduleGroup');
const maintenanceScheduleInput = document.getElementById('maintenanceScheduleInput');
const maintenanceReasonInput = document.getElementById('maintenanceReasonInput');
const maintenancePreAlertToggle = document.getElementById('maintenancePreAlertToggle');
const maintenancePreAlertGroup = document.getElementById('maintenancePreAlertGroup');
const maintenancePreAlertMessage = document.getElementById('maintenancePreAlertMessage');
const maintenancePreAlertMinutes = document.getElementById('maintenancePreAlertMinutes');
const maintenanceCredentialInput = document.getElementById('maintenanceCredentialInput');
const maintenanceCredentialLabel = document.getElementById('maintenanceCredentialLabel');
const maintenanceCredentialHint = document.getElementById('maintenanceCredentialHint');
const maintenanceSwitchLabel = maintenanceCard.querySelector('.switch');
if (maintenanceSwitchLabel) {
maintenanceSwitchLabel.addEventListener('click', (e) => e.stopPropagation());
}
let maintenanceActionTokens = {};
// adpanel:settings-token-registry — loadMaintenanceState() reassigns this
// binding on every fetch, so the refresher writes through a live view.
registerSettingsActionTokenRegistry(createSettingsActionTokenView(() => maintenanceActionTokens));
let detailsOpen = false;
let currentState = {};
let pendingToggleState = null;
function showFeedback(msg, isError = false) {
if (!maintenanceModalFeedback) return;
maintenanceModalFeedback.textContent = msg;
maintenanceModalFeedback.style.color = isError ? '#ef4444' : '#22c55e';
if (msg) {
setTimeout(() => {
if (maintenanceModalFeedback) maintenanceModalFeedback.textContent = '';
}, 4000);
}
}
function formatDateTime(isoString) {
if (!isoString) return '';
const d = new Date(isoString);
return d.toLocaleString(undefined, {
year: 'numeric', month: 'short', day: 'numeric',
hour: '2-digit', minute: '2-digit'
});
}
function updateUI() {
const isActive = currentState.is_active || currentState.enabled;
const isScheduled = !isActive && !!currentState.scheduled_at;
maintenanceToggle.checked = isActive || isScheduled;
if (isActive) {
maintenanceActiveBox.style.display = 'flex';
const enabledBy = currentState.enabled_by || 'admin';
const enabledAt = currentState.enabled_at ? formatDateTime(currentState.enabled_at) : '';
maintenanceActiveText.textContent = 'Maintenance mode is active' + (enabledAt ? ' — enabled ' + enabledAt : '') + (enabledBy ? ' by ' + enabledBy : '');
maintenanceDetails.style.display = 'block';
detailsOpen = true;
} else {
maintenanceActiveBox.style.display = 'none';
}
if (isScheduled) {
maintenanceScheduledBox.style.display = 'flex';
maintenanceScheduledText.textContent = 'Scheduled for ' + formatDateTime(currentState.scheduled_at);
maintenanceDetails.style.display = 'block';
detailsOpen = true;
} else {
maintenanceScheduledBox.style.display = 'none';
}
if (!isActive && !isScheduled) {
maintenanceDetails.style.display = detailsOpen ? 'block' : 'none';
}
}
function openModal() {
if (!maintenanceModalOverlay || !maintenanceModal) return;
maintenanceImmediate.checked = true;
maintenanceScheduleGroup.style.display = 'none';
maintenanceScheduleInput.value = '';
maintenanceReasonInput.value = '';
maintenancePreAlertToggle.checked = false;
maintenancePreAlertGroup.style.display = 'none';
maintenancePreAlertMessage.value = '';
maintenancePreAlertMinutes.value = '30';
configureStepUpCredentialField(maintenanceCredentialInput, maintenanceCredentialLabel, maintenanceCredentialHint);
bindStepUpCredentialInput(maintenanceCredentialInput);
if (maintenanceCredentialInput) maintenanceCredentialInput.value = '';
maintenanceModalSave.innerHTML = ' Enable Maintenance';
showFeedback('');
const now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
maintenanceScheduleInput.min = now.toISOString().slice(0, 16);
maintenanceModalOverlay.classList.add('show');
maintenanceModal.classList.add('show');
}
document.addEventListener(ASSISTANT_SETTINGS_ACTION_EVENT, (event) => {
if (event?.detail?.action === 'maintenance') {
openModal();
}
});
function closeModal(revertToggle = false) {
if (!maintenanceModalOverlay) return;
maintenanceModalOverlay.classList.remove('show');
if (maintenanceModal) maintenanceModal.classList.remove('show');
if (revertToggle && pendingToggleState !== null) {
maintenanceToggle.checked = !pendingToggleState;
}
if (maintenanceCredentialInput) maintenanceCredentialInput.value = '';
pendingToggleState = null;
}
async function loadMaintenanceState() {
try {
const res = await fetch('/api/settings/maintenance');
if (!res.ok) return;
const data = await res.json();
currentState = data;
maintenanceActionTokens = data.actionTokens || {};
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
updateUI();
} catch (e) {
console.error('Failed to load maintenance state:', e);
}
}
maintenanceImmediate.addEventListener('change', () => {
maintenanceScheduleGroup.style.display = 'none';
maintenanceModalSave.innerHTML = ' Enable Maintenance';
});
maintenanceScheduledRadio.addEventListener('change', () => {
maintenanceScheduleGroup.style.display = 'block';
maintenanceModalSave.innerHTML = ' Schedule Maintenance';
});
maintenancePreAlertToggle.addEventListener('change', () => {
maintenancePreAlertGroup.style.display = maintenancePreAlertToggle.checked ? 'block' : 'none';
});
maintenanceToggle.addEventListener('change', async () => {
const newState = maintenanceToggle.checked;
pendingToggleState = newState;
if (newState) {
openModal();
} else {
if (!confirm('Are you sure you want to disable maintenance mode? All users will regain access immediately.')) {
maintenanceToggle.checked = true;
pendingToggleState = null;
return;
}
try {
const res = await fetch('/api/settings/maintenance', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'x-action-token': maintenanceActionTokens.disableMaintenance || ''
}
});
const data = await res.json();
if (!res.ok) {
alert(data.error || 'Failed to disable maintenance mode');
maintenanceToggle.checked = true;
} else {
await loadMaintenanceState();
}
} catch (e) {
alert('Network error');
maintenanceToggle.checked = true;
}
pendingToggleState = null;
}
});
maintenanceCard.addEventListener('click', (e) => {
if (e.target.closest('.switch') || e.target.closest('input') || e.target.closest('button')) return;
detailsOpen = !detailsOpen;
if (maintenanceDetails) maintenanceDetails.style.display = detailsOpen ? 'block' : 'none';
});
maintenanceModalCancel.addEventListener('click', () => closeModal(true));
if (maintenanceModalClose) maintenanceModalClose.addEventListener('click', () => closeModal(true));
maintenanceModalOverlay.addEventListener('click', (e) => {
if (e.target === maintenanceModalOverlay) closeModal(true);
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && maintenanceModalOverlay.classList.contains('show')) {
closeModal(true);
}
});
maintenanceModalSave.addEventListener('click', async () => {
const isImmediate = maintenanceImmediate.checked;
const reason = maintenanceReasonInput.value.trim();
const preAlertShow = maintenancePreAlertToggle.checked;
const preAlertMessage = maintenancePreAlertMessage.value.trim();
const preAlertMinutes = parseInt(maintenancePreAlertMinutes.value, 10);
if (!isImmediate) {
if (!maintenanceScheduleInput.value) {
showFeedback('Please select a date and time for the scheduled maintenance', true);
return;
}
const scheduledTime = new Date(maintenanceScheduleInput.value).getTime();
if (isNaN(scheduledTime) || scheduledTime <= Date.now()) {
showFeedback('Scheduled time must be in the future', true);
return;
}
}
if (preAlertShow) {
if (!preAlertMessage) {
showFeedback('Please enter an alert message', true);
maintenancePreAlertMessage.focus();
return;
}
if (!preAlertMinutes || preAlertMinutes < 1) {
showFeedback('Please enter a valid number of minutes', true);
maintenancePreAlertMinutes.focus();
return;
}
if (!isImmediate) {
const scheduledTime = new Date(maintenanceScheduleInput.value).getTime();
const alertTime = scheduledTime - (preAlertMinutes * 60 * 1000);
if (alertTime <= Date.now()) {
showFeedback('The alert time (scheduled time minus minutes) is already in the past', true);
return;
}
}
}
configureStepUpCredentialField(maintenanceCredentialInput, maintenanceCredentialLabel, maintenanceCredentialHint);
const credential = validateStepUpCredential(maintenanceCredentialInput, showFeedback);
if (!credential) return;
maintenanceModalSave.disabled = true;
showFeedback('Enabling maintenance mode...');
try {
const body = {
immediate: isImmediate,
reason: reason || null,
scheduled_at: !isImmediate ? new Date(maintenanceScheduleInput.value).toISOString() : null,
pre_alert_show: preAlertShow,
pre_alert_message: preAlertShow ? preAlertMessage : null,
pre_alert_minutes_before: preAlertShow ? preAlertMinutes : null
};
appendStepUpCredentialPayload(body, credential);
const res = await fetch('/api/settings/maintenance', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': maintenanceActionTokens.enableMaintenance || ''
},
body: JSON.stringify(body)
});
const data = await res.json();
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (!res.ok) {
showFeedback(data.error || 'Failed to enable maintenance mode', true);
} else {
closeModal(false);
await loadMaintenanceState();
}
} catch (e) {
showFeedback('Network error', true);
} finally {
maintenanceModalSave.disabled = false;
}
});
const securityBtn = document.querySelector('button[data-panel="security"]');
if (securityBtn) {
securityBtn.addEventListener('click', loadMaintenanceState);
}
const securityPanel = document.getElementById('security');
if (securityPanel && securityPanel.classList.contains('active')) {
loadMaintenanceState();
}
})();
(function () {
const sessionsPanel = document.getElementById('sessions');
if (!sessionsPanel) return;
const sessionsBtn = document.querySelector('button[data-panel="sessions"]');
const sessionsSearchInput = document.getElementById('sessionsSearchInput');
const sessionsSummary = document.getElementById('sessionsSummary');
const sessionsFeedback = document.getElementById('sessionsFeedback');
const sessionsList = document.getElementById('sessionsList');
const sessionsPagination = document.getElementById('sessionsPagination');
const sessionsCountBadge = document.getElementById('sessionsCountBadge');
const sessionsGraceBadge = document.getElementById('sessionsGraceBadge');
const sessionRevokeModalOverlay = document.getElementById('sessionRevokeModalOverlay');
const sessionRevokeModal = document.getElementById('sessionRevokeModal');
const sessionRevokeModalClose = document.getElementById('sessionRevokeModalClose');
const sessionRevokeModalCancel = document.getElementById('sessionRevokeModalCancel');
const sessionRevokeModalConfirm = document.getElementById('sessionRevokeModalConfirm');
const sessionRevokeTwoFactorInput = document.getElementById('sessionRevokeTwoFactorInput');
const sessionRevokeCredentialLabel = document.getElementById('sessionRevokeCredentialLabel');
const sessionRevokeCredentialHint = document.getElementById('sessionRevokeCredentialHint');
const sessionRevokeTargetSession = document.getElementById('sessionRevokeTargetSession');
const sessionRevokeTargetEmail = document.getElementById('sessionRevokeTargetEmail');
// Account-action TOTP companion: hidden until the server answers the
// acting admin's password with a 2fa-required challenge (account modes
// only; server modes never reveal it).
const sessionRevokeTotpSection = document.getElementById('sessionRevokeTotpSection');
const sessionRevokeTotpInput = document.getElementById('sessionRevokeTotpInput');
const sessionRevokeTotpLabel = document.getElementById('sessionRevokeTotpLabel');
const sessionRevokeTotpHint = document.getElementById('sessionRevokeTotpHint');
const sessionRevokeModalFeedback = document.getElementById('sessionRevokeModalFeedback');
const PAGE_GROUP_SIZE = 6;
const sessionsState = {
actionTokens: {},
items: [],
total: 0,
activeTotal: 0,
rememberedTotal: 0,
page: 1,
totalPages: 1,
search: '',
searchActive: false,
searchTruncated: false,
from: 0,
to: 0,
twoFactorEnabled: currentUserHas2FA,
graceExpiresAt: 0,
loading: false,
loadedOnce: false,
abortController: null,
searchTimer: null,
selectedSession: null,
selectedServerDelete: null,
selectedServerSuspension: null,
selectedAccountDelete: null,
selectedAccountSuspension: null,
selectedDatabaseInstall: null,
selectedPermsGrant: null,
selectedAccessRevoke: null,
selectedAgentAccess: null,
securityModalMode: 'session',
graceTicker: null,
authMethod: currentUserHas2FA ? '2fa' : 'password',
// Whether the account-action TOTP companion is currently revealed by a
// 2fa-required challenge; reset on every open/close of the shared
// security modal. The reveal itself only happens in account modes.
accountTotpRevealed: false,
};
// adpanel:settings-token-registry — loadSessions() reassigns the
// actionTokens property on every fetch, so the refresher writes through a
// live view of the current property object.
registerSettingsActionTokenRegistry(createSettingsActionTokenView(() => sessionsState.actionTokens));
function showSessionsFeedback(message, isError = false) {
if (!sessionsFeedback) return;
sessionsFeedback.textContent = message || '';
sessionsFeedback.style.color = isError ? '#f87171' : '#4ade80';
if (message) {
window.clearTimeout(sessionsFeedback._timer);
sessionsFeedback._timer = window.setTimeout(() => {
sessionsFeedback.textContent = '';
}, 4000);
}
}
function showSessionRevokeModalFeedback(message, isError = false) {
if (!sessionRevokeModalFeedback) return;
sessionRevokeModalFeedback.textContent = message || '';
sessionRevokeModalFeedback.style.display = message ? 'block' : 'none';
sessionRevokeModalFeedback.style.color = isError ? '#f87171' : '#4ade80';
}
function showSuccessToast(message) {
const toast = document.createElement('div');
toast.className = 'perm-success-toast';
toast.innerHTML = ` ${escapeHtml(message || 'Done')}`;
document.body.appendChild(toast);
window.setTimeout(() => toast.classList.add('show'), 10);
window.setTimeout(() => {
toast.classList.remove('show');
window.setTimeout(() => toast.remove(), 300);
}, 2200);
}
function isGraceActive() {
return Number(sessionsState.graceExpiresAt || 0) > Date.now();
}
function isSessionsPanelActive() {
return !!sessionsPanel?.classList.contains('active');
}
function formatDateTime(value) {
const ts = Number(value || 0);
if (!ts) return 'Unknown';
try {
return new Intl.DateTimeFormat(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(ts));
} catch {
return new Date(ts).toLocaleString();
}
}
function formatRelativeTime(value) {
const ts = Number(value || 0);
if (!ts) return 'unknown';
const diffMs = Date.now() - ts;
const diffMinutes = Math.round(diffMs / 60000);
if (Math.abs(diffMinutes) < 1) return 'just now';
if (Math.abs(diffMinutes) < 60) return `${Math.abs(diffMinutes)}m ago`;
const diffHours = Math.round(diffMinutes / 60);
if (Math.abs(diffHours) < 24) return `${Math.abs(diffHours)}h ago`;
const diffDays = Math.round(diffHours / 24);
return `${Math.abs(diffDays)}d ago`;
}
function shortenSessionId(sessionId) {
const raw = String(sessionId || '').trim();
if (!raw) return '—';
if (raw.length <= 20) return raw;
return `${raw.slice(0, 10)}...${raw.slice(-8)}`;
}
function syncGraceTicker() {
const shouldTick = isSessionsPanelActive() && isGraceActive();
if (shouldTick && !sessionsState.graceTicker) {
sessionsState.graceTicker = window.setInterval(() => {
updateSessionsHeaderMeta();
}, 1000);
return;
}
if (!shouldTick && sessionsState.graceTicker) {
window.clearInterval(sessionsState.graceTicker);
sessionsState.graceTicker = null;
}
}
function updateSessionsHeaderMeta() {
if (sessionsCountBadge) {
const total = Number(sessionsState.total || 0);
const activeTotal = Number(sessionsState.activeTotal || 0);
const rememberedTotal = Number(sessionsState.rememberedTotal || 0);
sessionsCountBadge.textContent = `${total} login${total === 1 ? '' : 's'}`;
sessionsCountBadge.title = `${activeTotal} active, ${rememberedTotal} offline`;
}
if (sessionsGraceBadge) {
sessionsGraceBadge.classList.remove('security-inline-chip-success', 'security-inline-chip-warning');
if (isGraceActive()) {
const remainingMs = Math.max(0, Number(sessionsState.graceExpiresAt || 0) - Date.now());
const minutes = Math.floor(remainingMs / 60000);
const seconds = Math.floor((remainingMs % 60000) / 1000);
sessionsGraceBadge.textContent = `Trusted ${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
sessionsGraceBadge.classList.add('security-inline-chip-success');
} else {
sessionsGraceBadge.textContent = sessionsState.authMethod === 'password' ? 'Password required' : '2FA required';
sessionsGraceBadge.classList.add('security-inline-chip-warning');
}
}
syncGraceTicker();
}
function renderSessionsSummary() {
if (!sessionsSummary) return;
if (sessionsState.loading && !sessionsState.loadedOnce) {
sessionsSummary.textContent = 'Loading browser sessions...';
return;
}
if (sessionsState.searchActive) {
let summary = `${sessionsState.total} browser login${sessionsState.total === 1 ? '' : 's'} matched "${sessionsState.search}"`;
// Server caps search responses (ACTIVE_BROWSER_SESSION_SEARCH_MAX) so
// every returned row's single-use revoke token stays valid; say so
// instead of silently hiding the tail of the match list.
if (sessionsState.searchTruncated) {
const shown = Array.isArray(sessionsState.items) ? sessionsState.items.length : 0;
summary += ` — showing the first ${shown}; refine the search to narrow the results`;
}
sessionsSummary.textContent = summary;
return;
}
if (!sessionsState.total) {
sessionsSummary.textContent = 'No browser sessions or saved logins found.';
return;
}
const activeTotal = Number(sessionsState.activeTotal || 0);
const rememberedTotal = Number(sessionsState.rememberedTotal || 0);
sessionsSummary.textContent = `${sessionsState.from}-${sessionsState.to} of ${sessionsState.total} browser logins (${activeTotal} active, ${rememberedTotal} offline)`;
}
function renderEmptySessionsState(message, iconClass = 'fa-solid fa-circle-info') {
if (!sessionsList) return;
sessionsList.innerHTML = `
${escapeHtml(message)}
`;
}
function renderSessionsList() {
if (!sessionsList) return;
if (sessionsState.loading && !sessionsState.loadedOnce) {
renderEmptySessionsState('Loading browser sessions...', 'fa-solid fa-spinner fa-spin');
return;
}
if (!Array.isArray(sessionsState.items) || sessionsState.items.length === 0) {
if (sessionsState.searchActive) {
renderEmptySessionsState(`No browser logins found for "${sessionsState.search}".`, 'fa-solid fa-search');
} else {
renderEmptySessionsState('There are no browser sessions or saved logins right now.', 'fa-solid fa-window-restore');
}
return;
}
sessionsList.innerHTML = '';
sessionsState.items.forEach((item) => {
const displayId = item.displayId || item.sessionId || '';
const revokeToken = item.revokeToken || '';
const isRemembered = item.status === 'remembered' || item.targetType === 'remembered';
const statusPill = item.isCurrent
? ' Current session '
: (isRemembered
? ' Offline login '
: ' Active session ');
// userAgent arrives pre-parsed and redacted from the server (e.g.
// "Chrome 126 on Windows 10/11"); the raw string never reaches the
// browser, so there is nothing left to parse client-side.
const browserLabel = item.userAgent || (isRemembered ? 'Saved browser' : 'Browser not detected');
const row = document.createElement('div');
row.className = `session-row${isRemembered ? ' session-row-remembered' : ''}`;
row.innerHTML = `
${escapeHtml(shortenSessionId(displayId))}
${escapeHtml(item.email || 'Unknown user')}
${statusPill}
Last seen ${escapeHtml(formatRelativeTime(item.lastSeenAt))}
Expires ${escapeHtml(formatDateTime(item.expiresAt))}
${escapeHtml(browserLabel)}
${item.ip ? ` ${escapeHtml(item.ip)} ` : ''}
Revoke
`;
sessionsList.appendChild(row);
});
}
function getVisibleSessionPages(currentPage, totalPages) {
if (totalPages <= PAGE_GROUP_SIZE) {
return Array.from({ length: totalPages }, (_, index) => index + 1);
}
if (currentPage < PAGE_GROUP_SIZE) {
return Array.from({ length: PAGE_GROUP_SIZE }, (_, index) => index + 1);
}
const start = Math.floor((currentPage - PAGE_GROUP_SIZE) / PAGE_GROUP_SIZE) * PAGE_GROUP_SIZE + PAGE_GROUP_SIZE;
const end = Math.min(totalPages, start + PAGE_GROUP_SIZE);
const pages = [];
for (let page = start; page <= end; page += 1) {
pages.push(page);
}
return pages;
}
function renderSessionsPagination() {
if (!sessionsPagination) return;
if (sessionsState.searchActive || sessionsState.totalPages <= 1) {
sessionsPagination.innerHTML = '';
return;
}
const currentPage = Number(sessionsState.page || 1);
const totalPages = Number(sessionsState.totalPages || 1);
const visiblePages = getVisibleSessionPages(currentPage, totalPages);
sessionsPagination.innerHTML = `
`;
}
function applyRevokeSecurityFromPayload(security) {
if (!security || typeof security !== 'object') return;
const normalized = applyGlobalStepUpSecurityFromPayload(security);
sessionsState.twoFactorEnabled = !!normalized.twoFactorEnabled;
sessionsState.authMethod = normalized.authMethod === 'password' ? 'password' : '2fa';
sessionsState.graceExpiresAt = Number(normalized.graceExpiresAt || 0);
configureSessionRevokeCredentialField();
updateSessionsHeaderMeta();
}
window.applyRevokeSecurityFromPayload = applyRevokeSecurityFromPayload;
// Account modes of the shared security modal act ON ANOTHER USER and
// step up in "password-then-TOTP" mode; every other mode (session
// revoke, server delete/suspension, database install) keeps the legacy
// dual-mode single credential field.
function isAccountSecurityModalMode(mode) {
return (
mode === 'suspend-account' ||
mode === 'unsuspend-account' ||
mode === 'delete-account' ||
mode === 'grant-perms' ||
mode === 'revoke-access' ||
mode === 'agent-access'
);
}
function configureSessionRevokeCredentialField() {
if (isAccountSecurityModalMode(sessionsState.securityModalMode)) {
configureAccountActionCredentialFields(
sessionRevokeTwoFactorInput,
sessionRevokeCredentialLabel,
sessionRevokeCredentialHint,
sessionRevokeTotpSection,
sessionRevokeTotpInput,
sessionRevokeTotpLabel,
sessionRevokeTotpHint
);
sessionsState.accountTotpRevealed = false;
return;
}
const passwordMode = sessionsState.authMethod === 'password';
const trustedMode = isGraceActive();
const credentialField = sessionRevokeTwoFactorInput?.closest('.password-field');
if (credentialField) credentialField.style.display = trustedMode ? 'none' : '';
if (sessionRevokeCredentialLabel) {
sessionRevokeCredentialLabel.textContent = passwordMode ? 'Current Password' : '2FA Code';
}
if (sessionRevokeCredentialHint) {
sessionRevokeCredentialHint.textContent = passwordMode
? 'Enter your current password to confirm this action.'
: 'Enter the code from your authenticator app.';
}
if (sessionRevokeTwoFactorInput) {
sessionRevokeTwoFactorInput.type = passwordMode ? 'password' : 'text';
sessionRevokeTwoFactorInput.placeholder = passwordMode ? 'Current password' : '000000';
sessionRevokeTwoFactorInput.autocomplete = passwordMode ? 'current-password' : 'one-time-code';
sessionRevokeTwoFactorInput.maxLength = passwordMode ? 1024 : 6;
sessionRevokeTwoFactorInput.inputMode = passwordMode ? '' : 'numeric';
sessionRevokeTwoFactorInput.pattern = passwordMode ? '' : '[0-9]*';
}
}
// Validates the account-action credential pair before a send: the
// acting admin's password (always, when no grace covers the action) and
// the 6-digit TOTP code (only once a challenge revealed the companion).
// The grace-expiry rescue re-shows the pair if the window lapsed while
// the modal sat open with both fields hidden.
function validateSessionRevokeAccountCredentials(credentialValue) {
if (!isGraceActive()) {
const pwContainer = getStepUpCredentialContainer(sessionRevokeTwoFactorInput);
if (pwContainer && pwContainer.style.display === 'none') {
configureSessionRevokeCredentialField();
}
}
if (!String(credentialValue || '')) {
showSessionRevokeModalFeedback('Enter your current password.', true);
sessionRevokeTwoFactorInput?.focus();
return false;
}
if (sessionsState.accountTotpRevealed) {
const totpCode = String(sessionRevokeTotpInput?.value || '').replace(/\D/g, '').slice(0, 6);
if (!/^\d{6}$/.test(totpCode)) {
showSessionRevokeModalFeedback('Enter a valid 6-digit code.', true);
sessionRevokeTotpInput?.focus();
return false;
}
}
return true;
}
// Account-mode step-up challenge handling for the shared security modal.
// The challenge payload's revokeSecurity (applied inside
// handleAccountActionCredentialChallenge) keeps the grace/authMethod
// state fresh; without one, a challenge still means no live grant covers
// the action.
function handleSessionRevokeAccountChallenge(data, opts = {}) {
const includeRateLimit = opts.includeRateLimit === true;
if (!isAccountActionChallengeCode(data, includeRateLimit)) return false;
if (!data.revokeSecurity) {
sessionsState.graceExpiresAt = 0;
if (data.code === 'password-required' || data.code === 'invalid-password') {
sessionsState.authMethod = 'password';
}
updateSessionsHeaderMeta();
}
return handleAccountActionCredentialChallenge(data, {
totpSection: sessionRevokeTotpSection,
totpInput: sessionRevokeTotpInput,
showFeedback: showSessionRevokeModalFeedback,
includeRateLimit,
onTotpRevealed: () => { sessionsState.accountTotpRevealed = true; },
onTotpHidden: () => { sessionsState.accountTotpRevealed = false; },
});
}
async function loadSessions(page = sessionsState.page, search = sessionsState.search) {
if (sessionsState.abortController) {
sessionsState.abortController.abort();
}
sessionsState.abortController = new AbortController();
sessionsState.loading = true;
sessionsState.page = Math.max(1, Number(page || 1));
sessionsState.search = String(search || '').trim();
// Query this request was issued with, captured before any await; used to
// detect stale in-flight responses when the server's normalized echo comes
// back (see the echo write-back below).
const requestedSearch = sessionsState.search;
renderSessionsSummary();
renderSessionsList();
try {
const params = new URLSearchParams();
params.set('page', String(Math.max(1, Number(page || 1))));
if (sessionsState.search) {
params.set('search', sessionsState.search);
}
const res = await fetch(`/api/settings/sessions?${params.toString()}`, {
signal: sessionsState.abortController.signal,
});
const data = await res.json().catch(() => ({ error: 'Invalid server response' }));
if (!res.ok) {
throw new Error(data.error || 'Failed to load sessions');
}
sessionsState.items = Array.isArray(data.items) ? data.items : [];
sessionsState.total = Number(data.total || 0);
sessionsState.activeTotal = Number(data.activeTotal || 0);
sessionsState.rememberedTotal = Number(data.rememberedTotal || 0);
sessionsState.page = Number(data.page || 1) || 1;
sessionsState.totalPages = Number(data.totalPages || 1) || 1;
sessionsState.search = String(data.search || '').trim();
sessionsState.searchActive = !!data.searchActive;
sessionsState.searchTruncated = !!data.searchTruncated;
sessionsState.from = Number(data.from || 0);
sessionsState.to = Number(data.to || 0);
sessionsState.actionTokens = data.actionTokens || {};
sessionsState.twoFactorEnabled = !!data.revokeSecurity?.twoFactorEnabled;
sessionsState.authMethod = data.revokeSecurity?.authMethod === 'password' ? 'password' : '2fa';
sessionsState.graceExpiresAt = Number(data.revokeSecurity?.graceExpiresAt || 0);
sessionsState.loadedOnce = true;
configureSessionRevokeCredentialField();
// Echo the server's normalized search back into the input only when it
// cannot clobber the admin's typing: never while the input is focused,
// and only when the response actually corresponds to the current
// query — the echo must match the query this request was issued with
// AND the input must still hold that query, so a stale in-flight
// response can never revert newer input. The server lowercases and
// truncates the echo, so comparisons are case-insensitive on trimmed
// values; the admin's typed case is otherwise preserved.
if (sessionsSearchInput) {
const echoedSearch = String(sessionsState.search || '').trim();
const searchInputFocused = document.activeElement === sessionsSearchInput;
const echoMatchesRequest = echoedSearch.toLowerCase() === requestedSearch.toLowerCase();
const inputStillHoldsRequest = String(sessionsSearchInput.value || '').trim().toLowerCase() === requestedSearch.toLowerCase();
// The final comparison is case-insensitive too: when the echo equals
// the query modulo case, rewriting the input would only destroy the
// admin's typed case, so nothing is written back at all. Only a
// genuinely different echo could land here, and the two guards
// above already refuse it.
if (!searchInputFocused && echoMatchesRequest && inputStillHoldsRequest && String(sessionsSearchInput.value || '').trim().toLowerCase() !== echoedSearch.toLowerCase()) {
sessionsSearchInput.value = echoedSearch;
}
}
updateSessionsHeaderMeta();
renderSessionsSummary();
renderSessionsList();
renderSessionsPagination();
} catch (err) {
if (err?.name === 'AbortError') return;
console.error('[sessions]', err);
renderEmptySessionsState(err.message || 'Failed to load browser sessions.', 'fa-solid fa-circle-exclamation');
showSessionsFeedback(err.message || 'Failed to load browser sessions.', true);
} finally {
sessionsState.loading = false;
renderSessionsSummary();
}
}
function setSecurityModalPresentation(config = {}) {
const title = sessionRevokeModal?.querySelector('.enterprise-modal-title');
const targetLabel = sessionRevokeModal?.querySelector('.session-revoke-target-label');
if (title) title.textContent = config.title || 'Security Verification';
if (targetLabel) targetLabel.textContent = config.targetLabel || 'Target';
if (sessionRevokeTargetSession) sessionRevokeTargetSession.textContent = config.targetValue || '—';
if (sessionRevokeTargetEmail) sessionRevokeTargetEmail.textContent = config.targetSubvalue || '';
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.innerHTML = config.confirmHtml || ' Confirm';
sessionRevokeModalConfirm.style.background = config.danger ? '#ef4444' : '';
}
configureSessionRevokeCredentialField();
// The account-action TOTP companion only ever appears on the server's
// 2fa-required challenge; every (re)presentation of the modal starts
// with it hidden and the reveal flag reset.
sessionsState.accountTotpRevealed = false;
hideAccountActionTotpField(sessionRevokeTotpSection, sessionRevokeTotpInput);
}
function restoreSecurityModalConfirmButton() {
if (!sessionRevokeModalConfirm) return;
if (sessionsState.securityModalMode === 'delete-server') {
sessionRevokeModalConfirm.innerHTML = ' Delete Server';
sessionRevokeModalConfirm.style.background = '#ef4444';
} else if (sessionsState.securityModalMode === 'suspend-server') {
sessionRevokeModalConfirm.innerHTML = ' Suspend Server';
sessionRevokeModalConfirm.style.background = '#ef4444';
} else if (sessionsState.securityModalMode === 'restore-server') {
sessionRevokeModalConfirm.innerHTML = ' Restore Server';
sessionRevokeModalConfirm.style.background = '';
} else if (sessionsState.securityModalMode === 'delete-account') {
sessionRevokeModalConfirm.innerHTML = ' Delete User';
sessionRevokeModalConfirm.style.background = '#ef4444';
} else if (sessionsState.securityModalMode === 'suspend-account') {
sessionRevokeModalConfirm.innerHTML = ' Suspend Account';
sessionRevokeModalConfirm.style.background = '#ef4444';
} else if (sessionsState.securityModalMode === 'unsuspend-account') {
sessionRevokeModalConfirm.innerHTML = ' Unsuspend Account';
sessionRevokeModalConfirm.style.background = '';
} else if (sessionsState.securityModalMode === 'database-install') {
sessionRevokeModalConfirm.innerHTML = ' Continue';
sessionRevokeModalConfirm.style.background = '';
} else if (sessionsState.securityModalMode === 'grant-perms') {
sessionRevokeModalConfirm.innerHTML = ' Save Permissions';
sessionRevokeModalConfirm.style.background = '';
} else if (sessionsState.securityModalMode === 'revoke-access') {
sessionRevokeModalConfirm.innerHTML = ' Revoke Access';
sessionRevokeModalConfirm.style.background = '#ef4444';
} else if (sessionsState.securityModalMode === 'agent-access') {
sessionRevokeModalConfirm.innerHTML = ' Save Agent Access';
sessionRevokeModalConfirm.style.background = '';
} else if (sessionsState.selectedSession?.targetType === 'remembered') {
sessionRevokeModalConfirm.innerHTML = ' Revoke Login';
sessionRevokeModalConfirm.style.background = '';
} else {
sessionRevokeModalConfirm.innerHTML = ' Revoke Session';
sessionRevokeModalConfirm.style.background = '';
}
}
function openSessionRevokeModal(revokeToken, displayId, email, targetType = 'session') {
const isRemembered = targetType === 'remembered';
sessionsState.securityModalMode = 'session';
sessionsState.selectedServerDelete = null;
sessionsState.selectedServerSuspension = null;
sessionsState.selectedAccountDelete = null;
sessionsState.selectedAccountSuspension = null;
if (typeof window.resolvePendingDatabaseInstall === 'function') window.resolvePendingDatabaseInstall();
else sessionsState.selectedDatabaseInstall = null;
sessionsState.selectedPermsGrant = null;
sessionsState.selectedSession = {
revokeToken: String(revokeToken || '').trim(),
displayId: String(displayId || '').trim(),
email: String(email || '').trim().toLowerCase(),
targetType: isRemembered ? 'remembered' : 'session',
};
setSecurityModalPresentation({
title: isRemembered ? 'Revoke Saved Login' : 'Revoke Session',
targetLabel: isRemembered ? 'Saved Login' : 'Target Session',
targetValue: shortenSessionId(sessionsState.selectedSession.displayId),
targetSubvalue: isRemembered
? `${sessionsState.selectedSession.email || 'Unknown user'} - offline browser login`
: (sessionsState.selectedSession.email || 'Unknown user'),
confirmHtml: isRemembered
? ' Revoke Login'
: ' Revoke Session',
});
if (sessionRevokeTwoFactorInput) {
sessionRevokeTwoFactorInput.value = '';
}
showSessionRevokeModalFeedback('');
if (sessionRevokeModalOverlay) {
sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false');
sessionRevokeModalOverlay.classList.add('show');
}
if (sessionRevokeModal) {
sessionRevokeModal.classList.add('show');
}
window.setTimeout(() => {
if (isGraceActive()) sessionRevokeModalConfirm?.focus();
else sessionRevokeTwoFactorInput?.focus();
}, 40);
}
function openServerDeleteVerificationModal(serverName, sourceButton) {
sessionsState.securityModalMode = 'delete-server';
sessionsState.selectedSession = null;
sessionsState.selectedServerSuspension = null;
sessionsState.selectedAccountDelete = null;
sessionsState.selectedAccountSuspension = null;
sessionsState.selectedPermsGrant = null;
sessionsState.selectedServerDelete = {
name: String(serverName || '').trim(),
expectedTargetId: Number(sourceButton?.closest('.server-row')?.dataset?.targetId),
button: sourceButton || null,
actionToken: getServerDeleteToken(serverName),
};
setSecurityModalPresentation({
title: 'Delete Server',
targetLabel: 'Target Server',
targetValue: sessionsState.selectedServerDelete.name || '—',
targetSubvalue: 'This permanently removes server files, backups, schedules, and access records.',
confirmHtml: ' Delete Server',
danger: true,
});
if (sessionRevokeTwoFactorInput) {
sessionRevokeTwoFactorInput.value = '';
}
showSessionRevokeModalFeedback('');
if (sessionRevokeModalOverlay) {
sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false');
sessionRevokeModalOverlay.classList.add('show');
}
if (sessionRevokeModal) {
sessionRevokeModal.classList.add('show');
}
window.setTimeout(() => {
if (isGraceActive()) sessionRevokeModalConfirm?.focus();
else sessionRevokeTwoFactorInput?.focus();
}, 40);
}
window.openServerDeleteVerificationModal = openServerDeleteVerificationModal;
function openServerSuspensionVerificationModal(serverName, nextSuspended, sourceButton) {
const suspend = nextSuspended !== false;
sessionsState.securityModalMode = suspend ? 'suspend-server' : 'restore-server';
sessionsState.selectedSession = null;
sessionsState.selectedServerDelete = null;
sessionsState.selectedAccountDelete = null;
sessionsState.selectedAccountSuspension = null;
if (typeof window.resolvePendingDatabaseInstall === 'function') window.resolvePendingDatabaseInstall();
else sessionsState.selectedDatabaseInstall = null;
sessionsState.selectedPermsGrant = null;
sessionsState.selectedServerSuspension = {
name: String(serverName || '').trim(),
expectedTargetId: Number(sourceButton?.closest('.server-row')?.dataset?.targetId),
suspended: suspend,
button: sourceButton || null,
actionToken: getServerSuspensionToken(serverName),
};
setSecurityModalPresentation({
title: suspend ? 'Suspend Server' : 'Restore Server',
targetLabel: 'Target Server',
targetValue: sessionsState.selectedServerSuspension.name || '—',
targetSubvalue: suspend
? 'The server will be force-stopped, locked, and the suspended page will be shown instead.'
: 'Suspension records will be cleared and the server panel will be unlocked.',
confirmHtml: suspend
? ' Suspend Server'
: ' Restore Server',
danger: suspend,
});
if (sessionRevokeTwoFactorInput) {
sessionRevokeTwoFactorInput.value = '';
}
showSessionRevokeModalFeedback('');
if (sessionRevokeModalOverlay) {
sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false');
sessionRevokeModalOverlay.classList.add('show');
}
if (sessionRevokeModal) {
sessionRevokeModal.classList.add('show');
}
window.setTimeout(() => {
if (isGraceActive()) sessionRevokeModalConfirm?.focus();
else sessionRevokeTwoFactorInput?.focus();
}, 40);
}
window.openServerSuspensionVerificationModal = openServerSuspensionVerificationModal;
function openAccountDeleteVerificationModal(email, sourceButton) {
sessionsState.securityModalMode = 'delete-account';
sessionsState.selectedSession = null;
sessionsState.selectedServerDelete = null;
sessionsState.selectedServerSuspension = null;
sessionsState.selectedAccountSuspension = null;
sessionsState.selectedPermsGrant = null;
sessionsState.selectedAccountDelete = {
email: String(email || '').trim(),
accountTarget: window.ADPanelAccountTargets.select(email),
button: sourceButton || null,
actionToken: getAccountDeleteToken(email),
};
setSecurityModalPresentation({
title: 'Delete User',
targetLabel: 'Target Account',
targetValue: sessionsState.selectedAccountDelete.email || '—',
targetSubvalue: 'This permanently removes the user, server access records, and ACL entries.',
confirmHtml: ' Delete User',
danger: true,
});
if (sessionRevokeTwoFactorInput) {
sessionRevokeTwoFactorInput.value = '';
}
showSessionRevokeModalFeedback('');
if (sessionRevokeModalOverlay) {
sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false');
sessionRevokeModalOverlay.classList.add('show');
}
if (sessionRevokeModal) {
sessionRevokeModal.classList.add('show');
}
window.setTimeout(() => {
if (isGraceActive()) sessionRevokeModalConfirm?.focus();
else sessionRevokeTwoFactorInput?.focus();
}, 40);
}
window.openAccountDeleteVerificationModal = openAccountDeleteVerificationModal;
function openAccountSuspensionVerificationModal(email, nextSuspended, sourceButton) {
const suspend = !!nextSuspended;
sessionsState.securityModalMode = suspend ? 'suspend-account' : 'unsuspend-account';
sessionsState.selectedSession = null;
sessionsState.selectedServerDelete = null;
sessionsState.selectedServerSuspension = null;
sessionsState.selectedAccountDelete = null;
sessionsState.selectedPermsGrant = null;
sessionsState.selectedAccountSuspension = {
email: String(email || '').trim(),
accountTarget: window.ADPanelAccountTargets.select(email),
suspended: suspend,
button: sourceButton || null,
actionToken: getAccountSuspensionToken(email),
};
setSecurityModalPresentation({
title: suspend ? 'Suspend Account' : 'Unsuspend Account',
targetLabel: 'Target Account',
targetValue: sessionsState.selectedAccountSuspension.email || '—',
targetSubvalue: suspend
? 'All active sessions and persistent logins will be revoked immediately.'
: 'The user will be allowed to sign in again after this change.',
confirmHtml: suspend
? ' Suspend Account'
: ' Unsuspend Account',
danger: suspend,
});
if (sessionRevokeTwoFactorInput) {
sessionRevokeTwoFactorInput.value = '';
}
showSessionRevokeModalFeedback('');
if (sessionRevokeModalOverlay) {
sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false');
sessionRevokeModalOverlay.classList.add('show');
}
if (sessionRevokeModal) {
sessionRevokeModal.classList.add('show');
}
window.setTimeout(() => {
if (isGraceActive()) sessionRevokeModalConfirm?.focus();
else sessionRevokeTwoFactorInput?.focus();
}, 40);
}
window.openAccountSuspensionVerificationModal = openAccountSuspensionVerificationModal;
function getDatabaseInstallServiceMeta(service) {
const raw = String(service || 'database').trim().toLowerCase();
if (raw === 'phpmyadmin' || raw === 'phpmyadmin setup') return { key: 'phpmyadmin', label: 'phpMyAdmin' };
if (raw === 'pgadmin' || raw === 'pgadmin4') return { key: 'pgadmin', label: 'pgAdmin4' };
if (raw === 'mongodb' || raw === 'mongo') return { key: 'mongodb', label: 'MongoDB' };
return { key: raw || 'database', label: String(service || 'Database') };
}
function resolveDatabaseInstallVerification(result) {
const pending = sessionsState.selectedDatabaseInstall;
sessionsState.selectedDatabaseInstall = null;
if (pending && typeof pending.resolve === 'function') {
pending.resolve(result || { ok: false });
}
}
// Openers of OTHER security-modal flows null selected* state directly;
// a pending install-verification promise must never be dropped
// unresolved (its awaiter would hang with its control disabled), so
// those openers route the reset through this helper.
window.resolvePendingDatabaseInstall = function () {
resolveDatabaseInstallVerification({ ok: false, cancelled: true });
};
function isDatabaseInstallVerificationError(data) {
return [
'2fa-required',
'invalid-2fa',
'password-required',
'invalid-password',
'verification-rate-limit'
].includes(String(data?.code || ''));
}
window.isDatabaseInstallVerificationError = isDatabaseInstallVerificationError;
async function getDatabaseInstallVerifyToken(forceRefresh = false) {
let token = String((dbActionTokens || {}).verifyInstall || '').trim();
if ((!token || forceRefresh) && typeof window.refreshDbActionTokens === 'function') {
await window.refreshDbActionTokens();
token = String((dbActionTokens || {}).verifyInstall || '').trim();
}
return token;
}
async function verifyDatabaseInstallWithCredential(credentialValue = '') {
const pending = sessionsState.selectedDatabaseInstall;
if (!pending) return;
const passwordMode = sessionsState.authMethod === 'password';
const requiresVerification = !isGraceActive();
const credential = passwordMode ? String(credentialValue || '') : String(credentialValue || '').replace(/\D/g, '').slice(0, 6);
if (requiresVerification) {
if (passwordMode) {
if (!credential) {
showSessionRevokeModalFeedback('Enter your current password.', true);
sessionRevokeTwoFactorInput?.focus();
return;
}
} else if (!/^\d{6}$/.test(credential)) {
showSessionRevokeModalFeedback('Enter a valid 6-digit code.', true);
sessionRevokeTwoFactorInput?.focus();
return;
}
}
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = true;
sessionRevokeModalConfirm.innerHTML = ' Verifying...';
}
const sendVerification = async (token) => {
const res = await fetch('/api/settings/database/verify-install', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': token || '',
},
body: JSON.stringify({
service: pending.serviceKey,
twoFactorCode: requiresVerification && !passwordMode ? credential : undefined,
currentPassword: requiresVerification && passwordMode ? credential : undefined,
}),
});
const data = await res.json().catch(() => ({ error: 'Invalid server response' }));
return { res, data };
};
try {
let token = await getDatabaseInstallVerifyToken(false);
let result = await sendVerification(token);
if (!result.res.ok && result.data?.error === 'invalid or missing action token') {
token = await getDatabaseInstallVerifyToken(true);
if (token) result = await sendVerification(token);
}
const { res, data } = result;
if (!res.ok) {
if (data.revokeSecurity) applyRevokeSecurityFromPayload(data.revokeSecurity);
// The server deliberately reports replayed TOTP codes exactly like
// wrong ones (anti-phishing), but the most common way to hit this
// modal is right after signing in — when the authenticator still
// shows the code that was just consumed by the login. Surface that
// possibility instead of a dead-end "Incorrect 2FA code".
const replayHint = (!passwordMode && data.code === 'invalid-2fa')
? 'If you just signed in, that code was already used — wait for the next code from your authenticator app, then try again.'
: '';
const baseMsg = String(data.error || 'Verification failed.').replace(/\.\s*$/, '');
showSessionRevokeModalFeedback(baseMsg + (replayHint ? '. ' + replayHint : ''), true);
return;
}
if (data.revokeSecurity) applyRevokeSecurityFromPayload(data.revokeSecurity);
else if (data.graceExpiresAt) {
applyRevokeSecurityFromPayload({
twoFactorEnabled: sessionsState.twoFactorEnabled,
authMethod: sessionsState.authMethod,
graceExpiresAt: data.graceExpiresAt,
});
}
resolveDatabaseInstallVerification({ ok: true, graceExpiresAt: data.graceExpiresAt || sessionsState.graceExpiresAt || 0 });
closeSessionRevokeModal();
} catch (err) {
console.error('[database] install verification failed', err);
showSessionRevokeModalFeedback(err.message || 'Network error while verifying.', true);
} finally {
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = false;
restoreSecurityModalConfirmButton();
}
}
}
function openDatabaseInstallVerificationModal(service, options = {}) {
const meta = getDatabaseInstallServiceMeta(service);
if (isGraceActive() && !options.force) {
return Promise.resolve({ ok: true, trusted: true, graceExpiresAt: sessionsState.graceExpiresAt });
}
if (!sessionRevokeModalOverlay || !sessionRevokeModal) {
return Promise.resolve({ ok: false, error: 'Security verification modal unavailable' });
}
if (sessionsState.selectedDatabaseInstall?.resolve) {
resolveDatabaseInstallVerification({ ok: false, cancelled: true });
}
return new Promise((resolve) => {
sessionsState.securityModalMode = 'database-install';
sessionsState.selectedSession = null;
sessionsState.selectedServerDelete = null;
sessionsState.selectedServerSuspension = null;
sessionsState.selectedAccountDelete = null;
sessionsState.selectedAccountSuspension = null;
sessionsState.selectedPermsGrant = null;
sessionsState.selectedDatabaseInstall = {
serviceKey: meta.key,
serviceLabel: meta.label,
resolve,
};
setSecurityModalPresentation({
title: (options && typeof options.titleText === 'string' && options.titleText.trim()) || 'Confirm Installation',
targetLabel: 'Database Tool',
targetValue: meta.label,
targetSubvalue: (options && typeof options.targetSubvalue === 'string' && options.targetSubvalue.trim()) ||
'Confirm your identity before opening the install setup.',
confirmHtml: ' Continue',
});
if (sessionRevokeTwoFactorInput) {
sessionRevokeTwoFactorInput.value = '';
}
showSessionRevokeModalFeedback('');
sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false');
sessionRevokeModalOverlay.classList.add('show');
sessionRevokeModal.classList.add('show');
window.setTimeout(() => {
if (isGraceActive()) sessionRevokeModalConfirm?.focus();
else sessionRevokeTwoFactorInput?.focus();
}, 40);
});
}
window.openDatabaseInstallVerificationModal = openDatabaseInstallVerificationModal;
// Permission grants (grant-perms) are step-up protected server-side:
// console_write/files_write are code-execution equivalence on the
// server. The save is routed through the shared security modal, which
// collects the acting admin's current password and — once the server
// answers with a 2fa-required challenge — their own 6-digit TOTP code,
// unless a verified grace window from a recent step-up is still active.
async function grantPermsWithVerification(email, server, permissions, credentialValue = '') {
const targetEmail = String(email || '').trim();
const targetServer = String(server || '').trim();
if (!targetEmail || !targetServer) return;
const callbacks = sessionsState.selectedPermsGrant?.callbacks || {};
const accountTarget = sessionsState.selectedPermsGrant?.accountTarget;
const modalVisible = !!sessionRevokeModalOverlay?.classList.contains('show');
const requiresVerification = !isGraceActive();
const credential = String(credentialValue || '');
if (requiresVerification && !validateSessionRevokeAccountCredentials(credential)) return;
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = true;
sessionRevokeModalConfirm.innerHTML = ' Saving...';
}
const getGrantPermsToken = () => String((accountsListEl?._actionTokens || {}).grantPerms || '').trim();
const sendGrant = async (token) => {
const res = await fetch(`/api/settings/accounts/${encodeURIComponent(targetEmail)}/grant-perms`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': token || '',
},
body: JSON.stringify(window.ADPanelAccountTargets.payload(accountTarget, collectAccountActionCredentialPayload({
server: targetServer,
permissions,
}, sessionRevokeTwoFactorInput, sessionRevokeTotpSection, sessionRevokeTotpInput))),
});
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
return { res, data };
};
try {
let result = await sendGrant(getGrantPermsToken());
if (!result.res.ok && result.data?.error === 'invalid or missing action token' && typeof loadAccounts === 'function') {
await loadAccounts();
const freshToken = getGrantPermsToken();
if (freshToken) result = await sendGrant(freshToken);
}
const { res, data } = result;
if (!res.ok) {
if (isAccountActionChallengeCode(data, true)) {
// A challenge means no live grant covers this action; drop any
// local grace BEFORE potentially reopening the modal so it is
// shown instead of re-sending credential-less.
sessionsState.graceExpiresAt = 0;
if (!sessionRevokeModalOverlay?.classList.contains('show')) {
openPermsGrantVerificationModal(targetEmail, targetServer, permissions, { ...callbacks, accountTarget });
}
handleSessionRevokeAccountChallenge(data, { includeRateLimit: true });
return;
}
if (data.error === 'invalid or missing action token') {
showSessionRevokeModalFeedback('Security token expired. Please reopen the permissions dialog and try again.', true);
return;
}
showSessionRevokeModalFeedback(data.error || 'Failed to save permissions.', true);
return;
}
sessionsState.graceExpiresAt = Number(data.graceExpiresAt || sessionsState.graceExpiresAt || 0);
updateSessionsHeaderMeta();
closeSessionRevokeModal();
setSavedPerms(targetEmail, targetServer, permissions);
showSuccessToast(`Permissions saved for ${targetEmail}`);
if (typeof closePermsModal === 'function') closePermsModal();
if (typeof callbacks.onSaved === 'function') callbacks.onSaved();
} catch (err) {
console.error('[grant-perms] save failed', err);
if (modalVisible) {
showSessionRevokeModalFeedback(err.message || 'Network error while saving permissions.', true);
} else if (typeof callbacks.onError === 'function') {
callbacks.onError(err.message || 'Network error while saving permissions.');
} else {
alert(err.message || 'Network error while saving permissions.');
}
} finally {
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = false;
restoreSecurityModalConfirmButton();
}
}
}
function openPermsGrantVerificationModal(email, server, permissions, callbacks = {}) {
const pendingGrant = {
email: String(email || '').trim(),
accountTarget: callbacks.accountTarget || window.ADPanelAccountTargets.select(email),
server: String(server || '').trim(),
permissions,
callbacks,
};
// With a live verified grace window the step-up is already
// satisfied; save directly without prompting again (same rule as
// the database-install verification).
if (isGraceActive() && !callbacks.force) {
sessionsState.selectedPermsGrant = pendingGrant;
return grantPermsWithVerification(pendingGrant.email, pendingGrant.server, permissions, '');
}
if (!sessionRevokeModalOverlay || !sessionRevokeModal) {
if (typeof callbacks.onError === 'function') callbacks.onError('Security verification modal unavailable');
else alert('Security verification modal unavailable.');
return;
}
sessionsState.securityModalMode = 'grant-perms';
sessionsState.selectedSession = null;
sessionsState.selectedServerDelete = null;
sessionsState.selectedServerSuspension = null;
sessionsState.selectedAccountDelete = null;
sessionsState.selectedAccountSuspension = null;
if (typeof window.resolvePendingDatabaseInstall === 'function') window.resolvePendingDatabaseInstall();
else sessionsState.selectedDatabaseInstall = null;
sessionsState.selectedPermsGrant = pendingGrant;
setSecurityModalPresentation({
title: 'Save Server Permissions',
targetLabel: 'Target Account',
targetValue: pendingGrant.email || '—',
targetSubvalue: `Server: ${pendingGrant.server} — changes what this user can do on the server.`,
confirmHtml: ' Save Permissions',
});
if (sessionRevokeTwoFactorInput) {
sessionRevokeTwoFactorInput.value = '';
}
showSessionRevokeModalFeedback('');
sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false');
sessionRevokeModalOverlay.classList.add('show');
sessionRevokeModal.classList.add('show');
window.setTimeout(() => {
if (isGraceActive()) sessionRevokeModalConfirm?.focus();
else sessionRevokeTwoFactorInput?.focus();
}, 40);
}
window.openPermsGrantVerificationModal = openPermsGrantVerificationModal;
window.grantPermsWithVerification = grantPermsWithVerification;
function closeSessionRevokeModal() {
if (sessionsState.selectedDatabaseInstall?.resolve) {
resolveDatabaseInstallVerification({ ok: false, cancelled: true });
}
sessionsState.selectedSession = null;
sessionsState.selectedServerDelete = null;
sessionsState.selectedServerSuspension = null;
sessionsState.selectedAccountDelete = null;
sessionsState.selectedAccountSuspension = null;
sessionsState.selectedPermsGrant = null;
sessionsState.selectedAccessRevoke = null;
sessionsState.selectedAgentAccess = null;
if (sessionRevokeModalOverlay) {
sessionRevokeModalOverlay.setAttribute('aria-hidden', 'true');
sessionRevokeModalOverlay.classList.remove('show');
}
if (sessionRevokeModal) {
sessionRevokeModal.classList.remove('show');
}
// Credentials must not linger in hidden inputs after close: the actor's
// step-up password and a challenge-revealed TOTP code stay readable by
// anything with DOM access until the next open clears them.
if (sessionRevokeTwoFactorInput) sessionRevokeTwoFactorInput.value = '';
sessionsState.accountTotpRevealed = false;
hideAccountActionTotpField(sessionRevokeTotpSection, sessionRevokeTotpInput);
showSessionRevokeModalFeedback('');
}
async function revokeSession(targetRevokeToken, targetEmail, credentialValue = '', targetDisplayId = '', targetType = 'session') {
let trimmedRevokeToken = String(targetRevokeToken || '').trim();
const trimmedEmail = String(targetEmail || '').trim().toLowerCase();
const trimmedDisplayId = String(targetDisplayId || sessionsState.selectedSession?.displayId || '').trim();
if (!trimmedRevokeToken) return;
const modalVisible = !!sessionRevokeModalOverlay?.classList.contains('show');
const requiresVerification = !isGraceActive();
const passwordMode = sessionsState.authMethod === 'password';
const credential = passwordMode ? String(credentialValue || '') : String(credentialValue || '').replace(/\s+/g, '');
if (requiresVerification) {
if (passwordMode) {
if (!credential) {
showSessionRevokeModalFeedback('Enter your current password.', true);
sessionRevokeTwoFactorInput?.focus();
return;
}
} else if (!/^\d{6}$/.test(credential)) {
showSessionRevokeModalFeedback('Enter a valid 6-digit code.', true);
sessionRevokeTwoFactorInput?.focus();
return;
}
}
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = true;
sessionRevokeModalConfirm.innerHTML = ' Revoking...';
}
try {
const res = await fetch('/api/settings/sessions/revoke', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': sessionsState.actionTokens.revokeSession || '',
},
body: JSON.stringify({
revokeToken: trimmedRevokeToken,
twoFactorCode: requiresVerification && !passwordMode ? credential : undefined,
currentPassword: requiresVerification && passwordMode ? credential : undefined,
}),
});
const data = await res.json().catch(() => ({ error: 'Invalid server response' }));
if (!res.ok) {
// Revoke tokens are single-use: the server consumes each token on
// first verification and returns a fresh one (same target) in
// retryable failure responses. Adopt the renewal so a retry does not
// fail with session-action-expired. The token-matched guard keeps
// unrelated modal state untouched, and any stale token that slips
// through fails safe (server answers session-action-expired and the
// list reloads with fresh tokens).
const renewedRevokeToken = String(data.revokeToken || '').trim();
if (renewedRevokeToken && renewedRevokeToken !== trimmedRevokeToken) {
const staleRevokeToken = trimmedRevokeToken;
if (sessionsState.selectedSession && sessionsState.selectedSession.revokeToken === staleRevokeToken) {
sessionsState.selectedSession.revokeToken = renewedRevokeToken;
}
if (sessionsList && staleRevokeToken) {
const rowButton = sessionsList.querySelector(`.session-revoke-btn[data-revoke-token="${encodeURIComponent(staleRevokeToken)}"]`);
if (rowButton) rowButton.dataset.revokeToken = encodeURIComponent(renewedRevokeToken);
}
trimmedRevokeToken = renewedRevokeToken;
}
if (data.code === '2fa-required' || data.code === 'invalid-2fa' || data.code === 'password-required' || data.code === 'invalid-password') {
sessionsState.graceExpiresAt = 0;
sessionsState.authMethod = data.code === 'password-required' || data.code === 'invalid-password' ? 'password' : sessionsState.authMethod;
configureSessionRevokeCredentialField();
updateSessionsHeaderMeta();
if (!sessionRevokeModalOverlay?.classList.contains('show')) {
openSessionRevokeModal(trimmedRevokeToken, trimmedDisplayId, trimmedEmail, targetType);
}
showSessionRevokeModalFeedback(data.error || 'Verification failed.', true);
return;
}
if (data.error === 'invalid or missing action token') {
await loadSessions(sessionsState.page, sessionsSearchInput?.value || '');
}
if (data.code === 'session-action-expired' || data.code === 'session-not-active' || data.code === 'saved-login-not-found') {
await loadSessions(sessionsState.page, sessionsSearchInput?.value || '');
}
if (modalVisible) {
showSessionRevokeModalFeedback(data.error || 'Failed to revoke session.', true);
} else {
showSessionsFeedback(data.error || 'Failed to revoke session.', true);
}
return;
}
sessionsState.graceExpiresAt = Number(data.graceExpiresAt || 0);
updateSessionsHeaderMeta();
closeSessionRevokeModal();
if (data.revokedCurrentSession) {
window.location.href = '/login';
return;
}
showSuccessToast(`Revoked ${data.targetEmail || trimmedEmail || 'session'}`);
await loadSessions(sessionsState.page, sessionsSearchInput?.value || '');
} catch (err) {
console.error('[sessions] revoke failed', err);
if (modalVisible) {
showSessionRevokeModalFeedback(err.message || 'Network error while revoking session.', true);
} else {
showSessionsFeedback(err.message || 'Network error while revoking session.', true);
}
} finally {
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = false;
restoreSecurityModalConfirmButton();
}
}
}
async function deleteServerWithVerification(serverName, credentialValue = '') {
const name = String(serverName || '').trim();
if (!name) return;
const sourceButton = sessionsState.selectedServerDelete?.button || null;
const expectedTargetId = sessionsState.selectedServerDelete?.expectedTargetId;
let actionToken = String(sessionsState.selectedServerDelete?.actionToken || getServerDeleteToken(name) || '').trim();
const requiresVerification = !isGraceActive();
const passwordMode = sessionsState.authMethod === 'password';
const credential = passwordMode ? String(credentialValue || '') : String(credentialValue || '').replace(/\s+/g, '');
if (requiresVerification) {
if (passwordMode) {
if (!credential) {
showSessionRevokeModalFeedback('Enter your current password.', true);
sessionRevokeTwoFactorInput?.focus();
return;
}
} else if (!/^\d{6}$/.test(credential)) {
showSessionRevokeModalFeedback('Enter a valid 6-digit code.', true);
sessionRevokeTwoFactorInput?.focus();
return;
}
}
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = true;
sessionRevokeModalConfirm.innerHTML = ' Destroying...';
}
if (sourceButton) sourceButton.disabled = true;
try {
if (!actionToken) {
actionToken = await refreshServerDeleteToken(name);
if (sessionsState.selectedServerDelete) sessionsState.selectedServerDelete.actionToken = actionToken;
}
const sendDelete = async (token) => {
const res = await fetchWithTimeout(`/api/settings/servers/${encodeURIComponent(name)}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'x-action-token': token,
},
body: JSON.stringify({
expectedTargetId,
twoFactorCode: requiresVerification && !passwordMode ? credential : undefined,
currentPassword: requiresVerification && passwordMode ? credential : undefined,
}),
}, 30000);
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
return { res, data };
};
let result = await sendDelete(actionToken);
if (!result.res.ok && result.data?.error === 'invalid or missing action token') {
const freshToken = await refreshServerDeleteToken(name);
if (freshToken && freshToken !== actionToken) {
actionToken = freshToken;
if (sessionsState.selectedServerDelete) sessionsState.selectedServerDelete.actionToken = freshToken;
result = await sendDelete(freshToken);
}
}
const { res, data } = result;
if (!res.ok) {
if (data.code === '2fa-required' || data.code === 'invalid-2fa' || data.code === 'password-required' || data.code === 'invalid-password') {
sessionsState.graceExpiresAt = 0;
sessionsState.authMethod = data.code === 'password-required' || data.code === 'invalid-password' ? 'password' : sessionsState.authMethod;
configureSessionRevokeCredentialField();
updateSessionsHeaderMeta();
showSessionRevokeModalFeedback(data.error || 'Verification failed.', true);
return;
}
if (data.error === 'invalid or missing action token') {
showSessionRevokeModalFeedback('Security token expired. Please click Delete again.', true);
return;
}
showSessionRevokeModalFeedback(data.error || 'Failed to delete server.', true);
return;
}
sessionsState.graceExpiresAt = Number(data.graceExpiresAt || sessionsState.graceExpiresAt || 0);
updateSessionsHeaderMeta();
const deleteQueued = res.status === 202 || data.deleting === true;
closeSessionRevokeModal();
showSuccessToast(deleteQueued ? `Delete queued for ${name}` : `Deleted ${name}`);
const targetLower = name.toLowerCase();
if (serversListEl) {
serversListEl.querySelectorAll('.server-row').forEach(row => {
if (String(row.dataset.name || '').trim().toLowerCase() === targetLower) row.remove();
});
if (serversListEl.querySelectorAll('.server-row').length === 0) {
serversListEl.innerHTML = 'No servers found.
';
}
}
_resourcesCache.delete(targetLower);
_cachedServersList = _cachedServersList.filter(item => String(item?.name || item || '').trim().toLowerCase() !== targetLower);
loadServers(_serversPage, _serversSearch).catch((refreshErr) => {
console.warn('[servers] refresh after delete failed', refreshErr);
});
} catch (err) {
console.error('[servers] delete failed', err);
const isAbort = err && (err.name === 'AbortError' || /aborted/i.test(String(err.message || '')));
showSessionRevokeModalFeedback(isAbort ? 'Delete request timed out. Refresh the server list and check whether the node completed it.' : (err.message || 'Network error while deleting server.'), true);
} finally {
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = false;
restoreSecurityModalConfirmButton();
}
if (sourceButton) sourceButton.disabled = false;
}
}
async function changeServerSuspensionWithVerification(serverName, nextSuspended = true, credentialValue = '') {
const name = String(serverName || '').trim();
if (!name) return;
const suspend = nextSuspended !== false;
const sourceButton = sessionsState.selectedServerSuspension?.button || null;
const expectedTargetId = sessionsState.selectedServerSuspension?.expectedTargetId;
let actionToken = String(sessionsState.selectedServerSuspension?.actionToken || getServerSuspensionToken(name) || '').trim();
const requiresVerification = !isGraceActive();
const passwordMode = sessionsState.authMethod === 'password';
const credential = passwordMode ? String(credentialValue || '') : String(credentialValue || '').replace(/\s+/g, '');
if (requiresVerification) {
if (passwordMode) {
if (!credential) {
showSessionRevokeModalFeedback('Enter your current password.', true);
sessionRevokeTwoFactorInput?.focus();
return;
}
} else if (!/^\d{6}$/.test(credential)) {
showSessionRevokeModalFeedback('Enter a valid 6-digit code.', true);
sessionRevokeTwoFactorInput?.focus();
return;
}
}
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = true;
sessionRevokeModalConfirm.innerHTML = suspend
? ' Suspending...'
: ' Restoring...';
}
if (sourceButton) sourceButton.disabled = true;
try {
if (!actionToken) {
actionToken = await refreshServerSuspensionToken(name);
if (sessionsState.selectedServerSuspension) sessionsState.selectedServerSuspension.actionToken = actionToken;
}
const sendChange = async (token) => {
const res = await fetchWithTimeout(`/api/settings/servers/${encodeURIComponent(name)}/suspension`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': token,
},
body: JSON.stringify({
suspended: suspend,
expectedTargetId,
twoFactorCode: requiresVerification && !passwordMode ? credential : undefined,
currentPassword: requiresVerification && passwordMode ? credential : undefined,
}),
}, suspend ? 70000 : 15000);
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
return { res, data };
};
let result = await sendChange(actionToken);
if (!result.res.ok && result.data?.error === 'invalid or missing action token') {
const freshToken = await refreshServerSuspensionToken(name);
if (freshToken && freshToken !== actionToken) {
actionToken = freshToken;
if (sessionsState.selectedServerSuspension) sessionsState.selectedServerSuspension.actionToken = freshToken;
result = await sendChange(freshToken);
}
}
const { res, data } = result;
if (!res.ok) {
if (data.code === '2fa-required' || data.code === 'invalid-2fa' || data.code === 'password-required' || data.code === 'invalid-password') {
sessionsState.graceExpiresAt = 0;
sessionsState.authMethod = data.code === 'password-required' || data.code === 'invalid-password' ? 'password' : sessionsState.authMethod;
configureSessionRevokeCredentialField();
updateSessionsHeaderMeta();
showSessionRevokeModalFeedback(data.error || 'Verification failed.', true);
return;
}
if (data.error === 'invalid or missing action token') {
showSessionRevokeModalFeedback(`Security token expired. Please click ${suspend ? 'Suspend' : 'Restore'} again.`, true);
return;
}
showSessionRevokeModalFeedback(data.error || `Failed to ${suspend ? 'suspend' : 'restore'} server.`, true);
return;
}
if (data.revokeSecurity) applyRevokeSecurityFromPayload(data.revokeSecurity);
else {
sessionsState.graceExpiresAt = Number(data.graceExpiresAt || sessionsState.graceExpiresAt || 0);
updateSessionsHeaderMeta();
}
closeSessionRevokeModal();
showSuccessToast(`${suspend ? 'Suspended' : 'Restored'} ${data.server || name}`);
await loadServers(_serversPage, _serversSearch);
} catch (err) {
console.error('[servers] suspension change failed', err);
showSessionRevokeModalFeedback(err.message || `Network error while ${suspend ? 'suspending' : 'restoring'} server.`, true);
} finally {
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = false;
restoreSecurityModalConfirmButton();
}
if (sourceButton) sourceButton.disabled = false;
}
}
async function deleteAccountWithVerification(email, credentialValue = '') {
const targetEmail = String(email || '').trim();
if (!targetEmail) return;
const sourceButton = sessionsState.selectedAccountDelete?.button || null;
const accountTarget = sessionsState.selectedAccountDelete?.accountTarget;
let actionToken = String(sessionsState.selectedAccountDelete?.actionToken || getAccountDeleteToken(targetEmail) || '').trim();
const requiresVerification = !isGraceActive();
const credential = String(credentialValue || '');
if (requiresVerification && !validateSessionRevokeAccountCredentials(credential)) return;
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = true;
sessionRevokeModalConfirm.innerHTML = ' Deleting...';
}
if (sourceButton) sourceButton.disabled = true;
try {
if (!actionToken) {
actionToken = await refreshAccountDeleteToken(targetEmail);
if (sessionsState.selectedAccountDelete) sessionsState.selectedAccountDelete.actionToken = actionToken;
}
const sendDelete = async (token) => {
const res = await fetch(`/api/settings/accounts/${encodeURIComponent(targetEmail)}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'x-action-token': token,
},
body: JSON.stringify(window.ADPanelAccountTargets.payload(accountTarget, collectAccountActionCredentialPayload({}, sessionRevokeTwoFactorInput, sessionRevokeTotpSection, sessionRevokeTotpInput))),
});
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
return { res, data };
};
let result = await sendDelete(actionToken);
if (!result.res.ok && result.data?.error === 'invalid or missing action token') {
const freshToken = await refreshAccountDeleteToken(targetEmail);
if (freshToken && freshToken !== actionToken) {
actionToken = freshToken;
if (sessionsState.selectedAccountDelete) sessionsState.selectedAccountDelete.actionToken = freshToken;
result = await sendDelete(freshToken);
}
}
const { res, data } = result;
if (!res.ok) {
if (handleSessionRevokeAccountChallenge(data)) {
// The single-use delete token was consumed by this failed
// attempt; the server re-mints it on every step-up challenge.
const remintedDeleteToken = String(data.deleteToken || '').trim();
if (remintedDeleteToken) {
if (sessionsState.selectedAccountDelete) sessionsState.selectedAccountDelete.actionToken = remintedDeleteToken;
storeAccountDeleteToken(targetEmail, remintedDeleteToken);
}
return;
}
if (data.error === 'invalid or missing action token') {
showSessionRevokeModalFeedback('Security token expired. Please click Delete again.', true);
return;
}
showSessionRevokeModalFeedback(data.error || 'Failed to delete user.', true);
return;
}
sessionsState.graceExpiresAt = Number(data.graceExpiresAt || sessionsState.graceExpiresAt || 0);
updateSessionsHeaderMeta();
closeSessionRevokeModal();
showSuccessToast(`Deleted ${targetEmail}`);
await loadAccounts();
} catch (err) {
console.error('[accounts] delete failed', err);
showSessionRevokeModalFeedback(err.message || 'Network error while deleting user.', true);
} finally {
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = false;
restoreSecurityModalConfirmButton();
}
if (sourceButton) sourceButton.disabled = false;
}
}
async function changeAccountSuspensionWithVerification(email, nextSuspended, credentialValue = '') {
const targetEmail = String(email || '').trim();
if (!targetEmail) return;
const suspend = !!nextSuspended;
const sourceButton = sessionsState.selectedAccountSuspension?.button || null;
const accountTarget = sessionsState.selectedAccountSuspension?.accountTarget;
let actionToken = String(sessionsState.selectedAccountSuspension?.actionToken || getAccountSuspensionToken(targetEmail) || '').trim();
const requiresVerification = !isGraceActive();
const credential = String(credentialValue || '');
if (requiresVerification && !validateSessionRevokeAccountCredentials(credential)) return;
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = true;
sessionRevokeModalConfirm.innerHTML = suspend
? ' Suspending...'
: ' Unsuspending...';
}
if (sourceButton) sourceButton.disabled = true;
try {
if (!actionToken) {
actionToken = await refreshAccountSuspensionToken(targetEmail);
if (sessionsState.selectedAccountSuspension) sessionsState.selectedAccountSuspension.actionToken = actionToken;
}
const sendChange = async (token) => {
const res = await fetch(`/api/settings/accounts/${encodeURIComponent(targetEmail)}/suspension`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': token,
},
body: JSON.stringify(window.ADPanelAccountTargets.payload(accountTarget, collectAccountActionCredentialPayload({
suspended: suspend,
}, sessionRevokeTwoFactorInput, sessionRevokeTotpSection, sessionRevokeTotpInput))),
});
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
return { res, data };
};
let result = await sendChange(actionToken);
if (!result.res.ok && result.data?.error === 'invalid or missing action token') {
const freshToken = await refreshAccountSuspensionToken(targetEmail);
if (freshToken && freshToken !== actionToken) {
actionToken = freshToken;
if (sessionsState.selectedAccountSuspension) sessionsState.selectedAccountSuspension.actionToken = freshToken;
result = await sendChange(freshToken);
}
}
const { res, data } = result;
if (!res.ok) {
if (handleSessionRevokeAccountChallenge(data)) {
// The single-use suspension token was consumed by this failed
// attempt; the server re-mints it on every step-up challenge.
const remintedSuspensionToken = String(data.suspensionToken || '').trim();
if (remintedSuspensionToken) {
if (sessionsState.selectedAccountSuspension) sessionsState.selectedAccountSuspension.actionToken = remintedSuspensionToken;
storeAccountSuspensionToken(targetEmail, remintedSuspensionToken);
}
return;
}
if (data.error === 'invalid or missing action token') {
showSessionRevokeModalFeedback('Security token expired. Please click the account action again.', true);
return;
}
showSessionRevokeModalFeedback(data.error || `Failed to ${suspend ? 'suspend' : 'unsuspend'} account.`, true);
return;
}
sessionsState.graceExpiresAt = Number(data.graceExpiresAt || sessionsState.graceExpiresAt || 0);
updateSessionsHeaderMeta();
closeSessionRevokeModal();
showSuccessToast(`${suspend ? 'Suspended' : 'Unsuspended'} ${targetEmail}`);
await loadAccounts();
if (typeof loadSessions === 'function') {
loadSessions(sessionsState.page, sessionsSearchInput?.value || '').catch(() => {});
}
} catch (err) {
console.error('[accounts] suspension change failed', err);
showSessionRevokeModalFeedback(err.message || `Network error while ${suspend ? 'suspending' : 'unsuspending'} account.`, true);
} finally {
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = false;
restoreSecurityModalConfirmButton();
}
if (sourceButton) sourceButton.disabled = false;
}
}
// --- Access-list mutations (revoke access / agent-access toggle) ---
// Both endpoints are step-up protected server-side like grant-perms, so
// these flows route through the shared security modal: with a live grace
// window they send directly, otherwise the modal collects the acting
// admin's current password and — after a 2fa-required challenge — their
// own 6-digit TOTP code, and the request retries with it.
function openRevokeAccessVerificationModal(email, server, sourceButton) {
const targetEmail = String(email || '').trim();
const targetServer = String(server || '').trim();
if (!targetEmail || !targetServer) return;
// With a live verified grace window the step-up is already satisfied;
// send directly without prompting (same rule as the perms grant).
if (isGraceActive()) {
sessionsState.selectedAccessRevoke = { email: targetEmail, server: targetServer, button: sourceButton || null, accountTarget: accountModal._accountTarget };
return revokeAccessWithVerification(targetEmail, targetServer, '');
}
sessionsState.securityModalMode = 'revoke-access';
sessionsState.selectedSession = null;
sessionsState.selectedServerDelete = null;
sessionsState.selectedServerSuspension = null;
sessionsState.selectedAccountDelete = null;
sessionsState.selectedAccountSuspension = null;
if (typeof window.resolvePendingDatabaseInstall === 'function') window.resolvePendingDatabaseInstall();
else sessionsState.selectedDatabaseInstall = null;
sessionsState.selectedPermsGrant = null;
sessionsState.selectedAgentAccess = null;
sessionsState.selectedAccessRevoke = { email: targetEmail, server: targetServer, button: sourceButton || null, accountTarget: accountModal._accountTarget };
setSecurityModalPresentation({
title: 'Revoke Server Access',
targetLabel: 'Target Account',
targetValue: targetEmail,
targetSubvalue: `Server: ${targetServer} — the account loses its access to this server.`,
confirmHtml: ' Revoke Access',
danger: true,
});
if (sessionRevokeTwoFactorInput) {
sessionRevokeTwoFactorInput.value = '';
}
showSessionRevokeModalFeedback('');
if (sessionRevokeModalOverlay) {
sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false');
sessionRevokeModalOverlay.classList.add('show');
}
if (sessionRevokeModal) {
sessionRevokeModal.classList.add('show');
}
window.setTimeout(() => {
if (isGraceActive()) sessionRevokeModalConfirm?.focus();
else sessionRevokeTwoFactorInput?.focus();
}, 40);
}
window.openRevokeAccessVerificationModal = openRevokeAccessVerificationModal;
async function revokeAccessWithVerification(email, server, credentialValue = '') {
const targetEmail = String(email || '').trim();
const targetServer = String(server || '').trim();
if (!targetEmail || !targetServer) return;
const sourceButton = sessionsState.selectedAccessRevoke?.button || null;
const accountTarget = sessionsState.selectedAccessRevoke?.accountTarget;
const getRemoveToken = () => String((accountsListEl?._actionTokens || {}).removeAccess || '').trim();
const requiresVerification = !isGraceActive();
const credential = String(credentialValue || '');
if (requiresVerification && !validateSessionRevokeAccountCredentials(credential)) return;
const modalFeedback = (message) => {
if (sessionRevokeModalOverlay?.classList.contains('show')) showSessionRevokeModalFeedback(message, true);
else alert(message);
};
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = true;
sessionRevokeModalConfirm.innerHTML = ' Revoking...';
}
if (sourceButton) sourceButton.disabled = true;
try {
const sendRevoke = async (token) => {
const res = await fetch(`/api/settings/accounts/${encodeURIComponent(targetEmail)}/remove`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': token || '',
},
body: JSON.stringify(window.ADPanelAccountTargets.payload(accountTarget, collectAccountActionCredentialPayload({
server: targetServer,
}, sessionRevokeTwoFactorInput, sessionRevokeTotpSection, sessionRevokeTotpInput))),
});
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
return { res, data };
};
let result = await sendRevoke(getRemoveToken());
if (!result.res.ok && result.data?.error === 'invalid or missing action token' && typeof loadAccounts === 'function') {
await loadAccounts();
const freshToken = getRemoveToken();
if (freshToken) result = await sendRevoke(freshToken);
}
const { res, data } = result;
if (!res.ok) {
if (isAccountActionChallengeCode(data, true)) {
// A challenge means no live grant covers this action; drop any
// local grace BEFORE potentially reopening the modal so it is
// shown instead of re-sending credential-less.
sessionsState.graceExpiresAt = 0;
if (!sessionRevokeModalOverlay?.classList.contains('show')) {
openRevokeAccessVerificationModal(targetEmail, targetServer, sourceButton);
}
handleSessionRevokeAccountChallenge(data, { includeRateLimit: true });
return;
}
if (data.error === 'invalid or missing action token') {
modalFeedback('Security token expired. Please reopen the access dialog and try again.');
return;
}
modalFeedback(data.error || 'Failed to revoke access.');
return;
}
sessionsState.graceExpiresAt = Number(data.graceExpiresAt || sessionsState.graceExpiresAt || 0);
updateSessionsHeaderMeta();
closeSessionRevokeModal();
setSavedPerms(targetEmail, targetServer, {});
showSuccessToast(`Access revoked for ${targetEmail} on ${targetServer}`);
if (accountModalOverlay?.classList.contains('show')) {
openManageAccessModal(targetEmail);
}
} catch (err) {
console.error('[accounts] revoke access failed', err);
modalFeedback(err.message || 'Network error while revoking access.');
} finally {
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = false;
restoreSecurityModalConfirmButton();
}
if (sourceButton) sourceButton.disabled = false;
}
}
function openAgentAccessVerificationModal(email, enabled, toggleEl) {
const targetEmail = String(email || '').trim();
if (!targetEmail) return;
const nextEnabled = !!enabled;
sessionsState.securityModalMode = 'agent-access';
sessionsState.selectedSession = null;
sessionsState.selectedServerDelete = null;
sessionsState.selectedServerSuspension = null;
sessionsState.selectedAccountDelete = null;
sessionsState.selectedAccountSuspension = null;
if (typeof window.resolvePendingDatabaseInstall === 'function') window.resolvePendingDatabaseInstall();
else sessionsState.selectedDatabaseInstall = null;
sessionsState.selectedPermsGrant = null;
sessionsState.selectedAccessRevoke = null;
sessionsState.selectedAgentAccess = { email: targetEmail, enabled: nextEnabled, toggle: toggleEl || null, accountTarget: window.ADPanelAccountTargets.select(targetEmail) };
setSecurityModalPresentation({
title: nextEnabled ? 'Enable Agent Access' : 'Disable Agent Access',
targetLabel: 'Target Account',
targetValue: targetEmail,
targetSubvalue: nextEnabled
? 'The account will be able to use the panel AI assistant on its accessible servers.'
: 'The account will lose access to the panel AI assistant.',
confirmHtml: ` ${nextEnabled ? 'Enable' : 'Disable'}`,
danger: nextEnabled,
});
if (sessionRevokeTwoFactorInput) {
sessionRevokeTwoFactorInput.value = '';
}
showSessionRevokeModalFeedback('');
if (sessionRevokeModalOverlay) {
sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false');
sessionRevokeModalOverlay.classList.add('show');
}
if (sessionRevokeModal) {
sessionRevokeModal.classList.add('show');
}
window.setTimeout(() => {
if (isGraceActive()) sessionRevokeModalConfirm?.focus();
else sessionRevokeTwoFactorInput?.focus();
}, 40);
}
async function setAgentAccessWithVerification(email, enabled, credentialValue = '', toggleEl = null) {
const targetEmail = String(email || '').trim();
if (!targetEmail) return;
const nextEnabled = !!enabled;
const toggle = toggleEl || sessionsState.selectedAgentAccess?.toggle || null;
const accountTarget = sessionsState.selectedAgentAccess?.accountTarget || window.ADPanelAccountTargets.select(targetEmail);
const modalOpen = !!sessionRevokeModalOverlay?.classList.contains('show');
const requiresVerification = !isGraceActive();
const credential = String(credentialValue || '');
if (requiresVerification && !credential) {
// First hop from the toggle: the server state is unchanged, so put
// the switch back and collect the credential in the modal first.
if (!modalOpen) {
if (toggle && toggle.isConnected) toggle.checked = !nextEnabled;
openAgentAccessVerificationModal(targetEmail, nextEnabled, toggle);
return;
}
}
if (requiresVerification && !validateSessionRevokeAccountCredentials(credential)) return;
const modalFeedback = (message) => {
if (sessionRevokeModalOverlay?.classList.contains('show')) showSessionRevokeModalFeedback(message, true);
else alert(message);
};
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = true;
sessionRevokeModalConfirm.innerHTML = ' Saving...';
}
if (toggle) toggle.disabled = true;
try {
const getAgentToken = () => String((accountsListEl?._actionTokens || {}).setAgentAccess || '').trim();
const sendChange = async (token) => {
const res = await fetch(`/api/settings/accounts/${encodeURIComponent(targetEmail)}/agent-access`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': token || '',
},
body: JSON.stringify(window.ADPanelAccountTargets.payload(accountTarget, collectAccountActionCredentialPayload({
enabled: nextEnabled,
}, sessionRevokeTwoFactorInput, sessionRevokeTotpSection, sessionRevokeTotpInput))),
});
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
return { res, data };
};
let result = await sendChange(getAgentToken());
if (!result.res.ok && result.data?.error === 'invalid or missing action token' && typeof loadAccounts === 'function') {
await loadAccounts();
const freshToken = getAgentToken();
if (freshToken) result = await sendChange(freshToken);
}
const { res, data } = result;
if (!res.ok) {
if (isAccountActionChallengeCode(data, true)) {
sessionsState.graceExpiresAt = 0;
if (toggle && toggle.isConnected) toggle.checked = !nextEnabled;
if (!sessionRevokeModalOverlay?.classList.contains('show')) {
openAgentAccessVerificationModal(targetEmail, nextEnabled, toggle);
}
handleSessionRevokeAccountChallenge(data, { includeRateLimit: true });
return;
}
if (toggle && toggle.isConnected) toggle.checked = !nextEnabled;
if (data.error === 'invalid or missing action token') {
modalFeedback('Security token expired. Please try again.');
return;
}
modalFeedback(data.error || 'Failed to update agent access');
return;
}
sessionsState.graceExpiresAt = Number(data.graceExpiresAt || sessionsState.graceExpiresAt || 0);
updateSessionsHeaderMeta();
if (modalOpen) closeSessionRevokeModal();
if (toggle && toggle.isConnected) toggle.checked = nextEnabled;
else if (typeof loadAccounts === 'function') await loadAccounts(); // retry path re-rendered the list mid-flight
showSuccessToast(`Agent access ${nextEnabled ? 'enabled' : 'disabled'} for ${targetEmail}`);
} catch (err) {
console.error('[accounts] agent access change failed', err);
if (toggle && toggle.isConnected) toggle.checked = !nextEnabled;
modalFeedback(err.message || 'Network error while updating agent access.');
} finally {
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.disabled = false;
restoreSecurityModalConfirmButton();
}
if (toggle) toggle.disabled = false;
}
}
if (sessionsSearchInput) {
sessionsSearchInput.addEventListener('input', (event) => {
const nextValue = String(event.target.value || '').trim();
window.clearTimeout(sessionsState.searchTimer);
sessionsState.searchTimer = window.setTimeout(() => {
loadSessions(1, nextValue);
}, 280);
});
}
if (sessionsPagination) {
sessionsPagination.addEventListener('click', (e) => {
const button = e.target.closest('button[data-sessions-page]');
if (!button || button.disabled) return;
const nextPage = parseInt(button.dataset.sessionsPage, 10);
if (!nextPage || nextPage < 1 || nextPage > sessionsState.totalPages) return;
loadSessions(nextPage, sessionsSearchInput?.value || '');
});
}
if (sessionsList) {
sessionsList.addEventListener('click', (e) => {
const button = e.target.closest('.session-revoke-btn');
if (!button) return;
const revokeToken = decodeURIComponent(button.dataset.revokeToken || '');
const displayId = decodeURIComponent(button.dataset.sessionDisplay || '');
const email = decodeURIComponent(button.dataset.sessionEmail || '');
const targetType = button.dataset.targetType === 'remembered' ? 'remembered' : 'session';
if (isGraceActive()) {
// Same in-flight guard as the confirm button and the Enter key:
// revokeSession disables sessionRevokeModalConfirm for its whole
// duration, so a second click (double-click) must not double-submit
// this row's single-use revoke token.
if (sessionRevokeModalConfirm?.disabled) return;
revokeSession(revokeToken, email, '', displayId, targetType);
return;
}
openSessionRevokeModal(revokeToken, displayId, email, targetType);
});
}
if (sessionRevokeModalClose) sessionRevokeModalClose.addEventListener('click', closeSessionRevokeModal);
if (sessionRevokeModalCancel) sessionRevokeModalCancel.addEventListener('click', closeSessionRevokeModal);
if (sessionRevokeModalOverlay) {
sessionRevokeModalOverlay.addEventListener('click', (e) => {
if (e.target === sessionRevokeModalOverlay) {
closeSessionRevokeModal();
}
});
}
if (sessionRevokeTwoFactorInput) {
sessionRevokeTwoFactorInput.addEventListener('input', (e) => {
// Digit-sanitizing applies only while the field acts as the 2FA
// input (server modes). Account modes reconfigure it as the
// acting admin's password field, which must never be stripped.
if (isAccountSecurityModalMode(sessionsState.securityModalMode)) return;
if (sessionsState.authMethod !== 'password') {
e.target.value = String(e.target.value || '').replace(/\D/g, '').slice(0, 6);
}
});
sessionRevokeTwoFactorInput.addEventListener('keydown', (e) => {
// In-flight guard, the same one the confirm button relies on:
// while any verification action runs, sessionRevokeModalConfirm
// is disabled (and re-enabled in that action's finally block), so
// a second Enter must not start a concurrent one-time-token
// action. Double-submitting burns the single-use revoke token and
// the loser reports a misleading session-action-expired "reload
// Sessions" error even though the winner already adopted a fresh
// retryable token.
if (e.key === 'Enter' && sessionRevokeModalConfirm?.disabled) return;
if (e.key === 'Enter' && sessionsState.selectedDatabaseInstall) {
verifyDatabaseInstallWithCredential(sessionRevokeTwoFactorInput.value);
return;
}
if (e.key === 'Enter' && sessionsState.selectedPermsGrant) {
grantPermsWithVerification(
sessionsState.selectedPermsGrant.email,
sessionsState.selectedPermsGrant.server,
sessionsState.selectedPermsGrant.permissions,
sessionRevokeTwoFactorInput.value
);
return;
}
if (e.key === 'Enter' && sessionsState.selectedAccountDelete) {
deleteAccountWithVerification(
sessionsState.selectedAccountDelete.email,
sessionRevokeTwoFactorInput.value
);
return;
}
if (e.key === 'Enter' && sessionsState.selectedAccountSuspension) {
changeAccountSuspensionWithVerification(
sessionsState.selectedAccountSuspension.email,
sessionsState.selectedAccountSuspension.suspended,
sessionRevokeTwoFactorInput.value
);
return;
}
if (e.key === 'Enter' && sessionsState.selectedServerSuspension) {
changeServerSuspensionWithVerification(
sessionsState.selectedServerSuspension.name,
sessionsState.selectedServerSuspension.suspended,
sessionRevokeTwoFactorInput.value
);
return;
}
if (e.key === 'Enter' && sessionsState.selectedServerDelete) {
deleteServerWithVerification(
sessionsState.selectedServerDelete.name,
sessionRevokeTwoFactorInput.value
);
return;
}
if (e.key === 'Enter' && sessionsState.selectedAccessRevoke && sessionsState.securityModalMode === 'revoke-access') {
revokeAccessWithVerification(
sessionsState.selectedAccessRevoke.email,
sessionsState.selectedAccessRevoke.server,
sessionRevokeTwoFactorInput.value
);
return;
}
if (e.key === 'Enter' && sessionsState.selectedAgentAccess && sessionsState.securityModalMode === 'agent-access') {
setAgentAccessWithVerification(
sessionsState.selectedAgentAccess.email,
sessionsState.selectedAgentAccess.enabled,
sessionRevokeTwoFactorInput.value,
sessionsState.selectedAgentAccess.toggle
);
return;
}
if (e.key === 'Enter' && sessionsState.selectedSession) {
revokeSession(
sessionsState.selectedSession.revokeToken,
sessionsState.selectedSession.email,
sessionRevokeTwoFactorInput.value,
sessionsState.selectedSession.displayId,
sessionsState.selectedSession.targetType
);
}
});
}
if (sessionRevokeModalConfirm) {
sessionRevokeModalConfirm.addEventListener('click', () => {
if (sessionsState.selectedDatabaseInstall) {
verifyDatabaseInstallWithCredential(sessionRevokeTwoFactorInput?.value || '');
return;
}
if (sessionsState.selectedPermsGrant) {
grantPermsWithVerification(
sessionsState.selectedPermsGrant.email,
sessionsState.selectedPermsGrant.server,
sessionsState.selectedPermsGrant.permissions,
sessionRevokeTwoFactorInput?.value || ''
);
return;
}
if (sessionsState.selectedAccountDelete) {
deleteAccountWithVerification(
sessionsState.selectedAccountDelete.email,
sessionRevokeTwoFactorInput?.value || ''
);
return;
}
if (sessionsState.selectedAccountSuspension) {
changeAccountSuspensionWithVerification(
sessionsState.selectedAccountSuspension.email,
sessionsState.selectedAccountSuspension.suspended,
sessionRevokeTwoFactorInput?.value || ''
);
return;
}
if (sessionsState.selectedServerSuspension) {
changeServerSuspensionWithVerification(
sessionsState.selectedServerSuspension.name,
sessionsState.selectedServerSuspension.suspended,
sessionRevokeTwoFactorInput?.value || ''
);
return;
}
if (sessionsState.selectedServerDelete) {
deleteServerWithVerification(
sessionsState.selectedServerDelete.name,
sessionRevokeTwoFactorInput?.value || ''
);
return;
}
if (sessionsState.selectedAccessRevoke && sessionsState.securityModalMode === 'revoke-access') {
revokeAccessWithVerification(
sessionsState.selectedAccessRevoke.email,
sessionsState.selectedAccessRevoke.server,
sessionRevokeTwoFactorInput?.value || ''
);
return;
}
if (sessionsState.selectedAgentAccess && sessionsState.securityModalMode === 'agent-access') {
setAgentAccessWithVerification(
sessionsState.selectedAgentAccess.email,
sessionsState.selectedAgentAccess.enabled,
sessionRevokeTwoFactorInput?.value || '',
sessionsState.selectedAgentAccess.toggle
);
return;
}
if (!sessionsState.selectedSession) return;
revokeSession(
sessionsState.selectedSession.revokeToken,
sessionsState.selectedSession.email,
sessionRevokeTwoFactorInput?.value || '',
sessionsState.selectedSession.displayId,
sessionsState.selectedSession.targetType
);
});
}
// Enter on the challenge-revealed account-action TOTP field submits the
// pending action, mirroring the credential input above; the same in-flight
// guard applies (a disabled confirm button means an action is running).
if (sessionRevokeTotpInput) {
bindAccountActionTotpInput(sessionRevokeTotpInput);
sessionRevokeTotpInput.addEventListener('keydown', (e) => {
if (e.key !== 'Enter') return;
if (sessionRevokeModalConfirm?.disabled) return;
sessionRevokeModalConfirm?.click();
});
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && sessionRevokeModalOverlay?.classList.contains('show')) {
closeSessionRevokeModal();
}
});
if (sessionsBtn) {
sessionsBtn.addEventListener('click', () => {
loadSessions(sessionsState.searchActive ? 1 : sessionsState.page, sessionsSearchInput?.value || '');
});
}
if (sessionsPanel?.classList.contains('active')) {
loadSessions(1, sessionsSearchInput?.value || '');
} else {
updateSessionsHeaderMeta();
renderSessionsSummary();
}
})();
(function () {
'use strict';
const phpmyadminToggle = document.getElementById('phpmyadminToggle');
const phpmyadminDetails = document.getElementById('phpmyadminDetails');
const phpmyadminStatus = document.getElementById('phpmyadminStatus');
const phpmyadminCard = document.getElementById('phpmyadminCard');
const dbUsersSection = document.getElementById('dbUsersSection');
const dbUsersList = document.getElementById('dbUsersList');
const dbTypeSection = document.getElementById('dbTypeSection');
const dbTypeCurrent = document.getElementById('dbTypeCurrent');
const phpmyadminAccessSection = document.getElementById('phpmyadminAccessSection');
const phpmyadminUrl = document.getElementById('phpmyadminUrl');
const openPhpmyadminUrl = document.getElementById('openPhpmyadminUrl');
const addDbUserBtn = document.getElementById('addDbUserBtn');
const changeDbTypeBtn = document.getElementById('changeDbTypeBtn');
const dbSetupModalOverlay = document.getElementById('dbSetupModalOverlay');
const dbSetupModal = document.getElementById('dbSetupModal');
const dbSetupModalClose = document.getElementById('dbSetupModalClose');
const dbSetupCancel = document.getElementById('dbSetupCancel');
const dbSetupSave = document.getElementById('dbSetupSave');
const dbSetupFeedback = document.getElementById('dbSetupFeedback');
const dbHost = document.getElementById('db_host');
const dbPort = document.getElementById('db_port');
const dbUsername = document.getElementById('db_username');
const dbPassword = document.getElementById('db_password');
const dbUserModalOverlay = document.getElementById('dbUserModalOverlay');
const dbUserModal = document.getElementById('dbUserModal');
const dbUserModalTitle = document.getElementById('dbUserModalTitle');
const dbUserModalClose = document.getElementById('dbUserModalClose');
const dbUserCancel = document.getElementById('dbUserCancel');
const dbUserSave = document.getElementById('dbUserSave');
const dbUserFeedback = document.getElementById('dbUserFeedback');
const dbuserUsername = document.getElementById('dbuser_username');
const dbuserPassword = document.getElementById('dbuser_password');
const dbUserPasswordStrength = document.getElementById('dbUserPasswordStrength');
const dbPassModalOverlay = document.getElementById('dbPassModalOverlay');
const dbPassModal = document.getElementById('dbPassModal');
const dbPassModalSubtitle = document.getElementById('dbPassModalSubtitle');
const dbPassModalClose = document.getElementById('dbPassModalClose');
const dbPassCancel = document.getElementById('dbPassCancel');
const dbPassSave = document.getElementById('dbPassSave');
const dbPassFeedback = document.getElementById('dbPassFeedback');
const dbpassUsername = document.getElementById('dbpass_username');
const dbpassPassword = document.getElementById('dbpass_password');
const dbpassConfirm = document.getElementById('dbpass_confirm');
const dbPassPasswordStrength = document.getElementById('dbPassPasswordStrength');
const dbChangeTypeModalOverlay = document.getElementById('dbChangeTypeModalOverlay');
const dbChangeTypeModal = document.getElementById('dbChangeTypeModal');
const dbChangeTypeModalClose = document.getElementById('dbChangeTypeModalClose');
const dbChangeTypeCancel = document.getElementById('dbChangeTypeCancel');
const dbChangeTypeSave = document.getElementById('dbChangeTypeSave');
const dbChangeTypeFeedback = document.getElementById('dbChangeTypeFeedback');
const dbChangeHost = document.getElementById('db_change_host');
const dbChangePort = document.getElementById('db_change_port');
const dbChangeUsername = document.getElementById('db_change_username');
const dbChangePassword = document.getElementById('db_change_password');
let dbConfig = null;
let dbUsers = [];
let phpmyadminEnabled = false;
function escapeHtmlDb(str) {
if (!str) return '';
return String(str)
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function checkPasswordStrength(password) {
if (!password) return '';
let strength = 'weak';
if (password.length >= 12 && /[A-Z]/.test(password) && /[0-9]/.test(password) && /[^A-Za-z0-9]/.test(password)) {
strength = 'strong';
} else if (password.length >= 10 && /[A-Z]/.test(password) && /[0-9]/.test(password)) {
strength = 'good';
} else if (password.length >= 8) {
strength = 'fair';
}
return `
`;
}
function showDbFeedback(el, msg, isError = false) {
if (!el) return;
el.textContent = msg;
el.className = 'node-feedback' + (isError ? ' error' : ' success');
el.style.display = msg ? 'block' : 'none';
}
function clearDbFeedback(el) {
if (el) {
el.textContent = '';
el.style.display = 'none';
}
}
function openModal(overlay, modal) {
if (overlay) overlay.classList.add('show');
if (modal) modal.classList.add('show');
}
function closeModal(overlay, modal) {
if (overlay) overlay.classList.remove('show');
if (modal) modal.classList.remove('show');
}
function getDefaultPort(dbType) {
switch (dbType) {
case 'mysql': return 3306;
case 'postgresql': return 5432;
case 'mongodb': return 27017;
default: return 3306;
}
}
function getDbTypeIcon(dbType) {
switch (dbType) {
case 'mysql': return 'fa-solid fa-database';
case 'postgresql': return 'fa-solid fa-database';
case 'mongodb': return 'fa-solid fa-leaf';
default: return 'fa-solid fa-database';
}
}
async function loadDbConfig() {
try {
const res = await fetchWithTimeout('/api/settings/database', {}, 8000);
if (!res.ok) {
console.warn('[database] Failed to load config');
return;
}
const data = await res.json();
dbConfig = data.config || null;
dbUsers = data.users || [];
phpmyadminEnabled = !!data.enabled;
dbActionTokens = data.actionTokens || {};
try {
window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
} catch (_) { }
updateDbUI();
} catch (err) {
console.error('[database] Load config error:', err);
}
}
window.refreshDbActionTokens = async function () {
// Re-mints the one-time tokens into the private store only; returning
// the store would let any script harvest every token.
await loadDbConfig();
};
window.loadDbConfig = loadDbConfig;
// Database action tokens are one-time and expire after 120 seconds, so
// idling on a confirm dialog (or replaying an already-consumed token)
// gets a 403 "invalid or missing action token" whose only recovery used
// to be a full page reload. fetchDbRequestWithTokenRetry re-mints the
// tokens via the matching loader and retries the request ONCE when the
// 403 is specifically a token rejection; every other response is
// returned untouched so existing handling keeps working.
//
// Step-up challenges (2fa-required / password-required) get the same
// treatment: the client-side grace snapshot that let the request ride
// without a credential can go stale while the page sits open (grant
// spent, expired server-side, clock skew) — the modal was then skipped
// client-side while the server demanded a fresh verification, and the
// admin was left with a bare "a valid 6-digit code is required" error
// and no popup until a page reload. On such a 403 the challenge payload
// is applied FIRST (it carries the server's authoritative grace state,
// which un-poisons the stale snapshot for every later flow), the
// security modal is opened with force (the server's requirement outranks
// the local grace), and the request is retried once after verification.
function isDbActionTokenErrorPayload(payload) {
if (!payload || typeof payload !== 'object') return false;
if (payload.code === 'ACTION_TOKEN_INVALID') return true;
return typeof payload.error === 'string' && /action token/i.test(payload.error);
}
function isDbStepUpChallengePayload(payload) {
return !!payload && typeof payload === 'object' &&
(payload.code === '2fa-required' || payload.code === 'password-required');
}
// Only one flow may own the challenge modal at a time: a concurrent
// second challenge returns its original 403 instead of resolving the
// first flow's pending verification as "cancelled".
let _dbStepUpChallengeInFlight = false;
function _dbTokenRefreshFor(refreshKind) {
if (refreshKind === 'mongo') return window.loadMongoDBUsers;
if (refreshKind === 'db') return window.refreshDbActionTokens;
return null;
}
async function fetchDbRequestWithTokenRetry(fetchCall, refreshKind, options) {
const opts = options && typeof options === 'object' ? options : {};
let res = await fetchCall();
if (res.status !== 403) return res;
let probe = await res.clone().json().catch(() => ({}));
if (isDbStepUpChallengePayload(probe) && !_dbStepUpChallengeInFlight) {
// Server says a fresh step-up is required: sync the security state
// from the challenge payload, then verify through the modal and
// retry exactly once.
if (probe.revokeSecurity && typeof window.applyRevokeSecurityFromPayload === 'function') {
window.applyRevokeSecurityFromPayload(probe.revokeSecurity);
}
if (typeof window.openDatabaseInstallVerificationModal !== 'function') return res;
_dbStepUpChallengeInFlight = true;
let verified = null;
try {
verified = await window.openDatabaseInstallVerificationModal(opts.stepUpService || 'database', {
force: true,
titleText: 'Security Verification Required',
targetSubvalue: 'Confirm your identity to continue with this database action.',
});
} finally {
_dbStepUpChallengeInFlight = false;
}
if (!verified?.ok) return res;
if (typeof window.refreshDbActionTokens === 'function') {
await window.refreshDbActionTokens();
}
const retryRes = await fetchCall();
if (retryRes.status === 403) {
const retryProbe = await retryRes.clone().json().catch(() => ({}));
// The token re-mint can itself fail transiently (loadDbConfig
// swallows its own errors); a token rejection on the retry must
// not dead-end — fall back to the single token retry below.
if (isDbActionTokenErrorPayload(retryProbe)) {
const refresh = _dbTokenRefreshFor(refreshKind);
if (typeof refresh === 'function') {
await refresh();
return fetchCall();
}
}
if (isDbStepUpChallengePayload(retryProbe)) return retryRes;
}
return retryRes;
}
if (!isDbActionTokenErrorPayload(probe)) return res;
const refresh = _dbTokenRefreshFor(refreshKind);
if (typeof refresh !== 'function') return res;
await refresh();
return fetchCall();
}
// The pgAdmin/mongodb sections live in sibling IIFEs, so the bare helper
// name is unreachable there unless it is published on window.
window.fetchDbRequestWithTokenRetry = fetchDbRequestWithTokenRetry;
function updateDbUI() {
if (!phpmyadminToggle) return;
phpmyadminToggle.checked = phpmyadminEnabled;
if (phpmyadminEnabled && dbConfig) {
if (phpmyadminDetails) phpmyadminDetails.style.display = 'block';
if (phpmyadminStatus) {
// While a disable flow is running, its progress UI lives in this
// element (createDbDisableProgress captured the nodes). A config
// refresh mid-disable (e.g. the token re-mint inside a step-up
// challenge retry) must not overwrite the progress markup, or the
// deferred progress.finish() renders into detached nodes and the
// outcome feedback is lost.
if (typeof _dbDisableGuard === 'undefined' || !_dbDisableGuard) {
phpmyadminStatus.innerHTML = `
phpMyAdmin is active and running
`;
}
}
if (dbUsersSection) dbUsersSection.style.display = 'block';
renderDbUsers();
if (dbTypeSection) dbTypeSection.style.display = 'block';
updateDbTypeDisplay();
if (phpmyadminAccessSection) {
phpmyadminAccessSection.style.display = 'block';
if (phpmyadminUrl) phpmyadminUrl.textContent = 'Session-bound access (opens in a new tab)';
}
} else {
if (phpmyadminDetails) phpmyadminDetails.style.display = 'none';
if (dbUsersSection) dbUsersSection.style.display = 'none';
if (dbTypeSection) dbTypeSection.style.display = 'none';
if (phpmyadminAccessSection) phpmyadminAccessSection.style.display = 'none';
}
}
function updateDbTypeDisplay() {
if (!dbTypeCurrent || !dbConfig) return;
const icon = getDbTypeIcon(dbConfig.type);
const typeName = (dbConfig.type || 'mysql').charAt(0).toUpperCase() + (dbConfig.type || 'mysql').slice(1);
dbTypeCurrent.innerHTML = `
${escapeHtmlDb(typeName)}
${escapeHtmlDb(dbConfig.host || 'localhost')}:${dbConfig.port || getDefaultPort(dbConfig.type)}
`;
}
function renderDbUsers() {
if (!dbUsersList) return;
if (!dbUsers || dbUsers.length === 0) {
dbUsersList.innerHTML = `
No database users configured
`;
return;
}
dbUsersList.innerHTML = '';
dbUsers.forEach(user => {
const row = document.createElement('div');
row.className = 'db-user-row';
row.innerHTML = `
${escapeHtmlDb(user.username)}
${user.createdAt ? 'Created ' + new Date(user.createdAt).toLocaleDateString() : ''}
Password
`;
dbUsersList.appendChild(row);
});
}
async function confirmDatabaseInstallBeforeSetup(serviceLabel, resetToggle) {
if (typeof window.openDatabaseInstallVerificationModal !== 'function') {
alert('Security verification is unavailable. Please reload the page and try again.');
if (resetToggle) resetToggle();
return false;
}
const result = await window.openDatabaseInstallVerificationModal(serviceLabel);
if (!result?.ok) {
if (resetToggle) resetToggle();
return false;
}
if (typeof window.refreshDbActionTokens === 'function') {
await window.refreshDbActionTokens();
}
return true;
}
window.confirmDatabaseInstallBeforeSetup = confirmDatabaseInstallBeforeSetup;
// Audit finding 2.6: binding a database daemon to a non-loopback
// address exposes it to the network. The server enforces the
// ADPANEL_DB_ALLOWED_HOSTS allowlist and rejects wildcard binds
// regardless; this step-up makes the operator acknowledge the
// exposure explicitly before the request is even sent.
function isLoopbackDbHostClient(host) {
const h = String(host || '').trim().toLowerCase();
return h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '[::1]';
}
async function confirmRemoteDbBind(host, serviceLabel) {
if (isLoopbackDbHostClient(host)) return true;
const first = window.confirm(
`WARNING: "${host}" is not a loopback address.\n\n` +
`Binding ${serviceLabel} to this address makes the database reachable from the network it is attached to (and from the internet if the server has a public IP and the port is open).\n\n` +
`Recommended: keep the bind on localhost and use an SSH tunnel or the built-in web interface for remote access.\n\n` +
`Do you really want a remote (non-loopback) bind?`
);
if (!first) return false;
const second = window.confirm(
`Final confirmation: ${serviceLabel} will listen on "${host}" — NOT just localhost.\n\n` +
`Databases exposed to untrusted networks are routinely scanned and compromised. Only continue if this address is on a trusted private network AND the server firewall blocks the port from untrusted sources.\n\n` +
`Click OK to proceed with the remote bind.`
);
return second;
}
window.confirmRemoteDbBind = confirmRemoteDbBind;
// Shared with the pgAdmin/MongoDB IIFEs below (used to compute
// confirmRemoteBind on the setup payloads).
window.isLoopbackDbHostClient = isLoopbackDbHostClient;
async function openSetupModal(options = {}) {
if (!dbSetupModalOverlay || !dbSetupModal) return;
if (!options.skipVerification) {
const verified = await confirmDatabaseInstallBeforeSetup('phpmyadmin', () => {
if (phpmyadminToggle && !phpmyadminEnabled) phpmyadminToggle.checked = false;
});
if (!verified) return;
}
if (dbHost) dbHost.value = 'localhost';
if (dbPort) dbPort.value = '3306';
if (dbUsername) dbUsername.value = '';
if (dbPassword) dbPassword.value = '';
const mysqlRadio = document.querySelector('input[name="db_type"][value="mysql"]');
if (mysqlRadio) mysqlRadio.checked = true;
clearDbFeedback(dbSetupFeedback);
openModal(dbSetupModalOverlay, dbSetupModal);
}
window.openSetupModal = openSetupModal;
function closeSetupModal() {
closeModal(dbSetupModalOverlay, dbSetupModal);
}
async function saveDbSetup(confirmOrphan) {
if (!(await confirmDatabaseInstallBeforeSetup('phpmyadmin'))) return;
const dbType = document.querySelector('input[name="db_type"]:checked')?.value || 'mysql';
const host = dbHost?.value?.trim() || 'localhost';
const port = parseInt(dbPort?.value || getDefaultPort(dbType), 10);
const username = dbUsername?.value?.trim();
const password = dbPassword?.value;
if (!username) {
showDbFeedback(dbSetupFeedback, 'Username is required', true);
return;
}
if (!password) {
showDbFeedback(dbSetupFeedback, 'Password is required', true);
return;
}
if (dbSetupSave) {
dbSetupSave.disabled = true;
dbSetupSave.innerHTML = ' Setting up...';
}
try {
const res = await fetchDbRequestWithTokenRetry(() => fetch('/api/settings/database/setup', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-action-token': dbActionTokens.setup || '' },
body: JSON.stringify({
type: dbType,
host,
port,
username,
password,
confirmOrphan: confirmOrphan === true
})
}), 'db', { stepUpService: 'phpmyadmin' });
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
// Mirror of the confirmRemoteBind client pattern: a 409 asks for an
// explicit orphan confirmation, then the request is re-sent with
// confirmOrphan: true (the burned one-time token is re-minted by
// fetchDbRequestWithTokenRetry on the 403).
if (res.status === 409 && data.code === 'REMOTE_DROP_CONFIRMATION_REQUIRED' && confirmOrphan !== true) {
if (window.confirm(data.error + '\n\nClick OK to proceed anyway.')) {
return await saveDbSetup(true);
}
return;
}
if (!res.ok) {
showDbFeedback(dbSetupFeedback, data.error || 'Setup failed', true);
return;
}
const setupWarnings = Array.isArray(data.warnings) ? data.warnings : [];
showDbFeedback(dbSetupFeedback, setupWarnings.length > 0 ? 'phpMyAdmin setup complete! ' + setupWarnings.join(' ') : 'phpMyAdmin setup complete!', false);
phpmyadminEnabled = true;
await loadDbConfig();
if (phpmyadminToggle) phpmyadminToggle.checked = true;
setTimeout(() => {
closeSetupModal();
}, 800);
} catch (err) {
console.error('[database] Setup error:', err);
showDbFeedback(dbSetupFeedback, 'Network error', true);
} finally {
if (dbSetupSave) {
dbSetupSave.disabled = false;
dbSetupSave.innerHTML = ' Setup & Enable';
}
}
}
function openUserModal() {
if (!dbUserModalOverlay || !dbUserModal) return;
if (dbuserUsername) dbuserUsername.value = '';
if (dbuserPassword) dbuserPassword.value = '';
if (dbUserPasswordStrength) dbUserPasswordStrength.innerHTML = '';
clearDbFeedback(dbUserFeedback);
openModal(dbUserModalOverlay, dbUserModal);
}
function closeUserModal() {
closeModal(dbUserModalOverlay, dbUserModal);
}
async function saveDbUser() {
const username = dbuserUsername?.value?.trim();
const password = dbuserPassword?.value;
if (!username) {
showDbFeedback(dbUserFeedback, 'Username is required', true);
return;
}
if (!password || password.length < 8) {
showDbFeedback(dbUserFeedback, 'Password must be at least 8 characters', true);
return;
}
if (dbUserSave) {
dbUserSave.disabled = true;
dbUserSave.innerHTML = ' Creating...';
}
try {
const res = await fetchDbRequestWithTokenRetry(() => fetch('/api/settings/database/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-action-token': dbActionTokens.createUser || '' },
body: JSON.stringify({ username, password })
}), 'db');
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
if (!res.ok) {
showDbFeedback(dbUserFeedback, data.error || 'Failed to create user', true);
return;
}
showDbFeedback(dbUserFeedback, 'User created successfully!', false);
await loadDbConfig();
setTimeout(() => {
closeUserModal();
}, 600);
} catch (err) {
console.error('[database] Create user error:', err);
showDbFeedback(dbUserFeedback, 'Network error', true);
} finally {
if (dbUserSave) {
dbUserSave.disabled = false;
dbUserSave.innerHTML = ' Create User';
}
}
}
function openPasswordModal(username) {
if (!dbPassModalOverlay || !dbPassModal) return;
if (dbpassUsername) dbpassUsername.value = username;
if (dbPassModalSubtitle) dbPassModalSubtitle.textContent = `Update password for ${username}`;
if (dbpassPassword) dbpassPassword.value = '';
if (dbpassConfirm) dbpassConfirm.value = '';
if (dbPassPasswordStrength) dbPassPasswordStrength.innerHTML = '';
clearDbFeedback(dbPassFeedback);
openModal(dbPassModalOverlay, dbPassModal);
}
function closePasswordModal() {
closeModal(dbPassModalOverlay, dbPassModal);
}
async function saveDbPassword() {
const username = dbpassUsername?.value;
const password = dbpassPassword?.value;
const confirm = dbpassConfirm?.value;
if (!password || password.length < 8) {
showDbFeedback(dbPassFeedback, 'Password must be at least 8 characters', true);
return;
}
if (password !== confirm) {
showDbFeedback(dbPassFeedback, 'Passwords do not match', true);
return;
}
if (dbPassSave) {
dbPassSave.disabled = true;
dbPassSave.innerHTML = ' Updating...';
}
try {
const res = await fetchDbRequestWithTokenRetry(() => fetch(`/api/settings/database/users/${encodeURIComponent(username)}/password`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-action-token': dbActionTokens[`changePassword_${username}`] || '' },
body: JSON.stringify({ password })
}), 'db');
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
if (!res.ok) {
showDbFeedback(dbPassFeedback, data.error || 'Failed to update password', true);
return;
}
showDbFeedback(dbPassFeedback, 'Password updated successfully!', false);
setTimeout(() => {
closePasswordModal();
}, 600);
} catch (err) {
console.error('[database] Update password error:', err);
showDbFeedback(dbPassFeedback, 'Network error', true);
} finally {
if (dbPassSave) {
dbPassSave.disabled = false;
dbPassSave.innerHTML = ' Update Password';
}
}
}
async function deleteDbUser(username, confirmOrphan) {
if (!confirm(`Delete database user "${username}"? This cannot be undone.`)) return;
try {
const res = await fetchDbRequestWithTokenRetry(() => fetch(`/api/settings/database/users/${encodeURIComponent(username)}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json', 'x-action-token': dbActionTokens[`deleteUser_${username}`] || '' },
body: JSON.stringify({ confirmOrphan: confirmOrphan === true })
}), 'db');
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
// Mirror of the confirmRemoteBind client pattern: 409 asks for an
// explicit orphan confirmation (the account on a remote server cannot
// be revoked), then re-send with confirmOrphan: true.
if (res.status === 409 && data.code === 'REMOTE_DROP_CONFIRMATION_REQUIRED' && confirmOrphan !== true) {
if (window.confirm(data.error + '\n\nClick OK to remove the panel entry anyway.')) {
return await deleteDbUser(username, true);
}
return;
}
if (!res.ok) {
alert(data.error || 'Failed to delete user');
return;
}
if (data.warning) {
alert(data.warning);
}
await loadDbConfig();
} catch (err) {
console.error('[database] Delete user error:', err);
alert('Network error');
}
}
function openChangeTypeModal() {
if (!dbChangeTypeModalOverlay || !dbChangeTypeModal) return;
if (dbChangeHost) dbChangeHost.value = 'localhost';
if (dbChangePort) dbChangePort.value = '';
if (dbChangeUsername) dbChangeUsername.value = '';
if (dbChangePassword) dbChangePassword.value = '';
document.querySelectorAll('input[name="db_change_type"]').forEach(r => r.checked = false);
clearDbFeedback(dbChangeTypeFeedback);
openModal(dbChangeTypeModalOverlay, dbChangeTypeModal);
}
function closeChangeTypeModal() {
closeModal(dbChangeTypeModalOverlay, dbChangeTypeModal);
}
async function saveDbTypeChange(confirmOrphan) {
const dbType = document.querySelector('input[name="db_change_type"]:checked')?.value;
const host = dbChangeHost?.value?.trim() || 'localhost';
const port = parseInt(dbChangePort?.value || getDefaultPort(dbType), 10);
const username = dbChangeUsername?.value?.trim();
const password = dbChangePassword?.value;
if (!dbType) {
showDbFeedback(dbChangeTypeFeedback, 'Please select a database type', true);
return;
}
if (!username) {
showDbFeedback(dbChangeTypeFeedback, 'Username is required', true);
return;
}
if (!password) {
showDbFeedback(dbChangeTypeFeedback, 'Password is required', true);
return;
}
if (!confirm('This will remove all existing database users and settings. Continue?')) {
return;
}
// Change-type drops every previous engine's accounts, so it requires the
// same install-verification step-up as setup and disable (server-enforced;
// this prompt mints the grace grant the request rides on). The modal
// short-circuits without prompting when a verified grace window is
// already active — same pattern as disablePgAdmin.
if (typeof window.confirmDatabaseInstallBeforeSetup === 'function') {
const verified = await window.confirmDatabaseInstallBeforeSetup('phpmyadmin');
if (!verified) return;
}
if (dbChangeTypeSave) {
dbChangeTypeSave.disabled = true;
dbChangeTypeSave.innerHTML = ' Changing...';
}
try {
const res = await fetchDbRequestWithTokenRetry(() => fetch('/api/settings/database/change-type', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-action-token': dbActionTokens.changeType || '' },
body: JSON.stringify({
type: dbType,
host,
port,
username,
password,
confirmOrphan: confirmOrphan === true
})
}), 'db', { stepUpService: 'phpmyadmin' });
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
// Mirror of the confirmRemoteBind client pattern: 409 asks for an
// explicit orphan confirmation (the previous engine's users on a remote
// server cannot be revoked), then re-send with confirmOrphan: true.
if (res.status === 409 && data.code === 'REMOTE_DROP_CONFIRMATION_REQUIRED' && confirmOrphan !== true) {
if (window.confirm(data.error + '\n\nClick OK to proceed anyway.')) {
return await saveDbTypeChange(true);
}
return;
}
if (!res.ok) {
showDbFeedback(dbChangeTypeFeedback, data.error || 'Failed to change database type', true);
return;
}
const changeWarnings = Array.isArray(data.warnings) ? data.warnings : [];
showDbFeedback(dbChangeTypeFeedback, changeWarnings.length > 0 ? 'Database type changed successfully! ' + changeWarnings.join(' ') : 'Database type changed successfully!', false);
await loadDbConfig();
setTimeout(() => {
closeChangeTypeModal();
}, 800);
} catch (err) {
console.error('[database] Change type error:', err);
showDbFeedback(dbChangeTypeFeedback, 'Network error', true);
} finally {
if (dbChangeTypeSave) {
dbChangeTypeSave.disabled = false;
dbChangeTypeSave.innerHTML = ' Change Database';
}
}
}
async function togglePhpmyadmin(enabled, confirmOrphan) {
if (enabled && !phpmyadminEnabled) {
if (phpmyadminToggle) phpmyadminToggle.checked = false;
openSetupModal();
return;
}
if (!enabled && phpmyadminEnabled) {
if (!confirm('Disable phpMyAdmin? Web access will be blocked and every database user the panel created will be revoked from the database server.')) {
if (phpmyadminToggle) phpmyadminToggle.checked = true;
return;
}
// Disable drops every database user the panel created, so it requires
// the same install-verification step-up as setup (it is the more
// destructive operation). The grace grant must exist before the
// request: the modal short-circuits without prompting when one is
// already active — same pattern as disablePgAdmin.
if (typeof window.confirmDatabaseInstallBeforeSetup === 'function') {
const verified = await window.confirmDatabaseInstallBeforeSetup('phpmyadmin');
if (!verified) {
if (phpmyadminToggle) phpmyadminToggle.checked = true;
return;
}
}
const statusEl = document.getElementById('phpmyadminStatus');
const detailsEl = document.getElementById('phpmyadminDetails');
const accessSection = document.getElementById('phpmyadminAccessSection');
const usersSection = document.getElementById('dbUsersSection');
if (detailsEl) detailsEl.style.display = 'block';
if (accessSection) accessSection.style.display = 'none';
if (usersSection) usersSection.style.display = 'none';
const progress = statusEl ? createDbDisableProgress(statusEl, [
'Disabling web access',
'Revoking database users',
'Removing configuration',
'Saving settings'
], 15, '#f89d21') : null;
if (phpmyadminToggle) phpmyadminToggle.disabled = true;
try {
const res = await fetchDbRequestWithTokenRetry(() => fetch('/api/settings/database/disable', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-action-token': dbActionTokens.disable || '' },
body: JSON.stringify({ confirmOrphan: confirmOrphan === true })
}), 'db', { stepUpService: 'phpmyadmin' });
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
// Mirror of the deleteDbUser client pattern: 409 asks for an explicit
// orphan confirmation (accounts on a remote server cannot be revoked
// by the panel and would stay live while the panel forgets them),
// then re-sends with confirmOrphan: true. The 409 fires before the
// one-time action token is consumed, so the same token is still valid.
if (res.status === 409 && data.code === 'REMOTE_DROP_CONFIRMATION_REQUIRED' && confirmOrphan !== true) {
if (progress) progress.finish(false, 'phpMyAdmin was not disabled');
if (phpmyadminToggle) { phpmyadminToggle.checked = true; phpmyadminToggle.disabled = false; }
if (window.confirm(data.error + '\n\nClick OK to disable anyway.')) {
return await togglePhpmyadmin(false, true);
}
return;
}
if (!res.ok) {
if (progress) progress.finish(false, data.error || 'Failed to disable phpMyAdmin');
if (phpmyadminToggle) { phpmyadminToggle.checked = true; phpmyadminToggle.disabled = false; }
return;
}
const disableWarnings = Array.isArray(data.warnings) ? data.warnings : [];
const doneMessage = disableWarnings.length > 0
? 'phpMyAdmin disabled — ' + disableWarnings.join(' ')
: 'phpMyAdmin disabled successfully — refresh to update';
if (progress) progress.finish(true, doneMessage);
phpmyadminEnabled = false;
dbConfig = null;
dbUsers = [];
if (phpmyadminToggle) { phpmyadminToggle.checked = false; phpmyadminToggle.disabled = false; }
} catch (err) {
console.error('[database] Disable error:', err);
if (progress) progress.finish(false, 'Network error — please try again');
if (phpmyadminToggle) { phpmyadminToggle.checked = true; phpmyadminToggle.disabled = false; }
}
}
}
if (phpmyadminToggle) {
phpmyadminToggle.addEventListener('change', (e) => {
togglePhpmyadmin(e.target.checked);
});
}
if (dbSetupModalClose) dbSetupModalClose.addEventListener('click', closeSetupModal);
if (dbSetupCancel) dbSetupCancel.addEventListener('click', closeSetupModal);
if (dbSetupModalOverlay) {
dbSetupModalOverlay.addEventListener('click', (e) => {
if (e.target === dbSetupModalOverlay) closeSetupModal();
});
}
if (dbSetupSave) dbSetupSave.addEventListener('click', saveDbSetup);
document.querySelectorAll('input[name="db_type"]').forEach(radio => {
radio.addEventListener('change', (e) => {
if (dbPort) dbPort.value = getDefaultPort(e.target.value);
});
});
document.querySelectorAll('input[name="db_change_type"]').forEach(radio => {
radio.addEventListener('change', (e) => {
if (dbChangePort) dbChangePort.value = getDefaultPort(e.target.value);
});
});
if (addDbUserBtn) addDbUserBtn.addEventListener('click', openUserModal);
if (dbUserModalClose) dbUserModalClose.addEventListener('click', closeUserModal);
if (dbUserCancel) dbUserCancel.addEventListener('click', closeUserModal);
if (dbUserModalOverlay) {
dbUserModalOverlay.addEventListener('click', (e) => {
if (e.target === dbUserModalOverlay) closeUserModal();
});
}
if (dbUserSave) dbUserSave.addEventListener('click', saveDbUser);
if (dbuserPassword) {
dbuserPassword.addEventListener('input', (e) => {
if (dbUserPasswordStrength) {
dbUserPasswordStrength.innerHTML = checkPasswordStrength(e.target.value);
}
});
}
if (dbPassModalClose) dbPassModalClose.addEventListener('click', closePasswordModal);
if (dbPassCancel) dbPassCancel.addEventListener('click', closePasswordModal);
if (dbPassModalOverlay) {
dbPassModalOverlay.addEventListener('click', (e) => {
if (e.target === dbPassModalOverlay) closePasswordModal();
});
}
if (dbPassSave) dbPassSave.addEventListener('click', saveDbPassword);
if (dbpassPassword) {
dbpassPassword.addEventListener('input', (e) => {
if (dbPassPasswordStrength) {
dbPassPasswordStrength.innerHTML = checkPasswordStrength(e.target.value);
}
});
}
if (changeDbTypeBtn) changeDbTypeBtn.addEventListener('click', openChangeTypeModal);
if (dbChangeTypeModalClose) dbChangeTypeModalClose.addEventListener('click', closeChangeTypeModal);
if (dbChangeTypeCancel) dbChangeTypeCancel.addEventListener('click', closeChangeTypeModal);
if (dbChangeTypeModalOverlay) {
dbChangeTypeModalOverlay.addEventListener('click', (e) => {
if (e.target === dbChangeTypeModalOverlay) closeChangeTypeModal();
});
}
if (dbChangeTypeSave) dbChangeTypeSave.addEventListener('click', saveDbTypeChange);
if (dbUsersList) {
dbUsersList.addEventListener('click', (e) => {
const editBtn = e.target.closest('.db-user-btn-edit');
if (editBtn) {
const username = editBtn.dataset.username;
if (username) openPasswordModal(username);
return;
}
const deleteBtn = e.target.closest('.db-user-btn-delete');
if (deleteBtn) {
const username = deleteBtn.dataset.username;
if (username) deleteDbUser(username);
return;
}
});
}
// Database-tool access is session- and cookie-bound: POSTing
// /api/settings/database/access-token sets a short-lived HttpOnly cookie,
// and the returned URL only works in THIS browser with THIS admin session.
// There is deliberately no copy-URL affordance — a shared URL would still
// fail without the cookie, and the cookie never appears in any URL.
if (openPhpmyadminUrl) {
openPhpmyadminUrl.setAttribute('href', '/db-open/phpmyadmin');
openPhpmyadminUrl.setAttribute('target', '_blank');
openPhpmyadminUrl.setAttribute('rel', 'noopener noreferrer');
}
window.setupPasswordToggle = function (toggleId, inputId) {
const toggle = document.getElementById(toggleId);
const input = document.getElementById(inputId);
if (toggle && input && !toggle.dataset.listenerAdded) {
toggle.dataset.listenerAdded = 'true';
toggle.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
const icon = toggle.querySelector('i');
if (input.type === 'password') {
input.type = 'text';
if (icon) {
icon.classList.remove('fa-eye');
icon.classList.add('fa-eye-slash');
}
toggle.setAttribute('aria-label', 'Hide password');
} else {
input.type = 'password';
if (icon) {
icon.classList.remove('fa-eye-slash');
icon.classList.add('fa-eye');
}
toggle.setAttribute('aria-label', 'Show password');
}
});
}
}
setupPasswordToggle('pgadmin_password_toggle', 'pgadmin_password');
setupPasswordToggle('mongodb_password_toggle', 'mongodb_password');
const observer = new MutationObserver(() => {
setupPasswordToggle('pgadmin_password_toggle', 'pgadmin_password');
setupPasswordToggle('mongodb_password_toggle', 'mongodb_password');
});
observer.observe(document.body, { childList: true, subtree: true });
const sidebarNav = document.getElementById('sidebarNav');
if (sidebarNav) {
sidebarNav.addEventListener('click', (e) => {
const btn = e.target.closest('button');
if (btn && btn.dataset.panel === 'databases') {
if (typeof window.loadDbConfig === 'function') window.loadDbConfig();
else if (typeof loadDbConfig === 'function') loadDbConfig();
if (typeof window.loadPgAdminStatus === 'function') window.loadPgAdminStatus();
if (typeof window.loadMongoDBStatus === 'function') window.loadMongoDBStatus();
}
});
}
const databasesPanel = document.getElementById('databases');
if (databasesPanel && databasesPanel.classList.contains('active')) {
if (typeof window.loadDbConfig === 'function') window.loadDbConfig();
else if (typeof loadDbConfig === 'function') loadDbConfig();
if (typeof window.loadPgAdminStatus === 'function') window.loadPgAdminStatus();
if (typeof window.loadMongoDBStatus === 'function') window.loadMongoDBStatus();
}
})();
var _dbDisableGuard = null;
function _dbBeforeUnload(e) { e.preventDefault(); e.returnValue = ''; }
function _dbDisableGuardOn() {
if (!_dbDisableGuard) {
_dbDisableGuard = true;
window.addEventListener('beforeunload', _dbBeforeUnload);
}
}
function _dbDisableGuardOff() {
if (_dbDisableGuard) {
_dbDisableGuard = null;
window.removeEventListener('beforeunload', _dbBeforeUnload);
}
}
function createDbDisableProgress(statusEl, steps, estimatedSecs, brandColor) {
const color = brandColor || '#f59e0b';
const stepsHtml = steps.map((s, i) =>
`${s}
`
).join('');
statusEl.innerHTML = `
`;
_dbDisableGuardOn();
const barFill = statusEl.querySelector('.db-disable-bar-fill');
const elapsedEl = statusEl.querySelector('.db-disable-elapsed');
const stepEls = statusEl.querySelectorAll('.db-disable-step');
let elapsed = 0;
let currentStep = 0;
if (stepEls[0]) stepEls[0].classList.add('active');
const stepInterval = Math.floor(estimatedSecs / steps.length);
const timer = setInterval(() => {
elapsed++;
if (elapsedEl) elapsedEl.textContent = `Elapsed: ${elapsed}s`;
const pct = Math.min(90, Math.round((elapsed / estimatedSecs) * 90));
if (barFill) barFill.style.width = pct + '%';
const expectedStep = Math.min(steps.length - 1, Math.floor(elapsed / stepInterval));
while (currentStep < expectedStep) {
if (stepEls[currentStep]) {
stepEls[currentStep].classList.remove('active');
stepEls[currentStep].classList.add('done');
stepEls[currentStep].querySelector('i').className = 'fa-solid fa-check';
}
currentStep++;
if (stepEls[currentStep]) stepEls[currentStep].classList.add('active');
}
}, 1000);
return {
finish(success, message) {
clearInterval(timer);
_dbDisableGuardOff();
stepEls.forEach(el => {
el.classList.remove('active');
if (success) {
el.classList.add('done');
el.querySelector('i').className = 'fa-solid fa-check';
}
});
if (barFill) barFill.style.width = '100%';
// message can carry raw privileged-job stderr from the API — render it as text, never HTML.
if (success) {
setTimeout(() => {
const done = document.createElement('div');
done.className = 'db-disable-done';
done.style.setProperty('--db-brand', color);
const doneIcon = document.createElement('i');
doneIcon.className = 'fa-solid fa-circle-check';
const doneText = document.createElement('span');
doneText.textContent = message || 'Disabled successfully';
done.appendChild(doneIcon);
done.appendChild(doneText);
statusEl.textContent = '';
statusEl.appendChild(done);
}, 400);
} else {
const errBox = document.createElement('div');
errBox.className = 'db-status-error';
const errIcon = document.createElement('i');
errIcon.className = 'fa-solid fa-exclamation-triangle';
const errText = document.createElement('span');
errText.textContent = message || 'Failed to disable';
errBox.appendChild(errIcon);
errBox.appendChild(errText);
statusEl.textContent = '';
statusEl.appendChild(errBox);
}
}
};
}
(function () {
'use strict';
const pgadminToggle = document.getElementById('pgadminToggle');
const pgadminStatus = document.getElementById('pgadminStatus');
const pgadminAccessSection = document.getElementById('pgadminAccessSection');
const pgadminUrl = document.getElementById('pgadminUrl');
const openPgadminUrl = document.getElementById('openPgadminUrl');
const pgadminSetupModalOverlay = document.getElementById('pgadminSetupModalOverlay');
const pgadminSetupModal = document.getElementById('pgadminSetupModal');
const pgadminSetupModalClose = document.getElementById('pgadminSetupModalClose');
const pgadminSetupCancel = document.getElementById('pgadminSetupCancel');
const pgadminSetupSave = document.getElementById('pgadminSetupSave');
const pgadminSetupFeedback = document.getElementById('pgadminSetupFeedback');
const pgadminEmail = document.getElementById('pgadmin_email');
const pgadminPassword = document.getElementById('pgadmin_password');
const pgadminPasswordStrength = document.getElementById('pgadminPasswordStrength');
let loadPgAdminStatus = null;
function showPgAdminFeedback(msg, isError = false) {
if (pgadminSetupFeedback) {
pgadminSetupFeedback.textContent = msg;
pgadminSetupFeedback.className = 'node-feedback' + (isError ? ' error' : ' success');
pgadminSetupFeedback.style.display = msg ? 'block' : 'none';
}
}
async function openPgAdminSetupModal(options = {}) {
if (!options.skipVerification && typeof window.confirmDatabaseInstallBeforeSetup === 'function') {
const verified = await window.confirmDatabaseInstallBeforeSetup('pgadmin', () => {
if (pgadminToggle && !pgadminToggle.dataset.wasEnabled) pgadminToggle.checked = false;
});
if (!verified) return;
}
if (pgadminEmail) pgadminEmail.value = '';
if (pgadminPassword) pgadminPassword.value = '';
if (pgadminPasswordStrength) pgadminPasswordStrength.innerHTML = '';
showPgAdminFeedback('');
if (pgadminSetupModalOverlay) {
pgadminSetupModalOverlay.classList.add('show');
pgadminSetupModalOverlay.setAttribute('aria-hidden', 'false');
}
if (pgadminSetupModal) {
pgadminSetupModal.classList.add('show');
}
}
document.addEventListener(ASSISTANT_SETTINGS_ACTION_EVENT, (event) => {
if (event?.detail?.action === 'pgadmin_setup') {
openPgAdminSetupModal().catch(err => console.error('[pgadmin] Setup modal failed:', err));
}
});
function closePgAdminSetupModal() {
if (pgadminSetupModalOverlay) {
pgadminSetupModalOverlay.classList.remove('show');
pgadminSetupModalOverlay.setAttribute('aria-hidden', 'true');
}
if (pgadminSetupModal) {
pgadminSetupModal.classList.remove('show');
}
if (pgadminToggle && !pgadminToggle.dataset.wasEnabled) {
pgadminToggle.checked = false;
}
}
loadPgAdminStatus = async function () {
if (!pgadminStatus) return;
pgadminStatus.innerHTML = 'Checking status...
';
try {
const res = await fetchWithTimeout('/api/settings/database/pgadmin/status', {}, 6000);
if (!res.ok) throw new Error('Failed to fetch status');
const data = await res.json();
if (pgadminToggle) {
pgadminToggle.checked = data.enabled;
pgadminToggle.dataset.wasEnabled = data.enabled ? 'true' : '';
}
if (data.enabled && data.postgresRunning) {
if (pgadminUrl) pgadminUrl.textContent = 'Session-bound access (opens in a new tab)';
if (pgadminAccessSection) pgadminAccessSection.style.display = 'block';
pgadminStatus.innerHTML = 'PostgreSQL & pgAdmin4 running
';
} else if (data.installed) {
pgadminStatus.innerHTML = 'PostgreSQL installed but not enabled
';
if (pgadminAccessSection) pgadminAccessSection.style.display = 'none';
} else {
pgadminStatus.innerHTML = 'Not installed - Enable to install
';
if (pgadminAccessSection) pgadminAccessSection.style.display = 'none';
}
} catch (err) {
console.error('[pgadmin] Status error:', err);
pgadminStatus.innerHTML = 'Error checking status
';
}
};
window.loadPgAdminStatus = loadPgAdminStatus;
async function savePgAdminSetup() {
if (typeof window.confirmDatabaseInstallBeforeSetup === 'function') {
const verified = await window.confirmDatabaseInstallBeforeSetup('pgadmin');
if (!verified) return;
}
const email = pgadminEmail?.value?.trim() || '';
const password = pgadminPassword?.value || '';
const dbUser = document.getElementById('pgadmin_db_user')?.value?.trim() || 'pgadmin_user';
const dbHost = document.getElementById('pgadmin_db_host')?.value?.trim() || '127.0.0.1';
const dbPort = document.getElementById('pgadmin_db_port')?.value?.trim() || '5432';
if (!email || !email.includes('@')) {
showPgAdminFeedback('Please enter a valid email address', true);
return;
}
if (!password || password.length < 8) {
showPgAdminFeedback('Password must be at least 8 characters', true);
return;
}
if (!dbUser || dbUser.length < 2) {
showPgAdminFeedback('Please enter a valid database username', true);
return;
}
if (typeof window.confirmRemoteDbBind === 'function') {
const remoteBindOk = await window.confirmRemoteDbBind(dbHost, 'PostgreSQL');
if (!remoteBindOk) {
showPgAdminFeedback('Setup cancelled: the listen host stays local unless you confirm the remote-bind warning.', true);
return;
}
}
const progressContainer = document.getElementById('pgadminProgressContainer');
const progressText = document.getElementById('pgadminProgressText');
const progressPercent = document.getElementById('pgadminProgressPercent');
const progressFill = document.getElementById('pgadminProgressFill');
if (progressContainer) progressContainer.style.display = 'block';
if (progressText) progressText.textContent = 'Starting installation...';
if (progressPercent) progressPercent.textContent = '0%';
if (progressFill) progressFill.style.width = '0%';
if (pgadminSetupSave) {
pgadminSetupSave.disabled = true;
pgadminSetupSave.innerHTML = ' Installing...';
}
if (pgadminSetupCancel) pgadminSetupCancel.disabled = true;
showPgAdminFeedback('', false);
try {
const res = await fetchDbRequestWithTokenRetry(() => fetch('/api/settings/database/pgadmin/setup', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-action-token': (dbActionTokens || {}).pgadminSetup || '' },
body: JSON.stringify({ email, password, dbUser, dbHost, dbPort, confirmRemoteBind: !(window.isLoopbackDbHostClient ? window.isLoopbackDbHostClient(dbHost) : false) })
}), 'db', { stepUpService: 'pgadmin' });
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Setup failed');
const jobId = data.jobId;
const accessUrl = data.accessUrl;
let consecutivePollFailures = 0;
// adpanel:progress-poll-429-backoff — HTTP 429 is the limiter telling
// this poller to slow down, not a failed install: 429 must NOT consume
// the consecutivePollFailures budget (which exists for gateway blips),
// or a running install gets marked failed by the very throttling its
// own polling caused. Re-poll after a longer delay honoring a numeric
// Retry-After (clamped 2-15s, else 5s); a bounded consecutive-429
// counter keeps a permanently-throttled panel from polling forever.
let consecutivePollThrottles = 0;
const pollProgress = async () => {
try {
const statusRes = await fetch(`/api/settings/database/install-progress/${jobId}`);
if (!statusRes.ok) {
// A 404 is terminal: the job record is gone (expired or lost), so
// polling forever would hide the failure — the original bug this
// guard fixes. Any other non-OK response (a 502/503 gateway
// blip, a transient auth hiccup) must NOT abort an install that
// is still running, so it rides out a small budget of
// consecutive failures before surfacing as a failure.
if (statusRes.status === 429) {
consecutivePollThrottles += 1;
if (consecutivePollThrottles > 30) {
throw new Error('Progress check failed (HTTP 429)');
}
const retryAfter = Number(statusRes.headers && statusRes.headers.get('retry-after'));
const backoffMs = (Number.isFinite(retryAfter) && retryAfter > 0)
? Math.min(15000, Math.max(2000, Math.round(retryAfter * 1000)))
: 5000;
setTimeout(pollProgress, backoffMs);
return;
}
consecutivePollThrottles = 0;
if (statusRes.status === 404 || ++consecutivePollFailures > 3) {
throw new Error(statusRes.status === 404
? 'Installation progress record not found (HTTP 404)'
: `Progress check failed (HTTP ${statusRes.status})`);
}
setTimeout(pollProgress, 2000);
return;
}
consecutivePollFailures = 0;
consecutivePollThrottles = 0;
const status = await statusRes.json();
if (progressText) progressText.textContent = status.message || 'Installing...';
if (progressPercent) progressPercent.textContent = `${status.progress || 0}%`;
if (progressFill) progressFill.style.width = `${status.progress || 0}%`;
if (status.status === 'completed') {
if (progressContainer) progressContainer.style.display = 'none';
if (pgadminSetupSave) { pgadminSetupSave.disabled = false; pgadminSetupSave.innerHTML = ' Install & Setup'; }
if (pgadminSetupCancel) pgadminSetupCancel.disabled = false;
showPgAdminFeedback('pgAdmin4 setup complete!', false);
setTimeout(() => {
closePgAdminSetupModal();
loadPgAdminStatus();
const toast = document.createElement('div');
toast.className = 'perm-success-toast';
toast.innerHTML = ` pgAdmin4 installed! Use the Open button for secure access.`;
document.body.appendChild(toast);
setTimeout(() => { toast.classList.add('show'); }, 10);
setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 300); }, 4000);
}, 1000);
return;
} else if (status.status === 'failed') {
throw new Error(status.error || 'Installation failed');
} else {
setTimeout(pollProgress, 2000);
}
} catch (pollErr) {
console.error('[pgadmin] Poll error:', pollErr);
showPgAdminFeedback('Installation failed: ' + pollErr.message, true);
if (progressContainer) progressContainer.style.display = 'none';
if (pgadminToggle) pgadminToggle.checked = false;
if (pgadminToggle) pgadminToggle.dataset.wasEnabled = '';
if (pgadminSetupSave) { pgadminSetupSave.disabled = false; pgadminSetupSave.innerHTML = ' Install & Setup'; }
if (pgadminSetupCancel) pgadminSetupCancel.disabled = false;
}
};
setTimeout(pollProgress, 2000);
} catch (err) {
console.error('[pgadmin] Setup error:', err);
showPgAdminFeedback('Setup failed: ' + err.message, true);
if (progressContainer) progressContainer.style.display = 'none';
if (pgadminToggle) pgadminToggle.checked = false;
if (pgadminToggle) pgadminToggle.dataset.wasEnabled = '';
if (pgadminSetupSave) { pgadminSetupSave.disabled = false; pgadminSetupSave.innerHTML = ' Install & Setup'; }
if (pgadminSetupCancel) pgadminSetupCancel.disabled = false;
}
}
async function disablePgAdmin() {
// Disable purges pgAdmin4, its data directories and firewall rules, so it
// requires the same install-verification step-up as setup (it is the more
// destructive operation). The grace grant must exist before the request:
// the modal short-circuits without prompting when one is already active.
if (typeof window.confirmDatabaseInstallBeforeSetup === 'function') {
const verified = await window.confirmDatabaseInstallBeforeSetup('pgadmin');
if (!verified) {
if (pgadminToggle) pgadminToggle.checked = true;
return;
}
}
const pgadminDetails = document.getElementById('pgadminDetails');
if (pgadminDetails) pgadminDetails.style.display = 'block';
const progress = pgadminStatus ? createDbDisableProgress(pgadminStatus, [
'Stopping PostgreSQL service',
'Stopping Apache service',
'Removing Apache config',
'Cleaning up nginx config',
'Uninstalling pgAdmin4 packages',
'Removing data directories',
'Cleaning up apt sources',
'Finalizing'
], 60, '#336791') : null;
if (pgadminToggle) pgadminToggle.disabled = true;
if (pgadminAccessSection) pgadminAccessSection.style.display = 'none';
try {
const res = await fetchDbRequestWithTokenRetry(() => fetch('/api/settings/database/pgadmin/disable', { method: 'POST', headers: { 'x-action-token': (dbActionTokens || {}).pgadminDisable || '' } }), 'db', { stepUpService: 'pgadmin' });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || 'Failed to disable');
}
if (progress) progress.finish(true, 'pgAdmin4 disabled and uninstalled — refresh to update');
if (pgadminToggle) { pgadminToggle.checked = false; pgadminToggle.dataset.wasEnabled = ''; }
} catch (err) {
console.error('[pgadmin] Disable error:', err);
if (progress) progress.finish(false, err.message || 'Failed to disable pgAdmin4');
if (pgadminToggle) pgadminToggle.checked = true;
} finally {
if (pgadminToggle) pgadminToggle.disabled = false;
}
}
if (pgadminToggle) {
pgadminToggle.addEventListener('change', (e) => {
if (e.target.checked) {
openPgAdminSetupModal().catch(err => {
console.error('[pgadmin] Setup modal failed:', err);
alert(err?.message || 'Failed to open the pgAdmin4 setup. Please reload the page and try again.');
if (pgadminToggle && !pgadminToggle.dataset.wasEnabled) pgadminToggle.checked = false;
});
} else if (confirm('Disable pgAdmin4? This stops PostgreSQL, removes the pgAdmin4 setup and its data directories for a clean reinstall.')) {
disablePgAdmin();
} else if (pgadminToggle) {
pgadminToggle.checked = true;
}
});
}
if (pgadminSetupModalClose) pgadminSetupModalClose.addEventListener('click', closePgAdminSetupModal);
if (pgadminSetupCancel) pgadminSetupCancel.addEventListener('click', closePgAdminSetupModal);
if (pgadminSetupModalOverlay) {
pgadminSetupModalOverlay.addEventListener('click', (e) => {
if (e.target === pgadminSetupModalOverlay) closePgAdminSetupModal();
});
}
if (pgadminSetupSave) pgadminSetupSave.addEventListener('click', savePgAdminSetup);
if (pgadminPassword && pgadminPasswordStrength) {
pgadminPassword.addEventListener('input', (e) => {
const val = e.target.value;
let strength = 'weak';
if (val.length >= 12 && /[A-Z]/.test(val) && /[0-9]/.test(val) && /[^A-Za-z0-9]/.test(val)) {
strength = 'strong';
} else if (val.length >= 10 && /[A-Z]/.test(val) && /[0-9]/.test(val)) {
strength = 'good';
} else if (val.length >= 8) {
strength = 'fair';
}
pgadminPasswordStrength.innerHTML = val ? `
` : '';
});
}
if (openPgadminUrl) {
openPgadminUrl.setAttribute('href', '/db-open/pgadmin');
openPgadminUrl.setAttribute('target', '_blank');
openPgadminUrl.setAttribute('rel', 'noopener noreferrer');
}
// ── Saved pgAdmin login (one-time modal) ─────────────────────────
// Retrieval of the sealed pgAdmin bootstrap credential that the backend
// recovery path writes when it resets the admin password. The endpoint is
// admin + one-time action-token gated with Cache-Control: no-store; the
// credential is injected via textContent (never markup, URLs, storage, or
// logs) and scrubbed from the DOM when the dialog is acknowledged.
const showPgadminCredentialsBtn = document.getElementById('showPgadminCredentials');
const pgadminCredentialFeedback = document.getElementById('pgadminCredentialFeedback');
function showPgAdminCredentialNote(msg, isError = false) {
if (!pgadminCredentialFeedback) return;
pgadminCredentialFeedback.textContent = msg;
pgadminCredentialFeedback.className = 'node-feedback' + (isError ? ' error' : ' success');
pgadminCredentialFeedback.style.display = msg ? 'block' : 'none';
}
function copySecretValuePgAdmin(value, btn) {
if (!btn || !value) return;
const original = btn.textContent;
const done = () => {
btn.textContent = 'Copied';
setTimeout(function () { btn.textContent = original; }, 1500);
};
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(value).then(done).catch(function () { btn.textContent = original; });
} else {
// The async clipboard API needs a secure context; fall back to a
// transient textarea that is removed immediately after the copy.
try {
const ta = document.createElement('textarea');
ta.value = value;
ta.setAttribute('readonly', '');
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
ta.remove();
done();
} catch (err) {
btn.textContent = original;
}
}
}
// Displays the credential exactly once: the overlay is built fresh, the
// values are scrubbed on acknowledge, and the node is removed entirely so
// the secret cannot linger in the DOM.
function showPgAdminCredentialModal(email, password, subtitle) {
const overlay = document.createElement('div');
overlay.className = 'modal-overlay enterprise-modal-overlay';
overlay.setAttribute('aria-hidden', 'false');
// Static markup only — the credential values are injected via textContent
// below, never interpolated into HTML.
overlay.innerHTML = `
Handle with care: this is the login for the pgAdmin admin account. Copy it now —
once you acknowledge this dialog it is scrubbed from the page and never logged, stored in the browser,
or placed in any URL.
`;
overlay.querySelector('.enterprise-modal-subtitle').textContent = subtitle;
const emailEl = overlay.querySelector('[data-pgadmin-cred="email"]');
const passwordEl = overlay.querySelector('[data-pgadmin-cred="password"]');
emailEl.textContent = email;
passwordEl.textContent = password;
const copyBtnEmail = overlay.querySelector('[data-pgadmin-copy="email"]');
const copyBtnPassword = overlay.querySelector('[data-pgadmin-copy="password"]');
if (copyBtnEmail) copyBtnEmail.addEventListener('click', function () { copySecretValuePgAdmin(emailEl.textContent, copyBtnEmail); });
if (copyBtnPassword) copyBtnPassword.addEventListener('click', function () { copySecretValuePgAdmin(passwordEl.textContent, copyBtnPassword); });
const okBtn = overlay.querySelector('[data-pgadmin-ok]');
const acknowledge = function () {
emailEl.textContent = '';
passwordEl.textContent = '';
overlay.remove();
};
if (okBtn) okBtn.addEventListener('click', acknowledge);
// .modal-overlay is display:none until .show is set (same as openModal()).
overlay.classList.add('show');
document.body.appendChild(overlay);
}
// The database request helper with one-shot 403 token retry lives in a
// sibling IIFE, so mirror its 'db' behavior here against the shared
// top-level token store: retry ONCE after re-minting the action tokens, and
// only when the 403 is specifically an action-token rejection.
async function fetchPgAdminCredentialsWithTokenRetry() {
const send = () => fetch('/api/settings/database/pgadmin/credentials', {
method: 'POST',
headers: { 'x-action-token': String((dbActionTokens || {}).pgadminCredentials || '') }
});
let res = await send();
if (res.status === 403) {
const probe = await res.clone().json().catch(function () { return {}; });
const tokenRejected = (probe && probe.code === 'ACTION_TOKEN_INVALID') ||
(typeof probe.error === 'string' && /action token/i.test(probe.error));
if (tokenRejected && typeof window.refreshDbActionTokens === 'function') {
await window.refreshDbActionTokens();
res = await send();
}
}
return res;
}
if (showPgadminCredentialsBtn) {
showPgadminCredentialsBtn.addEventListener('click', async function () {
if (showPgadminCredentialsBtn.disabled) return;
// The server enforces the same credential step-up on retrieval as on
// setup/disable (the response carries the live pgAdmin admin password),
// so establish the grant first — exactly like disablePgAdmin(): the
// verification modal short-circuits without prompting while a grace
// grant is already active, and refreshDbActionTokens() re-mints the
// one-time pgadminCredentials token after a fresh verification.
if (typeof window.confirmDatabaseInstallBeforeSetup === 'function') {
const verified = await window.confirmDatabaseInstallBeforeSetup('pgadmin');
if (!verified) return;
}
showPgadminCredentialsBtn.disabled = true;
showPgAdminCredentialNote('', false);
try {
const res = await fetchPgAdminCredentialsWithTokenRetry();
const payload = await res.json().catch(function () { return null; });
if (res.ok && payload && payload.email && payload.password) {
showPgAdminCredentialModal(
String(payload.email),
String(payload.password),
'Saved login for the pgAdmin admin account (sealed on the server).'
);
} else if (res.status === 404) {
// The sealed store only holds a credential after a recovery reset;
// without one there is nothing to display.
showPgAdminCredentialNote('No saved pgAdmin login is stored. It is only created when backend recovery resets the pgAdmin admin password.', true);
} else if (res.status === 403) {
// A step-up challenge here means the grace grant expired between the
// verification modal and this POST (the rejected attempt also burned
// the one-time token) — retrying re-runs the whole flow.
if (typeof window.isDatabaseInstallVerificationError === 'function' && window.isDatabaseInstallVerificationError(payload)) {
showPgAdminCredentialNote('Identity verification is required. Please try again.', true);
} else {
showPgAdminCredentialNote('Security token rejected. Please try again.', true);
}
} else {
showPgAdminCredentialNote((payload && payload.error) || 'Failed to retrieve the saved pgAdmin login.', true);
}
} catch (err) {
showPgAdminCredentialNote((err && err.message) || 'Failed to retrieve the saved pgAdmin login.', true);
} finally {
showPgadminCredentialsBtn.disabled = false;
}
});
}
})();
(function () {
'use strict';
const mongodbToggle = document.getElementById('mongodbToggle');
const mongodbStatus = document.getElementById('mongodbStatus');
const mongodbAccessSection = document.getElementById('mongodbAccessSection');
const mongodbConnString = document.getElementById('mongodbConnString');
const copyMongodbUrl = document.getElementById('copyMongodbUrl');
const mongodbConnPass = document.getElementById('mongodbConnPass');
const toggleMongodbPassword = document.getElementById('toggleMongodbPassword');
const mongodbSetupModalOverlay = document.getElementById('mongodbSetupModalOverlay');
const mongodbSetupModal = document.getElementById('mongodbSetupModal');
const mongodbSetupModalClose = document.getElementById('mongodbSetupModalClose');
const mongodbSetupCancel = document.getElementById('mongodbSetupCancel');
const mongodbSetupSave = document.getElementById('mongodbSetupSave');
const mongodbSetupFeedback = document.getElementById('mongodbSetupFeedback');
const mongodbUsername = document.getElementById('mongodb_username');
const mongodbPassword = document.getElementById('mongodb_password');
const mongodbPasswordStrength = document.getElementById('mongodbPasswordStrength');
let loadMongoDBStatus = null;
// Security: the MongoDB admin password must never be persisted client-side
// (no localStorage/sessionStorage) or mirrored into data-* attributes —
// either would expose the root DB credential to any XSS on the origin and
// to DOM/storage inspection. It lives only in this closure variable for the
// current page session; the server stores a bcrypt hash and cannot reveal it.
const MONGODB_LEGACY_PASSWORD_CACHE_PREFIX = 'adpanel.mongodb.password.';
let pendingMongoPassword = '';
let sessionMongoPassword = '';
function purgeLegacyMongoPasswordCache() {
// One-way migration: older builds cached the password under
// adpanel.mongodb.password.@:. Sweep on every settings
// page load — idempotent, and re-population is impossible now that the
// only writer is gone. Keys are collected first because removing while
// iterating would shift localStorage key indexes.
try {
const staleKeys = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith(MONGODB_LEGACY_PASSWORD_CACHE_PREFIX)) staleKeys.push(key);
}
for (const key of staleKeys) localStorage.removeItem(key);
} catch { }
}
purgeLegacyMongoPasswordCache();
function getMongoConnectionUsername() {
const urlWrapper = document.querySelector('.db-access-url-wrapper');
const connUser = document.getElementById('mongodbConnUser');
return ((urlWrapper?.dataset.username || connUser?.textContent || 'admin').trim()) || 'admin';
}
function setMongoSessionPassword(password) {
sessionMongoPassword = typeof password === 'string' ? password : '';
}
function ensureMongoConnectionPassword() {
if (sessionMongoPassword) return sessionMongoPassword;
const username = getMongoConnectionUsername();
const entered = prompt(`Enter MongoDB password for "${username}" to use in the connection string:`);
if (!entered) return '';
setMongoSessionPassword(entered);
return entered;
}
function hideMongoConnectionPassword() {
if (!mongodbConnPass) return;
mongodbConnPass.classList.add('blurred');
mongodbConnPass.textContent = '••••••••';
if (toggleMongodbPassword) {
toggleMongodbPassword.innerHTML = ' ';
toggleMongodbPassword.title = 'Show password';
}
}
function showMongoConnectionPassword(password) {
if (!mongodbConnPass) return;
mongodbConnPass.classList.remove('blurred');
mongodbConnPass.textContent = password;
if (toggleMongodbPassword) {
toggleMongodbPassword.innerHTML = ' ';
toggleMongodbPassword.title = 'Hide password';
}
}
function showMongoDBFeedback(msg, isError = false) {
if (mongodbSetupFeedback) {
mongodbSetupFeedback.textContent = msg;
mongodbSetupFeedback.className = 'node-feedback' + (isError ? ' error' : ' success');
mongodbSetupFeedback.style.display = msg ? 'block' : 'none';
}
}
async function openMongoDBSetupModal(options = {}) {
if (!options.skipVerification && typeof window.confirmDatabaseInstallBeforeSetup === 'function') {
const verified = await window.confirmDatabaseInstallBeforeSetup('mongodb', () => {
if (mongodbToggle && !mongodbToggle.dataset.wasEnabled) mongodbToggle.checked = false;
});
if (!verified) return;
}
if (mongodbUsername) mongodbUsername.value = 'admin';
if (mongodbPassword) mongodbPassword.value = '';
if (mongodbPasswordStrength) mongodbPasswordStrength.innerHTML = '';
showMongoDBFeedback('');
if (mongodbSetupModalOverlay) {
mongodbSetupModalOverlay.classList.add('show');
mongodbSetupModalOverlay.setAttribute('aria-hidden', 'false');
}
if (mongodbSetupModal) {
mongodbSetupModal.classList.add('show');
}
}
document.addEventListener(ASSISTANT_SETTINGS_ACTION_EVENT, (event) => {
if (event?.detail?.action === 'mongodb_setup') {
openMongoDBSetupModal().catch(err => console.error('[mongodb] Setup modal failed:', err));
}
});
function closeMongoDBSetupModal() {
if (mongodbSetupModalOverlay) {
mongodbSetupModalOverlay.classList.remove('show');
mongodbSetupModalOverlay.setAttribute('aria-hidden', 'true');
}
if (mongodbSetupModal) {
mongodbSetupModal.classList.remove('show');
}
if (mongodbToggle && !mongodbToggle.dataset.wasEnabled) {
mongodbToggle.checked = false;
}
}
loadMongoDBStatus = async function () {
if (!mongodbStatus) return;
mongodbStatus.innerHTML = 'Checking status...
';
try {
const res = await fetchWithTimeout('/api/settings/database/mongodb/status', {}, 6000);
if (!res.ok) throw new Error('Failed to fetch status');
const data = await res.json();
if (mongodbToggle) {
mongodbToggle.checked = data.enabled;
mongodbToggle.dataset.wasEnabled = data.enabled ? 'true' : '';
}
if (data.enabled && data.mongoRunning) {
const host = data.host === '0.0.0.0' ? window.location.hostname : (data.host || 'localhost');
const port = data.port || '27017';
if (data.users && data.users[0]) {
const adminUser = data.users[0];
const connUser = document.getElementById('mongodbConnUser');
const connPass = document.getElementById('mongodbConnPass');
const connHost = document.getElementById('mongodbConnHost');
if (connUser) connUser.textContent = adminUser.username;
if (connPass) {
hideMongoConnectionPassword();
}
if (connHost) connHost.textContent = `${host}:${port}`;
const urlWrapper = document.querySelector('.db-access-url-wrapper');
if (urlWrapper) {
urlWrapper.dataset.username = adminUser.username || 'admin';
urlWrapper.dataset.host = host;
urlWrapper.dataset.port = port;
}
if (pendingMongoPassword) {
setMongoSessionPassword(pendingMongoPassword);
pendingMongoPassword = '';
}
}
if (mongodbAccessSection) mongodbAccessSection.style.display = 'block';
mongodbStatus.innerHTML = `MongoDB running on ${host}:${port}
`;
if (typeof window.loadMongoDBUsers === 'function') window.loadMongoDBUsers();
} else if (data.installed) {
mongodbStatus.innerHTML = 'MongoDB installed but not enabled
';
if (mongodbAccessSection) mongodbAccessSection.style.display = 'none';
} else {
mongodbStatus.innerHTML = 'Not installed - Enable to install
';
if (mongodbAccessSection) mongodbAccessSection.style.display = 'none';
}
} catch (err) {
console.error('[mongodb] Status error:', err);
mongodbStatus.innerHTML = 'Error checking status
';
}
};
window.loadMongoDBStatus = loadMongoDBStatus;
async function saveMongoDBSetup() {
if (typeof window.confirmDatabaseInstallBeforeSetup === 'function') {
const verified = await window.confirmDatabaseInstallBeforeSetup('mongodb');
if (!verified) return;
}
const username = mongodbUsername?.value?.trim() || 'admin';
const password = mongodbPassword?.value || '';
const host = document.getElementById('mongodb_host')?.value?.trim() || '127.0.0.1';
const port = document.getElementById('mongodb_port')?.value?.trim() || '27017';
if (!username || !/^[a-zA-Z0-9_-]+$/.test(username)) {
showMongoDBFeedback('Please enter a valid username (alphanumeric, _, - only)', true);
return;
}
if (!password || password.length < 8) {
showMongoDBFeedback('Password must be at least 8 characters', true);
return;
}
if (typeof window.confirmRemoteDbBind === 'function') {
const remoteBindOk = await window.confirmRemoteDbBind(host, 'MongoDB');
if (!remoteBindOk) {
showMongoDBFeedback('Setup cancelled: the listen host stays local unless you confirm the remote-bind warning.', true);
return;
}
}
const progressContainer = document.getElementById('mongodbProgressContainer');
const progressText = document.getElementById('mongodbProgressText');
const progressPercent = document.getElementById('mongodbProgressPercent');
const progressFill = document.getElementById('mongodbProgressFill');
if (progressContainer) progressContainer.style.display = 'block';
if (progressText) progressText.textContent = 'Starting installation...';
if (progressPercent) progressPercent.textContent = '0%';
if (progressFill) progressFill.style.width = '0%';
if (mongodbSetupSave) {
mongodbSetupSave.disabled = true;
mongodbSetupSave.innerHTML = ' Installing...';
}
if (mongodbSetupCancel) mongodbSetupCancel.disabled = true;
showMongoDBFeedback('', false);
try {
const res = await fetchDbRequestWithTokenRetry(() => fetch('/api/settings/database/mongodb/setup', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-action-token': (dbActionTokens || {}).mongodbSetup || '' },
body: JSON.stringify({ username, password, host, port, confirmRemoteBind: !(window.isLoopbackDbHostClient ? window.isLoopbackDbHostClient(host) : false) })
}), 'db', { stepUpService: 'mongodb' });
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Setup failed');
const jobId = data.jobId;
let consecutivePollFailures = 0;
// adpanel:progress-poll-429-backoff — HTTP 429 is the limiter telling
// this poller to slow down, not a failed install: 429 must NOT consume
// the consecutivePollFailures budget (which exists for gateway blips),
// or a running install gets marked failed by the very throttling its
// own polling caused. Re-poll after a longer delay honoring a numeric
// Retry-After (clamped 2-15s, else 5s); a bounded consecutive-429
// counter keeps a permanently-throttled panel from polling forever.
let consecutivePollThrottles = 0;
const pollProgress = async () => {
try {
const statusRes = await fetch(`/api/settings/database/install-progress/${jobId}`);
if (!statusRes.ok) {
// A 404 is terminal: the job record is gone (expired or lost), so
// polling forever would hide the failure — the original bug this
// guard fixes. Any other non-OK response (a 502/503 gateway
// blip, a transient auth hiccup) must NOT abort an install that
// is still running, so it rides out a small budget of
// consecutive failures before surfacing as a failure.
if (statusRes.status === 429) {
consecutivePollThrottles += 1;
if (consecutivePollThrottles > 30) {
throw new Error('Progress check failed (HTTP 429)');
}
const retryAfter = Number(statusRes.headers && statusRes.headers.get('retry-after'));
const backoffMs = (Number.isFinite(retryAfter) && retryAfter > 0)
? Math.min(15000, Math.max(2000, Math.round(retryAfter * 1000)))
: 5000;
setTimeout(pollProgress, backoffMs);
return;
}
consecutivePollThrottles = 0;
if (statusRes.status === 404 || ++consecutivePollFailures > 3) {
throw new Error(statusRes.status === 404
? 'Installation progress record not found (HTTP 404)'
: `Progress check failed (HTTP ${statusRes.status})`);
}
setTimeout(pollProgress, 2000);
return;
}
consecutivePollFailures = 0;
consecutivePollThrottles = 0;
const status = await statusRes.json();
if (progressText) progressText.textContent = status.message || 'Installing...';
if (progressPercent) progressPercent.textContent = `${status.progress || 0}%`;
if (progressFill) progressFill.style.width = `${status.progress || 0}%`;
if (status.status === 'completed') {
if (progressContainer) progressContainer.style.display = 'none';
if (mongodbSetupSave) { mongodbSetupSave.disabled = false; mongodbSetupSave.innerHTML = ' Install & Setup'; }
if (mongodbSetupCancel) mongodbSetupCancel.disabled = false;
showMongoDBFeedback('MongoDB setup complete!', false);
pendingMongoPassword = password;
setTimeout(() => {
closeMongoDBSetupModal();
loadMongoDBStatus();
const toast = document.createElement('div');
toast.className = 'perm-success-toast';
toast.innerHTML = ' MongoDB installed and ready!';
document.body.appendChild(toast);
setTimeout(() => { toast.classList.add('show'); }, 10);
setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 300); }, 4000);
}, 1000);
return;
} else if (status.status === 'failed') {
throw new Error(status.error || 'Installation failed');
} else {
setTimeout(pollProgress, 2000);
}
} catch (pollErr) {
console.error('[mongodb] Poll error:', pollErr);
showMongoDBFeedback('Installation failed: ' + pollErr.message, true);
if (progressContainer) progressContainer.style.display = 'none';
if (mongodbToggle) mongodbToggle.checked = false;
if (mongodbToggle) mongodbToggle.dataset.wasEnabled = '';
if (mongodbSetupSave) { mongodbSetupSave.disabled = false; mongodbSetupSave.innerHTML = ' Install & Setup'; }
if (mongodbSetupCancel) mongodbSetupCancel.disabled = false;
}
};
setTimeout(pollProgress, 2000);
} catch (err) {
console.error('[mongodb] Setup error:', err);
showMongoDBFeedback('Setup failed: ' + err.message, true);
if (progressContainer) progressContainer.style.display = 'none';
if (mongodbToggle) mongodbToggle.checked = false;
if (mongodbToggle) mongodbToggle.dataset.wasEnabled = '';
if (mongodbSetupSave) { mongodbSetupSave.disabled = false; mongodbSetupSave.innerHTML = ' Install & Setup'; }
if (mongodbSetupCancel) mongodbSetupCancel.disabled = false;
}
}
async function disableMongoDB() {
// Disable purges MongoDB, its data directory and firewall rules, so it
// requires the same install-verification step-up as setup (it is the
// more destructive operation). The grace grant must exist before the
// request: the modal short-circuits without prompting when one is
// already active — same pattern as disablePgAdmin.
if (typeof window.confirmDatabaseInstallBeforeSetup === 'function') {
const verified = await window.confirmDatabaseInstallBeforeSetup('mongodb');
if (!verified) {
if (mongodbToggle) mongodbToggle.checked = true;
return;
}
}
const mongodbStatus = document.getElementById('mongodbStatus');
const mongodbDetails = document.getElementById('mongodbDetails');
const mongodbAccessSection = document.getElementById('mongodbAccessSection');
if (mongodbDetails) mongodbDetails.style.display = 'block';
const progress = mongodbStatus ? createDbDisableProgress(mongodbStatus, [
'Stopping MongoDB service',
'Removing MongoDB packages',
'Removing data and config',
'Cleaning up apt sources',
'Reloading system services',
'Finalizing'
], 90, '#00ed64') : null;
if (mongodbToggle) mongodbToggle.disabled = true;
if (mongodbAccessSection) mongodbAccessSection.style.display = 'none';
try {
const res = await fetchDbRequestWithTokenRetry(() => fetch('/api/settings/database/mongodb/disable', { method: 'POST', headers: { 'x-action-token': (dbActionTokens || {}).mongodbDisable || '' } }), 'db', { stepUpService: 'mongodb' });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || 'Failed to disable');
}
if (progress) progress.finish(true, 'MongoDB disabled and removed — refresh to update');
if (mongodbToggle) { mongodbToggle.checked = false; mongodbToggle.dataset.wasEnabled = ''; }
} catch (err) {
console.error('[mongodb] Disable error:', err);
if (progress) progress.finish(false, err.message || 'Failed to disable MongoDB');
if (mongodbToggle) mongodbToggle.checked = true;
} finally {
if (mongodbToggle) mongodbToggle.disabled = false;
}
}
if (mongodbToggle) {
mongodbToggle.addEventListener('change', (e) => {
if (e.target.checked) {
openMongoDBSetupModal().catch(err => {
console.error('[mongodb] Setup modal failed:', err);
alert(err?.message || 'Failed to open the MongoDB setup. Please reload the page and try again.');
if (mongodbToggle && !mongodbToggle.dataset.wasEnabled) mongodbToggle.checked = false;
});
} else if (confirm('Disable MongoDB? This stops the service, removes MongoDB packages and its data for a clean reinstall.')) {
disableMongoDB();
} else if (mongodbToggle) {
mongodbToggle.checked = true;
}
});
}
if (mongodbSetupModalClose) mongodbSetupModalClose.addEventListener('click', closeMongoDBSetupModal);
if (mongodbSetupCancel) mongodbSetupCancel.addEventListener('click', closeMongoDBSetupModal);
if (mongodbSetupModalOverlay) {
mongodbSetupModalOverlay.addEventListener('click', (e) => {
if (e.target === mongodbSetupModalOverlay) closeMongoDBSetupModal();
});
}
if (mongodbSetupSave) mongodbSetupSave.addEventListener('click', saveMongoDBSetup);
if (mongodbPassword && mongodbPasswordStrength) {
mongodbPassword.addEventListener('input', (e) => {
const val = e.target.value;
let strength = 'weak';
if (val.length >= 12 && /[A-Z]/.test(val) && /[0-9]/.test(val) && /[^A-Za-z0-9]/.test(val)) {
strength = 'strong';
} else if (val.length >= 10 && /[A-Z]/.test(val) && /[0-9]/.test(val)) {
strength = 'good';
} else if (val.length >= 8) {
strength = 'fair';
}
mongodbPasswordStrength.innerHTML = val ? `
` : '';
});
}
if (mongodbConnPass) {
mongodbConnPass.addEventListener('click', () => {
const isBlurred = mongodbConnPass.classList.contains('blurred');
if (isBlurred) {
const password = ensureMongoConnectionPassword();
if (!password) return;
showMongoConnectionPassword(password);
} else if (!isBlurred) {
hideMongoConnectionPassword();
}
});
}
if (toggleMongodbPassword && mongodbConnPass) {
toggleMongodbPassword.addEventListener('click', () => {
const isBlurred = mongodbConnPass.classList.contains('blurred');
if (isBlurred) {
const password = ensureMongoConnectionPassword();
if (!password) return;
showMongoConnectionPassword(password);
} else if (!isBlurred) {
hideMongoConnectionPassword();
}
});
}
if (copyMongodbUrl) {
copyMongodbUrl.addEventListener('click', () => {
const urlWrapper = document.querySelector('.db-access-url-wrapper');
if (!urlWrapper) return;
const username = urlWrapper.dataset.username || 'admin';
let password = sessionMongoPassword;
if (!password) {
password = ensureMongoConnectionPassword();
if (!password) return;
}
const host = urlWrapper.dataset.host || 'localhost';
const port = urlWrapper.dataset.port || '27017';
const encodedUser = encodeURIComponent(username);
const encodedPass = encodeURIComponent(password);
const fullUrl = `mongodb://${encodedUser}:${encodedPass}@${host}:${port}/?authSource=admin`;
copyToClipboard(fullUrl).then(() => {
copyMongodbUrl.innerHTML = ' ';
setTimeout(() => { copyMongodbUrl.innerHTML = ' '; }, 1500);
});
});
}
let mongodbActionTokens = {};
window.loadMongoDBUsers = async function () {
try {
const res = await fetch('/api/settings/database/mongodb/users');
const data = await res.json();
if (!data.ok || !data.enabled) return;
mongodbActionTokens = data.actionTokens || {};
const portInfo = document.getElementById('mongodbPortInfo');
const host = data.host === '0.0.0.0' ? window.location.hostname : (data.host || 'localhost');
const port = data.port || '27017';
if (portInfo) {
portInfo.textContent = `Database is running on ${host}:${port}`;
}
const connUser = document.getElementById('mongodbConnUser');
const connPass = document.getElementById('mongodbConnPass');
const connHost = document.getElementById('mongodbConnHost');
const urlWrapper = document.querySelector('.db-access-url-wrapper');
if (data.users && data.users[0]) {
const adminUser = data.users[0];
if (connUser) connUser.textContent = adminUser.username;
if (connPass) {
hideMongoConnectionPassword();
}
if (connHost) connHost.textContent = `${host}:${port}`;
if (urlWrapper) {
urlWrapper.dataset.username = adminUser.username || 'admin';
urlWrapper.dataset.host = host;
urlWrapper.dataset.port = port;
}
if (pendingMongoPassword) {
setMongoSessionPassword(pendingMongoPassword);
pendingMongoPassword = '';
}
} else {
if (connUser) connUser.textContent = 'admin';
if (connPass) {
hideMongoConnectionPassword();
}
if (connHost) connHost.textContent = `${host}:${port}`;
}
const usersList = document.getElementById('mongodbUsersList');
if (!usersList) return;
if (!data.users || data.users.length === 0) {
usersList.innerHTML = `
`;
return;
}
// Local copy of escapeHtmlDb, the same helper renderDbUsers applies to
// the PostgreSQL users list. The original is declared inside another
// IIFE and is not in scope here, so redeclare it to keep server-derived
// values from being interpolated raw into innerHTML.
function escapeHtmlDb(str) {
if (!str) return '';
return String(str)
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
usersList.innerHTML = data.users.map((user, idx) => {
const createdAt = user.createdAt ? new Date(user.createdAt).toLocaleDateString() : 'N/A';
const isAdmin = idx === 0;
return `
${escapeHtmlDb(user.username)}${isAdmin ? ' root ' : ''}
Created ${escapeHtmlDb(createdAt)}
${!isAdmin ? `
` : ''}
`;
}).join('');
usersList.querySelectorAll('[data-action="change-password"]').forEach(btn => {
btn.addEventListener('click', () => {
const username = btn.getAttribute('data-username');
window.changeMongoDBPassword(username);
});
});
usersList.querySelectorAll('[data-action="delete-user"]').forEach(btn => {
btn.addEventListener('click', () => {
const username = btn.getAttribute('data-username');
window.showDeleteUserModal(username);
});
});
} catch (err) {
console.error('[mongodb] Load users error:', err);
}
}
const deleteModalOverlay = document.getElementById('mongodbDeleteUserModalOverlay');
const deleteUsernameEl = document.getElementById('mongodbDeleteUsername');
const deleteCancelBtn = document.getElementById('mongodbDeleteCancel');
const deleteConfirmBtn = document.getElementById('mongodbDeleteConfirm');
let pendingDeleteUsername = null;
function openDeleteModal(username) {
pendingDeleteUsername = username;
if (deleteUsernameEl) deleteUsernameEl.textContent = username;
if (deleteModalOverlay) {
deleteModalOverlay.classList.add('show');
deleteModalOverlay.setAttribute('aria-hidden', 'false');
}
}
function closeDeleteModal() {
if (deleteModalOverlay) {
deleteModalOverlay.classList.remove('show');
deleteModalOverlay.setAttribute('aria-hidden', 'true');
}
pendingDeleteUsername = null;
}
window.showDeleteUserModal = openDeleteModal;
if (deleteCancelBtn) {
deleteCancelBtn.addEventListener('click', closeDeleteModal);
}
if (deleteModalOverlay) {
deleteModalOverlay.addEventListener('click', (e) => {
if (e.target === deleteModalOverlay) closeDeleteModal();
});
}
if (deleteConfirmBtn) {
deleteConfirmBtn.addEventListener('click', async () => {
if (!pendingDeleteUsername) return;
deleteConfirmBtn.disabled = true;
deleteConfirmBtn.innerHTML = ' Deleting...';
const requestDelete = (confirmOrphan) => fetchDbRequestWithTokenRetry(() => fetch(`/api/settings/database/mongodb/users/${encodeURIComponent(pendingDeleteUsername)}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json', 'x-action-token': mongodbActionTokens[`deleteUser_${pendingDeleteUsername}`] || '' },
body: JSON.stringify({ confirmOrphan: confirmOrphan === true })
}), 'mongo');
try {
let res = await requestDelete(false);
let data = await res.json().catch(() => ({}));
// Mirror of the confirmRemoteBind client pattern: 409 asks for an
// explicit orphan confirmation (the account on a non-loopback server
// cannot be reliably revoked), then re-send with confirmOrphan: true.
if (res.status === 409 && data.code === 'REMOTE_DROP_CONFIRMATION_REQUIRED') {
if (!window.confirm(data.error + '\n\nClick OK to remove the panel entry anyway.')) return;
res = await requestDelete(true);
data = await res.json().catch(() => ({}));
}
if (!res.ok) throw new Error(data.error || 'Delete failed');
if (data.warning) alert(data.warning);
closeDeleteModal();
window.loadMongoDBUsers();
} catch (err) {
alert('Failed to delete user: ' + err.message);
} finally {
deleteConfirmBtn.disabled = false;
deleteConfirmBtn.innerHTML = ' Delete User';
}
});
}
window.deleteMongoDBUser = function (username) {
openDeleteModal(username);
};
window.changeMongoDBPassword = async function (username) {
const newPassword = prompt(`Enter new password for "${username}" (min 8 characters):`);
if (!newPassword) return;
if (newPassword.length < 8) {
alert('Password must be at least 8 characters');
return;
}
try {
const res = await fetchDbRequestWithTokenRetry(() => fetch(`/api/settings/database/mongodb/users/${encodeURIComponent(username)}/password`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-action-token': mongodbActionTokens[`changePassword_${username}`] || '' },
body: JSON.stringify({ password: newPassword })
}), 'mongo');
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Change password failed');
alert('Password changed successfully');
const currentConnUser = (document.getElementById('mongodbConnUser')?.textContent || '').trim() || 'admin';
if (String(username || '').trim() === currentConnUser) {
setMongoSessionPassword(newPassword);
hideMongoConnectionPassword();
}
} catch (err) {
alert('Failed to change password: ' + err.message);
}
};
const mongodbUserModalOverlay = document.getElementById('mongodbUserModalOverlay');
const mongodbUserModalClose = document.getElementById('mongodbUserModalClose');
const mongodbUserCancel = document.getElementById('mongodbUserCancel');
const mongodbUserSave = document.getElementById('mongodbUserSave');
const mongodbNewUsername = document.getElementById('mongodb_new_username');
const mongodbNewPassword = document.getElementById('mongodb_new_password');
const mongodbUserFeedback = document.getElementById('mongodbUserFeedback');
function openMongodbUserModal() {
if (mongodbNewUsername) mongodbNewUsername.value = '';
if (mongodbNewPassword) mongodbNewPassword.value = '';
showMongodbUserFeedback('');
if (mongodbUserModalOverlay) {
mongodbUserModalOverlay.classList.add('show');
mongodbUserModalOverlay.setAttribute('aria-hidden', 'false');
}
}
function closeMongodbUserModal() {
if (mongodbUserModalOverlay) {
mongodbUserModalOverlay.classList.remove('show');
mongodbUserModalOverlay.setAttribute('aria-hidden', 'true');
}
}
// msg can carry raw mongosh stderr from the api, so it must be rendered as text, never html
function showMongodbUserFeedback(msg, isError = false) {
if (mongodbUserFeedback) {
mongodbUserFeedback.textContent = msg;
mongodbUserFeedback.className = 'node-feedback' + (isError ? ' error' : ' success');
mongodbUserFeedback.style.display = msg ? 'block' : 'none';
}
}
const createMongodbUserBtn = document.getElementById('createMongodbUser');
if (createMongodbUserBtn) {
createMongodbUserBtn.addEventListener('click', openMongodbUserModal);
}
if (mongodbUserModalClose) mongodbUserModalClose.addEventListener('click', closeMongodbUserModal);
if (mongodbUserCancel) mongodbUserCancel.addEventListener('click', closeMongodbUserModal);
if (mongodbUserModalOverlay) {
mongodbUserModalOverlay.addEventListener('click', (e) => {
if (e.target === mongodbUserModalOverlay) closeMongodbUserModal();
});
}
if (mongodbUserSave) {
mongodbUserSave.addEventListener('click', async () => {
const username = mongodbNewUsername?.value?.trim();
const password = mongodbNewPassword?.value;
if (!username || !/^[a-zA-Z0-9_-]+$/.test(username)) {
showMongodbUserFeedback('Invalid username (alphanumeric, _, - only)', true);
return;
}
if (!password || password.length < 8) {
showMongodbUserFeedback('Password must be at least 8 characters', true);
return;
}
mongodbUserSave.disabled = true;
mongodbUserSave.innerHTML = ' Creating...';
showMongodbUserFeedback('', false);
try {
const res = await fetchDbRequestWithTokenRetry(() => fetch('/api/settings/database/mongodb/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-action-token': mongodbActionTokens.createUser || '' },
body: JSON.stringify({ username, password })
}), 'mongo');
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Create failed');
showMongodbUserFeedback('User created successfully!', false);
setTimeout(() => {
closeMongodbUserModal();
window.loadMongoDBUsers();
}, 1000);
} catch (err) {
showMongodbUserFeedback('Failed: ' + err.message, true);
} finally {
mongodbUserSave.disabled = false;
mongodbUserSave.innerHTML = ' Create User';
}
});
}
setupPasswordToggle('mongodb_new_password_toggle', 'mongodb_new_password');
const originalLoadMongoDBStatus = window.loadMongoDBStatus || loadMongoDBStatus;
loadMongoDBStatus = async function () {
if (typeof originalLoadMongoDBStatus === 'function') {
await originalLoadMongoDBStatus();
}
if (typeof window.loadMongoDBUsers === 'function') {
window.loadMongoDBUsers();
}
};
window.loadMongoDBStatus = loadMongoDBStatus;
})();
// Trigger initial database status checks if databases panel is active on page load
(function initActiveDatabasesPanel() {
const databasesPanel = document.getElementById('databases');
if (databasesPanel && (databasesPanel.classList.contains('active') || window.location.hash === '#databases')) {
if (typeof window.loadDbConfig === 'function') window.loadDbConfig();
if (typeof window.loadPgAdminStatus === 'function') window.loadPgAdminStatus();
if (typeof window.loadMongoDBStatus === 'function') window.loadMongoDBStatus();
}
})();
const adminChangePasswordOverlay = document.getElementById('adminChangePasswordOverlay');
const adminChangePasswordModal = document.getElementById('adminChangePasswordModal');
const adminChangePasswordTitle = document.getElementById('adminChangePasswordTitle');
const adminChangePasswordSubtitle = document.getElementById('adminChangePasswordSubtitle');
const adminChangePasswordClose = document.getElementById('adminChangePasswordClose');
const adminChangePasswordCancelBtn = document.getElementById('adminChangePasswordCancelBtn');
const adminChangePasswordSave = document.getElementById('adminChangePasswordSave');
const adminChangePasswordFeedback = document.getElementById('adminChangePasswordFeedback');
const adminNewPassword = document.getElementById('adminNewPassword');
const adminConfirmPassword = document.getElementById('adminConfirmPassword');
const adminPasswordStrength = document.getElementById('adminPasswordStrength');
const adminChangePasswordCredential = document.getElementById('adminChangePasswordCredential');
const adminChangePasswordCredentialLabel = document.getElementById('adminChangePasswordCredentialLabel');
const adminChangePasswordCredentialHint = document.getElementById('adminChangePasswordCredentialHint');
// Account-action TOTP companion: hidden until the server answers the acting
// admin's password with a 2fa-required challenge.
const adminChangePasswordTotpSection = document.getElementById('adminChangePasswordTotpSection');
const adminChangePasswordTotpInput = document.getElementById('adminChangePasswordTotpInput');
const adminChangePasswordTotpLabel = document.getElementById('adminChangePasswordTotpLabel');
const adminChangePasswordTotpHint = document.getElementById('adminChangePasswordTotpHint');
bindAccountActionTotpInput(adminChangePasswordTotpInput);
let currentAdminChangePasswordEmail = '';
let currentAdminChangePasswordTarget = null;
let adminChangePasswordTotpRevealed = false;
function showAdminPasswordFeedback(msg, isError = false) {
if (!adminChangePasswordFeedback) return;
adminChangePasswordFeedback.textContent = msg;
adminChangePasswordFeedback.className = 'node-feedback' + (isError ? ' error' : ' success');
adminChangePasswordFeedback.style.display = msg ? 'block' : 'none';
}
function clearAdminPasswordFeedback() {
if (adminChangePasswordFeedback) {
adminChangePasswordFeedback.textContent = '';
adminChangePasswordFeedback.style.display = 'none';
}
}
function openAdminChangePasswordModal(email) {
currentAdminChangePasswordEmail = email;
currentAdminChangePasswordTarget = window.ADPanelAccountTargets.select(email);
if (adminChangePasswordTitle) adminChangePasswordTitle.textContent = `Change password for ${email}`;
if (adminChangePasswordSubtitle) adminChangePasswordSubtitle.textContent = 'Set a new password for this user';
if (adminNewPassword) adminNewPassword.value = '';
if (adminConfirmPassword) adminConfirmPassword.value = '';
// Password-then-TOTP pair: the password field is always shown (unless a
// grace grant covers the action); the TOTP companion stays hidden until a
// 2fa-required challenge reveals it.
configureAccountActionCredentialFields(
adminChangePasswordCredential,
adminChangePasswordCredentialLabel,
adminChangePasswordCredentialHint,
adminChangePasswordTotpSection,
adminChangePasswordTotpInput,
adminChangePasswordTotpLabel,
adminChangePasswordTotpHint
);
adminChangePasswordTotpRevealed = false;
if (adminChangePasswordCredential) adminChangePasswordCredential.value = '';
if (adminPasswordStrength) adminPasswordStrength.innerHTML = '';
clearAdminPasswordFeedback();
if (adminChangePasswordOverlay) {
adminChangePasswordOverlay.setAttribute('aria-hidden', 'false');
adminChangePasswordOverlay.classList.add('show');
}
}
function closeAdminChangePasswordModal() {
if (adminChangePasswordOverlay) {
adminChangePasswordOverlay.setAttribute('aria-hidden', 'true');
adminChangePasswordOverlay.classList.remove('show');
}
currentAdminChangePasswordEmail = '';
adminChangePasswordTotpRevealed = false;
hideAccountActionTotpField(adminChangePasswordTotpSection, adminChangePasswordTotpInput);
if (adminChangePasswordCredential) adminChangePasswordCredential.value = '';
clearAdminPasswordFeedback();
}
async function saveAdminChangePassword() {
if (!currentAdminChangePasswordEmail) return;
const targetEmail = currentAdminChangePasswordEmail;
const accountTarget = currentAdminChangePasswordTarget;
const newPassword = adminNewPassword?.value || '';
const confirm = adminConfirmPassword?.value || '';
if (!newPassword || !confirm) {
showAdminPasswordFeedback('Please fill in all fields', true);
return;
}
if (newPassword.length < 8) {
showAdminPasswordFeedback('Password must be at least 8 characters', true);
return;
}
if (newPassword !== confirm) {
showAdminPasswordFeedback('Passwords do not match', true);
return;
}
// Password-then-TOTP: submit the acting admin's current password (and the
// TOTP code once a challenge revealed the companion field). With a live
// grace grant no credentials travel at all.
const graceActive = (typeof isStepUpGraceActive === 'function') ? isStepUpGraceActive() : false;
if (!graceActive) {
if (ensureAccountActionPasswordVisible(
adminChangePasswordCredential,
adminChangePasswordCredentialLabel,
adminChangePasswordCredentialHint,
adminChangePasswordTotpSection,
adminChangePasswordTotpInput,
adminChangePasswordTotpLabel,
adminChangePasswordTotpHint
)) {
adminChangePasswordTotpRevealed = false;
}
const password = String(adminChangePasswordCredential?.value || '');
if (!password) {
showAdminPasswordFeedback('Enter your current password.', true);
adminChangePasswordCredential?.focus();
return;
}
if (adminChangePasswordTotpRevealed) {
const totpCode = String(adminChangePasswordTotpInput?.value || '').replace(/\D/g, '').slice(0, 6);
if (!/^\d{6}$/.test(totpCode)) {
showAdminPasswordFeedback('Enter a valid 6-digit code.', true);
adminChangePasswordTotpInput?.focus();
return;
}
}
}
if (adminChangePasswordSave) {
adminChangePasswordSave.disabled = true;
adminChangePasswordSave.innerHTML = ' Updating...';
}
try {
const body = collectAccountActionCredentialPayload(
{ newPassword, confirm },
adminChangePasswordCredential,
adminChangePasswordTotpSection,
adminChangePasswordTotpInput
);
const getChangePasswordToken = () => String((accountsListEl?._actionTokens || {}).changePassword || '').trim();
const sendChange = async (token) => {
const res = await fetch(`/api/settings/accounts/${encodeURIComponent(targetEmail)}/change-password`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': token || ''
},
body: JSON.stringify(window.ADPanelAccountTargets.payload(accountTarget, body))
});
const data = await res.json().catch(() => ({ error: 'Invalid response' }));
return { res, data };
};
let result = await sendChange(getChangePasswordToken());
if (!result.res.ok && result.data?.error === 'invalid or missing action token' && typeof loadAccounts === 'function') {
await loadAccounts();
const freshToken = getChangePasswordToken();
if (freshToken) result = await sendChange(freshToken);
}
const { res, data } = result;
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (!res.ok) {
// Password-then-TOTP challenge: keep the modal open, keep the typed
// password, reveal the TOTP companion only on 2fa-required.
if (handleAccountActionCredentialChallenge(data, {
totpSection: adminChangePasswordTotpSection,
totpInput: adminChangePasswordTotpInput,
showFeedback: showAdminPasswordFeedback,
onTotpRevealed: () => { adminChangePasswordTotpRevealed = true; },
onTotpHidden: () => { adminChangePasswordTotpRevealed = false; },
})) return;
showAdminPasswordFeedback(data.error || 'Failed to change password', true);
return;
}
// The reset itself stands, but its sign-out sweep may have been
// incomplete: when the server reports sessionInvalidationWarnings,
// append the joined warning text to the existing feedback element
// instead of showing an unconditional clean success.
let adminPwFeedbackText = 'Password changed successfully!';
if (Array.isArray(data.sessionInvalidationWarnings) && data.sessionInvalidationWarnings.length) {
adminPwFeedbackText += ' Warning: ' + data.sessionInvalidationWarnings.join(' ');
}
showAdminPasswordFeedback(adminPwFeedbackText, false);
setTimeout(() => {
closeAdminChangePasswordModal();
const toast = document.createElement('div');
toast.className = 'perm-success-toast';
toast.innerHTML = ' Password changed successfully';
document.body.appendChild(toast);
setTimeout(() => { toast.classList.add('show'); }, 10);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 2000);
}, 1000);
} catch (err) {
console.error('[admin-change-password]', err);
showAdminPasswordFeedback('Network error', true);
} finally {
if (adminChangePasswordSave) {
adminChangePasswordSave.disabled = false;
adminChangePasswordSave.innerHTML = ' Update Password';
}
}
}
if (adminChangePasswordClose) adminChangePasswordClose.addEventListener('click', closeAdminChangePasswordModal);
if (adminChangePasswordCancelBtn) adminChangePasswordCancelBtn.addEventListener('click', closeAdminChangePasswordModal);
if (adminChangePasswordSave) adminChangePasswordSave.addEventListener('click', saveAdminChangePassword);
if (adminChangePasswordOverlay) {
adminChangePasswordOverlay.addEventListener('click', (e) => {
if (e.target === adminChangePasswordOverlay) closeAdminChangePasswordModal();
});
}
if (adminChangePasswordModal) {
adminChangePasswordModal.querySelectorAll('.password-toggle').forEach(btn => {
if (btn.dataset.listenerAdded) return;
btn.dataset.listenerAdded = 'true';
btn.addEventListener('click', () => {
const wrap = btn.closest('.password-input-wrap');
if (wrap) {
const input = wrap.querySelector('input');
const icon = btn.querySelector('i');
if (input && icon) {
if (input.type === 'password') {
input.type = 'text';
icon.classList.replace('fa-eye', 'fa-eye-slash');
} else {
input.type = 'password';
icon.classList.replace('fa-eye-slash', 'fa-eye');
}
}
}
});
});
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && adminChangePasswordOverlay?.classList.contains('show')) {
closeAdminChangePasswordModal();
}
});
const qrOptionsModalOverlay = document.getElementById('qrOptionsModalOverlay');
const qrOptionsModal = document.getElementById('qrOptionsModal');
const qrOptionsModalClose = document.getElementById('qrOptionsModalClose');
const qrOptionsUserEmail = document.getElementById('qrOptionsUserEmail');
const resetUser2FABtn = document.getElementById('resetUser2FABtn');
const resetUserRecoveryBtn = document.getElementById('resetUserRecoveryBtn');
const qrResetModalOverlay = document.getElementById('qrResetModalOverlay');
const qrResetModal = document.getElementById('qrResetModal');
const qrResetModalClose = document.getElementById('qrResetModalClose');
const qrResetUserEmail = document.getElementById('qrResetUserEmail');
const qrResetLoading = document.getElementById('qrResetLoading');
const qrResetContent = document.getElementById('qrResetContent');
const qrResetError = document.getElementById('qrResetError');
const qrResetErrorText = document.getElementById('qrResetErrorText');
const qrResetDoneBtn = document.getElementById('qrResetDoneBtn');
const qrResetConfirm = document.getElementById('qrResetConfirm');
const qrResetConfirmError = document.getElementById('qrResetConfirmError');
const qrResetCredential = document.getElementById('qrResetCredential');
const qrResetCredentialLabel = document.getElementById('qrResetCredentialLabel');
const qrResetCredentialHint = document.getElementById('qrResetCredentialHint');
// Account-action TOTP companion: hidden until the server answers the acting
// admin's password with a 2fa-required challenge.
const qrResetTotpSection = document.getElementById('qrResetTotpSection');
const qrResetTotpInput = document.getElementById('qrResetTotpInput');
const qrResetTotpLabel = document.getElementById('qrResetTotpLabel');
const qrResetTotpHint = document.getElementById('qrResetTotpHint');
bindAccountActionTotpInput(qrResetTotpInput);
let currentQRResetEmail = '';
let currentQRResetTarget = null;
let qrResetTotpRevealed = false;
let qrResetCompleted = false;
function openQROptionsModal(email, isAdmin = false) {
if (!qrOptionsModalOverlay) return;
currentQRResetEmail = email;
currentQRResetTarget = window.ADPanelAccountTargets.select(email);
if (qrOptionsUserEmail) qrOptionsUserEmail.textContent = email;
if (resetUserRecoveryBtn) {
resetUserRecoveryBtn.style.display = isAdmin ? 'none' : '';
}
qrOptionsModalOverlay.setAttribute('aria-hidden', 'false');
qrOptionsModalOverlay.classList.add('show');
}
function closeQROptionsModal() {
if (!qrOptionsModalOverlay) return;
qrOptionsModalOverlay.setAttribute('aria-hidden', 'true');
qrOptionsModalOverlay.classList.remove('show');
}
function openQRResetModal() {
if (!qrResetModalOverlay) return;
if (qrResetUserEmail) qrResetUserEmail.textContent = `Reset 2FA for ${currentQRResetEmail}`;
// Password-then-TOTP pair for the acting admin: the password field is
// always shown (unless a grace grant covers the action); the TOTP
// companion stays hidden until a 2fa-required challenge reveals it.
qrResetCompleted = false;
configureAccountActionCredentialFields(
qrResetCredential,
qrResetCredentialLabel,
qrResetCredentialHint,
qrResetTotpSection,
qrResetTotpInput,
qrResetTotpLabel,
qrResetTotpHint
);
qrResetTotpRevealed = false;
const qrResetDoneText = document.getElementById('qrResetDoneText');
if (qrResetDoneText) {
qrResetDoneText.textContent = '2FA has been reset. The user must set up 2FA again from their account settings after their next login.';
}
if (qrResetConfirm) qrResetConfirm.style.display = 'block';
if (qrResetLoading) qrResetLoading.style.display = 'none';
if (qrResetContent) qrResetContent.style.display = 'none';
if (qrResetError) qrResetError.style.display = 'none';
if (qrResetConfirmError) { qrResetConfirmError.style.display = 'none'; qrResetConfirmError.textContent = ''; }
if (qrResetDoneBtn) {
qrResetDoneBtn.disabled = false;
qrResetDoneBtn.innerHTML = ' Reset 2FA';
}
qrResetModalOverlay.setAttribute('aria-hidden', 'false');
qrResetModalOverlay.classList.add('show');
if (qrResetCredential) { try { qrResetCredential.focus(); } catch (_) {} }
}
function closeQRResetModal() {
if (!qrResetModalOverlay) return;
qrResetModalOverlay.setAttribute('aria-hidden', 'true');
qrResetModalOverlay.classList.remove('show');
if (qrResetCredential) qrResetCredential.value = '';
qrResetTotpRevealed = false;
hideAccountActionTotpField(qrResetTotpSection, qrResetTotpInput);
}
// Performs the admin 2FA reset. The backend clears the target user's 2FA after
// step-up verification; no TOTP secret is ever returned to the admin.
async function confirmQRReset() {
// After a successful reset the same button becomes "Done" and just closes.
if (qrResetCompleted) {
closeQRResetModal();
return;
}
const accountTarget = currentQRResetTarget;
const targetEmail = currentQRResetEmail;
const showConfirmError = (msg) => {
if (qrResetConfirmError) {
qrResetConfirmError.textContent = msg;
qrResetConfirmError.style.display = 'block';
}
};
// Password-then-TOTP: submit the acting admin's current password (and the
// TOTP code once a challenge revealed the companion field). With a live
// grace grant no credentials travel at all.
const graceActive = (typeof isStepUpGraceActive === 'function') ? isStepUpGraceActive() : false;
if (!graceActive) {
if (ensureAccountActionPasswordVisible(
qrResetCredential,
qrResetCredentialLabel,
qrResetCredentialHint,
qrResetTotpSection,
qrResetTotpInput,
qrResetTotpLabel,
qrResetTotpHint
)) {
qrResetTotpRevealed = false;
}
const password = String((qrResetCredential && qrResetCredential.value) || '');
if (!password) { showConfirmError('Enter your current password.'); qrResetCredential?.focus(); return; }
if (qrResetTotpRevealed) {
const totpCode = String((qrResetTotpInput && qrResetTotpInput.value) || '').replace(/\D/g, '').slice(0, 6);
if (!/^\d{6}$/.test(totpCode)) { showConfirmError('Enter a valid 6-digit code.'); qrResetTotpInput?.focus(); return; }
}
}
try {
if (qrResetDoneBtn) {
qrResetDoneBtn.disabled = true;
qrResetDoneBtn.innerHTML = ' Resetting...';
}
if (qrResetConfirmError) qrResetConfirmError.style.display = 'none';
const body = collectAccountActionCredentialPayload(
{ email: targetEmail },
qrResetCredential,
qrResetTotpSection,
qrResetTotpInput
);
const getQRResetToken = () => String((accountsListEl?._actionTokens || {}).reset2fa || '').trim();
const sendReset = async (token) => {
const res = await fetch('/api/admin/user/reset-2fa', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': token || ''
},
credentials: 'include',
body: JSON.stringify(window.ADPanelAccountTargets.payload(accountTarget, body))
});
const data = await res.json();
return { res, data };
};
let result = await sendReset(getQRResetToken());
// adpanel:settings-token-registry — the stashed reset token expires after
// 10 idle minutes. On a token-invalid rejection ONLY, reload the accounts
// list (it re-mints the pool), re-read the token and resend AT MOST ONCE;
// the body was built once from the still-open modal's live inputs, so the
// typed password and TOTP code survive the reload. A step-up challenge
// (a password or 2FA challenge code) is not a token error and must not
// retry — it falls through to handleAccountActionCredentialChallenge below.
if (!result.res.ok && result.data?.error === 'invalid or missing action token' && typeof loadAccounts === 'function') {
await loadAccounts();
const freshToken = getQRResetToken();
if (freshToken) result = await sendReset(freshToken);
}
const { res, data } = result;
if (!res.ok) {
// Keep the modal open so the admin can re-enter credentials on a
// verification failure rather than losing the dialog. Password-then-
// TOTP challenge: reveal the TOTP companion only on 2fa-required.
if (handleAccountActionCredentialChallenge(data, {
totpSection: qrResetTotpSection,
totpInput: qrResetTotpInput,
showFeedback: showConfirmError,
onTotpRevealed: () => { qrResetTotpRevealed = true; },
onTotpHidden: () => { qrResetTotpRevealed = false; },
})) return;
throw new Error((data && data.error) || 'Failed to reset 2FA');
}
// Success: show the "user must re-enroll" message.
qrResetCompleted = true;
if (qrResetConfirm) qrResetConfirm.style.display = 'none';
if (qrResetLoading) qrResetLoading.style.display = 'none';
if (qrResetContent) qrResetContent.style.display = 'block';
const evictedSessions = Number(data.sessionsDestroyed || 0);
const qrResetDoneText = document.getElementById('qrResetDoneText');
if (qrResetDoneText && evictedSessions > 0) {
qrResetDoneText.textContent += ` ${evictedSessions} session${evictedSessions === 1 ? ' was' : 's were'} signed out.`;
}
// The reset itself stands (the target's credential generation moved with
// it), but its sign-out sweep may have been incomplete: append the
// server's sessionInvalidationWarnings to the existing done text instead
// of showing an unconditional clean success.
if (qrResetDoneText && Array.isArray(data.sessionInvalidationWarnings) && data.sessionInvalidationWarnings.length) {
qrResetDoneText.textContent += ` Warning: ${data.sessionInvalidationWarnings.join(' ')}`;
}
if (qrResetError) qrResetError.style.display = 'none';
if (qrResetDoneBtn) {
qrResetDoneBtn.innerHTML = ' Done';
}
console.log('[admin] 2FA reset SUCCESS for', currentQRResetEmail);
} catch (err) {
console.error('[admin] 2FA reset error:', err);
showConfirmError(err.message || 'Failed to reset 2FA');
} finally {
if (qrResetDoneBtn) {
qrResetDoneBtn.disabled = false;
if (qrResetCompleted) {
qrResetDoneBtn.innerHTML = ' Done';
} else {
qrResetDoneBtn.innerHTML = ' Reset 2FA';
}
}
}
}
if (qrOptionsModalClose) qrOptionsModalClose.addEventListener('click', closeQROptionsModal);
if (qrOptionsModalOverlay) {
qrOptionsModalOverlay.addEventListener('click', (e) => {
if (e.target === qrOptionsModalOverlay) closeQROptionsModal();
});
}
if (resetUser2FABtn) {
resetUser2FABtn.addEventListener('click', () => {
closeQROptionsModal();
openQRResetModal();
});
}
if (qrResetModalClose) qrResetModalClose.addEventListener('click', closeQRResetModal);
if (qrResetModalOverlay) {
qrResetModalOverlay.addEventListener('click', (e) => {
if (e.target === qrResetModalOverlay) closeQRResetModal();
});
}
if (qrResetDoneBtn) {
qrResetDoneBtn.addEventListener('click', confirmQRReset);
}
if (accountsListEl) {
accountsListEl.addEventListener('click', (e) => {
const btn = e.target.closest('.qr-reset-btn');
if (btn) {
const email = decodeURIComponent(btn.dataset.email || '');
const isAdmin = btn.dataset.admin === '1';
if (email) openQROptionsModal(email, isAdmin);
}
});
}
const recoveryResetModalOverlay = document.getElementById('recoveryResetModalOverlay');
const recoveryResetModal = document.getElementById('recoveryResetModal');
const recoveryResetModalClose = document.getElementById('recoveryResetModalClose');
const recoveryResetUserEmail = document.getElementById('recoveryResetUserEmail');
const recoveryResetConfirm = document.getElementById('recoveryResetConfirm');
const recoveryResetConfirmError = document.getElementById('recoveryResetConfirmError');
const recoveryResetCredential = document.getElementById('recoveryResetCredential');
const recoveryResetCredentialLabel = document.getElementById('recoveryResetCredentialLabel');
const recoveryResetCredentialHint = document.getElementById('recoveryResetCredentialHint');
// Account-action TOTP companion: hidden until the server answers the acting
// admin's password with a 2fa-required challenge.
const recoveryResetTotpSection = document.getElementById('recoveryResetTotpSection');
const recoveryResetTotpInput = document.getElementById('recoveryResetTotpInput');
const recoveryResetTotpLabel = document.getElementById('recoveryResetTotpLabel');
const recoveryResetTotpHint = document.getElementById('recoveryResetTotpHint');
bindAccountActionTotpInput(recoveryResetTotpInput);
const recoveryResetLoading = document.getElementById('recoveryResetLoading');
const recoveryResetContent = document.getElementById('recoveryResetContent');
const recoveryResetError = document.getElementById('recoveryResetError');
const recoveryResetErrorText = document.getElementById('recoveryResetErrorText');
const recoveryCodesList = document.getElementById('recoveryCodesList');
const recoveryResetDoneBtn = document.getElementById('recoveryResetDoneBtn');
let recoveryResetCompleted = false;
let recoveryResetTotpRevealed = false;
function openRecoveryResetModal() {
if (!recoveryResetModalOverlay) return;
if (recoveryResetUserEmail) recoveryResetUserEmail.textContent = `New codes for ${currentQRResetEmail}`;
recoveryResetCompleted = false;
// Password-then-TOTP pair for the acting admin: the password field is
// always shown (unless a grace grant covers the action); the TOTP
// companion stays hidden until a 2fa-required challenge reveals it.
configureAccountActionCredentialFields(
recoveryResetCredential,
recoveryResetCredentialLabel,
recoveryResetCredentialHint,
recoveryResetTotpSection,
recoveryResetTotpInput,
recoveryResetTotpLabel,
recoveryResetTotpHint
);
recoveryResetTotpRevealed = false;
if (recoveryResetConfirm) recoveryResetConfirm.style.display = 'block';
if (recoveryResetLoading) recoveryResetLoading.style.display = 'none';
if (recoveryResetContent) recoveryResetContent.style.display = 'none';
if (recoveryResetError) recoveryResetError.style.display = 'none';
if (recoveryResetConfirmError) { recoveryResetConfirmError.style.display = 'none'; recoveryResetConfirmError.textContent = ''; }
if (recoveryResetDoneBtn) {
recoveryResetDoneBtn.disabled = false;
recoveryResetDoneBtn.innerHTML = ' Generate Codes';
}
recoveryResetModalOverlay.setAttribute('aria-hidden', 'false');
recoveryResetModalOverlay.classList.add('show');
if (recoveryResetCredential && recoveryResetCredential.closest('div') && recoveryResetCredential.closest('div').style.display !== 'none') {
try { recoveryResetCredential.focus(); } catch (_) {}
}
}
function closeRecoveryResetModal() {
if (!recoveryResetModalOverlay) return;
recoveryResetModalOverlay.setAttribute('aria-hidden', 'true');
recoveryResetModalOverlay.classList.remove('show');
if (recoveryResetCredential) recoveryResetCredential.value = '';
recoveryResetTotpRevealed = false;
hideAccountActionTotpField(recoveryResetTotpSection, recoveryResetTotpInput);
}
// Regenerates the target user's recovery codes. The backend requires
// password-then-TOTP step-up verification (the acting admin's current
// password, plus their own 6-digit code once a 2fa-required challenge reveals
// the field) before returning the plaintext codes, unless a recent
// verification grace window is active.
async function generateNewRecoveryCodes() {
// After a successful reset the same button becomes "Done" and just closes.
if (recoveryResetCompleted) {
closeRecoveryResetModal();
return;
}
const accountTarget = currentQRResetTarget;
const targetEmail = currentQRResetEmail;
const showConfirmError = (msg) => {
if (recoveryResetConfirmError) {
recoveryResetConfirmError.textContent = msg;
recoveryResetConfirmError.style.display = 'block';
}
};
// Password-then-TOTP: submit the acting admin's current password (and the
// TOTP code once a challenge revealed the companion field). With a live
// grace grant no credentials travel at all.
const graceActive = (typeof isStepUpGraceActive === 'function') ? isStepUpGraceActive() : false;
if (!graceActive) {
if (ensureAccountActionPasswordVisible(
recoveryResetCredential,
recoveryResetCredentialLabel,
recoveryResetCredentialHint,
recoveryResetTotpSection,
recoveryResetTotpInput,
recoveryResetTotpLabel,
recoveryResetTotpHint
)) {
recoveryResetTotpRevealed = false;
}
const password = String((recoveryResetCredential && recoveryResetCredential.value) || '');
if (!password) { showConfirmError('Enter your current password.'); recoveryResetCredential?.focus(); return; }
if (recoveryResetTotpRevealed) {
const totpCode = String((recoveryResetTotpInput && recoveryResetTotpInput.value) || '').replace(/\D/g, '').slice(0, 6);
if (!/^\d{6}$/.test(totpCode)) { showConfirmError('Enter a valid 6-digit code.'); recoveryResetTotpInput?.focus(); return; }
}
}
try {
if (recoveryResetDoneBtn) {
recoveryResetDoneBtn.disabled = true;
recoveryResetDoneBtn.innerHTML = ' Generating...';
}
if (recoveryResetConfirmError) recoveryResetConfirmError.style.display = 'none';
if (recoveryResetConfirm) recoveryResetConfirm.style.display = 'none';
if (recoveryResetError) recoveryResetError.style.display = 'none';
if (recoveryResetLoading) recoveryResetLoading.style.display = 'block';
const body = collectAccountActionCredentialPayload(
{ email: targetEmail },
recoveryResetCredential,
recoveryResetTotpSection,
recoveryResetTotpInput
);
const getRecoveryResetToken = () => String((accountsListEl?._actionTokens || {}).resetRecoveryCodes || '').trim();
const sendRecoveryReset = async (token) => {
const res = await fetch('/api/admin/user/reset-recovery-codes', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': token || ''
},
credentials: 'include',
body: JSON.stringify(window.ADPanelAccountTargets.payload(accountTarget, body))
});
const data = await res.json();
return { res, data };
};
let result = await sendRecoveryReset(getRecoveryResetToken());
// adpanel:settings-token-registry — the stashed reset token expires after
// 10 idle minutes. On a token-invalid rejection ONLY, reload the accounts
// list (it re-mints the pool), re-read the token and resend AT MOST ONCE;
// the body was built once from the still-open modal's live inputs, so the
// typed password and TOTP code survive the reload. A step-up challenge
// (a password or 2FA challenge code) is not a token error and must not
// retry — it falls through to handleAccountActionCredentialChallenge below.
if (!result.res.ok && result.data?.error === 'invalid or missing action token' && typeof loadAccounts === 'function') {
await loadAccounts();
const freshToken = getRecoveryResetToken();
if (freshToken) result = await sendRecoveryReset(freshToken);
}
const { res, data } = result;
if (!res.ok) {
// Keep the credential form visible so the admin can retry after a
// failed verification instead of losing the dialog. Password-then-TOTP
// challenge: reveal the TOTP companion only on 2fa-required.
if (recoveryResetLoading) recoveryResetLoading.style.display = 'none';
if (recoveryResetConfirm) recoveryResetConfirm.style.display = 'block';
if (handleAccountActionCredentialChallenge(data, {
totpSection: recoveryResetTotpSection,
totpInput: recoveryResetTotpInput,
showFeedback: showConfirmError,
onTotpRevealed: () => { recoveryResetTotpRevealed = true; },
onTotpHidden: () => { recoveryResetTotpRevealed = false; },
})) return;
throw new Error(data.error || 'Failed to generate recovery codes');
}
if (recoveryCodesList) {
recoveryCodesList.innerHTML = (Array.isArray(data.recoveryCodes) ? data.recoveryCodes : []).map((code, idx) => `
${idx + 1}. ${escapeHtml(code)}
`).join('');
}
recoveryResetCompleted = true;
if (recoveryResetLoading) recoveryResetLoading.style.display = 'none';
if (recoveryResetConfirm) recoveryResetConfirm.style.display = 'none';
if (recoveryResetContent) recoveryResetContent.style.display = 'block';
if (recoveryResetError) recoveryResetError.style.display = 'none';
if (recoveryResetDoneBtn) recoveryResetDoneBtn.innerHTML = ' Done';
console.log('[admin] Recovery codes reset SUCCESS for', currentQRResetEmail);
} catch (err) {
console.error('[admin] Recovery codes generation error:', err);
if (recoveryResetLoading) recoveryResetLoading.style.display = 'none';
if (recoveryResetConfirm) recoveryResetConfirm.style.display = 'none';
if (recoveryResetContent) recoveryResetContent.style.display = 'none';
if (recoveryResetError) recoveryResetError.style.display = 'block';
if (recoveryResetErrorText) recoveryResetErrorText.textContent = err.message || 'Failed to generate recovery codes';
} finally {
if (recoveryResetDoneBtn) {
recoveryResetDoneBtn.disabled = false;
if (recoveryResetCompleted) {
recoveryResetDoneBtn.innerHTML = ' Done';
} else {
recoveryResetDoneBtn.innerHTML = ' Generate Codes';
}
}
}
}
if (recoveryResetModalClose) recoveryResetModalClose.addEventListener('click', closeRecoveryResetModal);
if (recoveryResetModalOverlay) {
recoveryResetModalOverlay.addEventListener('click', (e) => {
if (e.target === recoveryResetModalOverlay) closeRecoveryResetModal();
});
}
if (recoveryResetDoneBtn) {
recoveryResetDoneBtn.addEventListener('click', generateNewRecoveryCodes);
}
if (resetUserRecoveryBtn) {
resetUserRecoveryBtn.addEventListener('click', () => {
closeQROptionsModal();
openRecoveryResetModal();
});
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
if (recoveryResetModalOverlay?.classList.contains('show')) {
closeRecoveryResetModal();
} else if (qrResetModalOverlay?.classList.contains('show')) {
closeQRResetModal();
} else if (qrOptionsModalOverlay?.classList.contains('show')) {
closeQROptionsModal();
} else if (createUserModalOverlay?.classList.contains('show')) {
closeCreateUserModal();
} else if (userCredentialsModalOverlay?.classList.contains('show')) {
closeCredentialsModal();
}
}
});
const openCreateUserBtn = document.getElementById('openCreateUserBtn');
const createUserModalOverlay = document.getElementById('createUserModalOverlay');
const createUserModal = document.getElementById('createUserModal');
const createUserModalClose = document.getElementById('createUserModalClose');
const createUserCancelBtn = document.getElementById('createUserCancelBtn');
const createUserSubmitBtn = document.getElementById('createUserSubmitBtn');
const createUserRoleNormal = document.getElementById('createUserRoleNormal');
const createUserRoleAdmin = document.getElementById('createUserRoleAdmin');
const createUserEmail = document.getElementById('createUserEmail');
const createUserPassword = document.getElementById('createUserPassword');
const createUserPasswordConfirm = document.getElementById('createUserPasswordConfirm');
const createUserAdminStepUp = document.getElementById('createUserAdminStepUp');
const createAdminPassword = document.getElementById('createAdminPassword');
const createAdminTwoFactorField = document.getElementById('createAdminTwoFactorField');
const createAdminTwoFactor = document.getElementById('createAdminTwoFactor');
const createUserError = document.getElementById('createUserError');
const userCredentialsModalOverlay = document.getElementById('userCredentialsModalOverlay');
const userCredentialsModal = document.getElementById('userCredentialsModal');
const credentialsModalClose = document.getElementById('credentialsModalClose');
const credentialsUserEmail = document.getElementById('credentialsUserEmail');
const credentialsUserRole = document.getElementById('credentialsUserRole');
const credentialsOneTimeNoticeText = document.getElementById('credentialsOneTimeNoticeText');
const downloadCredentialsBtn = document.getElementById('downloadCredentialsBtn');
const credentialsDoneBtn = document.getElementById('credentialsDoneBtn');
let lastCreatedUserCredentials = null;
let createUserSelectedRole = 'user';
function setCreateUserRole(role) {
createUserSelectedRole = role === 'admin' ? 'admin' : 'user';
if (createUserRoleNormal) createUserRoleNormal.classList.toggle('active', createUserSelectedRole === 'user');
if (createUserRoleAdmin) createUserRoleAdmin.classList.toggle('active', createUserSelectedRole === 'admin');
if (createUserAdminStepUp) createUserAdminStepUp.style.display = createUserSelectedRole === 'admin' ? 'block' : 'none';
if (createAdminTwoFactorField) createAdminTwoFactorField.style.display = createUserSelectedRole === 'admin' && currentUserHas2FA ? '' : 'none';
if (createUserSubmitBtn) {
createUserSubmitBtn.innerHTML = createUserSelectedRole === 'admin'
? ' Create Admin'
: ' Create User';
}
}
function openCreateUserModal() {
if (!createUserModalOverlay) return;
setCreateUserRole('user');
if (createUserEmail) createUserEmail.value = '';
if (createUserPassword) createUserPassword.value = '';
if (createUserPasswordConfirm) createUserPasswordConfirm.value = '';
if (createAdminPassword) createAdminPassword.value = '';
if (createAdminTwoFactor) createAdminTwoFactor.value = '';
if (createUserError) {
createUserError.style.display = 'none';
createUserError.textContent = '';
}
createUserModalOverlay.setAttribute('aria-hidden', 'false');
createUserModalOverlay.classList.add('show');
setTimeout(() => createUserEmail?.focus(), 100);
}
function closeCreateUserModal() {
if (!createUserModalOverlay) return;
createUserModalOverlay.setAttribute('aria-hidden', 'true');
createUserModalOverlay.classList.remove('show');
if (createAdminPassword) createAdminPassword.value = '';
if (createAdminTwoFactor) createAdminTwoFactor.value = '';
// The new account's password must not linger in hidden inputs after close
// (same DOM-hygiene rule as the step-up modal credential fields).
if (createUserPassword) createUserPassword.value = '';
if (createUserPasswordConfirm) createUserPasswordConfirm.value = '';
}
function showCreateUserError(msg) {
if (createUserError) {
createUserError.textContent = msg;
createUserError.style.display = 'block';
}
}
function getUtf8ByteLength(value) {
try {
return new TextEncoder().encode(String(value || '')).length;
} catch {
return unescape(encodeURIComponent(String(value || ''))).length;
}
}
async function ensureCreateUserActionToken(forceRefresh = false) {
if (!forceRefresh && (accountsListEl._actionTokens || {}).createUser) return true;
if (typeof loadAccounts === 'function') {
await loadAccounts();
}
return !!((accountsListEl._actionTokens || {}).createUser);
}
async function submitCreateUser() {
const email = createUserEmail?.value?.trim() || '';
const password = createUserPassword?.value || '';
const confirmPassword = createUserPasswordConfirm?.value || '';
const role = createUserSelectedRole === 'admin' ? 'admin' : 'user';
const adminPassword = createAdminPassword?.value || '';
const adminTwoFactorCode = (createAdminTwoFactor?.value || '').replace(/\s+/g, '');
if (!email) {
showCreateUserError('Email is required');
return;
}
if (!password) {
showCreateUserError('Password is required');
return;
}
if (password.length < 8) {
showCreateUserError('Password must be at least 8 characters');
return;
}
if (getUtf8ByteLength(password) > 72) {
showCreateUserError('Password must be 72 bytes or less');
return;
}
if (password !== confirmPassword) {
showCreateUserError('Passwords do not match');
return;
}
if (role === 'admin') {
if (!adminPassword) {
showCreateUserError('Your password is required');
return;
}
if (currentUserHas2FA && !/^\d{6}$/.test(adminTwoFactorCode)) {
showCreateUserError('Enter a valid 6-digit 2FA code');
return;
}
}
if (createUserError) createUserError.style.display = 'none';
try {
if (createUserSubmitBtn) {
createUserSubmitBtn.disabled = true;
createUserSubmitBtn.innerHTML = ' Creating...';
}
const hasActionToken = await ensureCreateUserActionToken();
if (!hasActionToken) {
throw new Error('Admin action token missing');
}
const sendCreate = () => fetch('/api/admin/user/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-action-token': (accountsListEl._actionTokens || {}).createUser || ''
},
credentials: 'include',
body: JSON.stringify({
email,
password,
confirmPassword,
role,
adminPassword,
adminTwoFactorCode: currentUserHas2FA ? adminTwoFactorCode : ''
})
});
let res = await sendCreate();
let data = await res.json().catch(() => ({}));
// The settings page keeps a long-lived (10 min) action session, but if the
// token has expired after sitting in the modal, transparently refresh it
// once and retry so the admin never sees a spurious token error.
if (!res.ok && data.error === 'invalid or missing action token') {
const refreshed = await ensureCreateUserActionToken(true);
if (refreshed) {
res = await sendCreate();
data = await res.json().catch(() => ({}));
}
}
if (!res.ok) {
if (typeof loadAccounts === 'function') loadAccounts();
throw new Error(data.error || 'Failed to create user');
}
lastCreatedUserCredentials = data;
closeCreateUserModal();
openCredentialsModal(data);
if (typeof loadAccounts === 'function') {
loadAccounts();
}
} catch (err) {
console.error('[admin] Create user error:', err);
showCreateUserError(err.message || 'Failed to create user');
} finally {
if (createUserSubmitBtn) {
createUserSubmitBtn.disabled = false;
setCreateUserRole(createUserSelectedRole);
}
}
}
// Account creation result dialog. The create response never contains 2FA
// material (policy: the admin must never learn the user's TOTP seed or
// plaintext recovery codes — same non-repudiation model as the admin 2FA
// reset), so this dialog only confirms the account and points to the user's
// own enrollment from account security settings.
function openCredentialsModal(data) {
if (!userCredentialsModalOverlay) return;
if (credentialsUserEmail) credentialsUserEmail.textContent = `${data.email} is ready.`;
if (credentialsUserRole) {
const isAdmin = data.role === 'admin' || data.admin === true;
credentialsUserRole.textContent = isAdmin ? 'Admin User' : 'Normal User';
credentialsUserRole.classList.toggle('admin', isAdmin);
}
if (credentialsOneTimeNoticeText) {
credentialsOneTimeNoticeText.textContent = 'Share the password you set with the user securely. They can enable 2FA from their account security settings after signing in.';
}
userCredentialsModalOverlay.setAttribute('aria-hidden', 'false');
userCredentialsModalOverlay.classList.add('show');
}
function closeCredentialsModal() {
if (!userCredentialsModalOverlay) return;
userCredentialsModalOverlay.setAttribute('aria-hidden', 'true');
userCredentialsModalOverlay.classList.remove('show');
lastCreatedUserCredentials = null;
}
// Plain-text handoff note for the freshly created account. Contains only what
// the admin already knows (email + role): no TOTP seed or recovery codes are
// ever provisioned by the create flow, so there is nothing secret to include.
function downloadCredentials() {
if (!lastCreatedUserCredentials) return;
const data = lastCreatedUserCredentials;
const role = data.role === 'admin' || data.admin === true ? 'Admin User' : 'Normal User';
const content = `${window.__brandName} User Credentials
========================
Email: ${data.email}
Role: ${role}
2FA: Not provisioned at creation. The user enables 2FA themselves
from Account -> Security after signing in; the TOTP seed is never
issued to the admin.
IMPORTANT: Keep these credentials secure!
`;
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `adpanel-credentials-${data.email.replace('@', '_at_')}.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
if (openCreateUserBtn) openCreateUserBtn.addEventListener('click', openCreateUserModal);
if (createUserRoleNormal) createUserRoleNormal.addEventListener('click', () => setCreateUserRole('user'));
if (createUserRoleAdmin) createUserRoleAdmin.addEventListener('click', () => setCreateUserRole('admin'));
if (createUserModalClose) createUserModalClose.addEventListener('click', closeCreateUserModal);
if (createUserCancelBtn) createUserCancelBtn.addEventListener('click', closeCreateUserModal);
if (createUserSubmitBtn) createUserSubmitBtn.addEventListener('click', submitCreateUser);
if (createAdminTwoFactor) {
createAdminTwoFactor.addEventListener('input', () => {
createAdminTwoFactor.value = createAdminTwoFactor.value.replace(/\D+/g, '').slice(0, 6);
});
}
if (createUserModalOverlay) {
createUserModalOverlay.addEventListener('click', (e) => {
if (e.target === createUserModalOverlay) closeCreateUserModal();
});
}
if (credentialsModalClose) credentialsModalClose.addEventListener('click', closeCredentialsModal);
if (credentialsDoneBtn) credentialsDoneBtn.addEventListener('click', closeCredentialsModal);
if (downloadCredentialsBtn) downloadCredentialsBtn.addEventListener('click', downloadCredentials);
if (userCredentialsModalOverlay) {
userCredentialsModalOverlay.addEventListener('click', (e) => {
if (e.target === userCredentialsModalOverlay) closeCredentialsModal();
});
}
createUserModal?.querySelectorAll('.password-toggle').forEach(btn => {
if (btn.dataset.listenerAdded) return;
btn.dataset.listenerAdded = 'true';
btn.addEventListener('click', () => {
const targetId = btn.dataset.target;
const input = document.getElementById(targetId);
const icon = btn.querySelector('i');
if (input && icon) {
if (input.type === 'password') {
input.type = 'text';
icon.classList.replace('fa-eye', 'fa-eye-slash');
} else {
input.type = 'password';
icon.classList.replace('fa-eye-slash', 'fa-eye');
}
}
});
});
const openBrandingBtn = document.getElementById('openBrandingBtn');
const brandingModalOverlay = document.getElementById('brandingModalOverlay');
const brandingModal = document.getElementById('brandingModal');
const brandingModalClose = document.getElementById('brandingModalClose');
const brandingCancelBtn = document.getElementById('brandingCancelBtn');
const brandingSaveBtn = document.getElementById('brandingSaveBtn');
const brandingAppName = document.getElementById('brandingAppName');
const brandingLogoFile = document.getElementById('brandingLogoFile');
const brandingLogoUrl = document.getElementById('brandingLogoUrl');
const brandingLogoSelectBtn = document.getElementById('brandingLogoSelectBtn');
const brandingError = document.getElementById('brandingError');
const logoTabUpload = document.getElementById('logoTabUpload');
const logoTabUrl = document.getElementById('logoTabUrl');
const logoUploadSection = document.getElementById('logoUploadSection');
const logoUrlSection = document.getElementById('logoUrlSection');
const logoPreviewUpload = document.getElementById('logoPreviewUpload');
const logoPreviewImg = document.getElementById('logoPreviewImg');
const logoFileName = document.getElementById('logoFileName');
const logoPreviewUrl = document.getElementById('logoPreviewUrl');
const logoPreviewUrlImg = document.getElementById('logoPreviewUrlImg');
const logoUrlStatus = document.getElementById('logoUrlStatus');
let selectedLogoFile = null;
let currentLogoTab = 'upload';
// Branding update action token, minted by GET /api/admin/branding (and
// re-minted by every write response). The POST refuses session-only writes.
let brandingActionTokens = {};
function updateLogoUrlPreview() {
const url = brandingLogoUrl?.value?.trim();
if (!url || !logoPreviewUrlImg) {
if (logoPreviewUrl) logoPreviewUrl.style.display = 'none';
return;
}
if (!url.startsWith('http://') && !url.startsWith('https://')) {
if (logoUrlStatus) logoUrlStatus.textContent = 'Enter a valid http:// or https:// URL';
if (logoPreviewUrl) logoPreviewUrl.style.display = 'block';
return;
}
logoPreviewUrlImg.onload = () => {
if (logoUrlStatus) logoUrlStatus.textContent = 'Preview loaded successfully';
if (logoPreviewUrl) logoPreviewUrl.style.display = 'block';
};
logoPreviewUrlImg.onerror = () => {
if (logoUrlStatus) logoUrlStatus.textContent = 'Note: Direct preview not available or unreachable';
if (logoPreviewUrl) logoPreviewUrl.style.display = 'block';
};
logoPreviewUrlImg.src = url;
}
function openBrandingModal() {
if (!brandingModalOverlay) return;
selectedLogoFile = null;
currentLogoTab = 'upload';
if (brandingError) {
brandingError.style.display = 'none';
brandingError.textContent = '';
}
if (logoPreviewUpload) logoPreviewUpload.style.display = 'none';
if (logoPreviewUrl) logoPreviewUrl.style.display = 'none';
if (brandingLogoFile) brandingLogoFile.value = '';
if (brandingLogoUrl) brandingLogoUrl.value = '';
loadCurrentBranding();
brandingModalOverlay.setAttribute('aria-hidden', 'false');
brandingModalOverlay.classList.add('show');
}
function closeBrandingModal() {
if (!brandingModalOverlay) return;
brandingModalOverlay.setAttribute('aria-hidden', 'true');
brandingModalOverlay.classList.remove('show');
}
async function loadCurrentBranding() {
try {
const res = await fetch('/api/admin/branding', { credentials: 'include', cache: 'no-store' });
if (res.ok) {
const data = await res.json();
if (brandingAppName) brandingAppName.value = data.appName || '';
if (data.logoUrl && brandingLogoUrl) {
brandingLogoUrl.value = data.logoUrl;
switchLogoTab('url');
updateLogoUrlPreview();
} else if (data.hasLocalLogo) {
switchLogoTab('upload');
}
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (data.actionTokens) brandingActionTokens = data.actionTokens;
}
} catch (e) {
console.error('[branding] Failed to load current settings:', e);
}
}
function switchLogoTab(tab) {
currentLogoTab = tab;
if (tab === 'upload') {
if (logoTabUpload) {
logoTabUpload.style.border = '1px solid rgba(99,102,241,0.5)';
logoTabUpload.style.background = 'rgba(99,102,241,0.15)';
logoTabUpload.style.color = '#a5b4fc';
}
if (logoTabUrl) {
logoTabUrl.style.border = '1px solid rgba(255,255,255,0.1)';
logoTabUrl.style.background = 'rgba(255,255,255,0.03)';
logoTabUrl.style.color = 'rgba(255,255,255,0.6)';
}
if (logoUploadSection) logoUploadSection.style.display = 'block';
if (logoUrlSection) logoUrlSection.style.display = 'none';
} else {
if (logoTabUrl) {
logoTabUrl.style.border = '1px solid rgba(99,102,241,0.5)';
logoTabUrl.style.background = 'rgba(99,102,241,0.15)';
logoTabUrl.style.color = '#a5b4fc';
}
if (logoTabUpload) {
logoTabUpload.style.border = '1px solid rgba(255,255,255,0.1)';
logoTabUpload.style.background = 'rgba(255,255,255,0.03)';
logoTabUpload.style.color = 'rgba(255,255,255,0.6)';
}
if (logoUploadSection) logoUploadSection.style.display = 'none';
if (logoUrlSection) logoUrlSection.style.display = 'block';
updateLogoUrlPreview();
}
}
// Allowed logo image extensions (SVG supported with server-side XML sanitization & CSP sandbox)
const ALLOWED_LOGO_EXTENSIONS = ['png', 'jpg', 'jpeg', 'webp', 'ico', 'avif', 'gif', 'svg'];
function isAllowedLogoFile(file) {
const name = String(file?.name || '').toLowerCase();
const ext = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1) : '';
const type = String(file?.type || '').toLowerCase();
return ALLOWED_LOGO_EXTENSIONS.includes(ext) || type.startsWith('image/');
}
function handleLogoFileSelect(e) {
const file = e.target.files?.[0];
if (!file) return;
if (!isAllowedLogoFile(file)) {
alert('Please select a valid image file (PNG, JPG, WEBP, SVG, GIF, AVIF, or ICO).');
e.target.value = '';
return;
}
// Enforce 5MB limit on client side
if (file.size > 5 * 1024 * 1024) {
alert('Selected logo exceeds the 5MB size limit.');
e.target.value = '';
return;
}
selectedLogoFile = file;
const reader = new FileReader();
reader.onload = (evt) => {
if (logoPreviewImg) logoPreviewImg.src = evt.target.result;
if (logoFileName) logoFileName.textContent = file.name;
if (logoPreviewUpload) logoPreviewUpload.style.display = 'block';
};
reader.readAsDataURL(file);
}
// Server-side contract: the branding write requires the updateBranding
// action token AND a step-up credential (fresh password/2FA verification, or
// a live grace grant — the first attempt carries no credential so a live
// grant authorizes it silently). sendGuardedRequestWithStepUp owns the
// challenge/retry flow; this wrapper adds the token header and performs
// exactly one token refresh+retry when the 403 is a token rejection (stale
// modal load) rather than a step-up challenge.
async function sendBrandingUpdateWithGuards(body) {
if (!brandingActionTokens.updateBranding) {
await loadCurrentBranding();
}
if (!brandingActionTokens.updateBranding) {
return { ok: false, error: 'Branding settings not ready. Please try again.' };
}
const requestCopy = () => ({
headers: { 'x-action-token': brandingActionTokens.updateBranding || '' },
subtitle: 'Verify your identity to update branding',
reason: 'Branding changes what every user sees on the panel and the login page. Confirm your credentials to continue.',
confirmText: 'Confirm & Continue',
cancelledMessage: 'Branding update cancelled — nothing was modified.',
});
let result = await sendGuardedRequestWithStepUp('/api/admin/branding/update', 'POST', body, requestCopy());
if (result.data?.actionTokens) brandingActionTokens = result.data.actionTokens;
const tokenRejected = result.res.status === 403 && /action token/i.test(String(result.data?.error || ''));
if (tokenRejected) {
await loadCurrentBranding();
if (!brandingActionTokens.updateBranding) {
return { ok: false, error: 'Action token expired. Please refresh the page.' };
}
result = await sendGuardedRequestWithStepUp('/api/admin/branding/update', 'POST', body, requestCopy());
if (result.data?.actionTokens) brandingActionTokens = result.data.actionTokens;
}
return result.data;
}
async function saveBranding() {
const appName = brandingAppName?.value?.trim();
if (!appName) {
if (brandingError) {
brandingError.textContent = 'App name is required';
brandingError.style.display = 'block';
}
return;
}
if (brandingError) brandingError.style.display = 'none';
const body = { appName };
if (currentLogoTab === 'upload') {
if (selectedLogoFile) {
const reader = new FileReader();
const base64 = await new Promise((resolve) => {
reader.onload = (e) => resolve(e.target.result);
reader.readAsDataURL(selectedLogoFile);
});
body.logoBase64 = base64;
body.logoFilename = selectedLogoFile.name;
}
} else if (currentLogoTab === 'url') {
const url = brandingLogoUrl?.value?.trim();
if (url) {
body.logoUrl = url;
}
}
try {
if (brandingSaveBtn) {
brandingSaveBtn.disabled = true;
brandingSaveBtn.innerHTML = ' Saving...';
}
const data = await sendBrandingUpdateWithGuards(body);
if (!data || !data.ok) {
throw new Error(data?.error || 'Failed to update branding');
}
closeBrandingModal();
alert('Branding updated successfully! Refresh the page to see changes.');
} catch (err) {
console.error('[branding] Save error:', err);
if (brandingError) {
// A cancelled step-up verification already told the admin nothing was
// changed; mirror that here so the modal never shows a bare error.
brandingError.textContent = /cancel/i.test(String(err?.message || ''))
? 'Verification cancelled — nothing was modified.'
: (err.message || 'Failed to save branding');
brandingError.style.display = 'block';
}
} finally {
if (brandingSaveBtn) {
brandingSaveBtn.disabled = false;
brandingSaveBtn.innerHTML = ' Save Changes';
}
}
}
if (openBrandingBtn) openBrandingBtn.addEventListener('click', openBrandingModal);
if (brandingModalClose) brandingModalClose.addEventListener('click', closeBrandingModal);
if (brandingCancelBtn) brandingCancelBtn.addEventListener('click', closeBrandingModal);
if (brandingSaveBtn) brandingSaveBtn.addEventListener('click', saveBranding);
if (brandingModalOverlay) {
brandingModalOverlay.addEventListener('click', (e) => {
if (e.target === brandingModalOverlay) closeBrandingModal();
});
}
if (logoTabUpload) logoTabUpload.addEventListener('click', () => switchLogoTab('upload'));
if (logoTabUrl) logoTabUrl.addEventListener('click', () => switchLogoTab('url'));
if (brandingLogoSelectBtn) brandingLogoSelectBtn.addEventListener('click', () => brandingLogoFile?.click());
if (brandingLogoFile) brandingLogoFile.addEventListener('change', handleLogoFileSelect);
if (brandingLogoUrl) brandingLogoUrl.addEventListener('input', updateLogoUrlPreview);
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && brandingModalOverlay?.classList.contains('show')) {
closeBrandingModal();
}
});
const DEFAULT_LOGIN_BACKGROUND_URL = '/images/bgvid.webm';
const openLoginBackgroundBtn = document.getElementById('openLoginBackgroundBtn');
const loginBackgroundModalOverlay = document.getElementById('loginBackgroundModalOverlay');
const loginBackgroundModalClose = document.getElementById('loginBackgroundModalClose');
const loginBackgroundCancelBtn = document.getElementById('loginBackgroundCancelBtn');
const loginBackgroundSaveBtn = document.getElementById('loginBackgroundSaveBtn');
const loginBackgroundTabUpload = document.getElementById('loginBackgroundTabUpload');
const loginBackgroundTabUrl = document.getElementById('loginBackgroundTabUrl');
const loginBackgroundUploadSection = document.getElementById('loginBackgroundUploadSection');
const loginBackgroundUrlSection = document.getElementById('loginBackgroundUrlSection');
const loginBackgroundFile = document.getElementById('loginBackgroundFile');
const loginBackgroundSelectBtn = document.getElementById('loginBackgroundSelectBtn');
const loginBackgroundUrlInput = document.getElementById('loginBackgroundUrl');
const loginBackgroundPreviewImg = document.getElementById('loginBackgroundPreviewImg');
const loginBackgroundPreviewVideo = document.getElementById('loginBackgroundPreviewVideo');
const loginBackgroundPreviewBadge = document.getElementById('loginBackgroundPreviewBadge');
const loginBackgroundPreviewMeta = document.getElementById('loginBackgroundPreviewMeta');
const loginBackgroundFeedback = document.getElementById('loginBackgroundFeedback');
const loginBackgroundUploadMeta = document.getElementById('loginBackgroundUploadMeta');
const initialLoginBackgroundType = loginBackgroundPreviewImg?.classList.contains('is-visible') ? 'image' : 'video';
const initialLoginBackgroundSrc = initialLoginBackgroundType === 'image'
? (loginBackgroundPreviewImg?.currentSrc || loginBackgroundPreviewImg?.src || DEFAULT_LOGIN_BACKGROUND_URL)
: (loginBackgroundPreviewVideo?.currentSrc || loginBackgroundPreviewVideo?.src || DEFAULT_LOGIN_BACKGROUND_URL);
let loginBackgroundSourceMode = 'upload';
let selectedLoginBackgroundFile = null;
let loginBackgroundPreviewObjectUrl = null;
// Login-background update action token, minted by GET /api/admin/login-background
// (and re-minted by every write response). The POST refuses session-only writes.
let loginBackgroundActionTokens = {};
let loginBackgroundCurrentConfig = {
mode: 'upload',
mediaType: initialLoginBackgroundType,
backgroundUrl: initialLoginBackgroundSrc,
externalUrl: '',
mimeType: initialLoginBackgroundType === 'video' ? 'video/webm' : 'image/webp'
};
function setLoginBackgroundFeedback(message, type = 'error') {
if (!loginBackgroundFeedback) return;
loginBackgroundFeedback.textContent = message || '';
loginBackgroundFeedback.className = 'login-watermark-feedback';
if (!message) {
loginBackgroundFeedback.style.display = 'none';
return;
}
loginBackgroundFeedback.classList.add(type);
loginBackgroundFeedback.style.display = 'block';
}
function clearLoginBackgroundPreviewObjectUrl() {
if (!loginBackgroundPreviewObjectUrl) return;
try {
URL.revokeObjectURL(loginBackgroundPreviewObjectUrl);
} catch (err) {
console.warn('[login-background] Failed to revoke preview URL:', err);
}
loginBackgroundPreviewObjectUrl = null;
}
function safePlayLoginBackgroundPreview() {
if (!loginBackgroundPreviewVideo) return;
const playPromise = loginBackgroundPreviewVideo.play();
if (playPromise && typeof playPromise.then === 'function') {
playPromise.catch(() => { });
}
}
function getLoginBackgroundExtension(value) {
try {
const pathname = new URL(value, window.location.origin).pathname.toLowerCase();
if (!pathname.includes('.')) return '';
return pathname.slice(pathname.lastIndexOf('.') + 1).replace(/[^a-z0-9]/g, '');
} catch (err) {
return '';
}
}
function detectLoginBackgroundTypeFromUrl(value) {
const ext = getLoginBackgroundExtension(value);
if (['png', 'jpg', 'jpeg', 'webp', 'ico', 'avif', 'gif'].includes(ext)) return 'image';
if (['webm', 'mp4', 'ogg', 'ogv'].includes(ext)) return 'video';
return null;
}
function detectLoginBackgroundTypeFromFile(file) {
const fileType = String(file?.type || '').toLowerCase();
if (fileType.startsWith('image/')) return 'image';
if (fileType.startsWith('video/')) return 'video';
return detectLoginBackgroundTypeFromUrl(file?.name || '');
}
function getLoginBackgroundMimeType(value, mediaType) {
const ext = getLoginBackgroundExtension(value);
if (mediaType === 'image') {
if (ext === 'png') return 'image/png';
if (ext === 'jpg' || ext === 'jpeg') return 'image/jpeg';
if (ext === 'webp') return 'image/webp';
if (ext === 'avif') return 'image/avif';
if (ext === 'gif') return 'image/gif';
if (ext === 'ico') return 'image/x-icon';
return 'image/webp';
}
if (ext === 'mp4') return 'video/mp4';
if (ext === 'ogg' || ext === 'ogv') return 'video/ogg';
return 'video/webm';
}
function setLoginBackgroundPreview(src, mediaType, badgeText, metaText, mimeType) {
if (!loginBackgroundPreviewImg || !loginBackgroundPreviewVideo) return;
loginBackgroundPreviewImg.classList.toggle('is-visible', mediaType === 'image');
loginBackgroundPreviewVideo.classList.toggle('is-visible', mediaType === 'video');
if (mediaType === 'image') {
loginBackgroundPreviewVideo.pause();
loginBackgroundPreviewVideo.removeAttribute('src');
loginBackgroundPreviewVideo.load();
loginBackgroundPreviewImg.src = src;
} else {
loginBackgroundPreviewImg.removeAttribute('src');
loginBackgroundPreviewVideo.src = src;
if (mimeType) loginBackgroundPreviewVideo.dataset.mimeType = mimeType;
loginBackgroundPreviewVideo.load();
safePlayLoginBackgroundPreview();
}
if (loginBackgroundPreviewBadge) {
loginBackgroundPreviewBadge.textContent = badgeText || (mediaType === 'image' ? 'Image' : 'Video');
}
if (loginBackgroundPreviewMeta) {
loginBackgroundPreviewMeta.textContent = metaText || `Current ${mediaType}`;
}
}
function showLoginBackgroundToast(message) {
const toast = document.createElement('div');
toast.className = 'perm-success-toast';
toast.innerHTML = ' ' + escapeHtml(message || 'Login background updated');
document.body.appendChild(toast);
requestAnimationFrame(() => toast.classList.add('show'));
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 2800);
}
function syncLoginBackgroundPreviewToCurrent() {
setLoginBackgroundPreview(
loginBackgroundCurrentConfig.backgroundUrl || DEFAULT_LOGIN_BACKGROUND_URL,
loginBackgroundCurrentConfig.mediaType || 'video',
(loginBackgroundCurrentConfig.mediaType || 'video') === 'image' ? 'Image' : 'Video',
`Current ${(loginBackgroundCurrentConfig.mediaType || 'video') === 'image' ? 'image' : 'video'}`,
loginBackgroundCurrentConfig.mimeType || 'video/webm'
);
}
function switchLoginBackgroundTab(mode) {
loginBackgroundSourceMode = mode === 'url' ? 'url' : 'upload';
if (loginBackgroundTabUpload) loginBackgroundTabUpload.classList.toggle('active', loginBackgroundSourceMode === 'upload');
if (loginBackgroundTabUrl) loginBackgroundTabUrl.classList.toggle('active', loginBackgroundSourceMode === 'url');
if (loginBackgroundUploadSection) loginBackgroundUploadSection.style.display = loginBackgroundSourceMode === 'upload' ? 'block' : 'none';
if (loginBackgroundUrlSection) loginBackgroundUrlSection.style.display = loginBackgroundSourceMode === 'url' ? 'block' : 'none';
if (loginBackgroundSourceMode === 'upload' && selectedLoginBackgroundFile) {
const mediaType = detectLoginBackgroundTypeFromFile(selectedLoginBackgroundFile) || 'video';
if (loginBackgroundUploadMeta) {
const mediaLabel = mediaType === 'image' ? 'Image' : 'Video';
loginBackgroundUploadMeta.textContent = `${mediaLabel} ready: ${selectedLoginBackgroundFile.name}`;
}
if (loginBackgroundPreviewObjectUrl) {
setLoginBackgroundPreview(
loginBackgroundPreviewObjectUrl,
mediaType,
mediaType === 'image' ? 'Image' : 'Video',
`New ${mediaType}`,
selectedLoginBackgroundFile.type || getLoginBackgroundMimeType(selectedLoginBackgroundFile.name, mediaType)
);
}
return;
}
if (loginBackgroundSourceMode === 'url' && loginBackgroundUrlInput?.value?.trim()) {
handleLoginBackgroundUrlPreview();
return;
}
setLoginBackgroundFeedback('');
syncLoginBackgroundPreviewToCurrent();
}
async function loadCurrentLoginBackground() {
try {
const res = await fetch('/api/admin/login-background', { credentials: 'include', cache: 'no-store' });
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || 'Failed to load login background');
}
loginBackgroundCurrentConfig = {
mode: data.mode || 'upload',
mediaType: data.mediaType || 'video',
backgroundUrl: data.backgroundUrl || DEFAULT_LOGIN_BACKGROUND_URL,
externalUrl: data.externalUrl || '',
mimeType: data.mimeType || 'video/webm'
};
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (data.actionTokens) loginBackgroundActionTokens = data.actionTokens;
if (loginBackgroundUrlInput) {
loginBackgroundUrlInput.value = data.mode === 'url' ? (data.externalUrl || data.backgroundUrl || '') : '';
}
if (loginBackgroundUploadMeta) {
loginBackgroundUploadMeta.textContent = data.mode === 'upload'
? `${data.mediaType === 'image' ? 'Image' : 'Video'} active`
: (data.mode === 'none' ? 'Default background in use' : 'Ready for a local upload');
}
switchLoginBackgroundTab(data.mode || 'upload');
setLoginBackgroundFeedback('');
syncLoginBackgroundPreviewToCurrent();
} catch (err) {
console.error('[login-background] Failed to load current settings:', err);
loginBackgroundCurrentConfig = {
mode: 'upload',
mediaType: initialLoginBackgroundType,
backgroundUrl: initialLoginBackgroundSrc,
externalUrl: '',
mimeType: initialLoginBackgroundType === 'video' ? 'video/webm' : 'image/webp'
};
switchLoginBackgroundTab('upload');
setLoginBackgroundFeedback('Could not load the current background.', 'error');
syncLoginBackgroundPreviewToCurrent();
}
}
function openLoginBackgroundModal() {
if (!loginBackgroundModalOverlay) return;
selectedLoginBackgroundFile = null;
clearLoginBackgroundPreviewObjectUrl();
if (loginBackgroundFile) loginBackgroundFile.value = '';
if (loginBackgroundUploadMeta) loginBackgroundUploadMeta.textContent = '';
setLoginBackgroundFeedback('');
syncLoginBackgroundPreviewToCurrent();
loginBackgroundModalOverlay.setAttribute('aria-hidden', 'false');
loginBackgroundModalOverlay.classList.add('show');
loadCurrentLoginBackground();
}
function closeLoginBackgroundModal() {
if (!loginBackgroundModalOverlay) return;
if (loginBackgroundPreviewVideo) {
loginBackgroundPreviewVideo.pause();
}
clearLoginBackgroundPreviewObjectUrl();
loginBackgroundModalOverlay.setAttribute('aria-hidden', 'true');
loginBackgroundModalOverlay.classList.remove('show');
}
function handleLoginBackgroundFileSelect(e) {
const file = e.target.files?.[0];
if (!file) return;
if (isSvgFile(file)) {
setLoginBackgroundFeedback('SVG files are not supported for security reasons. Use PNG, JPG, WEBP, AVIF, GIF, WEBM, MP4 or OGG.', 'error');
if (loginBackgroundFile) loginBackgroundFile.value = '';
return;
}
const mediaType = detectLoginBackgroundTypeFromFile(file);
if (!mediaType) {
setLoginBackgroundFeedback('Choose a valid image or video file.', 'error');
if (loginBackgroundFile) loginBackgroundFile.value = '';
return;
}
const maxBytes = mediaType === 'image' ? 5 * 1024 * 1024 : 40 * 1024 * 1024;
if (file.size > maxBytes) {
setLoginBackgroundFeedback(mediaType === 'image' ? 'Image must be under 5MB.' : 'Video must be under 40MB.', 'error');
if (loginBackgroundFile) loginBackgroundFile.value = '';
return;
}
clearLoginBackgroundPreviewObjectUrl();
loginBackgroundPreviewObjectUrl = URL.createObjectURL(file);
selectedLoginBackgroundFile = file;
if (loginBackgroundUploadMeta) {
loginBackgroundUploadMeta.textContent = `${mediaType === 'image' ? 'Image' : 'Video'} selected: ${file.name}`;
}
setLoginBackgroundFeedback('');
setLoginBackgroundPreview(
loginBackgroundPreviewObjectUrl,
mediaType,
mediaType === 'image' ? 'Image' : 'Video',
`New ${mediaType}`,
file.type || getLoginBackgroundMimeType(file.name, mediaType)
);
}
function handleLoginBackgroundUrlPreview() {
const url = loginBackgroundUrlInput?.value?.trim();
if (!url) {
setLoginBackgroundFeedback('');
syncLoginBackgroundPreviewToCurrent();
return;
}
const mediaType = detectLoginBackgroundTypeFromUrl(url);
if (!mediaType) {
setLoginBackgroundFeedback('Use a direct image or video URL.', 'error');
return;
}
setLoginBackgroundFeedback('');
setLoginBackgroundPreview(
url,
mediaType,
mediaType === 'image' ? 'Image' : 'Video',
`${mediaType === 'image' ? 'Image' : 'Video'} from web`,
getLoginBackgroundMimeType(url, mediaType)
);
}
async function saveLoginBackground() {
if (!loginBackgroundSaveBtn) return;
const body = {};
if (loginBackgroundSourceMode === 'upload') {
if (!selectedLoginBackgroundFile) {
setLoginBackgroundFeedback('Choose an image or video first.', 'error');
return;
}
const reader = new FileReader();
const base64 = await new Promise((resolve) => {
reader.onload = (event) => resolve(event.target?.result || '');
reader.readAsDataURL(selectedLoginBackgroundFile);
});
body.backgroundBase64 = base64;
body.backgroundFilename = selectedLoginBackgroundFile.name;
} else {
const url = loginBackgroundUrlInput?.value?.trim();
if (!url) {
setLoginBackgroundFeedback('Paste a media URL first.', 'error');
return;
}
const mediaType = detectLoginBackgroundTypeFromUrl(url);
if (!mediaType) {
setLoginBackgroundFeedback('Use a direct image or video URL.', 'error');
return;
}
body.backgroundUrl = url;
}
try {
setLoginBackgroundFeedback('');
loginBackgroundSaveBtn.disabled = true;
loginBackgroundSaveBtn.innerHTML = ' Saving...';
const data = await sendLoginBackgroundSaveWithGuards(body);
if (!data || !data.ok) {
throw new Error(data?.error || 'Failed to update login background');
}
loginBackgroundCurrentConfig = {
mode: data.mode || loginBackgroundSourceMode,
mediaType: data.mediaType || 'video',
backgroundUrl: data.backgroundUrl || DEFAULT_LOGIN_BACKGROUND_URL,
externalUrl: data.externalUrl || '',
mimeType: data.mimeType || 'video/webm'
};
closeLoginBackgroundModal();
showLoginBackgroundToast('Login background updated');
} catch (err) {
console.error('[login-background] Save error:', err);
setLoginBackgroundFeedback(
/cancel/i.test(String(err?.message || ''))
? 'Verification cancelled — nothing was modified.'
: (err.message || 'Failed to save login background'),
'error'
);
} finally {
loginBackgroundSaveBtn.disabled = false;
loginBackgroundSaveBtn.innerHTML = ' Save Background';
}
}
// Server-side contract: the login-background write requires the
// updateLoginBackground action token AND a step-up credential (fresh
// password/2FA verification, or a live grace grant — the first attempt carries
// no credential so a live grant authorizes it silently).
// sendGuardedRequestWithStepUp owns the challenge/retry flow; this wrapper
// adds the token header and performs exactly one token refresh+retry when the
// 403 is a token rejection (stale modal load) rather than a step-up challenge.
async function sendLoginBackgroundSaveWithGuards(body) {
if (!loginBackgroundActionTokens.updateLoginBackground) {
await loadCurrentLoginBackground();
}
if (!loginBackgroundActionTokens.updateLoginBackground) {
return { ok: false, error: 'Login background settings not ready. Please try again.' };
}
const requestCopy = () => ({
headers: { 'x-action-token': loginBackgroundActionTokens.updateLoginBackground || '' },
subtitle: 'Verify your identity to change the login background',
reason: 'The login background is the first thing every visitor sees. Confirm your credentials to continue.',
confirmText: 'Confirm & Continue',
cancelledMessage: 'Login background update cancelled — nothing was modified.',
});
let result = await sendGuardedRequestWithStepUp('/api/admin/login-background', 'POST', body, requestCopy());
if (result.data?.actionTokens) loginBackgroundActionTokens = result.data.actionTokens;
const tokenRejected = result.res.status === 403 && /action token/i.test(String(result.data?.error || ''));
if (tokenRejected) {
await loadCurrentLoginBackground();
if (!loginBackgroundActionTokens.updateLoginBackground) {
return { ok: false, error: 'Action token expired. Please refresh the page.' };
}
result = await sendGuardedRequestWithStepUp('/api/admin/login-background', 'POST', body, requestCopy());
if (result.data?.actionTokens) loginBackgroundActionTokens = result.data.actionTokens;
}
return result.data;
}
if (openLoginBackgroundBtn) openLoginBackgroundBtn.addEventListener('click', openLoginBackgroundModal);
if (loginBackgroundModalClose) loginBackgroundModalClose.addEventListener('click', closeLoginBackgroundModal);
if (loginBackgroundCancelBtn) loginBackgroundCancelBtn.addEventListener('click', closeLoginBackgroundModal);
if (loginBackgroundSaveBtn) loginBackgroundSaveBtn.addEventListener('click', saveLoginBackground);
if (loginBackgroundTabUpload) loginBackgroundTabUpload.addEventListener('click', () => switchLoginBackgroundTab('upload'));
if (loginBackgroundTabUrl) loginBackgroundTabUrl.addEventListener('click', () => switchLoginBackgroundTab('url'));
if (loginBackgroundSelectBtn) loginBackgroundSelectBtn.addEventListener('click', () => loginBackgroundFile?.click());
if (loginBackgroundFile) loginBackgroundFile.addEventListener('change', handleLoginBackgroundFileSelect);
if (loginBackgroundUrlInput) {
loginBackgroundUrlInput.addEventListener('input', () => {
if (loginBackgroundSourceMode === 'url') handleLoginBackgroundUrlPreview();
});
loginBackgroundUrlInput.addEventListener('change', handleLoginBackgroundUrlPreview);
}
if (loginBackgroundModalOverlay) {
loginBackgroundModalOverlay.addEventListener('click', (e) => {
if (e.target === loginBackgroundModalOverlay) closeLoginBackgroundModal();
});
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && loginBackgroundModalOverlay?.classList.contains('show')) {
closeLoginBackgroundModal();
}
});
const nodeStatsModalOverlay = document.getElementById('nodeStatsModalOverlay');
const statsModalClose = document.getElementById('statsModalClose');
const statsModalBody = document.getElementById('statsModalBody');
const statsNodeNameEl = document.getElementById('statsNodeName');
const statsImage = document.getElementById('nodeStatsImage');
if (statsImage) {
statsImage.addEventListener('error', () => {
if (!statsImage.src.includes('server.webp')) {
statsImage.src = '/images/server.webp';
}
});
if (statsImage.complete && statsImage.naturalHeight === 0) {
statsImage.src = '/images/server.webp';
}
}
let statsPollingInterval = null;
let statsRun = null;
function openNodeStatsModal(nodeId, nodeName) {
if (!nodeStatsModalOverlay) return;
closeNodeStatsModal();
const run = { nodeId, controller: new AbortController(), inFlight: false };
statsRun = run;
if (statsNodeNameEl) statsNodeNameEl.textContent = 'Node name: ' + (nodeName || 'Loading...');
nodeStatsModalOverlay.classList.add('show');
document.body.style.overflow = 'hidden';
statsModalBody.innerHTML = `
`;
fetchAndRenderStats(run);
statsPollingInterval = setInterval(() => {
fetchAndRenderStats(run);
}, 5000);
}
function closeNodeStatsModal() {
if (!nodeStatsModalOverlay) return;
nodeStatsModalOverlay.classList.remove('show');
document.body.style.overflow = '';
if (statsPollingInterval) {
clearInterval(statsPollingInterval);
statsPollingInterval = null;
}
const run = statsRun;
statsRun = null;
run?.controller.abort();
}
async function fetchAndRenderStats(run) {
if (statsRun !== run || run.inFlight) return;
run.inFlight = true;
try {
const res = await fetch(`/api/admin/nodes/${encodeURIComponent(run.nodeId)}/stats`, { cache: 'no-store', signal: run.controller.signal });
const data = await res.json();
if (statsRun !== run) return;
if (!res.ok || !data.ok || !data.online) {
renderOfflineStats(data.nodeName || run.nodeId, data.error);
return;
}
renderStats(data);
} catch (err) {
if (statsRun !== run) return;
console.error('[stats] Fetch error:', err);
renderOfflineStats(run.nodeId, 'Connection error');
} finally {
run.inFlight = false;
}
}
function renderOfflineStats(nodeName, error) {
statsNodeNameEl.textContent = 'Node name: ' + (nodeName || 'Node');
statsModalBody.innerHTML = `
Node Offline
${escapeHtml(error || 'Unable to connect to this node')}
`;
}
function renderStats(data) {
const s = data.stats;
statsNodeNameEl.textContent = 'Node name: ' + (data.nodeName || 'Node');
const cpuClass = s.cpu.percent > 90 ? 'warning' : '';
const ramClass = s.ram.freeMb < 100 ? 'critical' : s.ram.percent > 90 ? 'warning' : '';
const diskClass = s.disk.freeGb < 1 ? 'critical' : s.disk.percent > 90 ? 'warning' : '';
let html = '';
if (data.warnings && data.warnings.length > 0) {
html += '';
data.warnings.forEach(w => {
const icon = w.level === 'critical' ? 'fa-triangle-exclamation' : 'fa-circle-exclamation';
html += `
${escapeHtml(w.message)}
`;
});
html += '
';
}
html += `
Cores
${s.cpu.cores || 'N/A'}
`;
html += `
${formatBytes(s.ram.usedMb * 1024 * 1024)} used
${formatBytes(s.ram.totalMb * 1024 * 1024)} total
Used
${(s.ram.usedMb / 1024).toFixed(1)} GB
Free
${(s.ram.freeMb / 1024).toFixed(1)} GB
`;
html += `
${s.disk.usedGb} GB used
${s.disk.totalGb} GB total
Used
${s.disk.usedGb} GB
Free
${s.disk.freeGb} GB
`;
html += `
Hostname
${escapeHtml(s.hostname || 'N/A')}
OS
${escapeHtml(s.os || 'N/A')}
Uptime
${formatUptime(s.uptime)}
Status
● Online
`;
html += `
Last updated: ${new Date().toLocaleTimeString()} • Auto-refreshing every 5 seconds
`;
statsModalBody.innerHTML = html;
}
function formatBytes(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}
function formatUptime(seconds) {
if (!seconds || seconds <= 0) return 'N/A';
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const mins = Math.floor((seconds % 3600) / 60);
if (days > 0) return `${days}d ${hours}h ${mins}m`;
if (hours > 0) return `${hours}h ${mins}m`;
return `${mins}m`;
}
if (statsModalClose) statsModalClose.addEventListener('click', closeNodeStatsModal);
if (nodeStatsModalOverlay) {
nodeStatsModalOverlay.addEventListener('click', (e) => {
if (e.target === nodeStatsModalOverlay) closeNodeStatsModal();
});
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && nodeStatsModalOverlay?.classList.contains('show')) {
closeNodeStatsModal();
}
});
document.addEventListener('DOMContentLoaded', () => {
const openAlertModalBtn = document.getElementById('openAlertModalBtn');
const alertModal = document.getElementById('alertModal');
const closeAlertModal = document.getElementById('closeAlertModal');
const closeAlertModalFooter = document.getElementById('closeAlertModalFooter');
const addAlertBtn = document.getElementById('addAlertBtn');
const alertContent = document.getElementById('alertContent');
const alertDate = document.getElementById('alertDate');
const alertEndDate = document.getElementById('alertEndDate');
const alertNeverEnds = document.getElementById('alertNeverEnds');
const alertsList = document.getElementById('alertsList');
if (openAlertModalBtn) {
console.log('Setup alert listeners, button:', openAlertModalBtn, 'modal:', alertModal);
function formatAlertDate(value) {
if (!value) return 'Not set';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return 'Invalid date';
return date.toLocaleString([], {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
function parseLocalDateTimeInput(value) {
if (!value) return null;
const parts = value.split('T');
if (parts.length !== 2) return null;
const [y, m, d] = parts[0].split('-').map(Number);
const [h, min] = parts[1].split(':').map(Number);
if ([y, m, d, h, min].some((num) => Number.isNaN(num))) return null;
const localDate = new Date(y, m - 1, d, h, min);
if (Number.isNaN(localDate.getTime())) return null;
return localDate;
}
function getAlertStatusMeta(alert) {
const now = Date.now();
const startAt = alert?.date ? new Date(alert.date).getTime() : 0;
const endAt = alert?.neverEnds || !alert?.endDate ? null : new Date(alert.endDate).getTime();
if (Number.isFinite(startAt) && startAt > now) {
return {
label: 'Scheduled',
style: 'color:#fbbf24;font-size:10px;margin-left:6px;background:rgba(251,191,36,0.1);padding:2px 6px;border-radius:4px;'
};
}
if (endAt !== null && Number.isFinite(endAt) && endAt <= now) {
return {
label: 'Ended',
style: 'color:#f87171;font-size:10px;margin-left:6px;background:rgba(248,113,113,0.1);padding:2px 6px;border-radius:4px;'
};
}
return {
label: 'Active',
style: 'color:#4ade80;font-size:10px;margin-left:6px;background:rgba(74,222,128,0.1);padding:2px 6px;border-radius:4px;'
};
}
function syncAlertEndDateState() {
if (!alertEndDate || !alertNeverEnds) return;
const keepActive = !!alertNeverEnds.checked;
alertEndDate.disabled = keepActive;
alertEndDate.required = !keepActive;
alertEndDate.style.opacity = keepActive ? '0.55' : '1';
}
function toggleAlertModal(show) {
if (show) {
alertModal.setAttribute('aria-hidden', 'false');
alertModal.classList.add('show');
const inner = alertModal.querySelector('.enterprise-modal');
if (inner) setTimeout(() => inner.classList.add('show'), 10);
if (alertNeverEnds) alertNeverEnds.checked = true;
syncAlertEndDateState();
loadAlerts();
} else {
alertModal.setAttribute('aria-hidden', 'true');
const inner = alertModal.querySelector('.enterprise-modal');
if (inner) inner.classList.remove('show');
setTimeout(() => alertModal.classList.remove('show'), inner ? 200 : 0);
}
}
// Alert write action tokens, minted by GET /api/settings/alert (and
// re-minted by every write response). createAlert is multi-use;
// deleteAlert_ is one-time and bound to that exact alert.
let alertActionTokens = {};
function loadAlerts() {
if (!alertsList) return;
alertsList.innerHTML = 'Loading...
';
fetch('/api/settings/alert', { cache: 'no-store' })
.then(res => res.json())
.then(data => {
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (data.actionTokens) alertActionTokens = data.actionTokens;
const alerts = Array.isArray(data.alerts) ? data.alerts : [];
if (alerts.length === 0) {
alertsList.innerHTML = 'No alerts found.
';
return;
}
alertsList.innerHTML = '';
alerts.sort((a, b) => new Date(b.date || 0) - new Date(a.date || 0));
alerts.forEach(alert => {
const row = document.createElement('div');
row.style.background = 'rgba(255,255,255,0.03)';
row.style.padding = '10px';
row.style.borderRadius = '8px';
row.style.display = 'flex';
row.style.justifyContent = 'space-between';
row.style.alignItems = 'center';
const info = document.createElement('div');
const startDateStr = formatAlertDate(alert.date);
const endDateStr = alert.neverEnds ? 'Until removed' : formatAlertDate(alert.endDate);
const statusMeta = getAlertStatusMeta(alert);
// Build with DOM APIs + textContent: alert.message is admin-authored
// but must never be treated as markup (stored-XSS pivot admin->admin).
const titleLine = document.createElement('div');
titleLine.style.cssText = 'font-weight:600; font-size:14px; color:#fff;';
titleLine.append(startDateStr + ' ');
const statusBadge = document.createElement('span');
statusBadge.setAttribute('style', statusMeta.style);
statusBadge.textContent = statusMeta.label;
titleLine.appendChild(statusBadge);
const endLine = document.createElement('div');
endLine.style.cssText = 'font-size:12px; color:#7f8aa3; margin-top:4px;';
endLine.textContent = `Ends: ${endDateStr}`;
const messageLine = document.createElement('div');
messageLine.style.cssText = 'font-size:13px; color:#aaa; margin-top:6px;';
messageLine.textContent = alert.message;
info.append(titleLine, endLine, messageLine);
const delBtn = document.createElement('button');
delBtn.className = 'btn ghost';
delBtn.innerHTML = ' ';
delBtn.style.padding = '6px 10px';
delBtn.style.color = '#ff6b6b';
delBtn.style.borderColor = 'rgba(255,107,107,0.2)';
delBtn.onclick = () => deleteAlert(alert.id);
row.appendChild(info);
row.appendChild(delBtn);
alertsList.appendChild(row);
});
})
.catch(err => {
console.error(err);
alertsList.innerHTML = 'Failed to load alerts
';
});
}
async function sendAlertCreateWithGuards(body) {
if (!alertActionTokens.createAlert) {
await loadAlerts();
}
if (!alertActionTokens.createAlert) {
return { ok: false, error: 'Alert settings not ready. Please try again.' };
}
const requestCopy = () => ({
headers: { 'x-action-token': alertActionTokens.createAlert || '' },
subtitle: 'Verify your identity to publish an alert',
reason: 'Global alerts are shown to every user, including on the pre-auth login page. Confirm your credentials to continue.',
confirmText: 'Confirm & Continue',
cancelledMessage: 'Alert cancelled — nothing was published.',
});
let result = await sendGuardedRequestWithStepUp('/api/settings/alert', 'POST', body, requestCopy());
if (result.data?.actionTokens) alertActionTokens = result.data.actionTokens;
const tokenRejected = result.res.status === 403 && /action token/i.test(String(result.data?.error || ''));
if (tokenRejected) {
await loadAlerts();
if (!alertActionTokens.createAlert) {
return { ok: false, error: 'Action token expired. Please refresh the page.' };
}
result = await sendGuardedRequestWithStepUp('/api/settings/alert', 'POST', body, requestCopy());
if (result.data?.actionTokens) alertActionTokens = result.data.actionTokens;
}
return result.data;
}
async function sendAlertDeleteWithGuards(id) {
const tokenKey = `deleteAlert_${id}`;
if (!alertActionTokens[tokenKey]) {
await loadAlerts();
}
if (!alertActionTokens[tokenKey]) {
return { ok: false, error: 'Action token expired. Please reload the alert list.' };
}
const copy = {
headers: { 'x-action-token': alertActionTokens[tokenKey] || '' },
subtitle: 'Verify your identity to delete the alert',
reason: 'Global alerts are shown to every user, including on the pre-auth login page. Confirm your credentials to continue.',
confirmText: 'Confirm & Continue',
cancelledMessage: 'Alert deletion cancelled — nothing was removed.',
// Delete tokens are one-time and consumed before the server's step-up
// check, so a challenge response carries a freshly minted replacement
// for THIS id — stash it and ride it on the in-modal retry.
onStepUpChallenge: (data) => {
const fresh = data?.actionTokens?.[tokenKey];
if (fresh) {
alertActionTokens[tokenKey] = fresh;
copy.headers['x-action-token'] = fresh;
}
},
};
let result = await sendGuardedRequestWithStepUp(`/api/settings/alert/${encodeURIComponent(id)}`, 'DELETE', {}, copy);
if (result.data?.actionTokens) alertActionTokens = result.data.actionTokens;
const tokenRejected = result.res.status === 403 && /action token/i.test(String(result.data?.error || ''));
if (tokenRejected) {
await loadAlerts();
if (!alertActionTokens[tokenKey]) {
return { ok: false, error: 'Action token expired. Please reload the alert list.' };
}
copy.headers['x-action-token'] = alertActionTokens[tokenKey];
result = await sendGuardedRequestWithStepUp(`/api/settings/alert/${encodeURIComponent(id)}`, 'DELETE', {}, copy);
if (result.data?.actionTokens) alertActionTokens = result.data.actionTokens;
}
return result.data;
}
async function deleteAlert(id) {
if (!confirm('Delete this alert?')) return;
try {
const data = await sendAlertDeleteWithGuards(id);
if (data && data.ok) {
loadAlerts();
} else {
alert('Failed: ' + (data?.error || 'Unknown'));
}
} catch (err) {
if (/cancel/i.test(String(err?.message || ''))) return;
alert('Error: ' + err);
}
}
openAlertModalBtn.addEventListener('click', (e) => {
e.preventDefault();
toggleAlertModal(true);
});
if (closeAlertModal) {
closeAlertModal.addEventListener('click', () => toggleAlertModal(false));
}
if (closeAlertModalFooter) {
closeAlertModalFooter.addEventListener('click', () => toggleAlertModal(false));
}
window.addEventListener('click', (e) => {
if (e.target === alertModal) toggleAlertModal(false);
});
if (alertNeverEnds) {
alertNeverEnds.addEventListener('change', syncAlertEndDateState);
syncAlertEndDateState();
}
if (alertDate && alertEndDate) {
alertDate.addEventListener('change', () => {
alertEndDate.min = alertDate.value || '';
if (alertEndDate.value && alertDate.value && alertEndDate.value < alertDate.value) {
alertEndDate.value = '';
}
});
}
if (addAlertBtn) {
addAlertBtn.addEventListener('click', async () => {
const message = alertContent.value.trim();
const dateStr = alertDate.value;
const endDateStr = alertEndDate?.value || '';
const keepActive = !!alertNeverEnds?.checked;
if (!message) {
alert('Please enter a message');
return;
}
const startDate = parseLocalDateTimeInput(dateStr);
if (!startDate) {
alert('Please select a complete date and time.');
return;
}
let isoEndDate = null;
if (!keepActive) {
const endDate = parseLocalDateTimeInput(endDateStr);
if (!endDate) {
alert('Please select an end date.');
return;
}
if (endDate.getTime() <= startDate.getTime()) {
alert('End date must be after start date.');
return;
}
isoEndDate = endDate.toISOString();
}
try {
const data = await sendAlertCreateWithGuards({
message,
date: startDate.toISOString(),
endDate: isoEndDate,
neverEnds: keepActive
});
if (data && data.ok) {
alertContent.value = '';
alertDate.value = '';
if (alertEndDate) alertEndDate.value = '';
if (alertNeverEnds) alertNeverEnds.checked = true;
syncAlertEndDateState();
loadAlerts();
} else if (data && /cancel/i.test(String(data.error || ''))) {
// Cancelled challenge — the modal already said nothing was published.
} else {
alert('Failed: ' + (data?.error || 'Unknown'));
}
} catch (err) {
if (/cancel/i.test(String(err?.message || ''))) return;
alert('Error: ' + err);
}
});
}
}
let webhooksConfig = { mode: 'single', single: null, multiple: {}, fallbackToSingle: true };
let webhookCategories = [];
let webhookEditCategory = null;
let webhookActionTokens = {};
// adpanel:settings-token-registry — every webhook flow reassigns this
// binding from its responses, so the refresher writes through a live view.
registerSettingsActionTokenRegistry(createSettingsActionTokenView(() => webhookActionTokens));
const webhookModeSingle = document.getElementById('webhookModeSingle');
const webhookModeMultiple = document.getElementById('webhookModeMultiple');
const webhookModeMultipleDesc = document.getElementById('webhookModeMultipleDesc');
const webhookSingleSection = document.getElementById('webhookSingleSection');
const webhookMultipleSection = document.getElementById('webhookMultipleSection');
const webhookSingleList = document.getElementById('webhookSingleList');
const webhookSingleEmpty = document.getElementById('webhookSingleEmpty');
const webhookCategoriesGrid = document.getElementById('webhookCategoriesGrid');
const webhookFallbackNote = document.getElementById('webhookFallbackNote');
const webhookFallbackText = document.getElementById('webhookFallbackText');
const webhookFallbackToggle = document.getElementById('webhookFallbackToggle');
const webhookDormantCategoriesNote = document.getElementById('webhookDormantCategoriesNote');
const webhookDormantCategoriesText = document.getElementById('webhookDormantCategoriesText');
const openAddWebhookBtn = document.getElementById('openAddWebhookBtn');
const webhookModalOverlay = document.getElementById('webhookModalOverlay');
const webhookModalClose = document.getElementById('webhookModalClose');
const webhookModalCancel = document.getElementById('webhookModalCancel');
const webhookModalSave = document.getElementById('webhookModalSave');
const webhookModalTitle = document.getElementById('webhookModalTitle');
const webhookModalSubtitle = document.getElementById('webhookModalSubtitle');
const webhookUrlInput = document.getElementById('webhookUrlInput');
const webhookCredentialInput = document.getElementById('webhookCredentialInput');
const webhookCredentialLabel = document.getElementById('webhookCredentialLabel');
const webhookCredentialHint = document.getElementById('webhookCredentialHint');
const webhookModalError = document.getElementById('webhookModalError');
const webhookModeIndicator = document.getElementById('webhookModeIndicator');
const webhookCategoryLabel = document.getElementById('webhookCategoryLabel');
const webhookDeleteOverlay = document.getElementById('webhookDeleteOverlay');
const webhookDeleteClose = document.getElementById('webhookDeleteClose');
const webhookDeleteCancelBtn = document.getElementById('webhookDeleteCancelBtn');
const webhookDeleteConfirmBtn = document.getElementById('webhookDeleteConfirmBtn');
const webhookDeleteText = document.getElementById('webhookDeleteText');
const webhookDeleteCredentialInput = document.getElementById('webhookDeleteCredentialInput');
const webhookDeleteCredentialLabel = document.getElementById('webhookDeleteCredentialLabel');
const webhookDeleteCredentialHint = document.getElementById('webhookDeleteCredentialHint');
const webhookDeleteError = document.getElementById('webhookDeleteError');
let pendingDeleteCategory = null;
function toggleWebhookModal(show, options = {}) {
if (!webhookModalOverlay) return;
const resetInput = options.resetInput !== false;
const innerModal = webhookModalOverlay.querySelector('.enterprise-modal');
webhookModalOverlay.setAttribute('aria-hidden', show ? 'false' : 'true');
if (show) {
webhookModalOverlay.classList.add('show');
if (innerModal) {
innerModal.style.animation = 'none';
innerModal.offsetHeight;
innerModal.style.animation = '';
setTimeout(() => innerModal.classList.add('show'), 10);
}
if (webhookModalError) {
webhookModalError.textContent = '';
webhookModalError.style.display = 'none';
}
if (webhookUrlInput && resetInput) webhookUrlInput.value = '';
configureStepUpCredentialField(webhookCredentialInput, webhookCredentialLabel, webhookCredentialHint);
bindStepUpCredentialInput(webhookCredentialInput);
if (webhookCredentialInput) webhookCredentialInput.value = '';
setTimeout(() => webhookUrlInput && webhookUrlInput.focus(), 100);
} else {
if (innerModal) innerModal.classList.remove('show');
setTimeout(() => webhookModalOverlay.classList.remove('show'), 200);
}
}
function toggleWebhookDeleteModal(show) {
if (!webhookDeleteOverlay) return;
const innerModal = webhookDeleteOverlay.querySelector('.enterprise-modal');
webhookDeleteOverlay.setAttribute('aria-hidden', show ? 'false' : 'true');
if (show) {
webhookDeleteOverlay.classList.add('show');
configureStepUpCredentialField(webhookDeleteCredentialInput, webhookDeleteCredentialLabel, webhookDeleteCredentialHint);
bindStepUpCredentialInput(webhookDeleteCredentialInput);
if (webhookDeleteCredentialInput) webhookDeleteCredentialInput.value = '';
if (webhookDeleteError) {
webhookDeleteError.textContent = '';
webhookDeleteError.style.display = 'none';
}
if (innerModal) {
innerModal.style.animation = 'none';
innerModal.offsetHeight;
innerModal.style.animation = '';
setTimeout(() => innerModal.classList.add('show'), 10);
}
setTimeout(() => {
if (isStepUpGraceActive()) webhookDeleteConfirmBtn?.focus();
else webhookDeleteCredentialInput?.focus();
}, 100);
} else {
if (innerModal) innerModal.classList.remove('show');
setTimeout(() => webhookDeleteOverlay.classList.remove('show'), 200);
}
}
async function loadWebhooks() {
try {
const res = await fetch('/api/settings/webhooks', { cache: 'no-store' });
const data = await res.json();
if (data.ok) {
webhooksConfig = data.config || { mode: 'single', single: null, multiple: {}, fallbackToSingle: true };
webhookCategories = data.categories || [];
webhookActionTokens = data.actionTokens || {};
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
renderWebhooks();
}
} catch (e) {
console.error('[webhooks] Load error:', e);
}
}
window._loadWebhooks = loadWebhooks;
// Delete tokens are one-time and pinned to their exact target: the server
// mints deleteWebhook_single plus one deleteWebhook_ per
// category, so a token can only ever delete the target it was minted for.
// Pass null/undefined for the all-events (single) webhook.
function getWebhookDeleteToken(targetCategory) {
const key = targetCategory ? `deleteWebhook_${targetCategory}` : 'deleteWebhook_single';
return String(webhookActionTokens[key] || '').trim();
}
const webhooksPanel = document.getElementById('webhooks');
if (webhooksPanel && webhooksPanel.classList.contains('active')) {
loadWebhooks();
}
function renderWebhooks() {
if (!webhookModeSingle) return;
const fallbackEnabled = webhooksConfig.fallbackToSingle !== false;
if (webhookModeMultipleDesc) {
webhookModeMultipleDesc.textContent = fallbackEnabled
? 'Per category · falls back to single'
: 'Per category · strict isolation';
}
if (webhooksConfig.mode === 'single') {
webhookModeSingle.classList.add('active');
webhookModeMultiple.classList.remove('active');
if (webhookSingleSection) webhookSingleSection.style.display = '';
if (webhookMultipleSection) webhookMultipleSection.style.display = 'none';
} else {
webhookModeSingle.classList.remove('active');
webhookModeMultiple.classList.add('active');
if (webhookSingleSection) webhookSingleSection.style.display = 'none';
if (webhookMultipleSection) webhookMultipleSection.style.display = '';
}
// P4.2: category webhooks are only dispatched in "multiple" mode. When the
// mode is "single", configured category webhooks sit dormant — surface
// that state here instead of leaving a saved webhook silently inactive.
if (webhookDormantCategoriesNote) {
const dormantCount = webhooksConfig.mode === 'single'
? Object.keys(webhooksConfig.multipleConfigured || {}).length
: 0;
if (dormantCount > 0) {
if (webhookDormantCategoriesText) {
webhookDormantCategoriesText.textContent = dormantCount === 1
? '1 category webhook is saved but inactive while the mode is "Single". Switch to "Multiple Webhooks" to activate it.'
: `${dormantCount} category webhooks are saved but inactive while the mode is "Single". Switch to "Multiple Webhooks" to activate them.`;
}
webhookDormantCategoriesNote.style.display = 'flex';
} else {
webhookDormantCategoriesNote.style.display = 'none';
}
}
if (webhookFallbackNote) {
webhookFallbackNote.style.display = webhooksConfig.mode === 'multiple' ? 'flex' : 'none';
if (webhookFallbackText) {
webhookFallbackText.textContent = fallbackEnabled
? 'Categories without their own webhook are also sent to the single webhook (when configured).'
: 'Categories without their own webhook are not sent anywhere — strict per-category isolation is active.';
}
if (webhookFallbackToggle) {
webhookFallbackToggle.textContent = fallbackEnabled ? 'Disable fallback' : 'Enable fallback';
}
}
const singleConfigured = !!(webhooksConfig.singleConfigured || webhooksConfig.single);
if (singleConfigured) {
if (webhookSingleEmpty) webhookSingleEmpty.style.display = 'none';
if (webhookSingleList) webhookSingleList.innerHTML = renderWebhookItem('All Events', webhooksConfig.single);
} else {
if (webhookSingleEmpty) webhookSingleEmpty.style.display = 'flex';
if (webhookSingleList) webhookSingleList.innerHTML = '';
}
if (webhookCategoriesGrid) {
webhookCategoriesGrid.innerHTML = webhookCategories.map(cat => {
const maskedUrl = webhooksConfig.multiple && webhooksConfig.multiple[cat.id];
const isConfigured = !!(webhooksConfig.multipleConfigured && webhooksConfig.multipleConfigured[cat.id]);
const hasUrl = isConfigured || !!maskedUrl;
const safeColor = /^#[0-9a-fA-F]{3,8}$/.test(cat.color) ? cat.color : '#888';
const safeIcon = /^[a-zA-Z0-9\- ]+$/.test(cat.icon) ? cat.icon : 'fa-solid fa-circle';
return `
${escapeHtml(cat.label)}
${hasUrl ? escapeHtml(maskedUrl || 'Configured') : 'Not configured'}
${hasUrl ? 'Active ' : 'Inactive '}
${hasUrl ? `
` : ''}
${hasUrl ? 'Edit' : 'Set'}
`;
}).join('');
}
}
function renderWebhookItem(label, maskedUrl) {
return `
${escapeHtml(label)}
${escapeHtml(maskedUrl || 'Configured')}
`;
}
if (webhookModeSingle) {
webhookModeSingle.addEventListener('click', async () => {
if (webhooksConfig.mode === 'single') return;
try {
const data = await sendWebhookSaveWithGuards({ mode: 'single' });
if (data.ok) {
webhooksConfig.mode = 'single';
if (data.warning) showWebhookToast(data.warning, 'error');
renderWebhooks();
loadWebhooks();
} else {
showWebhookToast(data.error || 'Failed to change mode', 'error');
}
} catch (e) {
if (/cancel/i.test(String(e?.message || ''))) return;
console.error(e);
showWebhookToast('Network error', 'error');
}
});
}
if (webhookModeMultiple) {
webhookModeMultiple.addEventListener('click', async () => {
if (webhooksConfig.mode === 'multiple') return;
try {
const data = await sendWebhookSaveWithGuards({ mode: 'multiple' });
if (data.ok) {
webhooksConfig.mode = 'multiple';
if (data.warning) showWebhookToast(data.warning, 'error');
renderWebhooks();
loadWebhooks();
} else {
showWebhookToast(data.error || 'Failed to change mode', 'error');
}
} catch (e) {
if (/cancel/i.test(String(e?.message || ''))) return;
console.error(e);
showWebhookToast('Network error', 'error');
}
});
}
if (webhookFallbackToggle) {
webhookFallbackToggle.addEventListener('click', async () => {
const next = webhooksConfig.fallbackToSingle === false;
webhookFallbackToggle.disabled = true;
try {
const data = await sendWebhookSaveWithGuards({ fallbackToSingle: next });
if (data.ok) {
webhooksConfig.fallbackToSingle = data.config ? data.config.fallbackToSingle !== false : next;
renderWebhooks();
loadWebhooks();
} else {
showWebhookToast(data.error || 'Failed to update fallback', 'error');
}
} catch (e) {
if (/cancel/i.test(String(e?.message || ''))) return;
console.error(e);
showWebhookToast('Network error', 'error');
}
finally { webhookFallbackToggle.disabled = false; }
});
}
if (openAddWebhookBtn) {
openAddWebhookBtn.addEventListener('click', () => {
if (!webhookActionTokens.saveWebhook) loadWebhooks();
webhookEditCategory = null;
if (webhookModalTitle) webhookModalTitle.textContent = 'Add Single Webhook';
if (webhookModalSubtitle) webhookModalSubtitle.textContent = 'Enter a Discord webhook URL for all log categories';
if (webhookModeIndicator) webhookModeIndicator.style.display = 'none';
toggleWebhookModal(true, { resetInput: true });
});
}
if (webhookSingleList) {
webhookSingleList.addEventListener('click', (e) => {
const btn = e.target.closest('button[data-webhook-action]');
if (!btn || !webhookSingleList.contains(btn)) return;
const action = btn.getAttribute('data-webhook-action');
if (action === 'test-single') testWebhookSingle();
else if (action === 'edit-single') openEditWebhookSingle();
else if (action === 'delete-single') confirmDeleteWebhookSingle();
});
}
if (webhookCategoriesGrid) {
webhookCategoriesGrid.addEventListener('click', (e) => {
const btn = e.target.closest('button[data-webhook-action]');
if (!btn || !webhookCategoriesGrid.contains(btn)) return;
const action = btn.getAttribute('data-webhook-action');
const categoryId = btn.getAttribute('data-webhook-category');
if (!categoryId) return;
if (action === 'edit-category') openWebhookCategoryModal(categoryId);
else if (action === 'delete-category') deleteWebhookCategory(categoryId);
else if (action === 'test-category') testWebhookCategory(categoryId);
});
}
if (webhookModalClose) webhookModalClose.addEventListener('click', () => toggleWebhookModal(false));
if (webhookModalCancel) webhookModalCancel.addEventListener('click', () => toggleWebhookModal(false));
if (webhookModalOverlay) webhookModalOverlay.addEventListener('click', (e) => { if (e.target === webhookModalOverlay) toggleWebhookModal(false); });
if (webhookModalSave) {
webhookModalSave.addEventListener('click', async () => {
const url = (webhookUrlInput.value || '').trim();
if (!url) {
webhookModalError.textContent = 'Please enter a webhook URL';
webhookModalError.style.display = 'block';
return;
}
if (!/^https:\/\/(?:discord|discordapp)\.com\/api\/webhooks\/\d+\/[\w-]+$/.test(url)) {
webhookModalError.textContent = 'Invalid Discord webhook URL format';
webhookModalError.style.display = 'block';
return;
}
configureStepUpCredentialField(webhookCredentialInput, webhookCredentialLabel, webhookCredentialHint);
const credential = validateStepUpCredential(webhookCredentialInput, (message) => {
webhookModalError.textContent = message || '';
webhookModalError.style.display = message ? 'block' : 'none';
});
if (!credential) return;
if (!webhookActionTokens.saveWebhook) {
await loadWebhooks();
}
if (!webhookActionTokens.saveWebhook) {
webhookModalError.textContent = 'Action token expired. Please refresh the page.';
webhookModalError.style.display = 'block';
return;
}
webhookModalSave.disabled = true;
webhookModalSave.innerHTML = ' Saving...';
try {
const body = { url, mode: webhookEditCategory ? 'multiple' : 'single' };
if (webhookEditCategory) body.category = webhookEditCategory;
appendStepUpCredentialPayload(body, credential);
const requestCopy = () => ({
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-action-token': webhookActionTokens.saveWebhook || '' },
body: JSON.stringify(body)
});
let res = await fetch('/api/settings/webhooks', requestCopy());
let data = await res.json();
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (data.actionTokens) webhookActionTokens = data.actionTokens;
// Exactly one token refresh+retry when the 403 is a token rejection
// (a token older than its 300s TTL — the admin lingered on the page)
// rather than a step-up challenge: the server verifies the action token
// before the step-up credential, so the typed credential was never
// consumed and the same body is safe to resend. Same contract as the
// delete flow above and sendWebhookSaveWithGuards below.
const tokenRejected = res.status === 403 && /action token/i.test(String(data?.error || ''));
if (tokenRejected) {
await loadWebhooks();
if (webhookActionTokens.saveWebhook) {
res = await fetch('/api/settings/webhooks', requestCopy());
data = await res.json();
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (data.actionTokens) webhookActionTokens = data.actionTokens;
}
}
if (data.ok) {
toggleWebhookModal(false);
loadWebhooks();
} else {
webhookModalError.textContent = data.error || 'Failed to save';
webhookModalError.style.display = 'block';
}
} catch (e) {
webhookModalError.textContent = 'Network error';
webhookModalError.style.display = 'block';
} finally {
webhookModalSave.disabled = false;
webhookModalSave.innerHTML = ' Save Webhook';
}
});
}
if (webhookDeleteClose) webhookDeleteClose.addEventListener('click', () => toggleWebhookDeleteModal(false));
if (webhookDeleteCancelBtn) webhookDeleteCancelBtn.addEventListener('click', () => toggleWebhookDeleteModal(false));
if (webhookDeleteOverlay) webhookDeleteOverlay.addEventListener('click', (e) => { if (e.target === webhookDeleteOverlay) toggleWebhookDeleteModal(false); });
if (webhookDeleteConfirmBtn) {
webhookDeleteConfirmBtn.addEventListener('click', async () => {
configureStepUpCredentialField(webhookDeleteCredentialInput, webhookDeleteCredentialLabel, webhookDeleteCredentialHint);
const credential = validateStepUpCredential(webhookDeleteCredentialInput, (message) => {
if (!webhookDeleteError) return;
webhookDeleteError.textContent = message || '';
webhookDeleteError.style.display = message ? 'block' : 'none';
});
if (!credential) return;
// One-time delete tokens are pinned to the exact delete target, so each
// attempt needs the token minted for pendingDeleteCategory ("single"
// when removing the all-events webhook). A consumed token (burned by a
// rejected attempt) recovers via the refresh+retry below.
let deleteToken = getWebhookDeleteToken(pendingDeleteCategory);
if (!deleteToken) {
await loadWebhooks();
deleteToken = getWebhookDeleteToken(pendingDeleteCategory);
}
if (!deleteToken) {
if (webhookDeleteError) {
webhookDeleteError.textContent = 'Action token expired. Please refresh the page.';
webhookDeleteError.style.display = 'block';
}
return;
}
webhookDeleteConfirmBtn.disabled = true;
webhookDeleteConfirmBtn.innerHTML = ' Deleting...';
let deleted = false;
try {
const body = {};
if (pendingDeleteCategory) body.category = pendingDeleteCategory;
appendStepUpCredentialPayload(body, credential);
const requestCopy = () => ({
method: 'DELETE',
headers: { 'Content-Type': 'application/json', 'x-action-token': deleteToken },
body: JSON.stringify(body)
});
let res = await fetch('/api/settings/webhooks', requestCopy());
let data = await res.json();
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (data.actionTokens) webhookActionTokens = data.actionTokens;
// Exactly one token refresh+retry when the 403 is a token rejection
// (a one-time token already burned, or a stale settings load) rather
// than a step-up challenge — the same contract as
// sendWebhookTestWithGuards below.
const tokenRejected = res.status === 403 && /action token/i.test(String(data?.error || ''));
if (tokenRejected) {
await loadWebhooks();
const freshToken = getWebhookDeleteToken(pendingDeleteCategory);
if (freshToken) {
deleteToken = freshToken;
res = await fetch('/api/settings/webhooks', requestCopy());
data = await res.json();
if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity);
if (data.actionTokens) webhookActionTokens = data.actionTokens;
}
}
if (data.ok) {
deleted = true;
toggleWebhookDeleteModal(false);
loadWebhooks();
} else if (webhookDeleteError) {
webhookDeleteError.textContent = data.error || 'Failed to delete';
webhookDeleteError.style.display = 'block';
}
} catch (e) {
console.error(e);
if (webhookDeleteError) {
webhookDeleteError.textContent = 'Network error';
webhookDeleteError.style.display = 'block';
}
}
finally {
webhookDeleteConfirmBtn.disabled = false;
webhookDeleteConfirmBtn.innerHTML = ' Delete';
if (deleted) pendingDeleteCategory = null;
}
});
}
function openEditWebhookSingle() {
if (!webhookActionTokens.saveWebhook) loadWebhooks();
webhookEditCategory = null;
if (webhookModalTitle) webhookModalTitle.textContent = 'Replace Webhook';
if (webhookModalSubtitle) webhookModalSubtitle.textContent = 'Enter a new Discord webhook URL to replace the current one';
if (webhookModeIndicator) webhookModeIndicator.style.display = 'none';
toggleWebhookModal(true, { resetInput: true });
}
function confirmDeleteWebhookSingle() {
if (!getWebhookDeleteToken(null)) loadWebhooks();
pendingDeleteCategory = null;
if (webhookDeleteText) webhookDeleteText.textContent = 'Are you sure you want to remove the webhook? It will stop receiving all panel activity logs.';
toggleWebhookDeleteModal(true);
}
// Every webhook config write (URL, mode switch, fallback toggle) shares the
// server-side protection model: a session alone is not trusted, because
// re-routing dispatch — and in strict isolation, stopping it — is audit
// suppression. sendGuardedRequestWithStepUp owns the credential
// challenge/retry (the first attempt carries no credential, so a live grace
// grant authorizes it silently); this wrapper adds the saveWebhook
// action-token header and performs exactly one token refresh+retry when the
// 403 is a token rejection (stale settings load) rather than a step-up
// challenge. Returns the response payload; throws when the admin cancels
// the step-up modal — nothing was sent.
async function sendWebhookSaveWithGuards(body) {
if (!webhookActionTokens.saveWebhook) {
await loadWebhooks();
}
if (!webhookActionTokens.saveWebhook) {
return { ok: false, error: 'Webhook settings not ready. Please try again.' };
}
const requestCopy = () => ({
headers: { 'x-action-token': webhookActionTokens.saveWebhook || '' },
subtitle: 'Verify your identity to change webhook settings',
reason: 'Webhook routing decides where panel activity logs are delivered. Confirm your credentials to continue.',
confirmText: 'Confirm & Continue',
cancelledMessage: 'Webhook change cancelled — nothing was modified.',
});
let result = await sendGuardedRequestWithStepUp('/api/settings/webhooks', 'POST', body, requestCopy());
if (result.data?.actionTokens) webhookActionTokens = result.data.actionTokens;
const tokenRejected = result.res.status === 403 && /action token/i.test(String(result.data?.error || ''));
if (tokenRejected) {
await loadWebhooks();
if (!webhookActionTokens.saveWebhook) {
return { ok: false, error: 'Action token expired. Please refresh the page.' };
}
result = await sendGuardedRequestWithStepUp('/api/settings/webhooks', 'POST', body, requestCopy());
if (result.data?.actionTokens) webhookActionTokens = result.data.actionTokens;
}
return result.data;
}
// The test endpoint requires the same action token + step-up credential as
// every other webhook write. sendGuardedRequestWithStepUp owns the credential
// challenge/retry (the first attempt carries no credential, so a live grace
// grant authorizes it silently); this wrapper adds the token header and
// performs exactly one token refresh+retry when the 403 is a token rejection
// (stale settings load) rather than a step-up challenge. Returns the response
// payload, or null when the admin cancelled the step-up modal — nothing was
// sent.
async function sendWebhookTestWithGuards(body) {
if (!webhookActionTokens.testWebhook) {
await loadWebhooks();
}
if (!webhookActionTokens.testWebhook) {
return { ok: false, error: 'Webhook settings not ready. Please try again.' };
}
const requestCopy = () => ({
headers: { 'x-action-token': webhookActionTokens.testWebhook || '' },
subtitle: 'Verify your identity to send a webhook test',
reason: 'A webhook test sends a real message to your configured Discord webhook. Confirm your credentials to continue.',
confirmText: 'Confirm & Send Test',
cancelledMessage: 'Webhook test cancelled — no message was sent.',
});
let result = await sendGuardedRequestWithStepUp('/api/settings/webhooks/test', 'POST', body, requestCopy());
if (result.data?.actionTokens) webhookActionTokens = result.data.actionTokens;
const tokenRejected = result.res.status === 403 && /action token/i.test(String(result.data?.error || ''));
if (tokenRejected) {
await loadWebhooks();
if (!webhookActionTokens.testWebhook) {
return { ok: false, error: 'Action token expired. Please refresh the page.' };
}
result = await sendGuardedRequestWithStepUp('/api/settings/webhooks/test', 'POST', body, requestCopy());
if (result.data?.actionTokens) webhookActionTokens = result.data.actionTokens;
}
return result.data;
}
async function testWebhookSingle() {
try {
const data = await sendWebhookTestWithGuards({});
if (data) showWebhookToast(data.ok ? 'Test message sent!' : (data.error || 'Failed'), data.ok ? 'success' : 'error');
} catch (e) {
if (/cancel/i.test(String(e?.message || ''))) return;
showWebhookToast('Network error', 'error');
}
}
function openWebhookCategoryModal(catId) {
if (!webhookActionTokens.saveWebhook) loadWebhooks();
const cat = webhookCategories.find(c => c.id === catId);
if (!cat) return;
webhookEditCategory = catId;
const isConfigured = !!(webhooksConfig.multipleConfigured && webhooksConfig.multipleConfigured[catId]);
if (webhookModalTitle) webhookModalTitle.textContent = isConfigured ? 'Replace Webhook' : 'Set Webhook';
if (webhookModalSubtitle) webhookModalSubtitle.textContent = 'Webhook for: ' + cat.label;
if (webhookModeIndicator) webhookModeIndicator.style.display = 'block';
if (webhookCategoryLabel) webhookCategoryLabel.textContent = cat.label;
toggleWebhookModal(true, { resetInput: true });
}
function deleteWebhookCategory(catId) {
if (!getWebhookDeleteToken(catId)) loadWebhooks();
const cat = webhookCategories.find(c => c.id === catId);
pendingDeleteCategory = catId;
if (webhookDeleteText) webhookDeleteText.textContent = 'Remove the webhook for "' + (cat ? cat.label : catId) + '"?';
toggleWebhookDeleteModal(true);
}
async function testWebhookCategory(catId) {
try {
const data = await sendWebhookTestWithGuards({ category: catId });
if (data) showWebhookToast(data.ok ? 'Test message sent!' : (data.error || 'Failed'), data.ok ? 'success' : 'error');
} catch (e) {
if (/cancel/i.test(String(e?.message || ''))) return;
showWebhookToast('Network error', 'error');
}
}
window.openEditWebhookSingle = openEditWebhookSingle;
window.confirmDeleteWebhookSingle = confirmDeleteWebhookSingle;
window.testWebhookSingle = testWebhookSingle;
window.openWebhookCategoryModal = openWebhookCategoryModal;
window.deleteWebhookCategory = deleteWebhookCategory;
window.testWebhookCategory = testWebhookCategory;
function showWebhookToast(msg, type) {
const existing = document.querySelector('.webhook-toast');
if (existing) existing.remove();
const toast = document.createElement('div');
toast.className = 'webhook-toast';
toast.style.cssText = 'position:fixed;bottom:24px;right:24px;z-index:10001;padding:12px 20px;border-radius:10px;font-size:14px;font-weight:500;color:white;pointer-events:none;animation:fadeInUp 0.3s ease;' +
(type === 'success' ? 'background:rgba(34,197,94,0.9);' : 'background:rgba(239,68,68,0.9);');
toast.innerHTML = ' ' + escapeHtml(msg);
document.body.appendChild(toast);
setTimeout(() => { toast.style.opacity = '0'; toast.style.transition = 'opacity 0.3s'; setTimeout(() => toast.remove(), 300); }, 3000);
}
});
(function () {
let _panelInfoTokens = {};
// adpanel:settings-token-registry — registered for uniformity with the other
// section stores; the update flows reassign this binding from their
// responses, so the refresher writes through a live view.
registerSettingsActionTokenRegistry(createSettingsActionTokenView(() => _panelInfoTokens));
let _latestVersionFound = null;
let _cachedVersion = '';
let _cachedLastUpdate = '';
let _cachedArchitecture = '';
let _copyButtonsInitialized = false;
let panelInfoRequest = 0;
let panelInfoRendered = 0;
let panelInfoTokensReceived = 0;
let panelInfoPolling = false;
function clearPanelUpdateOffer() {
_latestVersionFound = null;
if (latestUpdateBox) latestUpdateBox.style.display = 'none';
if (upToDateTag) upToDateTag.style.display = 'none';
const statusEl = document.getElementById('panelUpdateStatus');
if (statusEl?.dataset.panelCheck) {
delete statusEl.dataset.panelCheck;
statusEl.textContent = '';
statusEl.style.display = 'none';
}
}
function initializePanelInfoCopyButtons() {
if (_copyButtonsInitialized) return;
const copyVersionBtn = document.getElementById('copyVersionBtn');
const copyLastUpdateBtn = document.getElementById('copyLastUpdateBtn');
const versionEl = document.getElementById('panelInfoVersion');
const lastUpdateEl = document.getElementById('panelInfoLastUpdate');
if (copyVersionBtn && versionEl) {
copyVersionBtn.addEventListener('click', () => {
const val = _cachedVersion || versionEl.textContent.trim();
if (!val || val === 'Loading...') return;
copyToClipboard(val).then(() => {
copyVersionBtn.classList.add('copied');
setTimeout(() => copyVersionBtn.classList.remove('copied'), 1500);
}).catch(() => {});
});
}
if (copyLastUpdateBtn && lastUpdateEl) {
copyLastUpdateBtn.addEventListener('click', () => {
const val = _cachedLastUpdate || lastUpdateEl.textContent.trim();
if (!val || val === 'Loading...') return;
copyToClipboard(val).then(() => {
copyLastUpdateBtn.classList.add('copied');
setTimeout(() => copyLastUpdateBtn.classList.remove('copied'), 1500);
}).catch(() => {});
});
}
_copyButtonsInitialized = true;
}
async function loadPanelInfo({ quiet = false, offer = _latestVersionFound } = {}) {
const versionEl = document.getElementById('panelInfoVersion');
const lastUpdateEl = document.getElementById('panelInfoLastUpdate');
const archEl = document.getElementById('panelInfoArchitecture');
const statusEl = document.getElementById('panelUpdateStatus');
const requestedRestart = statusEl?.dataset.panelRestart;
if (!versionEl && !lastUpdateEl) return;
if (!quiet) {
if (versionEl) versionEl.textContent = 'Loading...';
if (lastUpdateEl) lastUpdateEl.textContent = 'Loading...';
}
initializePanelInfoCopyButtons();
const requestId = ++panelInfoRequest;
try {
const statusUrl = `/api/settings/panel-info?status=1${offer ? `&offer=${encodeURIComponent(offer)}` : ''}`;
const res = await fetch(quiet ? statusUrl : '/api/settings/panel-info', {
credentials: 'include', signal: AbortSignal.timeout(8000),
});
if (!res.ok) {
if (!quiet && requestId > panelInfoRendered) {
if (versionEl) versionEl.textContent = 'Error';
if (lastUpdateEl) lastUpdateEl.textContent = 'Error';
}
return;
}
const data = await res.json();
if (!quiet && requestId > panelInfoTokensReceived) {
_panelInfoTokens = data.actionTokens || {};
panelInfoTokensReceived = requestId;
}
if (requestId < panelInfoRendered) return;
panelInfoRendered = requestId;
const previousVersion = _cachedVersion;
_cachedVersion = data.version || 'unknown';
_cachedLastUpdate = data.lastUpdate || 'unknown';
_cachedArchitecture = data.architecture || 'unknown';
if (versionEl) versionEl.textContent = _cachedVersion;
if (lastUpdateEl) lastUpdateEl.textContent = _cachedLastUpdate;
if (archEl) archEl.textContent = _cachedArchitecture;
renderAutoUpdateButton(!!data.autoUpdateEnabled);
if (data.updateBlocked || (previousVersion && previousVersion !== _cachedVersion) ||
(data.offerUnavailable && data.offeredVersion === _latestVersionFound)) clearPanelUpdateOffer();
const restartWarnEl = document.getElementById('panelRestartWarning');
if (restartWarnEl) {
let message = '';
let type = 'info';
if (data.updateError) {
message = data.updateError;
type = 'error';
} else if (data.recoveryPending) {
message = 'The panel is waiting to restore the previous version...';
} else if (data.restartPending) {
message = 'The panel is applying or verifying an update...';
} else if (data.restartRequired) {
message = 'This panel worker is still running the previous build. Restart the panel if this warning persists.';
}
if (restartWarnEl.textContent !== message) restartWarnEl.textContent = message;
restartWarnEl.className = `panelinfo-update-status ${type}`;
restartWarnEl.style.display = message ? '' : 'none';
if (requestedRestart && requestedRestart === statusEl.dataset.panelRestart &&
!data.restartPending && (!data.restartRequired || data.failedUpdate?.restored === false)) {
const verified = data.verifiedUpdate?.id === requestedRestart;
statusEl.textContent = verified ? `Update to ${data.verifiedUpdate.version} verified.` : '';
statusEl.className = 'panelinfo-update-status success';
statusEl.style.display = verified ? '' : 'none';
delete statusEl.dataset.panelRestart;
}
}
return data;
} catch (e) {
console.error('[panel-info] Failed to load:', e);
if (!quiet && requestId > panelInfoRendered) {
if (versionEl) versionEl.textContent = 'Error';
if (lastUpdateEl) lastUpdateEl.textContent = 'Error';
}
}
}
window.loadPanelInfo = loadPanelInfo;
const checkBtn = document.getElementById('checkForUpdatesBtn');
const autoUpdateBtn = document.getElementById('toggleAutoUpdateBtn');
const panelUpdateBtn = document.getElementById('panelUpdateBtn');
const upToDateTag = document.getElementById('panelUpToDateTag');
const latestUpdateBox = document.getElementById('latestUpdateBox');
const latestVersionEl = document.getElementById('panelInfoLatestVersion');
function renderAutoUpdateButton(enabled) {
if (!autoUpdateBtn) return;
autoUpdateBtn.dataset.enabled = enabled ? 'true' : 'false';
autoUpdateBtn.textContent = enabled ? 'On' : 'Off';
}
if (checkBtn) {
checkBtn.addEventListener('click', async () => {
const statusEl = document.getElementById('panelUpdateStatus');
clearPanelUpdateOffer();
checkBtn.disabled = true;
checkBtn.textContent = 'Checking...';
if (statusEl) {
delete statusEl.dataset.panelRestart;
statusEl.textContent = 'Checking for updates...';
statusEl.className = 'panelinfo-update-status info';
statusEl.style.display = '';
}
try {
const res = await fetch('/api/settings/panel-update/check', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-action-token': _panelInfoTokens.checkUpdate || '' },
credentials: 'include',
body: JSON.stringify({}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
if (statusEl) {
statusEl.textContent = data.error || 'Failed to check for updates';
statusEl.className = 'panelinfo-update-status error';
statusEl.style.display = '';
}
return;
}
if (data.updateDeferred) {
if (statusEl) {
statusEl.textContent = `Version ${data.latestVersion} was skipped after a failed update. Waiting for a newer release.`;
statusEl.className = 'panelinfo-update-status error';
statusEl.style.display = '';
}
await loadPanelInfo({ quiet: true });
return;
}
const current = await loadPanelInfo({ quiet: true, offer: data.updateAvailable ? data.latestVersion : null });
if (!current || current.updateBlocked || current.offerUnavailable || current.version !== data.currentVersion) {
if (statusEl) {
statusEl.textContent = current?.updateError || 'The update status changed. Check again.';
statusEl.className = 'panelinfo-update-status error';
statusEl.style.display = '';
}
return;
}
if (data.updateAvailable) {
_latestVersionFound = data.latestVersion;
if (data.actionTokens) _panelInfoTokens = { ..._panelInfoTokens, ...data.actionTokens };
if (latestUpdateBox) {
latestUpdateBox.style.display = 'flex';
const rawVer = String(data.latestVersion || '').trim();
const cleanVer = rawVer ? (rawVer.startsWith('v') ? rawVer : `v${rawVer}`) : 'v1.0.1';
if (latestVersionEl) latestVersionEl.textContent = cleanVer;
}
if (statusEl) {
statusEl.dataset.panelCheck = 'available';
statusEl.textContent = `New version available: ${data.latestVersion}`;
statusEl.className = 'panelinfo-update-status success';
statusEl.style.display = '';
}
} else {
if (upToDateTag) upToDateTag.style.display = 'inline-flex';
if (statusEl) {
statusEl.dataset.panelCheck = 'current';
statusEl.textContent = `You are running the latest version (${data.currentVersion || _cachedVersion})`;
statusEl.className = 'panelinfo-update-status success';
statusEl.style.display = '';
}
}
} catch (e) {
console.error('[panel-update] Check failed:', e);
if (statusEl) {
statusEl.textContent = 'Network error while checking for updates';
statusEl.className = 'panelinfo-update-status error';
statusEl.style.display = '';
}
} finally {
checkBtn.disabled = false;
checkBtn.textContent = 'Check';
}
});
}
if (panelUpdateBtn) {
panelUpdateBtn.addEventListener('click', async () => {
if (_latestVersionFound) {
await doInstall(_latestVersionFound, 'auto');
}
});
}
if (autoUpdateBtn) {
autoUpdateBtn.addEventListener('click', async () => {
const statusEl = document.getElementById('panelUpdateStatus');
const currentlyEnabled = autoUpdateBtn.dataset.enabled === 'true';
const nextEnabled = !currentlyEnabled;
autoUpdateBtn.disabled = true;
try {
if (!_panelInfoTokens.setAutoUpdate) {
await loadPanelInfo();
}
// Disabling auto-update freezes the panel on its current build, so the
// server requires step-up for that direction; the guarded flow shows
// the credential modal only when the server actually challenges.
const { res, data } = await sendGuardedRequestWithStepUp('/api/settings/panel-update/auto', 'POST', { enabled: nextEnabled }, {
headers: { 'x-action-token': _panelInfoTokens.setAutoUpdate || '' },
subtitle: 'Verify your identity to disable auto update',
reason: 'Disabling auto update stops the panel from receiving security patches automatically. Confirm your credentials to continue.',
confirmText: 'Verify & Disable',
cancelledMessage: 'Verification cancelled — auto update was not changed.',
});
if (!res.ok) {
if (statusEl) {
delete statusEl.dataset.panelCheck;
statusEl.textContent = data.error || 'Failed to toggle auto update';
statusEl.className = 'panelinfo-update-status error';
statusEl.style.display = '';
}
await loadPanelInfo({ quiet: true });
return;
}
renderAutoUpdateButton(!!data.autoUpdateEnabled);
} catch (e) {
console.error('[panel-auto-update] Toggle failed:', e);
if (statusEl) {
delete statusEl.dataset.panelCheck;
statusEl.textContent = (e && e.message) ? e.message : 'Network error while toggling auto update';
statusEl.className = 'panelinfo-update-status error';
statusEl.style.display = '';
}
} finally {
autoUpdateBtn.disabled = false;
}
});
}
async function doInstall(version, source) {
const statusEl = document.getElementById('panelUpdateStatus');
if (!version) return;
const cleanVersion = String(version).trim();
if (!confirm(`Install ${window.__brandName || 'ADPanel'} ${cleanVersion}? The panel will restart after installation.`)) {
return;
}
if (panelUpdateBtn) {
panelUpdateBtn.disabled = true;
panelUpdateBtn.textContent = 'Installing...';
}
if (statusEl) {
delete statusEl.dataset.panelCheck;
statusEl.textContent = 'Downloading and installing update...';
statusEl.className = 'panelinfo-update-status info';
statusEl.style.display = '';
}
try {
const current = await loadPanelInfo({ quiet: true, offer: cleanVersion });
if (!current || current.updateBlocked || current.offerUnavailable) {
clearPanelUpdateOffer();
throw new Error(current?.updateError || 'The update is no longer available. Check again.');
}
delete _panelInfoTokens.installUpdate;
await loadPanelInfo();
if (!_panelInfoTokens.installUpdate) throw new Error('Could not get a fresh update token. Try again.');
// Installing an update is step-up protected server-side: the action
// token only proves CSRF-cleanliness, so the request rides the shared
// guarded flow. The install token is one-time and is consumed by the
// very attempt that triggers the challenge, so onStepUpChallenge stashes
// the fresh token the server re-mints into the challenge response.
const headers = { 'x-action-token': _panelInfoTokens.installUpdate || '' };
const { res, data } = await sendGuardedRequestWithStepUp('/api/settings/panel-update/install', 'POST', { version: cleanVersion, checkedOffer: true }, {
headers,
onStepUpChallenge: (challenge) => {
const fresh = challenge?.actionTokens?.installUpdate;
if (fresh) {
_panelInfoTokens.installUpdate = fresh;
headers['x-action-token'] = fresh;
}
},
subtitle: 'Verify your identity to install this update',
reason: `Installing ${window.__brandName || 'ADPanel'} ${cleanVersion} replaces the panel's own code and restarts the service. Confirm your credentials to continue.`,
confirmText: 'Verify & Install',
cancelledMessage: 'Verification cancelled — the update was not installed.',
});
if (!res.ok) {
if (statusEl) {
statusEl.textContent = data.error || 'Failed to install update';
statusEl.className = 'panelinfo-update-status error';
statusEl.style.display = '';
}
_latestVersionFound = null;
if (latestUpdateBox) latestUpdateBox.style.display = 'none';
await loadPanelInfo({ quiet: true });
return;
}
_latestVersionFound = null;
if (latestUpdateBox) latestUpdateBox.style.display = 'none';
if (statusEl) {
statusEl.textContent = data.message || `Restarting to verify ${data.version || cleanVersion}...`;
statusEl.className = 'panelinfo-update-status info';
if (data.updateId) statusEl.dataset.panelRestart = data.updateId;
// The element ships with an inline `display: none` that beats the class
// rules; clear it so the class decides visibility.
statusEl.style.display = '';
}
setTimeout(() => {
loadPanelInfo({ quiet: true });
}, 3000);
} catch (e) {
console.error('[panel-update] Install failed:', e);
if (statusEl) {
statusEl.textContent = (e && e.message) ? e.message : 'Network error while installing update';
statusEl.className = 'panelinfo-update-status error';
statusEl.style.display = '';
}
} finally {
if (panelUpdateBtn) { panelUpdateBtn.disabled = false; panelUpdateBtn.textContent = 'Update'; }
}
}
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('panel') === 'panelinfo') {
loadPanelInfo();
}
if (checkBtn) {
setInterval(async () => {
if (panelInfoPolling || document.hidden || !document.getElementById('panelinfo')?.classList.contains('active')) return;
panelInfoPolling = true;
try { await loadPanelInfo({ quiet: true }); } finally { panelInfoPolling = false; }
}, 10000);
}
// Action tokens stashed by the section loaders expire after 5-10 minutes.
// Refresh them periodically (and whenever the tab becomes visible again) so
// actions never fail with "invalid or missing action token" after the page
// has been open a while. The refresh endpoint only mints tokens for the
// current admin session and never mints one-time tokens, so this adds no
// capability and step-up re-auth for destructive actions is unaffected.
let _settingsTokenRefreshAt = 0;
async function refreshSettingsActionTokens() {
const now = Date.now();
if (now - _settingsTokenRefreshAt < 3 * 60 * 1000) return;
_settingsTokenRefreshAt = now;
try {
const res = await fetch('/api/settings/action-tokens', { credentials: 'include' });
if (!res.ok) return;
const data = await res.json().catch(() => ({}));
const tokens = data.actionTokens;
if (!tokens || typeof tokens !== 'object') return;
// adpanel:settings-token-registry — every scope-local store is reachable
// ONLY through the registry (the owning IIFEs register live views of
// their reassigning bindings); referencing those names directly here was
// the pre-fix ReferenceError this loop exists to prevent.
for (const registry of settingsActionTokenRegistries) {
if (registry && typeof registry === 'object') Object.assign(registry, tokens);
}
if (accountsListEl) accountsListEl._actionTokens = { ...(accountsListEl._actionTokens || {}), ...tokens };
if (serversListEl) serversListEl._actionTokens = { ...(serversListEl._actionTokens || {}), ...tokens };
} catch (e) {
console.error('[settings] Action-token refresh failed:', e);
}
}
setInterval(refreshSettingsActionTokens, 3 * 60 * 1000);
document.addEventListener('visibilitychange', () => {
if (!document.hidden) {
_settingsTokenRefreshAt = 0;
refreshSettingsActionTokens();
}
});
refreshSettingsActionTokens();
})();
(function () {
const overlay = document.getElementById('nodeUpdateOverlay');
const modal = document.getElementById('nodeUpdateModal');
const openBtns = [
document.getElementById('openNodeUpdateBtn'),
document.getElementById('openNodeUpdateCardBtn')
].filter(Boolean);
const closeBtn = document.getElementById('nodeUpdateClose');
const cancelBtn = document.getElementById('nodeUpdateCancel');
const nodeSelect = document.getElementById('nodeUpdateSelect');
const versionEl = document.getElementById('nodeUpdateVersion');
const archEl = document.getElementById('nodeUpdateArchitecture');
const checkBtn = document.getElementById('checkNodeUpdatesBtn');
const autoBtn = document.getElementById('toggleNodeAutoUpdateBtn');
const manualBtn = document.getElementById('nodeManualInstallBtn');
const manualInput = document.getElementById('nodeManualVersionInput');
const statusEl = document.getElementById('nodeUpdateStatus');
if (!overlay || !modal) return;
let _tokens = {};
let _nodes = [];
let _selectedNodeId = '';
let _selectedNodeName = '';
let _latestVersionFound = null;
let _copyInitialized = false;
let _nodeUpdateInfoRequest = 0;
function setNodeStatus(message, type) {
if (!statusEl) return;
statusEl.textContent = message || '';
statusEl.className = `panelinfo-update-status ${type || ''}`.trim();
}
function setNodeStatusHtml(html, type) {
if (!statusEl) return;
statusEl.innerHTML = html || '';
statusEl.className = `panelinfo-update-status ${type || ''}`.trim();
}
function renderNodeAutoButton(enabled) {
if (!autoBtn) return;
autoBtn.dataset.enabled = enabled ? 'true' : 'false';
autoBtn.className = `btn btn-auto-update ${enabled ? 'enabled' : 'disabled'}`;
autoBtn.innerHTML = enabled
? ' Auto Update: On'
: ' Auto Update: Off';
}
function resetNodeCheckButton() {
if (!checkBtn) return;
checkBtn.dataset.mode = '';
checkBtn.className = 'btn btn-update-check';
checkBtn.innerHTML = ' Check for Updates';
checkBtn.disabled = false;
}
function initializeNodeCopyButtons() {
if (_copyInitialized) return;
const copyVersionBtn = document.getElementById('copyNodeVersionBtn');
const copyArchBtn = document.getElementById('copyNodeArchBtn');
if (copyVersionBtn && versionEl) {
copyVersionBtn.addEventListener('click', () => {
copyToClipboard(versionEl.textContent.trim()).then(() => {
const icon = copyVersionBtn.querySelector('i');
if (icon) {
icon.className = 'fa-solid fa-check';
setTimeout(() => { icon.className = 'fa-solid fa-copy'; }, 1500);
}
}).catch(() => {});
});
}
if (copyArchBtn && archEl) {
copyArchBtn.addEventListener('click', () => {
copyToClipboard(archEl.textContent.trim()).then(() => {
const icon = copyArchBtn.querySelector('i');
if (icon) {
icon.className = 'fa-solid fa-check';
setTimeout(() => { icon.className = 'fa-solid fa-copy'; }, 1500);
}
}).catch(() => {});
});
}
_copyInitialized = true;
}
function populateNodeSelect(nodes, selectedNode) {
if (!nodeSelect) return;
_nodes = Array.isArray(nodes) ? nodes : [];
if (!_nodes.length) {
nodeSelect.innerHTML = 'No nodes available ';
nodeSelect.disabled = true;
return;
}
nodeSelect.disabled = false;
const selectedId = selectedNode?.id || _selectedNodeId || _nodes[0].id;
nodeSelect.innerHTML = _nodes.map(node => {
const label = `${node.name || node.id} (${node.address || 'unknown'})`;
return `${escapeHtml(label)} `;
}).join('');
_selectedNodeId = String(selectedId || '');
const found = _nodes.find(node => String(node.id) === _selectedNodeId);
_selectedNodeName = found?.name || selectedNode?.name || _selectedNodeId;
}
async function loadNodeUpdateInfo(nodeId) {
const request = ++_nodeUpdateInfoRequest;
_tokens = {};
_latestVersionFound = null;
_selectedNodeId = String(nodeId || '');
_selectedNodeName = '';
initializeNodeCopyButtons();
if (versionEl) versionEl.innerHTML = 'Loading...';
if (archEl) archEl.innerHTML = 'Loading...';
resetNodeCheckButton();
if (nodeSelect && _nodes.length) nodeSelect.disabled = false;
if (checkBtn) checkBtn.disabled = true;
if (autoBtn) autoBtn.disabled = true;
if (manualBtn) manualBtn.disabled = true;
if (manualInput) manualInput.disabled = true;
try {
const params = new URLSearchParams();
if (nodeId) params.set('nodeId', nodeId);
const res = await fetch('/api/settings/node-update/info' + (params.toString() ? `?${params.toString()}` : ''), {
credentials: 'include',
});
const data = await res.json().catch(() => ({}));
if (request !== _nodeUpdateInfoRequest) return;
if (!res.ok) {
if (versionEl) versionEl.innerHTML = 'Error';
if (archEl) archEl.innerHTML = 'Error';
setNodeStatus(data.error || 'Failed to load node update information', 'error');
return;
}
populateNodeSelect(data.nodes || [], data.selectedNode);
_tokens = data.actionTokens || {};
if (data.selectedNode?.id) {
_selectedNodeId = String(data.selectedNode.id);
_selectedNodeName = data.selectedNode.name || _selectedNodeId;
}
if (versionEl) versionEl.innerHTML = `${escapeHtml(data.version || 'unknown')}`;
if (archEl) archEl.innerHTML = `${escapeHtml(data.architecture || 'unknown')}`;
renderNodeAutoButton(!!data.autoUpdateEnabled);
if (data.error) {
setNodeStatus(data.error, 'error');
} else if (data.updateApiAvailable === false) {
setNodeStatus('This node is online but does not expose the new update endpoint yet.', 'info');
} else {
setNodeStatus('', '');
}
} catch (e) {
if (request !== _nodeUpdateInfoRequest) return;
console.error('[node-update] Failed to load:', e);
if (versionEl) versionEl.innerHTML = 'Network error';
if (archEl) archEl.innerHTML = 'Network error';
setNodeStatus('Network error while loading node update information', 'error');
} finally {
if (request === _nodeUpdateInfoRequest) {
if (checkBtn) checkBtn.disabled = !_tokens.checkUpdate;
if (autoBtn) autoBtn.disabled = !_tokens.setAutoUpdate;
if (manualBtn) manualBtn.disabled = !_tokens.installUpdate;
if (manualInput) manualInput.disabled = !_tokens.installUpdate;
}
}
}
function showNodeUpdateModal(show, nodeId) {
if (show) {
overlay.classList.add('show');
modal.classList.add('show');
window.setTimeout(() => {
if (typeof syncModalBaseline === 'function') syncModalBaseline(overlay);
}, 0);
loadNodeUpdateInfo(nodeId || _selectedNodeId);
return;
}
_nodeUpdateInfoRequest++;
_tokens = {};
overlay.classList.remove('show');
modal.classList.remove('show');
if (typeof resetModalUnsavedState === 'function') resetModalUnsavedState(overlay);
}
window.openNodeUpdateModal = (nodeId) => showNodeUpdateModal(true, nodeId);
openBtns.forEach(btn => btn.addEventListener('click', () => showNodeUpdateModal(true)));
if (closeBtn) closeBtn.addEventListener('click', () => showNodeUpdateModal(false));
if (cancelBtn) cancelBtn.addEventListener('click', () => showNodeUpdateModal(false));
overlay.addEventListener('click', (e) => {
if (e.target === overlay) showNodeUpdateModal(false);
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && overlay.classList.contains('show')) showNodeUpdateModal(false);
});
if (nodeSelect) {
nodeSelect.addEventListener('change', () => {
_selectedNodeId = nodeSelect.value;
loadNodeUpdateInfo(_selectedNodeId);
});
}
async function doNodeInstall(version, source) {
if (!_selectedNodeId) {
setNodeStatus('Select a node first.', 'error');
return;
}
const cleanVersion = String(version || '').trim();
if (!/^v?\d+\.\d+\.\d+([\-+][A-Za-z0-9_.-]+)?$/.test(cleanVersion)) {
setNodeStatus('Invalid version format. Use format: v1.0.0', 'error');
return;
}
const targetId = _selectedNodeId;
const targetName = _selectedNodeName || targetId;
const request = _nodeUpdateInfoRequest;
if (!_tokens.installUpdate) {
await loadNodeUpdateInfo(targetId);
return;
}
if (!confirm(`Install ADaemon ${cleanVersion} on ${targetName}? The node will run go clean and restart adaemon.`)) {
return;
}
if (checkBtn) {
checkBtn.className = 'btn btn-update-installing';
checkBtn.innerHTML = ' Installing...';
checkBtn.disabled = true;
}
if (manualBtn) manualBtn.disabled = true;
if (manualInput) manualInput.disabled = true;
if (nodeSelect) nodeSelect.disabled = true;
setNodeStatus('Downloading update and sending it securely to the node...', 'info');
try {
// Node update installs are step-up protected server-side; the one-time
// install token is consumed by the challenge-triggering attempt, so
// onStepUpChallenge stashes the re-minted token for in-modal retries.
const headers = { 'x-action-token': _tokens.installUpdate || '' };
const { res, data } = await sendGuardedRequestWithStepUp('/api/settings/node-update/install', 'POST', { nodeId: targetId, version: cleanVersion }, {
headers,
onStepUpChallenge: (challenge) => {
const fresh = challenge?.actionTokens?.installUpdate;
if (fresh) {
if (request === _nodeUpdateInfoRequest) _tokens.installUpdate = fresh;
headers['x-action-token'] = fresh;
}
},
subtitle: 'Verify your identity to install this update',
reason: `Installing ADaemon ${cleanVersion} replaces the daemon code on ${targetName} and restarts it. Confirm your credentials to continue.`,
confirmText: 'Verify & Install',
cancelledMessage: 'Verification cancelled — the update was not installed.',
});
if (request !== _nodeUpdateInfoRequest) return;
delete _tokens.installUpdate;
if (!res.ok) {
setNodeStatus(data.error || 'Failed to install node update', 'error');
resetNodeCheckButton();
await loadNodeUpdateInfo(targetId);
return;
}
setNodeStatusHtml(` Update to ${escapeHtml(data.version)} installed. ${Number(data.filesUpdated || 0)} files updated, go clean completed, and adaemon restart was scheduled.`, 'success');
if (checkBtn) {
checkBtn.className = 'btn btn-update-check';
checkBtn.innerHTML = ' Update Installed';
checkBtn.disabled = true;
checkBtn.dataset.mode = '';
}
if (manualInput) manualInput.value = '';
setTimeout(() => {
if (request !== _nodeUpdateInfoRequest) return;
resetNodeCheckButton();
loadNodeUpdateInfo(targetId);
}, 3500);
} catch (e) {
if (request !== _nodeUpdateInfoRequest) return;
console.error('[node-update] Install failed:', e);
setNodeStatus((e && e.message) ? e.message : 'Network error while installing node update', 'error');
resetNodeCheckButton();
} finally {
if (request === _nodeUpdateInfoRequest) {
if (manualBtn) manualBtn.disabled = false;
if (manualInput) manualInput.disabled = false;
if (nodeSelect) nodeSelect.disabled = false;
}
}
}
if (checkBtn) {
checkBtn.addEventListener('click', async () => {
if (checkBtn.dataset.mode === 'install') {
await doNodeInstall(_latestVersionFound, 'auto');
return;
}
if (!_selectedNodeId) {
setNodeStatus('Select a node first.', 'error');
return;
}
const targetId = _selectedNodeId;
const request = _nodeUpdateInfoRequest;
if (!_tokens.checkUpdate) {
await loadNodeUpdateInfo(targetId);
return;
}
const icon = checkBtn.querySelector('.fa-arrows-rotate');
if (icon) {
icon.classList.remove('spinning');
void icon.offsetWidth;
icon.classList.add('spinning');
icon.addEventListener('animationend', () => icon.classList.remove('spinning'), { once: true });
}
checkBtn.disabled = true;
setNodeStatus('Checking for node updates...', 'info');
try {
const res = await fetch('/api/settings/node-update/check', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-action-token': _tokens.checkUpdate || '' },
credentials: 'include',
body: JSON.stringify({ nodeId: targetId }),
});
const data = await res.json().catch(() => ({}));
if (request !== _nodeUpdateInfoRequest) return;
if (!res.ok) {
setNodeStatus(data.error || 'Failed to check node updates', 'error');
checkBtn.disabled = false;
return;
}
if (data.updateAvailable) {
_latestVersionFound = data.latestVersion;
if (data.actionTokens) _tokens = { ..._tokens, ...data.actionTokens };
setNodeStatusHtml(` New node version found: ${escapeHtml(data.latestVersion)} (current: ${escapeHtml(data.currentVersion)})`, 'success');
checkBtn.dataset.mode = 'install';
checkBtn.className = 'btn btn-update-install';
checkBtn.innerHTML = ' Install Update';
checkBtn.disabled = false;
} else {
setNodeStatusHtml(` This node is running the latest version (${escapeHtml(data.currentVersion)})`, 'success');
checkBtn.disabled = false;
await loadNodeUpdateInfo(targetId);
}
} catch (e) {
if (request !== _nodeUpdateInfoRequest) return;
console.error('[node-update] Check failed:', e);
setNodeStatus('Network error while checking node updates', 'error');
checkBtn.disabled = false;
}
});
}
if (autoBtn) {
autoBtn.addEventListener('click', async () => {
if (!_selectedNodeId) {
setNodeStatus('Select a node first.', 'error');
return;
}
const targetId = _selectedNodeId;
const request = _nodeUpdateInfoRequest;
if (!_tokens.setAutoUpdate) {
await loadNodeUpdateInfo(targetId);
return;
}
const currentlyEnabled = autoBtn.dataset.enabled === 'true';
const nextEnabled = !currentlyEnabled;
autoBtn.disabled = true;
setNodeStatus(nextEnabled ? 'Enabling node auto update...' : 'Disabling node auto update...', 'info');
try {
// Disabling a node's auto-update freezes it on its current daemon
// build; the server requires step-up for that direction only.
const { res, data } = await sendGuardedRequestWithStepUp('/api/settings/node-update/auto', 'POST', { nodeId: targetId, enabled: nextEnabled }, {
headers: { 'x-action-token': _tokens.setAutoUpdate || '' },
subtitle: 'Verify your identity to disable node auto update',
reason: `Disabling auto update stops ${_selectedNodeName || _selectedNodeId} from receiving daemon updates automatically. Confirm your credentials to continue.`,
confirmText: 'Verify & Disable',
cancelledMessage: 'Verification cancelled — auto update was not changed.',
});
if (request !== _nodeUpdateInfoRequest) return;
if (!res.ok) {
setNodeStatus(data.error || 'Failed to toggle node auto update', 'error');
return;
}
renderNodeAutoButton(!!data.autoUpdateEnabled);
setNodeStatus(data.autoUpdateEnabled
? 'Auto Update enabled. New ADaemon releases will be installed on this node.'
: 'Node auto update disabled.', 'success');
} catch (e) {
if (request !== _nodeUpdateInfoRequest) return;
console.error('[node-auto-update] Toggle failed:', e);
setNodeStatus((e && e.message) ? e.message : 'Network error while toggling node auto update', 'error');
} finally {
if (request === _nodeUpdateInfoRequest) autoBtn.disabled = false;
}
});
}
if (manualBtn && manualInput) {
manualBtn.addEventListener('click', async () => {
const version = manualInput.value.trim();
if (!version) {
setNodeStatus('Please enter a version number.', 'error');
manualInput.focus();
return;
}
await doNodeInstall(version, 'manual');
});
manualInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
manualBtn.click();
}
});
}
})();
(function () {
const tip = document.createElement('div');
tip.className = 'resource-tooltip-floating';
tip.style.cssText = 'position:fixed;z-index:10010;display:none;pointer-events:none;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.1);background:rgba(18,18,24,0.96);box-shadow:0 14px 34px rgba(0,0,0,0.34);color:rgba(255,255,255,0.82);font-size:12px;font-weight:500;line-height:1.45;max-width:260px;white-space:normal;';
document.body.appendChild(tip);
document.addEventListener('mouseover', (e) => {
const trigger = e.target.closest('.resource-tooltip');
if (!trigger) return;
const card = trigger.querySelector('.resource-tooltip-card');
if (!card) return;
tip.textContent = card.textContent.trim();
tip.style.display = 'block';
const r = trigger.getBoundingClientRect();
const tw = tip.offsetWidth;
tip.style.left = Math.max(4, r.left + r.width / 2 - tw / 2) + 'px';
tip.style.top = (r.top - tip.offsetHeight - 8) + 'px';
});
document.addEventListener('mouseout', (e) => {
if (e.target.closest('.resource-tooltip')) tip.style.display = 'none';
});
})();