Files
Sebastian Flint bd97996502 Design refresh
2026-11-06 23:20:56 +01:00

1710 lines
85 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { icon } from '/shared/icons.js';
import { renderSecurity } from '/shared/twofa.js';
import { renderPasskeys } from '/shared/passkeys.js';
import { applyScheme } from '/shared/icons.js';
// Administration area: assign servers, manage customers, read the activity log.
// Receives the shared helpers from app.js so it behaves like the rest of the panel.
const ACTION_LABELS = {
login: 'Signed in',
login_failed: 'Failed sign-in',
power_start: 'Started server',
power_shutdown: 'Shut down server',
power_reboot: 'Restarted server',
power_stop: 'Force stopped server',
snapshot_create: 'Took snapshot',
snapshot_rollback: 'Rolled back snapshot',
snapshot_delete: 'Deleted snapshot',
console_open: 'Opened console',
admin_user_create: 'Added user',
admin_user_delete: 'Deleted user',
admin_password_reset: 'Reset password',
admin_grant: 'Granted admin rights',
admin_revoke: 'Removed admin rights',
admin_vm_assign: 'Assigned server',
admin_vm_unassign: 'Unassigned server',
admin_vm_rename: 'Renamed server',
admin_login: 'Signed in to administration',
admin_login_failed: 'Failed administration sign-in',
admin_limits: 'Changed limits',
admin_template_offer: 'Offered template',
admin_template_withdraw: 'Withdrew template',
server_create_started: 'Started creating server',
server_created: 'Created server',
server_create_failed: 'Server creation failed',
server_delete_started: 'Started deleting server',
server_deleted: 'Deleted server',
vpn_device_add: 'Added VPN device',
admin_power_start: 'Started server (admin)',
admin_power_shutdown: 'Shut down server (admin)',
admin_power_reboot: 'Restarted server (admin)',
admin_power_stop: 'Force stopped server (admin)',
admin_server_deleted: 'Deleted server (admin)',
admin_user_delete_started: 'Started deleting customer',
admin_user_delete_failed: 'Deleting customer failed',
admin_invite_sent: 'Sent invitation',
server_resized: 'Changed server size',
server_reinstall_started: 'Started reinstalling server',
server_expired: 'Server expired and was stopped',
server_expired_deleted: 'Expired server deleted',
server_expiry_extended: 'Extended server expiry',
server_expiry_set: 'Set server expiry',
server_expiry_removed: 'Removed server expiry',
admin_expiry_rule: 'Changed customer expiry rule',
admin_expiry_settings: 'Changed expiry settings',
admin_expiry_run: 'Ran expiry check',
admin_backup_settings: 'Changed backup settings',
admin_backup_limit: 'Changed backup limit',
backup_create: 'Started a backup',
backup_created: 'Backup made',
backup_failed: 'Backup failed',
backup_delete: 'Deleted a backup',
backup_restore_started: 'Started a restore',
backup_restored: 'Restored a backup',
backup_restore_failed: 'Restore failed',
backup_schedule: 'Changed automatic backups',
backup_file_download: 'Downloaded a file from a backup',
admin_setup_check: 'Ran the setup check',
admin_setup_check_settings: 'Changed setup check alerts',
admin_appearance: 'Changed the color scheme',
admin_winupdates: 'Changed Windows update setting',
winupdate_started: 'Started Windows updates',
winupdate_finished: 'Windows updates finished',
winupdate_failed: 'Windows updates failed',
server_reinstalled: 'Reinstalled server',
server_reinstall_failed: 'Reinstalling server failed',
invite_accepted: 'Accepted invitation, password set',
admin_email_settings: 'Changed email settings',
admin_email_settings_removed: 'Removed email settings',
admin_email_test: 'Sent test email',
twofa_enabled: 'Turned on two-factor authentication',
twofa_disabled: 'Turned off two-factor authentication',
twofa_recovery_codes: 'Created new recovery codes',
admin_twofa_require: 'Required two-factor authentication',
admin_twofa_unrequire: 'Made two-factor authentication optional',
admin_twofa_reset: 'Reset two-factor authentication',
passkey_added: 'Added a passkey',
passkey_removed: 'Removed a passkey',
admin_passkeys_removed: 'Removed passkeys of a user',
cli_twofa_reset: 'Reset two-factor authentication (command line)',
sso_login_failed: 'Failed single sign-on',
admin_sso_login_failed: 'Failed single sign-on (administration)',
sso_account_linked: 'Linked account to single sign-on',
sso_account_created: 'Account created by single sign-on',
admin_sso_unlink: 'Unlinked account from single sign-on',
tailscale_connect_started: 'Started connecting to Tailscale',
tailscale_connected: 'Connected to Tailscale',
tailscale_connect_failed: 'Tailscale connection failed',
tailscale_disconnected: 'Disconnected from Tailscale',
vpn_device_remove: 'Removed VPN device',
admin_vpn_device_remove: 'Removed VPN device',
};
export function generatePassword(length = 16) {
// No look-alike characters (0/O, 1/l/I), so it can be read out or typed by hand.
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789';
const bytes = crypto.getRandomValues(new Uint32Array(length));
return Array.from(bytes, (b) => chars[b % chars.length]).join('');
}
export function createAdmin({ root, api, toast, fail, confirmAction, promptText, esc, getMe, onAbout }) {
const st = {
tab: 'servers', users: [], vms: [], audit: [], filter: '', newUser: null,
templates: [], storages: {}, vpn: null,
};
const gb = (mb) => `${+(mb / 1024).toFixed(1)} GB`;
const utc = (s) => new Date(`${s.replace(' ', 'T')}Z`);
// ---- loading ----------------------------------------------------------
async function load({ quiet = false } = {}) {
const body = root.querySelector('#admin-body');
if (!quiet) body.innerHTML = '<p class="muted">Loading…</p>';
try {
if (st.tab === 'servers') {
[st.vms, st.users] = await Promise.all([api('/api/admin/vms'), api('/api/admin/users')]);
} else if (st.tab === 'users') {
[st.users, st.email] = await Promise.all([api('/api/admin/users'), api('/api/admin/settings/email')]);
if (!quiet) setTimeout(watchDeletions);
} else if (st.tab === 'settings') {
[st.email, st.expiry, st.appearance, st.winupdates, st.backups] = await Promise.all([
api('/api/admin/settings/email'), api('/api/admin/settings/expiry'), api('/api/admin/settings/appearance'),
api('/api/admin/settings/winupdates'), api('/api/admin/settings/backups'),
]);
} else if (st.tab === 'setup') {
st.setup = await api('/api/admin/setup-check');
if (!st.setup.result) {
renderTab();
await runSetupCheck();
return;
}
} else if (st.tab === 'about') {
st.about = await api(`/api/admin/about${st.refreshAbout ? '?refresh=1' : ''}`);
st.refreshAbout = false;
onAbout?.(st.about);
} else if (st.tab === 'account') {
// rendered by the shared security panel
} else if (st.tab === 'vpn') {
st.vpn = await api('/api/admin/vpn');
} else if (st.tab === 'templates') {
const t = await api('/api/admin/templates');
({ templates: st.templates, storages: st.storages } = t);
st.ct = { images: t.containers ?? [], missing: t.missingContainers ?? [], storages: t.containerStorages ?? {}, networksEnabled: t.networksEnabled };
} else {
st.audit = await api('/api/admin/audit?limit=200');
}
renderTab();
} catch (err) {
body.innerHTML = '';
fail(err);
}
}
// ---- shell ------------------------------------------------------------
function render() {
const tabs = [['servers', 'Servers', 'server'], ['users', 'Customers', 'users'], ['templates', 'Templates', 'layers'], ['vpn', 'VPN', 'shield'],
['activity', 'Activity', 'pulse'], ['account', 'Your account', 'user'], ['settings', 'Settings', 'gear'], ['setup', 'Setup check', 'check'], ['about', 'About', 'info']];
const count = (id) => (id === 'setup' && st.setupProblems ? ` <span class="tab-count" title="Problems found">${st.setupProblems}</span>` : '');
root.innerHTML = `
<div class="admin-inner">
<h1>Administration</h1>
<div class="tabs" role="tablist">
${tabs.map(([id, label, ic]) =>
`<button class="tab" role="tab" data-admin-tab="${id}" aria-selected="${st.tab === id}">${icon(ic, { size: 16 })}<span>${label}</span>${count(id)}</button>`).join('')}
</div>
<section id="admin-body"></section>
</div>`;
}
function renderTab() {
if (st.tab === 'servers') renderServers();
if (st.tab === 'users') renderUsers();
if (st.tab === 'templates') renderTemplates();
if (st.tab === 'vpn') renderVpn();
if (st.tab === 'activity') renderActivity();
if (st.tab === 'account') {
const body = root.querySelector('#admin-body');
body.innerHTML = '<div id="admin-2fa"></div><div id="admin-passkeys" class="account-section"></div>';
renderSecurity(body.querySelector('#admin-2fa'), { email: getMe().email });
renderPasskeys(body.querySelector('#admin-passkeys'));
}
if (st.tab === 'about') renderAbout();
if (st.tab === 'setup') renderSetupCheck();
if (st.tab === 'settings') renderSettings();
if (st.tab !== 'settings' && st.schemePreview) { st.schemePreview = null; applyScheme(st.appearance?.scheme); }
}
// ---- servers ----------------------------------------------------------
function renderServers() {
root.querySelector('#admin-body').innerHTML = `
<div class="section-head">
<p class="muted" style="margin:0" id="vm-summary"></p>
<input type="search" id="vm-filter" class="filter" placeholder="Filter by ID, name or customer"
value="${esc(st.filter)}" aria-label="Filter servers">
</div>
<div class="table-wrap">
<table class="table">
<thead><tr>
<th>ID</th><th>Name in Proxmox</th><th>Node</th><th>Customer</th><th>Name shown to customer</th><th><span class="sr-only">Actions</span></th>
</tr></thead>
<tbody id="vm-rows"></tbody>
</table>
</div>
<p class="muted small">Changes save immediately. Customers see a server as soon as it's assigned to them.</p>`;
renderServerRows();
}
/** Power and delete buttons, only for servers assigned to a customer. */
function serverActions(v) {
if (!v.userId || v.status === 'missing') return '';
const idle = v.state === 'ready' || v.state === 'failed';
const on = v.status === 'running';
const b = (action, ic, label, enabled, cls = '') =>
`<button class="icon-btn act ${cls}" data-server-action="${action}" title="${label}" aria-label="${label} ${esc(v.name)}" ${enabled ? '' : 'disabled'}>${icon(ic, { size: 17 })}</button>`;
return `<span class="act-group">
${b('start', 'play', 'Start', idle && !on && v.state === 'ready')}
${b('shutdown', 'power', 'Shut down', idle && on && v.state === 'ready')}
${b('reboot', 'restart', 'Restart', idle && on && v.state === 'ready')}
${b('stop', 'stop', 'Force stop', idle && on && v.state === 'ready')}
${b('expiry', 'clock', 'Expiry', true)}
${b('delete', 'trash', 'Delete server', idle, 'danger')}
</span>`;
}
// Reload the current tab quietly every 3 s until done() says so (max 3 min).
let watchTimer = null;
function watch(done) {
clearInterval(watchTimer);
const until = Date.now() + 180_000;
watchTimer = setInterval(async () => {
if (Date.now() > until) return clearInterval(watchTimer);
await load({ quiet: true });
if (done()) clearInterval(watchTimer);
}, 3000);
}
async function waitForTask(upid) {
for (let i = 0; i < 60 && upid; i += 1) {
await new Promise((r) => setTimeout(r, 1500));
const s = await api(`/api/admin/tasks/${encodeURIComponent(upid)}`);
if (s.done) return s;
}
return null;
}
const POWER_TEXT = {
start: ['Starting', 'started'], shutdown: ['Shutting down', 'shut down'],
reboot: ['Restarting', 'restarted'], stop: ['Stopping', 'stopped'],
};
async function serverAction(vm, action) {
if (action === 'expiry') { editServerExpiry(vm); return; }
if (action === 'delete') {
const answer = await promptText(`Type ${vm.vmid} to delete “${vm.name}” of ${vm.owner}`, {
hint: 'The server is stopped if needed and deleted with its disks and snapshots. The customer loses it immediately.',
okLabel: 'Delete server', pattern: String(vm.vmid), danger: true,
});
if (answer !== String(vm.vmid)) return;
try {
await api(`/api/admin/vms/${vm.vmid}/server`, { method: 'DELETE' });
toast(`Deleting ${vm.name}`);
await load({ quiet: true });
watch(() => !st.vms.some((x) => x.vmid === vm.vmid && x.state === 'deleting'));
} catch (err) { fail(err); }
return;
}
if (action !== 'start') {
const q = { shutdown: `Shut down ${vm.name}?`, reboot: `Restart ${vm.name}?`,
stop: `Force stop ${vm.name}? This cuts power immediately; unsaved data in the server may be lost.` }[action];
const okLabel = { shutdown: 'Shut down', reboot: 'Restart', stop: 'Force stop' }[action];
if (!(await confirmAction(`${q} The customer ${vm.owner} is affected.`, okLabel))) return;
}
try {
const { task } = await api(`/api/admin/vms/${vm.vmid}/power/${action}`, { method: 'POST' });
toast(`${POWER_TEXT[action][0]} ${vm.name}…`);
const result = await waitForTask(task);
if (result && !result.ok) toast(`${vm.name}: ${result.message}`, 'error');
else if (result) toast(`${vm.name} ${POWER_TEXT[action][1]}`);
await load({ quiet: true });
} catch (err) { fail(err); }
}
function renderServerRows() {
const assigned = st.vms.filter((v) => v.userId).length;
root.querySelector('#vm-summary').textContent =
`${st.vms.length} servers in the cluster, ${assigned} assigned to customers.`;
const q = st.filter.trim().toLowerCase();
const rows = st.vms.filter((v) => !q
|| String(v.vmid).includes(q)
|| v.name.toLowerCase().includes(q)
|| (v.owner ?? '').toLowerCase().includes(q)
|| (v.label ?? '').toLowerCase().includes(q));
const options = (selected) => `
<option value="">Not assigned</option>
${st.users.map((u) =>
`<option value="${u.id}" ${u.id === selected ? 'selected' : ''}>${esc(u.email)}</option>`).join('')}`;
root.querySelector('#vm-rows').innerHTML = rows.length ? rows.map((v) => `
<tr data-vmid="${v.vmid}">
<td class="mono">${v.vmid}</td>
<td>
<span class="led ${v.status === 'running' ? 'running' : ''}" title="${esc(v.status)}"></span>
${esc(v.name) || '<span class="muted">–</span>'}
${v.type === 'lxc' ? '<span class="tag">container</span>' : ''}
${v.status === 'missing' ? '<span class="tag warn">deleted in Proxmox</span>' : ''}
${v.state === 'creating' ? '<span class="tag">being created</span>' : ''}
${v.state === 'deleting' ? '<span class="tag">being deleted</span>' : ''}
${v.state === 'failed' ? '<span class="tag warn">setup failed</span>' : ''}
${v.createdByCustomer ? '<span class="tag">created by customer</span>' : ''}
${expiryTag(v)}
</td>
<td class="muted">${esc(v.node ?? '–')}</td>
<td>
<select data-owner aria-label="Customer for server ${v.vmid}" ${v.status === 'missing' && !v.userId ? 'disabled' : ''}>
${options(v.userId)}
</select>
</td>
<td>
<input data-label value="${esc(v.label ?? '')}" placeholder="${esc(v.name || `Server ${v.vmid}`)}"
maxlength="80" aria-label="Name shown to customer for server ${v.vmid}" ${v.userId ? '' : 'disabled'}>
</td>
<td class="actions">${serverActions(v)}</td>
</tr>`).join('')
: `<tr><td colspan="6" class="muted">No servers match “${esc(st.filter)}”.</td></tr>`;
}
async function saveAssignment(row) {
const vmid = Number(row.dataset.vmid);
const vm = st.vms.find((v) => v.vmid === vmid);
const select = row.querySelector('[data-owner]');
const input = row.querySelector('[data-label]');
const userId = select.value ? Number(select.value) : null;
const label = input.value.trim();
select.disabled = input.disabled = true;
try {
if (!userId) {
await api(`/api/admin/vms/${vmid}`, { method: 'DELETE' });
Object.assign(vm, { userId: null, owner: null, label: null });
toast(`Server ${vmid} unassigned`);
if (vm.status === 'missing') st.vms = st.vms.filter((v) => v !== vm);
} else {
const res = await api(`/api/admin/vms/${vmid}`, {
method: 'PUT',
body: label ? { userId, label } : { userId },
});
const ownerChanged = vm.userId !== userId;
Object.assign(vm, { userId, owner: res.owner, label: res.label });
toast(ownerChanged ? `Server ${vmid} assigned to ${res.owner}` : 'Name saved');
}
} catch (err) {
fail(err);
}
renderServerRows();
}
// ---- customers --------------------------------------------------------
function renderUsers() {
const me = getMe();
const note = st.newUser?.inviteError ? `
<div class="notice warn" role="status">
<p>Added <strong>${esc(st.newUser.email)}</strong>, but the invitation couldn't be sent:
${esc(st.newUser.inviteError)}</p>
<p class="small">Fix the email settings, then use <strong>Resend invitation</strong> in the list below.</p>
<div class="row"><button class="btn ghost" data-dismiss-note>Dismiss</button></div>
</div>` : st.newUser?.invited ? `
<div class="notice" role="status">
<p>Added <strong>${esc(st.newUser.email)}</strong> and sent the invitation. The link is valid for 3 days.</p>
<div class="row"><button class="btn ghost" data-dismiss-note>Dismiss</button></div>
</div>` : st.newUser ? `
<div class="notice" role="status">
<p>Added <strong>${esc(st.newUser.email)}</strong>.
${st.newUser.password ? `Their password is <span class="mono selectable">${esc(st.newUser.password)}</span>. Copy it now and send it securely; it won't be shown again.` : ''}</p>
<div class="row">
${st.newUser.password ? '<button class="btn" data-copy-password>Copy password</button>' : ''}
<button class="btn ghost" data-dismiss-note>Dismiss</button>
</div>
</div>` : '';
root.querySelector('#admin-body').innerHTML = `
<h2 class="h2">Add a customer</h2>
<form id="user-form" class="user-form" autocomplete="off">
<label>Email <input name="email" type="email" required maxlength="254"></label>
<label id="pw-field">Password
<span class="with-button">
<input name="password" type="password" required minlength="12" maxlength="200" autocomplete="new-password">
<button type="button" class="btn" data-generate>Generate</button>
</span>
</label>
<button class="btn primary">Add customer</button>
<label class="check">
<input type="checkbox" name="isAdmin">
<span>Administrator <span class="muted">Can open this area and manage all customers and servers.</span></span>
</label>
<label class="check">
<input type="checkbox" name="invite" ${st.email?.configured ? '' : 'disabled'}>
<span>Send an invitation email
<span class="muted">${st.email?.configured
? 'The user gets an email with the panel address and a personal link to set their own password (valid 3 days). No password needed here.'
: 'Set up email in the Settings tab to invite users by email.'}</span>
</span>
</label>
<label class="check">
<input type="checkbox" name="requireTotp">
<span>Require two-factor authentication <span class="muted">The user sets up an authenticator app at the first sign-in, before they can do anything else.</span></span>
</label>
</form>
${note}
<h2 class="h2">Customers</h2>
<div class="table-wrap">
<table class="table">
<thead><tr><th>Email</th><th>Role</th><th>2FA</th><th>Servers</th><th>Can create servers</th><th>Network</th><th>Added</th><th><span class="sr-only">Actions</span></th></tr></thead>
<tbody>
${st.users.map((u) => {
const self = u.id === me.id;
return `
<tr data-user="${u.id}">
<td>${esc(u.email)}${self ? ' <span class="muted">(you)</span>' : ''}${u.ssoLinked ? ' <span class="tag" title="Linked to single sign-on">SSO</span>' : ''}${u.passkeyCount ? ` <span class="tag" title="${u.passkeyCount} passkey${u.passkeyCount > 1 ? 's' : ''}">Passkey</span>` : ''}${u.expiryMode ? ` <span class="tag" title="${esc(expiryRuleText(u))}">${icon('clock', { size: 12 })} Expiry</span>` : ''}${
u.invite?.status === 'pending' ? ` <span class="tag" title="Link valid until ${esc(new Date(u.invite.expires).toLocaleString())}">Invitation pending</span>`
: u.invite?.status === 'expired' ? ' <span class="tag warn">Invitation expired</span>'
: u.invite?.status === 'sent' ? ' <span class="tag">Invited</span>' : ''}</td>
<td>${u.isAdmin ? 'Administrator' : 'Customer'}</td>
<td>${u.totpEnabled
? `<span class="pill pill-running">On</span>${u.totpRequired ? ' <span class="muted small">required</span>' : ''}`
: u.totpRequired ? '<span class="pill pill-busy" title="Set up at the next sign-in">Required</span>'
: '<span class="pill">Off</span>'}</td>
<td>${u.servers ? `<button class="linklike" data-show-servers="${esc(u.email)}">${u.servers}</button>` : '0'}</td>
<td>${u.canCreate
? `Yes <span class="muted small">(up to ${u.maxServers} servers, ${u.maxCores} cores, ${gb(u.maxMemoryMb)}, ${u.maxDiskGb} GB disk)</span>`
: '<span class="muted">No</span>'}</td>
<td>${u.network
? `<span class="mono">${esc(u.network.subnet)}</span> <span class="muted small">${esc(u.network.vnet)}</span>`
: '<span class="muted">–</span>'}</td>
<td class="muted">${utc(u.createdAt).toLocaleDateString()}</td>
<td class="actions">${u.deleting ? (u.deletionError ? `
<span class="pill pill-failed" title="${esc(u.deletionError)}">Deletion failed</span>
<button class="btn danger" data-delete-user>Retry</button>` : `
<span class="pill pill-busy">Deleting…</span>`) : `
${u.invite && st.email?.configured ? '<button class="btn" data-resend-invite>Resend invitation</button>' : ''}
<button class="btn" data-limits>Limits</button>
<button class="btn" data-twofa>Sign-in</button>
<button class="btn" data-reset>Reset password</button>
${self ? '' : `<button class="btn" data-toggle-admin>${u.isAdmin ? 'Remove admin' : 'Make admin'}</button>`}
${self ? '' : '<button class="btn danger" data-delete-user>Delete</button>'}`}
</td>
</tr>
${u.deleting && u.deletionError ? `<tr class="row-warn"><td colspan="8" class="small">Deleting ${esc(u.email)} stopped: ${esc(u.deletionError)}</td></tr>` : ''}`;
}).join('')}
</tbody>
</table>
</div>`;
}
function watchDeletions() {
if (st.users.some((u) => u.deleting && !u.deletionError)) {
watch(() => st.tab !== 'users' || !st.users.some((u) => u.deleting && !u.deletionError));
}
}
/** Confirmation dialog listing everything that will be deleted. */
async function deleteCustomer(user) {
let plan;
try {
plan = await api(`/api/admin/users/${user.id}/deletion-plan`);
if (!st.vms.length) st.vms = await api('/api/admin/vms').catch(() => []);
} catch (err) { return fail(err); }
const dialog = document.getElementById('delete-user');
const form = document.getElementById('delete-user-form');
const created = plan.servers.filter((x) => x.createdByCustomer);
const assigned = plan.servers.filter((x) => !x.createdByCustomer);
const names = new Map(st.vms.map((v) => [v.vmid, v.name]));
const item = (x) => `<li><span class="mono">${x.vmid}</span> ${esc(x.label || names.get(x.vmid) || '')}</li>`;
document.getElementById('du-title').textContent = `Delete ${user.email}?`;
document.getElementById('du-plan').innerHTML = `
<p>This deletes the account and everything that belongs to it. It can't be undone.</p>
<ul class="plan-list">
${created.length ? `<li><strong>${created.length} server${created.length > 1 ? 's' : ''} the customer created</strong> are stopped and deleted with their disks and snapshots:<ul>${created.map(item).join('')}</ul></li>` : ''}
${assigned.length ? `<li><strong>${assigned.length} server${assigned.length > 1 ? 's' : ''} you assigned</strong>:<ul>${assigned.map(item).join('')}</ul></li>` : ''}
${plan.vpnDevices ? `<li><strong>${plan.vpnDevices} VPN device${plan.vpnDevices > 1 ? 's' : ''}</strong> lose access.</li>` : ''}
${plan.network ? `<li><strong>The private network</strong> <span class="mono">${esc(plan.network.vnet)}</span> (<span class="mono">${esc(plan.network.subnet)}</span>) is removed from Proxmox${plan.othersInNetwork.length ? ', unless you keep it (see below)' : ''}.</li>` : ''}
${!plan.servers.length && !plan.vpnDevices && !plan.network ? '<li>No servers, VPN devices or network.</li>' : ''}
</ul>`;
const others = plan.othersInNetwork ?? [];
if (others.length) {
document.getElementById('du-plan').insertAdjacentHTML('beforeend', `
<div class="notice warn">
<p><strong>${others.length === 1 ? 'This server is' : 'These servers are'} still in the customer's network
but no longer theirs:</strong></p>
<ul class="plan-list">${others.map((g) => `<li><span class="mono">${g.vmid}</span> ${esc(g.name)}
<span class="muted">${g.owner ? `assigned to ${esc(g.owner)}` : 'not assigned'}</span></li>`).join('')}</ul>
<p class="small">They are not deleted. Proxmox can't remove a network that is in use, so either keep the
network, or first move ${others.length === 1 ? 'it' : 'them'} to another network (Hardware, Network Device).</p>
</div>`);
}
const keepNetWrap = document.getElementById('du-keepnet-wrap');
keepNetWrap.hidden = !others.length;
form.keepNetwork.checked = others.length > 0;
const keepWrap = document.getElementById('du-keep-wrap');
keepWrap.hidden = !assigned.length;
form.keepAssigned.checked = false;
form.confirm.value = '';
const ok = document.getElementById('du-ok');
ok.disabled = true;
const matches = () => form.confirm.value.trim().toLowerCase() === user.email.toLowerCase();
form.confirm.oninput = () => { ok.disabled = !matches(); };
form.confirm.onkeydown = (e) => {
if (e.key === 'Enter') { e.preventDefault(); if (matches()) dialog.close('ok'); }
};
dialog.returnValue = '';
dialog.showModal();
form.confirm.focus();
const confirmed = await new Promise((resolve) => {
dialog.addEventListener('close', () => resolve(dialog.returnValue === 'ok' && matches()), { once: true });
});
if (!confirmed) return;
try {
const q = new URLSearchParams();
if (form.keepAssigned.checked) q.set('keepAssigned', 'true');
if (form.keepNetwork.checked && !keepNetWrap.hidden) q.set('keepNetwork', 'true');
const qs = q.toString();
await api(`/api/admin/users/${user.id}${qs ? `?${qs}` : ''}`, { method: 'DELETE' });
toast(`Deleting ${user.email}`);
st.users = await api('/api/admin/users');
renderUsers();
watchDeletions();
} catch (err) { fail(err); }
}
/** Require / not require 2FA for a user, or reset it (lost phone). */
async function editTwoFactor(user) {
const dialog = document.getElementById('twofa-admin');
const form = document.getElementById('twofa-admin-form');
document.getElementById('ta-title').textContent = `Sign-in for ${user.email}`;
document.getElementById('ta-state').innerHTML = user.totpEnabled
? '<span class="pill pill-running">On</span> The user has set it up.'
: user.totpRequired
? '<span class="pill pill-busy">Required</span> The user sets it up at the next sign-in.'
: '<span class="pill">Off</span> The user signs in with password only.';
form.required.checked = user.totpRequired;
document.getElementById('ta-reset-box').hidden = !user.totpEnabled;
const pkBox = document.getElementById('ta-passkey-box');
pkBox.hidden = !user.passkeyCount;
document.getElementById('ta-passkey-count').textContent = `${user.passkeyCount} passkey${user.passkeyCount === 1 ? '' : 's'}`;
document.getElementById('ta-remove-passkeys').onclick = async () => {
if (!(await confirmAction(`Remove all passkeys of ${user.email}? They then sign in with password or single sign-on and can add new passkeys.`, 'Remove'))) return;
try {
await api(`/api/admin/users/${user.id}`, { method: 'PATCH', body: { removePasskeys: true } });
toast(`Passkeys removed for ${user.email}`);
dialog.close('reset');
} catch (err) { fail(err); }
};
const ssoBox = document.getElementById('ta-sso-box');
ssoBox.hidden = !user.ssoLinked;
document.getElementById('ta-sso-issuer').textContent = user.ssoIssuer ?? '';
document.getElementById('ta-unlink').onclick = async () => {
if (!(await confirmAction(`Unlink ${user.email} from single sign-on? The next single sign-on links the account again by verified email, or is refused.`, 'Unlink'))) return;
try {
await api(`/api/admin/users/${user.id}`, { method: 'PATCH', body: { unlinkSso: true } });
toast(`${user.email} unlinked from single sign-on`);
dialog.close('reset');
} catch (err) { fail(err); }
};
document.getElementById('ta-reset').onclick = async () => {
if (!(await confirmAction(`Reset two-factor authentication for ${user.email}? Their authenticator app and recovery codes stop working.`, 'Reset'))) return;
try {
await api(`/api/admin/users/${user.id}`, { method: 'PATCH', body: { resetTotp: true } });
toast(`Two-factor authentication reset for ${user.email}`);
dialog.close('reset');
} catch (err) { fail(err); }
};
dialog.returnValue = '';
dialog.showModal();
const result = await new Promise((resolve) => dialog.addEventListener('close', () => resolve(dialog.returnValue), { once: true }));
if (result === 'ok' && form.required.checked !== user.totpRequired) {
try {
await api(`/api/admin/users/${user.id}`, { method: 'PATCH', body: { totpRequired: form.required.checked } });
toast(form.required.checked ? `Two-factor authentication is now required for ${user.email}` : `Two-factor authentication is optional for ${user.email}`);
} catch (err) { fail(err); }
}
if (result === 'ok' || result === 'reset') {
st.users = await api('/api/admin/users');
renderUsers();
}
}
async function createUser(form) {
const email = form.email.value.trim();
const invite = form.invite.checked;
const password = invite ? undefined : form.password.value;
const isAdmin = form.isAdmin.checked;
const requireTotp = form.requireTotp.checked;
const generated = !invite && form.dataset.generated === password;
const button = form.querySelector('.btn.primary');
button.disabled = true;
try {
const r = await api('/api/admin/users', { method: 'POST', body: { email, password, isAdmin, requireTotp, invite } });
st.newUser = { email, password: generated ? password : null, invited: r.invited, inviteError: r.inviteError };
st.users = await api('/api/admin/users');
renderUsers();
} catch (err) {
fail(err);
button.disabled = false;
}
}
// ---- limits -----------------------------------------------------------
function editLimits(user) {
const dialog = document.getElementById('limits');
const form = document.getElementById('limits-form');
document.getElementById('limits-title').textContent = `Limits and expiry for ${user.email}`;
form.expiryMode.value = user.expiryMode ?? '';
form.expiryDays.value = user.expiryDays ?? 14;
form.expiryDate.value = user.expiryDate ?? '';
form.expirySelfExtend.checked = !!user.expirySelfExtend;
const showRule = () => {
document.getElementById('lim-exp-days').hidden = form.expiryMode.value !== 'after_creation';
document.getElementById('lim-exp-date').hidden = form.expiryMode.value !== 'fixed_date';
document.getElementById('lim-exp-extend').hidden = !form.expiryMode.value;
};
form.expiryMode.onchange = showRule;
showRule();
// Sensible starting values the first time self-service is switched on
const fresh = !user.canCreate && !user.maxServers && !user.maxCores;
form.canCreate.checked = user.canCreate;
form.maxServers.value = fresh ? 2 : user.maxServers;
form.maxCores.value = fresh ? 4 : user.maxCores;
form.maxMemoryGb.value = fresh ? 8 : +(user.maxMemoryMb / 1024).toFixed(1);
form.maxDiskGb.value = fresh ? 100 : user.maxDiskGb;
form.maxBackups.value = user.maxBackups ?? '';
const u = user.usage;
document.getElementById('limits-usage').textContent = u
? `In use now: ${u.servers} servers, ${u.cores} cores, ${gb(u.memoryMb)} memory, ${u.diskGb} GB disk.`
: `${user.servers} server${user.servers === 1 ? '' : 's'} assigned.`;
dialog.returnValue = '';
dialog.showModal();
return new Promise((resolve) => {
dialog.addEventListener('close', async () => {
if (dialog.returnValue !== 'ok') return resolve(false);
try {
await api(`/api/admin/users/${user.id}`, {
method: 'PATCH',
body: {
canCreate: form.canCreate.checked,
maxServers: Number(form.maxServers.value),
maxCores: Number(form.maxCores.value),
maxMemoryMb: Math.round(Number(form.maxMemoryGb.value) * 1024),
maxDiskGb: Number(form.maxDiskGb.value),
expiryMode: form.expiryMode.value || null,
...(form.expiryMode.value === 'after_creation' ? { expiryDays: Number(form.expiryDays.value) } : {}),
...(form.expiryMode.value === 'fixed_date' ? { expiryDate: form.expiryDate.value } : {}),
expirySelfExtend: form.expirySelfExtend.checked,
maxBackups: form.maxBackups.value === '' ? null : Number(form.maxBackups.value),
},
});
toast(`Limits and expiry saved for ${user.email}`);
resolve(true);
} catch (err) {
fail(err);
resolve(false);
}
}, { once: true });
});
}
// ---- templates --------------------------------------------------------
function renderTemplates() {
const body = root.querySelector('#admin-body');
body.innerHTML = `
<h2 class="h2">VM templates</h2>
${st.templates.length ? vmTemplatesTable() : `
<p class="muted">No VM templates in the cluster. Prepare a VM with cloud-init (or a sysprep'd Windows), convert it to a
template in Proxmox and add it to the panel's templates pool; it then appears here.</p>`}
<h2 class="h2">Container images (LXC)</h2>
${containersTable()}`;
}
function containersTable() {
const ct = st.ct ?? { images: [], missing: [], storages: {} };
const size = (b) => (b ? `${(b / 2 ** 20).toFixed(0)} MB` : '');
return `
<p class="muted" style="margin-top:-4px">Images downloaded in Proxmox under <em>node → storage → CT Templates</em>
(e.g. Debian, Ubuntu, Alpine). Customers get an <strong>unprivileged</strong> container and sign in as <span class="mono">root</span>
with their password or SSH key. Containers start in seconds and use little memory, but run on the host's kernel:
no Windows, no own kernel modules, no Tailscale or Windows updates through the panel.</p>
${ct.missing.length ? `<div class="notice warn"><p><strong>Offered but the file is gone:</strong>
${ct.missing.map((m) => `${esc(m.label)} <span class="mono small">(${esc(m.volid)} on ${esc(m.node)})</span>
<button class="btn" data-ct-withdraw="${m.id}">Withdraw</button>`).join(' ')}</p></div>` : ''}
${ct.images.length ? `
<div class="table-wrap">
<table class="table">
<thead><tr>
<th>Image in Proxmox</th><th>Offered</th><th>Name shown to customers</th><th>Disk storage</th>
<th>Min. disk (GB)</th>${ct.networksEnabled ? '' : '<th>Bridge</th>'}<th>Nesting</th><th><span class="sr-only">Save</span></th>
</tr></thead>
<tbody>
${ct.images.map((c, i) => `
<tr data-ct="${i}">
<td><span class="mono">${esc(c.file)}</span><br><span class="muted small">${esc(c.node)}${c.shared ? ' (shared storage)' : ''} · ${esc(c.volid.split(':')[0])} · ${esc(size(c.size))}</span></td>
<td><input type="checkbox" data-f="offered" ${c.offered ? 'checked' : ''} aria-label="Offer ${esc(c.file)}"></td>
<td><input data-f="label" value="${esc(c.label)}" placeholder="e.g. Debian 13 (container)" maxlength="80"></td>
<td><select data-f="storage" aria-label="Disk storage for ${esc(c.file)}">
${(ct.storages[c.node] ?? []).map((s) => `<option ${s === (c.storage || 'local-lvm') ? 'selected' : ''}>${esc(s)}</option>`).join('')}
</select></td>
<td><input data-f="minDiskGb" type="number" min="1" max="1024" value="${esc(c.minDiskGb)}" class="narrow"></td>
${ct.networksEnabled ? '' : `<td><input data-f="bridge" value="${esc(c.bridge)}" maxlength="32" class="narrow mono"></td>`}
<td><input type="checkbox" data-f="nesting" ${c.nesting ? 'checked' : ''} aria-label="Nesting for ${esc(c.file)}"></td>
<td><button class="btn" data-save-ct>Save</button></td>
</tr>`).join('')}
</tbody>
</table>
</div>
<p class="muted small"><strong>Disk storage:</strong> where the container's disk is created (content “Container”).
<strong>Nesting:</strong> needed by systemd in current distributions (Debian 12+, Ubuntu 24.04+); keep it on unless you have a reason.
${ct.networksEnabled ? 'Containers join the customer\'s private network and are isolated like VMs.' : '<strong>Bridge:</strong> the network the container is connected to (customer networks are off).'}</p>`
: '<p class="muted">No container images found. Download one in Proxmox: node → local → CT Templates → Templates.</p>'}`;
}
function vmTemplatesTable() {
return `
<p class="muted" style="margin-top:-4px">Customers who may create servers can choose from the templates offered here.
Linux templates are set up with cloud-init, Windows templates through the QEMU guest agent.</p>
<div class="table-wrap">
<table class="table">
<thead><tr>
<th>ID</th><th>Template in Proxmox</th><th>Offered</th><th>Name shown to customers</th>
<th>Setup</th><th>Target storage</th><th>User</th><th>Network (cloud-init)</th><th><span class="sr-only">Save</span></th>
</tr></thead>
<tbody>
${st.templates.map((t) => `
<tr data-template="${t.vmid}">
<td class="mono">${t.vmid}</td>
<td>${esc(t.name)} <span class="muted small">${esc(t.node)}</span></td>
<td><input type="checkbox" data-f="offered" ${t.offered ? 'checked' : ''} aria-label="Offer template ${t.vmid}"></td>
<td><input data-f="label" value="${esc(t.label)}" placeholder="e.g. Debian 12" maxlength="80"></td>
<td>
<select data-f="setup" aria-label="Setup method for template ${t.vmid}">
<option value="cloudinit" ${t.setup !== 'windows' ? 'selected' : ''}>Cloud-init (Linux)</option>
<option value="windows" ${t.setup === 'windows' ? 'selected' : ''}>Guest agent (Windows)</option>
</select>
</td>
<td>
<select data-f="storage">
<option value="">Same as template</option>
${(st.storages[t.node] ?? []).map((name) =>
`<option ${name === t.storage ? 'selected' : ''}>${esc(name)}</option>`).join('')}
</select>
</td>
<td><input data-f="ciUser" value="${esc(t.ciUser)}" placeholder="${t.setup === 'windows' ? 'Administrator' : 'from template'}" maxlength="32" class="narrow"></td>
<td><input data-f="ipconfig" value="${esc(t.ipconfig)}" maxlength="200" class="mono narrow"></td>
<td><button class="btn" data-save-template>Save</button></td>
</tr>`).join('')}
</tbody>
</table>
</div>
<p class="muted small">
<strong>Cloud-init:</strong> the customer chooses the user name (User is only the suggestion); Network is the
<span class="mono">ipconfig0</span> value, e.g. <span class="mono">ip=dhcp</span>.
<strong>Guest agent (Windows):</strong> the template must be sysprep'd with the QEMU guest agent installed and enabled;
the panel sets the password of User (default Administrator) and the computer name.</p>`;
}
async function saveContainer(row) {
const c = st.ct.images[Number(row.dataset.ct)];
const field = (f) => row.querySelector(`[data-f="${f}"]`);
const offered = field('offered').checked;
const label = field('label').value.trim();
try {
if (!offered) {
if (c.id) await api(`/api/admin/ct-templates/${c.id}`, { method: 'DELETE' });
Object.assign(c, { offered: false, id: null });
return toast(`${c.file} is not offered`);
}
if (!label) {
field('label').focus();
return toast('Give the image a name customers will recognise', 'error');
}
const r = await api('/api/admin/ct-templates', {
method: 'PUT',
body: {
volid: c.volid, node: c.node, label, storage: field('storage').value,
minDiskGb: Number(field('minDiskGb').value) || 4,
...(field('bridge') ? { bridge: field('bridge').value.trim() || 'vmbr0' } : {}),
nesting: field('nesting').checked,
},
});
Object.assign(c, { offered: true, id: r.id, label });
toast(`${label} is offered to customers`);
} catch (err) { fail(err); }
}
async function saveTemplate(row) {
const vmid = Number(row.dataset.template);
const field = (f) => row.querySelector(`[data-f="${f}"]`);
const offered = field('offered').checked;
const label = field('label').value.trim();
try {
if (!offered) {
await api(`/api/admin/templates/${vmid}`, { method: 'DELETE' });
toast(`Template ${vmid} is not offered`);
} else {
if (!label) {
field('label').focus();
return toast('Give the template a name customers will recognise', 'error');
}
await api(`/api/admin/templates/${vmid}`, {
method: 'PUT',
body: {
label,
storage: field('storage').value,
ciUser: field('ciUser').value.trim(),
ipconfig: field('ipconfig').value.trim(),
setup: field('setup').value,
},
});
toast(`${label} is offered to customers`);
}
const t = st.templates.find((x) => x.vmid === vmid);
Object.assign(t, { offered, label });
} catch (err) { fail(err); }
}
// ---- VPN --------------------------------------------------------------
function tailscaleSection() {
const ts = st.vpn.tailscale;
if (!ts?.enabled) return '';
const stateWord = { connected: 'Connected', installing: 'Connecting…', disconnecting: 'Disconnecting…', failed: 'Failed' };
const pill = { connected: 'pill-running', installing: 'pill-busy', disconnecting: 'pill-busy', failed: 'pill-failed' };
return `
<h2 class="h2">Tailscale</h2>
<p class="muted" style="margin-top:-4px">Servers customers connected to their own tailnet. The panel doesn't
see or manage the customers' Tailscale accounts.</p>
${ts.servers.length ? `
<div class="table-wrap">
<table class="table">
<thead><tr><th>Customer</th><th>Server</th><th>Mode</th><th>Tailscale address</th><th>State</th></tr></thead>
<tbody>
${ts.servers.map((x) => `
<tr>
<td>${esc(x.email)}</td>
<td><span class="mono">${x.vmid}</span> ${esc(x.label ?? x.hostname ?? '')}</td>
<td>${x.mode === 'gateway' ? 'Gateway to private network' : 'Just this server'}</td>
<td class="mono">${esc(x.ip ?? '–')}</td>
<td><span class="pill ${pill[x.state] ?? ''}" title="${esc(x.error ?? '')}">${stateWord[x.state] ?? esc(x.state)}</span></td>
</tr>`).join('')}
</tbody>
</table>
</div>` : '<p class="muted">No server is connected to Tailscale yet.</p>'}`;
}
function renderVpn() {
const { status, devices } = st.vpn;
const body = root.querySelector('#admin-body');
if (!status.enabled) {
body.innerHTML = `
<div class="empty">
<h2>WireGuard VPN is switched off</h2>
<p class="muted">Set up the WireGuard gateway VM and set <span class="mono">VPN_ENABLED=true</span>,
<span class="mono">VPN_GATEWAY_VMID</span> and <span class="mono">VPN_ENDPOINT</span> in the panel's
<span class="mono">.env</span>. The documentation (Networking → WireGuard VPN) has the steps.</p>
</div>
${tailscaleSection()}`;
return;
}
const since = (ts) => (ts == null ? 'unknown' : !ts ? 'Never'
: Date.now() / 1000 - ts < 180 ? 'Connected now' : new Date(ts * 1000).toLocaleString());
body.innerHTML = `
<dl class="specs cols-3">
<div><dt>Gateway</dt><dd>${status.reachable
? '<span class="led running"></span> Running' : '<span class="led failed"></span> Not reachable'}
<span class="muted small">VM ${status.gatewayVmid}</span></dd></div>
<div><dt>Endpoint for customers</dt><dd class="mono">${esc(status.endpoint)}</dd></div>
<div><dt>Devices</dt><dd>${devices.length}</dd></div>
<div class="wide"><dt>${status.reachable ? 'Gateway public key' : 'Problem'}</dt>
<dd class="${status.reachable ? 'mono' : ''}">${esc(status.reachable ? status.publicKey : status.error)}</dd></div>
</dl>
<div class="section-head">
<h2 class="h2" style="margin:0">Devices</h2>
<button class="btn" data-vpn-sync>Re-apply configuration</button>
</div>
${devices.length ? `
<div class="table-wrap">
<table class="table">
<thead><tr><th>Customer</th><th>Device</th><th>VPN address</th><th>Last connected</th><th>Added</th><th><span class="sr-only">Remove</span></th></tr></thead>
<tbody>
${devices.map((d) => `
<tr>
<td>${esc(d.email ?? '–')}</td>
<td>${esc(d.name)}</td>
<td class="mono">${esc(d.address)}</td>
<td>${esc(since(d.lastHandshake))}</td>
<td class="muted">${utc(d.createdAt).toLocaleDateString()}</td>
<td class="actions"><button class="btn danger" data-vpn-remove="${d.id}" data-name="${esc(d.name)}">Remove</button></td>
</tr>`).join('')}
</tbody>
</table>
</div>` : '<p class="muted">No VPN devices yet. Customers add them under “VPN access”.</p>'}
${tailscaleSection()}`;
}
// ---- expiry ---------------------------------------------------------------
const day = (iso) => new Date(iso).toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' });
function expiryTag(v) {
const e = v.expiry;
if (!e) return '';
if (e.expired) {
return e.deleteAt
? `<span class="tag warn" title="Expired ${esc(day(e.expiredAt))}">Expired · deleted ${esc(day(e.deleteAt))}</span>`
: `<span class="tag warn" title="Assigned by you: not deleted automatically">Expired · your decision</span>`;
}
return `<span class="tag" title="${v.expiryManual ? 'Set for this server' : "From the customer's rule"}">Expires ${esc(day(e.expiresAt))}</span>`;
}
/** Set, extend or remove a server's expiry. */
async function editServerExpiry(vm) {
const dialog = document.getElementById('expiry-dialog');
const form = document.getElementById('expiry-form');
document.getElementById('ex-title').textContent = `Expiry of ${vm.label || vm.name} (${vm.vmid})`;
const e = vm.expiry;
document.getElementById('ex-state').textContent = !e ? 'This server does not expire.'
: e.expired ? `Expired on ${day(e.expiredAt)}${e.deleteAt ? `; deleted on ${day(e.deleteAt)} unless extended` : '; assigned by you, so it is not deleted automatically'}.`
: `Expires on ${day(e.expiresAt)}.`;
form.date.value = e && !e.expired ? e.expiresAt.slice(0, 10) : '';
form.date.min = new Date(Date.now() + 86_400_000).toISOString().slice(0, 10);
document.getElementById('ex-remove').hidden = !e;
form.date.onkeydown = (ev) => { if (ev.key === 'Enter') { ev.preventDefault(); dialog.close('ok'); } };
dialog.returnValue = '';
dialog.showModal();
const result = await new Promise((resolve) => dialog.addEventListener('close', () => resolve(dialog.returnValue), { once: true }));
let body = null;
if (result === 'ok') body = form.date.value ? { expiresAt: form.date.value } : null;
if (result === 'plus7') body = { extendDays: 7 };
if (result === 'plus30') body = { extendDays: 30 };
if (result === 'remove') body = { expiresAt: null };
if (!body) return;
try {
const r = await api(`/api/admin/vms/${vm.vmid}/expiry`, { method: 'PUT', body });
toast(r.expiry ? `${vm.label || vm.name} now expires on ${day(r.expiry.expiresAt)}` : `${vm.label || vm.name} no longer expires`);
load({ quiet: true });
} catch (err) { fail(err); }
}
function expiryRuleText(u) {
if (u.expiryMode === 'after_creation') return `Servers expire ${u.expiryDays} days after creation`;
if (u.expiryMode === 'fixed_date') return `Servers expire on ${day(`${u.expiryDate}T12:00:00`)}`;
return '';
}
// ---- settings: email ----------------------------------------------------
function renderSettings() {
const e = st.email;
const me = getMe();
const ap = st.appearance;
root.querySelector('#admin-body').innerHTML = `
<div class="settings">
<section class="security-card settings-card">
<div class="settings-head">
<h2 class="twofa-title"><span class="title-ico">${icon('palette', { size: 18 })}</span>Appearance</h2>
<p class="muted">The color scheme for everyone: this admin interface, the customer portal, the sign-in pages
and emails. Each scheme has a light and a dark variant; the panel follows each device's light/dark setting.</p>
</div>
<div class="scheme-grid" role="radiogroup" aria-label="Color scheme">
${ap.schemes.map((sc) => `
<button type="button" class="scheme-tile" role="radio" data-scheme-pick="${esc(sc.id)}"
aria-checked="${sc.id === ap.scheme}">
<span class="scheme-preview" aria-hidden="true">
<span class="sp-side" style="background:${esc(sc.side)}"><i></i><i></i><i></i></span>
<span class="sp-main"><span class="sp-line"></span><span class="sp-line short"></span>
<span class="sp-btn" style="background:${esc(sc.accent)}"></span></span>
</span>
<span class="scheme-name">${esc(sc.name)}${sc.id === ap.scheme ? ' <span class="pill pill-running">Active</span>' : ''}</span>
<span class="muted small">${esc(sc.description)}</span>
</button>`).join('')}
</div>
<div class="row">
<button type="button" class="btn primary" data-scheme-save disabled>Save for everyone</button>
<button type="button" class="btn ghost" data-scheme-cancel hidden>Cancel preview</button>
<span class="muted small" id="scheme-note"></span>
</div>
</section>
<section class="security-card settings-card">
<div class="settings-head">
<h2 class="twofa-title"><span class="title-ico">${icon('mail', { size: 18 })}</span>Email <span class="pill ${e.configured ? 'pill-running' : ''}">${e.configured ? 'Configured' : 'Not set up'}</span></h2>
<p class="muted">Used to send invitations to new users. Settings are stored in the panel's database; the
password is kept encrypted and never shown again.</p>
</div>
<form id="email-form" class="email-form" novalidate>
<div class="grid-3">
<label>SMTP server <input name="host" required value="${esc(e.host)}" placeholder="smtp.example.com" autocomplete="off"></label>
<label>Encryption
<select name="security">
<option value="starttls" ${e.security === 'starttls' ? 'selected' : ''}>STARTTLS (587)</option>
<option value="tls" ${e.security === 'tls' ? 'selected' : ''}>TLS (465)</option>
<option value="none" ${e.security === 'none' ? 'selected' : ''}>None (internal relay only)</option>
</select>
</label>
<label>Port <input name="port" type="number" min="1" max="65535" required value="${esc(e.port)}"></label>
</div>
<div class="grid-2">
<label>Username <input name="username" value="${esc(e.username)}" autocomplete="off" placeholder="often the sender address"></label>
<label>Password
<input name="password" type="password" autocomplete="new-password" placeholder="${e.hasPassword ? 'Stored; leave empty to keep it' : ''}">
${e.hasPassword ? '<span class="hint"><label class="inline-check"><input type="checkbox" name="clearPassword"> Remove the stored password</label></span>' : ''}
</label>
</div>
<div class="grid-2">
<label>Sender name <input name="fromName" value="${esc(e.fromName)}" maxlength="80"></label>
<label>Sender address <input name="fromAddress" type="email" required value="${esc(e.fromAddress)}" placeholder="panel@example.com"></label>
</div>
<label>Panel address for links
<input name="panelUrl" type="url" required value="${esc(e.panelUrl)}" placeholder="https://panel.example.com">
<span class="hint">The customer panel's address as users open it; invitation links point there.</span>
</label>
<p id="email-warning" class="form-error" role="alert"></p>
<div class="row">
<button class="btn primary">Save</button>
${e.configured ? '<button type="button" class="btn danger" data-email-remove>Remove email settings</button>' : ''}
${e.updatedAt ? `<span class="muted small">Last changed ${esc(new Date(`${e.updatedAt.replace(' ', 'T')}Z`).toLocaleString())}</span>` : ''}
</div>
</form>
</section>
<section class="security-card settings-card">
<div class="settings-head">
<h2 class="twofa-title"><span class="title-ico">${icon('windows', { size: 18 })}</span>Windows updates</h2>
<p class="muted">Customers can install Windows updates on their Windows servers from the server page
(Updates tab): security or all quality updates, optionally with a snapshot first and automatic restarts.
Feature upgrades and previews are never installed.</p>
</div>
<label class="check"><input type="checkbox" data-winupdates ${st.winupdates?.enabled ? 'checked' : ''}>
<span>Allow customers to install Windows updates</span></label>
</section>
<section class="security-card settings-card">
<div class="settings-head">
<h2 class="twofa-title"><span class="title-ico">${icon('archive', { size: 18 })}</span>Backups</h2>
<p class="muted">Customers back up their servers, restore them and — with a Proxmox Backup Server — download
single files from a backup (Backups tab on the server page). Backups go to the storage chosen here; the
panel uses the Proxmox API, so it never needs the backup server's credentials. Backups of your own Proxmox
backup jobs are shown to the customer too (from the day the server became theirs), but can't be deleted by them.</p>
</div>
<form id="backup-settings" class="email-form" novalidate>
<label class="check"><input type="checkbox" name="enabled" ${st.backups.settings.enabled ? 'checked' : ''}>
<span>Allow customers to make and restore backups</span></label>
<div class="grid-3">
<label>Backup storage
<select name="storage">
<option value="">Choose…</option>
${st.backups.storages.map((x) => `<option value="${esc(x.id)}" ${x.id === st.backups.settings.storage ? 'selected' : ''}>${esc(x.id)}${x.type === 'pbs' ? ' (Proxmox Backup Server)' : x.type ? ` (${esc(x.type)})` : ''}</option>`).join('')}
${st.backups.settings.storage && !st.backups.storages.some((x) => x.id === st.backups.settings.storage)
? `<option value="${esc(st.backups.settings.storage)}" selected>${esc(st.backups.settings.storage)} (not found)</option>` : ''}
</select>
<span class="hint">Storages with the content “backup”. Browsing files needs a Proxmox Backup Server.</span>
</label>
<label>Backups per server
<input name="maxPerServer" type="number" min="1" max="100" value="${esc(st.backups.settings.maxPerServer)}" required>
<span class="hint">Made by the customer or automatically. Per customer: <em>Limits</em>.</span>
</label>
</div>
<label class="check"><input type="checkbox" name="schedules" ${st.backups.settings.schedules ? 'checked' : ''}>
<span>Automatic backups <span class="muted">Customers can back up daily or weekly; older automatic backups are rotated out.</span></span></label>
<label class="check"><input type="checkbox" name="keepAfterDelete" ${st.backups.settings.keepAfterDelete ? 'checked' : ''}>
<span>Keep backups of deleted servers <span class="muted">Otherwise the panel's backups of a server are deleted together with it.</span></span></label>
<div class="row"><button class="btn primary">Save</button></div>
</form>
</section>
<section class="security-card settings-card">
<div class="settings-head">
<h2 class="twofa-title"><span class="title-ico">${icon('calendar', { size: 18 })}</span>Server expiry</h2>
<p class="muted">For customers or servers you give an expiry date (customer: <em>Limits</em>; server: the
clock button in <em>Servers</em>). Reminders by email, stopped at expiry, deleted after the grace period —
only servers the customer created; servers you assigned are only stopped.</p>
${e.configured ? '' : '<p class="small warn-text">Email is not set up: customers get no reminders, and nothing is deleted automatically (servers are only stopped).</p>'}
</div>
<form id="expiry-settings" class="email-form" novalidate>
<div class="grid-3">
<label>Reminders (days before)
<input name="reminderDays" value="${esc((st.expiry.reminderDays ?? []).join(', '))}" placeholder="7, 1" pattern="[0-9 ,]*">
</label>
<label>Grace period (days)
<input name="graceDays" type="number" min="0" max="365" value="${esc(st.expiry.graceDays)}" required>
<span class="hint">Stopped but kept, then deleted.</span>
</label>
<label>Self-extension (days)
<input name="selfExtendDays" type="number" min="1" max="365" value="${esc(st.expiry.selfExtendDays)}" required>
<span class="hint">For customers allowed to extend once.</span>
</label>
</div>
<label class="check"><input type="checkbox" name="pauseDeletions" ${st.expiry.pauseDeletions ? 'checked' : ''}>
<span>Pause deletions <span class="muted">Expired servers are only stopped, never deleted, until you switch this off.</span></span></label>
<label class="check"><input type="checkbox" name="adminSummary" ${st.expiry.adminSummary ? 'checked' : ''}>
<span>Daily summary to administrators <span class="muted">Only on days when something happened or expires soon.</span></span></label>
<div class="row">
<button class="btn primary">Save</button>
<button type="button" class="btn" data-expiry-run>Check now</button>
<span class="muted small" id="expiry-result"></span>
</div>
</form>
</section>
<section class="security-card settings-card" ${e.configured ? '' : 'hidden'}>
<div class="settings-head">
<h2 class="twofa-title"><span class="title-ico">${icon('mail', { size: 18 })}</span>Send a test email</h2>
<p class="muted">Checks the settings end to end: connection, encryption, sign-in and delivery.</p>
</div>
<form id="email-test" class="vpn-form" novalidate>
<label>Send to <input name="to" type="email" required value="${esc(me.email)}"></label>
<button class="btn">Send test email</button>
</form>
</section>
</div>`;
warnPlain();
}
// Plain SMTP with a password sends that password unencrypted
function warnPlain() {
const f = root.querySelector('#email-form');
if (!f) return;
root.querySelector('#email-warning').textContent = f.security.value === 'none' && f.username.value
? 'Without encryption the SMTP password travels unencrypted. Use this only for a mail relay inside your own network.'
: '';
}
root.addEventListener('input', (ev) => { if (ev.target.closest('#email-form')) warnPlain(); });
root.addEventListener('change', (ev) => {
const f = ev.target.closest('#email-form');
if (!f || ev.target.name !== 'security') return;
// suggest the usual port when it's still one of the defaults
const usual = { starttls: 587, tls: 465, none: 25 };
if ([587, 465, 25].includes(Number(f.port.value))) f.port.value = usual[f.security.value];
warnPlain();
});
root.addEventListener('submit', async (ev) => {
if (ev.target.id === 'email-form') {
ev.preventDefault();
const f = ev.target;
if (!f.reportValidity()) return;
const body = {
host: f.host.value.trim(),
port: Number(f.port.value),
security: f.security.value,
username: f.username.value.trim(),
fromName: f.fromName.value.trim(),
fromAddress: f.fromAddress.value.trim(),
panelUrl: f.panelUrl.value.trim(),
};
if (f.clearPassword?.checked) body.password = '';
else if (f.password.value) body.password = f.password.value;
try {
st.email = await api('/api/admin/settings/email', { method: 'PUT', body });
toast('Email settings saved');
renderSettings();
} catch (err) { fail(err); }
}
if (ev.target.id === 'backup-settings') {
ev.preventDefault();
const f = ev.target;
if (!f.reportValidity()) return;
try {
st.backups.settings = await api('/api/admin/settings/backups', {
method: 'PUT',
body: {
enabled: f.enabled.checked, storage: f.storage.value, maxPerServer: Number(f.maxPerServer.value),
schedules: f.schedules.checked, keepAfterDelete: f.keepAfterDelete.checked,
},
});
toast(st.backups.settings.enabled ? 'Backups are on for customers' : 'Backup settings saved');
renderSettings();
} catch (err) { fail(err); }
return;
}
if (ev.target.id === 'expiry-settings') {
ev.preventDefault();
const f = ev.target;
if (!f.reportValidity()) return;
try {
st.expiry = await api('/api/admin/settings/expiry', {
method: 'PUT',
body: {
reminderDays: f.reminderDays.value.split(/[ ,]+/).filter(Boolean).map(Number),
graceDays: Number(f.graceDays.value),
selfExtendDays: Number(f.selfExtendDays.value),
pauseDeletions: f.pauseDeletions.checked,
adminSummary: f.adminSummary.checked,
},
});
toast('Expiry settings saved');
renderSettings();
} catch (err) { fail(err); }
return;
}
if (ev.target.id === 'email-test') {
ev.preventDefault();
const f = ev.target;
if (!f.reportValidity()) return;
const b = f.querySelector('button');
b.disabled = true;
b.textContent = 'Sending…';
try {
await api('/api/admin/settings/email/test', { method: 'POST', body: { to: f.to.value.trim() } });
toast(`Test email sent to ${f.to.value.trim()}`);
} catch (err) { fail(err); }
b.disabled = false;
b.textContent = 'Send test email';
}
});
// ---- setup check ----------------------------------------------------------
const CHECK_MARK = { ok: '✓', warn: '!', error: '✕', info: 'i', skipped: '–' };
const CHECK_WORD = { ok: 'OK', warn: 'Warning', error: 'Error', info: 'Note', skipped: 'Not checked' };
function setupProblemCount(result) {
return result ? (result.summary.error ?? 0) + (result.summary.warn ?? 0) : 0;
}
function updateSetupBadge(result) {
st.setupProblems = setupProblemCount(result);
const tab = root.querySelector('[data-admin-tab="setup"]');
if (!tab) return;
tab.querySelector('.tab-count')?.remove();
if (st.setupProblems) tab.insertAdjacentHTML('beforeend', ` <span class="tab-count" title="Problems found">${st.setupProblems}</span>`);
}
async function runSetupCheck() {
st.setupRunning = true;
if (st.tab === 'setup') renderSetupCheck();
try {
st.setup = await api('/api/admin/setup-check/run', { method: 'POST' });
updateSetupBadge(st.setup.result);
} catch (err) {
fail(err);
} finally {
st.setupRunning = false;
if (st.tab === 'setup') renderSetupCheck();
}
}
function renderSetupCheck() {
const body = root.querySelector('#admin-body');
const data = st.setup ?? {};
const r = data.result;
if (!r) {
body.innerHTML = `<div class="setup-check"><p class="muted">${st.setupRunning
? '<span class="spinner"></span> Checking Proxmox and the panel\'s configuration… this takes a few seconds.'
: 'No check has run yet.'}</p></div>`;
return;
}
const s = r.summary;
const onlyProblems = !!st.setupOnlyProblems;
const shown = r.checks.filter((c) => !onlyProblems || ['error', 'warn', 'skipped'].includes(c.status));
const fix = (f) => (f ? `
<details class="check-fix">
<summary>How to fix</summary>
${f.text ? `<p>${esc(f.text)}</p>` : ''}
${(f.commands ?? []).map((cmd) => `
<div class="cmd"><code>${esc(cmd)}</code><button type="button" class="btn ghost cmd-copy" data-copy="${esc(cmd)}" title="Copy">Copy</button></div>`).join('')}
</details>` : '');
const groups = data.groups.map(([id, label]) => {
const items = shown.filter((c) => c.group === id);
if (!items.length) return '';
return `
<section class="check-group">
<h2 class="check-group-title">${esc(label)}</h2>
<ul class="check-list">
${items.map((c) => `
<li class="check-item status-${c.status}" data-check="${esc(c.id)}">
<span class="check-mark" aria-label="${CHECK_WORD[c.status]}" title="${CHECK_WORD[c.status]}">${CHECK_MARK[c.status]}</span>
<div class="check-body">
<p class="check-title">${esc(c.title)}</p>
${c.detail ? `<p class="check-detail">${esc(c.detail)}</p>` : ''}
${['ok'].includes(c.status) ? '' : fix(c.fix)}
</div>
</li>`).join('')}
</ul>
</section>`;
}).join('');
const problems = s.error + s.warn;
body.innerHTML = `
<div class="setup-check">
<div class="section-head setup-head">
<div>
<p class="setup-verdict ${s.error ? 'bad' : s.warn ? 'meh' : 'good'}">${s.error
? `${s.error} error${s.error > 1 ? 's' : ''}${s.warn ? ` and ${s.warn} warning${s.warn > 1 ? 's' : ''}` : ''} need your attention`
: s.warn ? `${s.warn} warning${s.warn > 1 ? 's' : ''}, no errors` : 'Everything checked is set up correctly'}</p>
<p class="muted small" style="margin:4px 0 0">Checked ${esc(new Date(r.at).toLocaleString())}${r.automatic ? ' (automatic)' : ''},
${(r.durationMs / 1000).toFixed(1)} s · ${s.ok} OK${s.info ? ` · ${s.info} note${s.info > 1 ? 's' : ''}` : ''}${s.skipped ? ` · ${s.skipped} not checked` : ''}</p>
</div>
<button class="btn primary" data-setup-run ${st.setupRunning ? 'disabled' : ''}>${st.setupRunning ? '<span class="spinner"></span> Checking…' : 'Run again'}</button>
</div>
<div class="row setup-options">
<label class="check"><input type="checkbox" data-setup-only ${onlyProblems ? 'checked' : ''}><span>Show only problems</span></label>
<label class="check"><input type="checkbox" data-setup-notify ${data.settings?.notify ? 'checked' : ''}>
<span>Email administrators about new problems <span class="muted">(automatic check every day; needs email under Settings)</span></span></label>
</div>
${onlyProblems && !problems && !s.skipped ? '<p class="muted">No problems found.</p>' : groups}
<p class="muted small">The setup check only reads: it never changes anything in Proxmox. Commands under
“How to fix” are run by you on a Proxmox node (or the panel host).</p>
</div>`;
}
// ---- about --------------------------------------------------------------
function renderAbout() {
const a = st.about;
const u = a.update ?? {};
const date = (d) => (d ? new Date(d).toLocaleString() : '–');
const uptime = (sec) => {
const d = Math.floor(sec / 86400), h = Math.floor((sec % 86400) / 3600), m = Math.floor((sec % 3600) / 60);
return d ? `${d} d ${h} h` : h ? `${h} h ${m} min` : `${m} min`;
};
const ext = (href, text) => `<a href="${esc(href)}" target="_blank" rel="noopener noreferrer">${text}</a>`;
const status = !u.checked
? `<div class="notice about-notice"><p><strong>Couldn't check for updates.</strong> ${esc(u.reason ?? '')}</p></div>`
: u.updateAvailable
? `<div class="notice warn about-notice">
<p><strong>Version ${esc(u.latest.version)} is available</strong>${u.latest.publishedAt ? `, released ${esc(new Date(u.latest.publishedAt).toLocaleDateString())}` : ''}.
${ext(u.latest.url, "See what's new")}.</p>
</div>`
: u.latest
? `<div class="notice about-notice ok"><p><strong>You're running the latest release.</strong></p></div>`
: `<div class="notice about-notice"><p>${esc(u.reason ?? 'No releases published yet.')}</p></div>`;
root.querySelector('#admin-body').innerHTML = `
<div class="about">
<div class="about-head">
<span class="about-version">v${esc(a.version)}</span>
<span class="pill ${a.isRelease ? 'pill-running' : 'pill-busy'}">${a.isRelease ? 'Release' : 'Development build'}</span>
</div>
${status}
<dl class="specs cols-3">
<div><dt>Version</dt><dd class="mono">${a.releaseUrl && a.isRelease ? ext(a.releaseUrl, esc(a.version)) : esc(a.version)}</dd></div>
<div><dt>Commit</dt><dd class="mono">${a.commit ? (a.commitUrl ? ext(a.commitUrl, esc(a.commit.slice(0, 7))) : esc(a.commit.slice(0, 7))) : '–'}</dd></div>
<div><dt>Built</dt><dd>${esc(date(a.buildDate))}</dd></div>
<div><dt>Running since</dt><dd>${esc(date(a.startedAt))} <span class="muted small">(${esc(uptime(a.uptimeSeconds))})</span></dd></div>
<div><dt>Node.js</dt><dd class="mono">${esc(a.node)}</dd></div>
<div><dt>Source</dt><dd>${a.repoUrl ? ext(a.repoUrl, esc(a.repoUrl.replace(/^https:\/\//, ''))) : '–'}</dd></div>
</dl>
<div class="row">
<button class="btn" data-check-updates>Check for updates now</button>
${u.checkedAt ? `<span class="muted small">Last checked ${esc(date(u.checkedAt))}</span>` : ''}
</div>
<h2 class="h2">How to update</h2>
<ol class="about-steps">
<li><strong>Portainer:</strong> Stacks, your stack, <em>Update the stack</em> with
<em>Re-pull image and redeploy</em> switched on.</li>
<li><strong>UGREEN Docker app:</strong> Project, your project, redeploy it (it pulls the image again).</li>
<li><strong>Command line:</strong> <span class="mono">docker compose pull && docker compose up -d</span></li>
</ol>
<p class="muted small">If you pinned a release in <span class="mono">PANEL_IMAGE</span>, change the version
there first. Your data stays in the volume; database changes are applied automatically at start.</p>
</div>`;
}
// ---- activity ---------------------------------------------------------
function renderActivity() {
root.querySelector('#admin-body').innerHTML = `
<div class="section-head">
<p class="muted" style="margin:0">The last ${st.audit.length} events, newest first.</p>
<button class="btn" data-refresh-audit>Refresh</button>
</div>
<div class="table-wrap">
<table class="table">
<thead><tr><th>Time</th><th>Who</th><th>What</th><th>Server</th><th>IP address</th></tr></thead>
<tbody>
${st.audit.map((a) => {
let detail = '';
try {
const d = a.detail ? JSON.parse(a.detail) : null;
if (d?.email && (a.action.startsWith('admin_') || a.action.endsWith('login_failed'))) detail = d.email;
if (d?.hostname) detail = d.hostname;
if (d?.label && a.action.startsWith('admin_template')) detail = d.label;
if (d?.error) detail = d.error;
if (d?.reason && a.action.includes('sso')) detail = d.reason;
if (d?.passkey) detail = d.reason ? `passkey: ${d.reason}` : 'with a passkey';
} catch { /* ignore */ }
return `
<tr class="${a.action.endsWith('login_failed') || a.action.endsWith('_failed') ? 'row-warn' : ''}">
<td class="nowrap">${utc(a.createdAt).toLocaleString()}</td>
<td>${esc(a.email ?? '–')}</td>
<td>${esc(ACTION_LABELS[a.action] ?? a.action)}${detail ? ` <span class="muted">${esc(detail)}</span>` : ''}</td>
<td class="mono">${a.vmid ?? ''}</td>
<td class="mono muted">${esc(a.ip ?? '')}</td>
</tr>`;
}).join('')}
</tbody>
</table>
</div>`;
}
// ---- events (bound once) ----------------------------------------------
root.addEventListener('click', async (e) => {
const t = e.target.closest('button');
if (!t) return;
if (t.dataset.adminTab) {
st.tab = t.dataset.adminTab;
st.newUser = null;
render();
load();
return;
}
if (t.hasAttribute('data-resend-invite')) {
const u = st.users.find((x) => x.id === Number(t.closest('[data-user]').dataset.user));
t.disabled = true;
try {
await api(`/api/admin/users/${u.id}/invite`, { method: 'POST' });
toast(`Invitation sent to ${u.email}. Earlier links no longer work.`);
st.users = await api('/api/admin/users');
renderUsers();
} catch (err) { fail(err); t.disabled = false; }
return;
}
if (t.hasAttribute('data-generate')) {
const form = t.closest('form');
const pw = generatePassword();
form.password.value = pw;
form.password.type = 'text';
form.dataset.generated = pw;
return;
}
if (t.hasAttribute('data-copy-password')) {
await navigator.clipboard?.writeText(st.newUser.password)
.then(() => toast('Password copied'))
.catch(() => toast('Copy failed. Select the password and copy it manually.', 'error'));
return;
}
if (t.hasAttribute('data-dismiss-note')) {
st.newUser = null;
renderUsers();
return;
}
if (t.dataset.showServers) {
st.tab = 'servers';
st.filter = t.dataset.showServers;
render();
load();
return;
}
if (t.hasAttribute('data-refresh-audit')) {
load();
return;
}
if (t.dataset.schemePick) {
// live preview on this page; Save applies it for everyone
st.schemePreview = t.dataset.schemePick;
document.documentElement.dataset.scheme = st.schemePreview;
root.querySelectorAll('[data-scheme-pick]').forEach((b) => b.setAttribute('aria-checked', String(b === t)));
const changed = st.schemePreview !== st.appearance.scheme;
root.querySelector('[data-scheme-save]').disabled = !changed;
root.querySelector('[data-scheme-cancel]').hidden = !changed;
root.querySelector('#scheme-note').textContent = changed ? 'Preview on this page only. Save to apply it everywhere.' : '';
return;
}
if (t.hasAttribute('data-scheme-cancel')) {
st.schemePreview = null;
applyScheme(st.appearance.scheme);
renderSettings();
return;
}
if (t.hasAttribute('data-scheme-save')) {
try {
st.appearance = await api('/api/admin/settings/appearance', { method: 'PUT', body: { scheme: st.schemePreview } });
applyScheme(st.appearance.scheme);
st.schemePreview = null;
const name = st.appearance.schemes.find((x) => x.id === st.appearance.scheme)?.name;
toast(`Color scheme “${name}” is now used everywhere. Open pages pick it up when they reload.`);
renderSettings();
} catch (err) { fail(err); }
return;
}
if (t.hasAttribute('data-expiry-run')) {
t.disabled = true;
try {
const r = await api('/api/admin/expiry/run', { method: 'POST' });
const parts = [['stopped', r.stopped], ['deleted', r.deleted], ['reminded', r.reminded], ['waiting for your decision', r.awaitingAdmin],
['deletion paused', r.paused], ['not deleted (no email)', r.blocked]].filter(([, l]) => l?.length).map(([k, l]) => `${l.length} ${k}`);
root.querySelector('#expiry-result').textContent = parts.length ? `Done: ${parts.join(', ')}.` : 'Done: nothing to do.';
if (r.errors?.length) toast(r.errors.join(' '), 'error');
} catch (err) { fail(err); }
t.disabled = false;
return;
}
if (t.hasAttribute('data-email-remove')) {
if (!(await confirmAction('Remove the email settings? Invitations can no longer be sent until email is set up again.', 'Remove'))) return;
try {
await api('/api/admin/settings/email', { method: 'DELETE' });
st.email = await api('/api/admin/settings/email');
toast('Email settings removed');
renderSettings();
} catch (err) { fail(err); }
return;
}
if (t.hasAttribute('data-setup-run')) {
await runSetupCheck();
return;
}
if (t.dataset.copy !== undefined && t.classList.contains('cmd-copy')) {
try {
await navigator.clipboard.writeText(t.dataset.copy);
toast('Copied');
} catch {
// no clipboard (plain http): select the command so Ctrl+C works
const range = document.createRange();
range.selectNodeContents(t.previousElementSibling);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
return;
}
if (t.hasAttribute('data-check-updates')) {
st.refreshAbout = true;
t.disabled = true;
t.textContent = 'Checking…';
load({ quiet: true });
return;
}
if (t.hasAttribute('data-vpn-sync')) {
try {
await api('/api/admin/vpn/sync', { method: 'POST' });
toast('VPN configuration re-applied on the gateway');
} catch (err) { fail(err); }
load();
return;
}
if (t.dataset.vpnRemove) {
if (!(await confirmAction(`Remove VPN device “${t.dataset.name}”? It can no longer connect.`, 'Remove'))) return;
try {
await api(`/api/admin/vpn/devices/${t.dataset.vpnRemove}`, { method: 'DELETE' });
toast(`${t.dataset.name} removed`);
} catch (err) { fail(err); }
load();
return;
}
if (t.dataset.serverAction) {
const vm = st.vms.find((x) => x.vmid === Number(t.closest('tr').dataset.vmid));
if (vm) serverAction(vm, t.dataset.serverAction);
return;
}
if (t.hasAttribute('data-save-template')) {
saveTemplate(t.closest('tr'));
return;
}
if (t.hasAttribute('data-save-ct')) {
saveContainer(t.closest('tr'));
return;
}
if (t.dataset.ctWithdraw) {
try {
await api(`/api/admin/ct-templates/${t.dataset.ctWithdraw}`, { method: 'DELETE' });
toast('Withdrawn');
load();
} catch (err) { fail(err); }
return;
}
const userRow = t.closest('[data-user]');
if (!userRow) return;
const user = st.users.find((u) => u.id === Number(userRow.dataset.user));
if (t.hasAttribute('data-twofa')) {
editTwoFactor(user);
return;
}
if (t.hasAttribute('data-limits')) {
if (await editLimits(user)) {
st.users = await api('/api/admin/users');
renderUsers();
}
return;
}
if (t.hasAttribute('data-reset')) {
const password = await promptText(`New password for ${user.email}`, {
value: generatePassword(),
hint: 'At least 12 characters. A random password is filled in; copy it before saving.',
okLabel: 'Reset password',
minLength: 12,
});
if (!password) return;
try {
await api(`/api/admin/users/${user.id}`, { method: 'PATCH', body: { password } });
toast(`Password reset for ${user.email}`);
} catch (err) { fail(err); }
}
if (t.hasAttribute('data-toggle-admin')) {
const makeAdmin = !user.isAdmin;
const ok = await confirmAction(
makeAdmin
? `Make ${user.email} an administrator? They will be able to see and manage all customers and servers.`
: `Remove administrator rights from ${user.email}?`,
makeAdmin ? 'Make admin' : 'Remove admin'
);
if (!ok) return;
try {
await api(`/api/admin/users/${user.id}`, { method: 'PATCH', body: { isAdmin: makeAdmin } });
user.isAdmin = makeAdmin;
toast(makeAdmin ? `${user.email} is now an administrator` : `${user.email} is now a customer`);
renderUsers();
} catch (err) { fail(err); }
}
if (t.hasAttribute('data-delete-user')) {
deleteCustomer(user);
}
});
root.addEventListener('change', async (e) => {
if (e.target.matches?.('[data-setup-only]')) {
st.setupOnlyProblems = e.target.checked;
renderSetupCheck();
return;
}
if (e.target.matches?.('[data-setup-notify]')) {
const box = e.target;
try {
st.setup.settings = await api('/api/admin/setup-check/settings', { method: 'PUT', body: { notify: box.checked } });
toast(box.checked ? 'Administrators get an email when the daily check finds new problems' : 'No more setup check emails');
} catch (err) { fail(err); box.checked = !box.checked; }
return;
}
if (e.target.matches?.('[data-winupdates]')) {
const box = e.target;
try {
st.winupdates = await api('/api/admin/settings/winupdates', { method: 'PUT', body: { enabled: box.checked } });
toast(st.winupdates.enabled ? 'Customers can install Windows updates' : 'Windows updates through the panel are switched off');
} catch (err) { fail(err); box.checked = !box.checked; }
return;
}
if (e.target.name === 'invite' && e.target.closest('#user-form')) {
const form = e.target.closest('#user-form');
const on = e.target.checked;
form.querySelector('#pw-field').hidden = on;
form.password.required = !on;
form.password.disabled = on;
return;
}
const row = e.target.closest('tr[data-vmid]');
if (row && (e.target.matches('[data-owner]') || e.target.matches('[data-label]'))) saveAssignment(row);
});
root.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && e.target.matches('[data-label]')) e.target.blur(); // blur fires "change"
});
root.addEventListener('input', (e) => {
if (e.target.id === 'vm-filter') {
st.filter = e.target.value;
renderServerRows();
}
});
root.addEventListener('submit', (e) => {
if (e.target.id !== 'user-form') return;
e.preventDefault();
createUser(e.target);
});
return {
open() {
render();
load();
api('/api/admin/setup-check').then((d) => updateSetupBadge(d.result)).catch(() => {});
},
openTab(tab) {
st.tab = tab;
render();
load();
},
};
}