Files
2026-11-30 16:32:37 +00:00

2728 lines
107 KiB
JavaScript

if (typeof globalThis === "undefined") window.globalThis = window;
// White-label brand name (set inline in page <head> via window.__BRANDING__); idempotent across scripts.
window.__brandName = window.__brandName || (window.__BRANDING__ && window.__BRANDING__.appName) || "ADPanel";
window.addEventListener("securitypolicyviolation", (e) => {
console.log("[CSP]", e.violatedDirective, "blocked:", e.blockedURI, "sample:", e.sample);
});
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, function (m) {
return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[m]);
});
}
// The single uptime formatter for dashboard cards, shared by the live
// resources:data handler and the infinite-scroll builder. Mirrors the
// server-side formatter in views/index.ejs (bot-card__uptime-value):
// seconds → "1d 2h 3m", with the same em-dash placeholder for absent or
// invalid values, so first paint, live updates and infinite-scroll cards
// all render one consistent format.
function formatUptimeShort(seconds) {
const n = Number(seconds);
if (!Number.isFinite(n) || n <= 0) return '—';
const days = Math.floor(n / 86400);
const hours = Math.floor((n % 86400) / 3600);
const minutes = Math.floor((n % 3600) / 60);
const parts = [];
if (days > 0) parts.push(`${days}d`);
if (hours > 0) parts.push(`${hours}h`);
if (minutes > 0 || parts.length === 0) parts.push(`${minutes}m`);
return parts.join(' ');
}
const PANEL_EWS_ICON_SIZE = "1.6rem";
function ensurePanelEwsSvgStyles() {
if (document.getElementById("panel-ews-svg-styles")) return;
const style = document.createElement("style");
style.id = "panel-ews-svg-styles";
style.textContent = `
.panel-ews-svg {
width: ${PANEL_EWS_ICON_SIZE};
height: ${PANEL_EWS_ICON_SIZE};
display: block;
flex: 0 0 auto;
}
`;
// style-src is nonce-gated: copy the nonce from an existing nonced element via the
// .nonce IDL property (CSS attribute selectors cannot see nonce attributes) before append.
for (const el of document.head.querySelectorAll("style, script")) {
if (el.nonce) { style.nonce = el.nonce; break; }
}
document.head.appendChild(style);
}
function createPanelEwsSvg() {
const template = document.createElement("template");
template.innerHTML = `
<svg class="panel-ews-svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
<rect x="5" y="5" width="54" height="54" rx="7" fill="#232C67"></rect>
<rect x="13" y="12" width="14" height="22" rx="4.5" fill="#FFFFFF"></rect>
<path d="M18 30H24V43C24 49.6274 18.6274 55 12 55H5V49H12C15.3137 49 18 46.3137 18 43V30Z" fill="#FFFFFF"></path>
<rect x="35" y="12" width="16" height="5" rx="2.5" fill="#FFFFFF"></rect>
<rect x="35" y="22" width="16" height="5" rx="2.5" fill="#FFFFFF"></rect>
<rect x="35" y="32" width="16" height="15" rx="4.5" fill="#FFFFFF"></rect>
</svg>
`.trim();
return template.content.firstElementChild;
}
function replaceLegacyPanelEwsIcons(root = document) {
ensurePanelEwsSvgStyles();
root.querySelectorAll("i.fa-panel-ews").forEach((icon) => {
const svg = createPanelEwsSvg();
const inlineStyle = icon.getAttribute("style");
if (inlineStyle) svg.setAttribute("style", `${inlineStyle};width:${PANEL_EWS_ICON_SIZE};height:${PANEL_EWS_ICON_SIZE};display:block;`);
icon.replaceWith(svg);
});
}
window.addEventListener('DOMContentLoaded', () => {
replaceLegacyPanelEwsIcons();
const splash = document.getElementById('splash-screen');
if (splash && splash.isConnected) splash.remove();
document.querySelectorAll('[data-scroll-target]').forEach(button => {
button.addEventListener('click', () => {
const targetId = button.getAttribute('data-scroll-target');
const section = document.getElementById(targetId);
if (section) section.scrollIntoView({ behavior: 'smooth' });
});
});
document.querySelectorAll('.bot-card').forEach(card => {
const nodeOffline = card.classList.contains('node-offline');
card.classList.toggle('is-offline', nodeOffline);
});
function updateNodeOfflineStatus(name, nodeOnline) {
if (!name) return;
const cards = document.querySelectorAll(`.bot-card[data-name="${String(name).toLowerCase()}"]`);
cards.forEach(card => {
if (nodeOnline) {
card.classList.remove('node-offline', 'is-offline');
} else {
card.classList.add('node-offline', 'is-offline');
}
});
}
window.updateNodeOfflineStatus = updateNodeOfflineStatus;
function formatBytes(mb) {
if (mb === null || mb === undefined) return null;
if (mb === 0) return '0 MB';
if (mb >= 1024) return `${(mb / 1024).toFixed(1)} GB`;
return `${Math.round(mb)} MB`;
}
function formatResourceLabel(usedMb, limitMb) {
const used = formatBytes(usedMb);
// A genuine zero reading is a real value: show "0 MB" instead of N/A
// whether or not a limit is known.
if (usedMb > 0) return used || '0 MB';
return '0 MB';
}
function updateCardFromResourceData(data) {
if (!data || !data.server) return;
const name = data.server.toLowerCase();
const card = document.querySelector(`.bot-card[data-name="${name}"]`);
if (!card) return;
const status = data.status;
if (status) {
const isOnline = status === 'running' || status === 'online';
const isStopped = status === 'stopped' || status === 'exited';
// An unrecognized status ('unknown', 'installing', ...) carries no
// authoritative container state, so it must not rewrite the card:
// node-outage pushes arrive with status 'unknown' (already surfaced by
// the offline overlay below), and rewriting only some prior states to
// status-unknown would make the same event change cards differently
// depending on their previous class.
if (isOnline || isStopped) {
card.classList.remove('status-online', 'status-stopped', 'status-unknown');
const statusEl = card.querySelector('.bot-card__status');
if (statusEl) statusEl.classList.remove('status-online', 'status-stopped', 'status-unknown');
if (isOnline) {
card.classList.add('status-online');
if (statusEl) statusEl.classList.add('status-online');
} else {
card.classList.add('status-stopped');
if (statusEl) statusEl.classList.add('status-stopped');
}
}
}
// Reflect BOTH transitions: show the "Can't establish connection" overlay
// the moment the panel reports the node as unreachable, and hide it when
// the node comes back. Previously only nodeOnline === true was handled, so
// cards kept stale RAM/disk metrics while the node was down.
if (typeof window.updateNodeOfflineStatus === 'function') {
if (data.nodeOnline === false || (data.ok === false && data.nodeOnline !== true)) {
window.updateNodeOfflineStatus(data.server, false);
return;
} else if (data.nodeOnline === true) {
window.updateNodeOfflineStatus(data.server, true);
}
}
if (data.nodeOnline === false) return;
if (data.memory != null) {
let usedMb = 0, limitMb = 0, pct = 0;
if (typeof data.memory === 'object') {
usedMb = data.memory.used || 0;
limitMb = data.memory.total || 0;
pct = data.memory.percent ?? (limitMb > 0 ? Math.min(100, Math.round((usedMb / limitMb) * 100)) : 0);
} else {
usedMb = data.memory; limitMb = 0; pct = 0;
}
const memLabel = card.querySelector('.bot-card__stat-icon--memory')?.closest('.bot-card__stat')?.querySelector('.bot-card__stat-chip span');
const memProgress = card.querySelector('.bot-card__stat-icon--memory')?.closest('.bot-card__stat')?.querySelector('.bot-card__progress span');
if (memLabel) memLabel.textContent = formatResourceLabel(usedMb, limitMb);
if (memProgress) { memProgress.style.width = `${Math.min(100, Math.max(0, pct))}%`; }
}
if (data.disk != null) {
let usedMb = 0, limitMb = 0, pct = 0;
if (typeof data.disk === 'object') {
usedMb = (data.disk.used || 0) * 1024;
limitMb = (data.disk.total || 0) * 1024;
pct = data.disk.percent ?? (limitMb > 0 ? Math.min(100, Math.round((usedMb / limitMb) * 100)) : 0);
} else {
usedMb = data.disk; limitMb = 0; pct = 0;
}
const diskLabel = card.querySelector('.bot-card__stat-icon--disk')?.closest('.bot-card__stat')?.querySelector('.bot-card__stat-chip span');
const diskProgress = card.querySelector('.bot-card__stat-icon--disk')?.closest('.bot-card__stat')?.querySelector('.bot-card__progress span');
if (diskLabel) diskLabel.textContent = formatResourceLabel(usedMb, limitMb);
if (diskProgress) { diskProgress.style.width = `${Math.min(100, Math.max(0, pct))}%`; }
}
if (data.cpu != null) {
const cpuMax = data.cpuLimit || 100;
const cpuPct = Math.min(cpuMax, Math.max(0, data.cpu || 0));
const cpuBarWidth = cpuMax > 0 ? Math.min(100, (cpuPct / cpuMax) * 100) : 0;
const cpuLabel = card.querySelector('.bot-card__stat-icon--cpu')?.closest('.bot-card__stat')?.querySelector('.bot-card__stat-chip span');
const cpuProgress = card.querySelector('.bot-card__stat-icon--cpu')?.closest('.bot-card__stat')?.querySelector('.bot-card__progress span');
// cpuPct is always finite (NaN collapses to 0 via `data.cpu || 0`, then
// clamped), so an idle server shows 0.0% rather than N/A.
if (cpuLabel) cpuLabel.textContent = `${cpuPct.toFixed(1)}%`;
if (cpuProgress) cpuProgress.style.width = `${cpuBarWidth}%`;
}
if (data.status) {
const isOnline = data.status === 'running' || data.status === 'online';
const uptimeWrapper = card.querySelector('.bot-card__uptime-wrapper');
if (uptimeWrapper) {
uptimeWrapper.style.display = isOnline ? 'flex' : 'none';
}
}
if (data.uptime !== undefined) {
const uptimeLabel = card.querySelector('.bot-card__uptime-value');
if (uptimeLabel) {
uptimeLabel.textContent = formatUptimeShort(data.uptime);
}
}
}
let _dashResourceSocket = null;
let _dashResourceSubscribed = false;
window._dashResourceSocket = null;
function getDashboardServerNames() {
return Array.from(document.querySelectorAll('[data-bot-card]'))
.map(c => c.dataset.name)
.filter(Boolean);
}
function subscribeDashboardResources(socket) {
if (!socket || !socket.connected) return;
const names = getDashboardServerNames();
if (!names.length) return;
// The server caps resources:subscribe-bulk at 100 names per call
// (slice(0, 100)), and this list grows with infinite scroll — chunk so
// servers past the cap are not silently dropped from resource updates.
for (let i = 0; i < names.length; i += 100) {
socket.emit('resources:subscribe-bulk', { servers: names.slice(i, i + 100) });
}
_dashResourceSubscribed = true;
}
function unsubscribeDashboardResources(socket) {
if (!socket) return;
socket.emit('resources:unsubscribe-all');
_dashResourceSubscribed = false;
}
function initDashboardResourceSocket() {
if (!window.io) return;
const socket = window.io({
transports: ['websocket'],
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000
});
_dashResourceSocket = socket;
window._dashResourceSocket = socket;
socket.on('connect', () => {
if (document.visibilityState !== 'hidden') {
subscribeDashboardResources(socket);
}
});
socket.on('disconnect', () => {
_dashResourceSubscribed = false;
});
socket.on('resources:data', updateCardFromResourceData);
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
unsubscribeDashboardResources(socket);
} else {
subscribeDashboardResources(socket);
}
});
// Use 'pagehide' instead of 'beforeunload' so the page stays eligible for
// the browser back/forward cache (bfcache), enabling instant back navigation.
window.addEventListener('pagehide', () => {
unsubscribeDashboardResources(socket);
});
}
initDashboardResourceSocket();
// Bridge for code outside this DOMContentLoaded closure (the infinite
// scroll loader) that must reach the shared resource socket: the
// resources:data listener lives on this socket only, so resource room
// joins for dynamically added cards have to go through it.
window.__dashResourceBridge = {
isActive: () => _dashResourceSubscribed,
subscribe(names) {
if (!_dashResourceSocket) return;
const list = (Array.isArray(names) ? names : [])
.map(n => String(n || '').trim())
.filter(Boolean);
if (!list.length) return;
// Server caps resources:subscribe-bulk at 100 names per call.
for (let i = 0; i < list.length; i += 100) {
_dashResourceSocket.emit('resources:subscribe-bulk', { servers: list.slice(i, i + 100) });
}
}
};
document.querySelectorAll('[data-href]').forEach(el => {
el.addEventListener('click', (event) => {
// If the click is inside a pin button, ignore this click handler to allow pin toggling
if (event.target.closest('.bot-card__pin-btn')) {
return;
}
event.preventDefault();
event.stopPropagation();
const href = el.getAttribute('data-href');
if (!href) return;
const target = el.getAttribute('data-target');
if (target === '_blank') {
window.open(href, '_blank', 'noopener,noreferrer');
} else {
window.location.href = href;
}
});
});
document.querySelectorAll('[data-bot-card]').forEach(card => {
const cover = card.dataset.cover;
if (cover) card.style.setProperty('--bot-cover', `url("${cover.replace(/"/g, '\\"')}")`);
});
document.querySelectorAll('.bot-card__progress span[data-pct]').forEach(span => {
span.style.width = (span.dataset.pct || '0') + '%';
});
const searchInput = document.getElementById('searchBots');
const botGrid = document.querySelector('[data-bot-grid]');
const emptyStateTemplate = document.getElementById('empty-state');
const dashPagination = document.getElementById('dashPagination');
function navigateDashboard(page, search) {
const params = new URLSearchParams();
if (page && page > 1) params.set('page', String(page));
if (search) params.set('search', search);
const qs = params.toString();
window.location.href = '/' + (qs ? '?' + qs : '');
}
function updateBotVisibility() {
if (dashPagination) {
clearTimeout(_searchTimer);
_searchTimer = setTimeout(() => navigateDashboard(1, (searchInput?.value || '').trim()), 500);
return;
}
if (!botGrid) return;
const term = (searchInput?.value || '').trim().toLowerCase();
const botCards = Array.from(botGrid.querySelectorAll('[data-bot-card]'));
let visible = 0;
botCards.forEach(card => {
const name = card.getAttribute('data-name') || '';
const displayName = card.getAttribute('data-display-name') || '';
// Match on name OR displayName so the client-side filter behaves like the
// server-side search in GET / (and GET /api/dashboard/servers).
const match = !term || name.includes(term) || displayName.includes(term);
card.classList.toggle('is-hidden', !match);
if (match) visible++;
});
const existing = botGrid.querySelector('.empty-state');
if (visible === 0) {
if (!existing) {
const clone = emptyStateTemplate.content.cloneNode(true);
botGrid.appendChild(clone);
}
} else if (existing) existing.remove();
}
let _searchTimer;
searchInput?.addEventListener('input', () => {
clearTimeout(_searchTimer);
_searchTimer = setTimeout(updateBotVisibility, dashPagination ? 500 : 150);
});
if (botGrid && !dashPagination) updateBotVisibility();
if (searchInput) {
const searchField = searchInput.closest('.nav-search-field');
if (searchField) {
searchInput.addEventListener('focus', () => {
searchField.classList.add('active');
});
searchInput.addEventListener('blur', () => {
searchField.classList.remove('active');
});
document.addEventListener('click', (e) => {
if (!searchField.contains(e.target) && document.activeElement === searchInput) {
searchInput.blur();
}
});
}
}
const urlParams = new URLSearchParams(window.location.search);
if (searchInput && urlParams.get('search')) {
searchInput.value = urlParams.get('search');
}
if (dashPagination) {
dashPagination.querySelectorAll('button[data-dash-page]').forEach(btn => {
btn.addEventListener('click', () => {
const p = parseInt(btn.dataset.dashPage, 10);
if (p >= 1) navigateDashboard(p, (searchInput?.value || '').trim());
});
});
}
const topBar = document.getElementById('topBar');
const spacer = document.getElementById('topbar-spacer');
const spacerExtraOffset = spacer ? parseInt(spacer.getAttribute('data-topbar-extra-offset') || '0', 10) || 0 : 0;
function measureExpandedHeight() {
const hadCompact = topBar.classList.contains('top-bar--compact');
topBar.classList.remove('top-bar--compact');
const h = Math.ceil(topBar.getBoundingClientRect().height);
if (hadCompact) topBar.classList.add('top-bar--compact');
return h;
}
function applySpacerHeight() {
if (!spacer) return;
spacer.style.height = Math.max(0, expandedHeight - spacerExtraOffset) + 'px';
}
let expandedHeight = measureExpandedHeight();
applySpacerHeight();
let resizeRAF = null;
window.addEventListener('resize', () => {
if (resizeRAF) cancelAnimationFrame(resizeRAF);
resizeRAF = requestAnimationFrame(() => {
expandedHeight = measureExpandedHeight();
applySpacerHeight();
});
});
new ResizeObserver(() => {
expandedHeight = measureExpandedHeight();
applySpacerHeight();
fitHero();
}).observe(topBar);
function fitHero() {
const hero = document.querySelector('.hero');
if (!hero) return;
hero.style.minHeight = '';
hero.style.marginBottom = '';
const rect = hero.getBoundingClientRect();
const scrollTop = window.scrollY || document.documentElement.scrollTop;
const absTop = rect.top + scrollTop;
const heroHeight = hero.offsetHeight;
const totalContentHeight = absTop + heroHeight;
const viewHeight = window.innerHeight;
const diff = viewHeight - totalContentHeight;
if (diff > 0) {
hero.style.marginBottom = `${diff + 32}px`;
}
}
window.addEventListener('resize', fitHero);
fitHero();
let lastY = window.scrollY || 0, ticking = false, pinnedTimeout = null;
function onScrollTick() {
const y = window.scrollY || 0, d = y - lastY;
if (y > 36) topBar.classList.add('top-bar--compact'); else topBar.classList.remove('top-bar--compact');
if (y <= 24) {
topBar.classList.remove('top-bar--hidden', 'top-bar--pinned');
lastY = y; ticking = false; return;
}
if (Math.abs(d) > 4) {
if (d > 0 && y > 120) {
topBar.classList.add('top-bar--hidden'); topBar.classList.remove('top-bar--pinned');
} else if (d < 0) {
topBar.classList.remove('top-bar--hidden'); topBar.classList.add('top-bar--pinned');
if (pinnedTimeout) clearTimeout(pinnedTimeout);
pinnedTimeout = setTimeout(() => topBar.classList.remove('top-bar--pinned'), 900);
}
}
lastY = y; ticking = false;
}
window.addEventListener('scroll', () => {
if (!ticking) {
requestAnimationFrame(onScrollTick);
ticking = true;
}
}, { passive: true });
if ((window.scrollY || 0) > 36) topBar.classList.add('top-bar--compact'); else topBar.classList.remove('top-bar--compact');
topBar.classList.remove('top-bar--hidden');
function deleteAllClientCookies() {
const cookies = document.cookie ? document.cookie.split('; ') : [];
for (const cookie of cookies) {
const eqPos = cookie.indexOf('=');
const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=${location.hostname}`;
const parts = location.hostname.split('.');
for (let i = 0; i < parts.length - 1; i++) {
const dom = '.' + parts.slice(i).join('.');
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=${dom}`;
}
}
}
// adpanel:logout-reliability — the server's verdict decides, not the click:
// logout is complete ONLY when the response is ok AND carries success ===
// true. On a 429 (throttled) or 500 (failed revocation) the server may
// still hold a LIVE session, so cookies stay and no redirect happens — the
// old unconditional delete+redirect presented a failed logout as success.
// Cookie deletion is cosmetic (HttpOnly auth cookies are server-cleared)
// and is deliberately moved AFTER the confirmed response. Errors surface
// through this file's existing alert idiom, preferring the server's error
// text (same fix as settings.js — one behavior, both frontends).
document.getElementById('logoutBtn')?.addEventListener('click', async (e) => {
e.preventDefault();
try {
const res = await fetch('/logout', { method: 'POST', credentials: 'include' });
let body = null;
try { body = await res.json(); } catch { body = null; }
if (res.ok && body && body.success === true) {
deleteAllClientCookies();
location.href = '/login';
return;
}
console.error('[logout] Refused:', res.status, body);
alert((body && body.error) || 'Failed to log out');
} catch {
alert('Failed to log out');
}
});
const accountBtn = document.getElementById('accountBtn');
const accountBackBtn = document.getElementById('accountBackBtn');
const accountPage = document.getElementById('accountPage');
const mainContent = document.getElementById('mainContent');
const footerEl = document.getElementById('upload');
const topBarEl = document.getElementById('topBar');
const topbarSpacerEl = document.getElementById('topbar-spacer');
const accountLoadErrorEl = document.getElementById('accountLoadError');
const accountLoadRetryBtn = document.getElementById('accountLoadRetry');
function showAccountLoadError() {
if (accountLoadErrorEl) accountLoadErrorEl.style.display = 'flex';
}
function hideAccountLoadError() {
if (accountLoadErrorEl) accountLoadErrorEl.style.display = 'none';
}
let accountLoadRetryInFlight = false;
if (accountLoadRetryBtn) {
accountLoadRetryBtn.addEventListener('click', async () => {
if (accountLoadRetryInFlight) return;
accountLoadRetryInFlight = true;
accountLoadRetryBtn.disabled = true;
try {
await loadAccountData();
} finally {
accountLoadRetryInFlight = false;
accountLoadRetryBtn.disabled = false;
}
});
}
async function showAccountPage() {
if (!accountPage) return;
if (window.location.hash !== '#account' && window.location.hash !== '#accounts') {
window.history.pushState(null, null, '#account');
}
document.body.classList.add('account-active');
if (mainContent) mainContent.style.setProperty('display', 'none', 'important');
if (footerEl) footerEl.style.setProperty('display', 'none', 'important');
accountPage.style.display = 'flex';
await loadAccountData();
window.scrollTo({ top: 0, behavior: 'smooth' });
}
// Degrade the remaining username-change lockout into the friendliest unit:
// days (matching the server's own 429 message) down to hours, then minutes,
// so a lock entered with only hours left does not read as "in 1 day".
function formatUsernameCooldown(ms) {
const hourMs = 60 * 60 * 1000;
if (ms >= 24 * hourMs) {
const days = Math.ceil(ms / (24 * hourMs));
return `You can change your username again in ${days} day${days !== 1 ? 's' : ''}`;
}
if (ms >= hourMs) {
const hours = Math.ceil(ms / hourMs);
return `You can change your username again in ${hours} hour${hours !== 1 ? 's' : ''}`;
}
const minutes = Math.max(1, Math.ceil(ms / (60 * 1000)));
return `You can change your username again in ${minutes} minute${minutes !== 1 ? 's' : ''}`;
}
function renderAccountData(data) {
const usernameEl = document.getElementById('accountUsername');
const usernameCredEl = document.getElementById('accountUsernameCred');
const emailEl = document.getElementById('accountEmail');
const emailCredEl = document.getElementById('accountEmailCred');
const usernameValEl = document.getElementById('accountUsernameValue');
const emailValEl = document.getElementById('accountEmailValue');
const roleValEl = document.getElementById('accountRoleValue');
const idValEl = document.getElementById('accountIdValue');
const avatarImgEl = document.getElementById('accountAvatarImg');
const avatarImgCredEl = document.getElementById('accountAvatarImgCred');
const statusTextEl = document.getElementById('accountStatusText');
const cooldownEl = document.getElementById('usernameCooldown');
if (usernameEl) usernameEl.textContent = data.username;
if (usernameCredEl) usernameCredEl.textContent = data.username;
if (emailEl) emailEl.textContent = data.email;
if (emailCredEl) emailCredEl.textContent = data.email;
if (usernameValEl) usernameValEl.textContent = data.username;
if (emailValEl) emailValEl.textContent = data.email;
if (roleValEl) roleValEl.textContent = data.isAdmin ? 'Administrator' : 'Standard User';
if (idValEl) idValEl.textContent = data.userId || 'N/A';
if (avatarImgEl && data.avatarUrl) avatarImgEl.src = data.avatarUrl;
if (avatarImgCredEl && data.avatarUrl) avatarImgCredEl.src = data.avatarUrl;
if (statusTextEl) statusTextEl.textContent = data.status || 'Available';
if (cooldownEl && data.usernameChangeCooldown) {
cooldownEl.textContent = formatUsernameCooldown(data.usernameChangeCooldown);
cooldownEl.style.display = 'block';
} else if (cooldownEl) {
cooldownEl.style.display = 'none';
}
}
async function loadAccountData() {
try {
const res = await fetch('/api/account', { credentials: 'include' });
if (!res.ok) throw new Error('Failed to load account');
const data = await res.json();
renderAccountData(data);
window._accountData = data;
syncAccountSecurityUi();
hideAccountLoadError();
return true;
} catch (err) {
console.error('[account] Failed to load:', err);
showAccountLoadError();
return false;
}
}
function hideAccountPage() {
if (!accountPage) return;
if (window.location.hash === '#account' || window.location.hash === '#accounts') {
history.pushState("", document.title, window.location.pathname + window.location.search);
}
document.body.classList.remove('account-active');
accountPage.style.display = 'none';
if (topBarEl) topBarEl.style.display = '';
if (topbarSpacerEl) topbarSpacerEl.style.display = '';
if (mainContent) mainContent.style.display = '';
if (footerEl) footerEl.style.display = '';
window.scrollTo({ top: 0, behavior: 'smooth' });
}
const avatarWrapper = document.getElementById('accountAvatarWrapper');
const avatarWrapperCred = document.getElementById('accountAvatarWrapperCred');
const avatarFileInput = document.getElementById('avatarFileInput');
avatarWrapper?.addEventListener('click', () => {
avatarFileInput?.click();
});
avatarWrapperCred?.addEventListener('click', () => {
avatarFileInput?.click();
});
let avatarUploadInFlight = false;
avatarFileInput?.addEventListener('change', async (e) => {
if (avatarUploadInFlight) {
alert('Please wait for the current upload to finish.');
e.target.value = '';
return;
}
const file = e.target.files?.[0];
if (!file) return;
if (file.size > 5 * 1024 * 1024) {
alert('File too large. Maximum size is 5MB.');
e.target.value = '';
return;
}
const formData = new FormData();
formData.append('avatar', file);
avatarUploadInFlight = true;
try {
const res = await fetch('/api/account/avatar/upload', {
method: 'POST',
credentials: 'include',
body: formData
});
// Body may not be JSON when a proxy rejects the request (e.g. 413 HTML page).
let data = null;
try {
data = await res.json();
} catch (parseErr) {
data = null;
}
if (!res.ok) {
throw new Error((data && data.error) || ('HTTP ' + res.status + ' error'));
}
if (!data || !data.avatarUrl) {
throw new Error('Upload failed: invalid server response');
}
const avatarImgEl = document.getElementById('accountAvatarImg');
const avatarImgCredEl = document.getElementById('accountAvatarImgCred');
if (avatarImgEl) avatarImgEl.src = data.avatarUrl;
if (avatarImgCredEl) avatarImgCredEl.src = data.avatarUrl;
const headerAvatarImg = document.querySelector('.account-btn-avatar');
if (headerAvatarImg) headerAvatarImg.src = data.avatarUrl;
} catch (err) {
alert('Failed to upload avatar: ' + err.message);
} finally {
avatarUploadInFlight = false;
e.target.value = '';
}
});
const usernameEditBtn = document.getElementById('usernameEditBtn');
const usernameSaveBtn = document.getElementById('usernameSaveBtn');
const usernameCancelBtn = document.getElementById('usernameCancelBtn');
const usernameInput = document.getElementById('usernameInput');
const usernameValEl = document.getElementById('accountUsernameValue');
usernameEditBtn?.addEventListener('click', () => {
if (usernameInput && usernameValEl) {
usernameInput.value = usernameValEl.textContent || '';
usernameValEl.style.display = 'none';
usernameInput.style.display = 'block';
usernameEditBtn.style.display = 'none';
usernameSaveBtn.style.display = 'inline-flex';
usernameCancelBtn.style.display = 'inline-flex';
usernameInput.focus();
}
});
usernameCancelBtn?.addEventListener('click', () => {
usernameValEl.style.display = 'inline';
usernameInput.style.display = 'none';
usernameEditBtn.style.display = 'inline-flex';
usernameSaveBtn.style.display = 'none';
usernameCancelBtn.style.display = 'none';
});
usernameSaveBtn?.addEventListener('click', async () => {
const newUsername = usernameInput?.value?.trim();
if (!newUsername || newUsername.length < 3) {
alert('Username must be at least 3 characters');
return;
}
usernameSaveBtn.disabled = true;
try {
const res = await fetch('/api/account/username', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ username: newUsername })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Failed to update username');
// The server echoes the saved username on success; prefer it over the
// raw trimmed input for the label updates.
const savedUsername = data.username || newUsername;
if (usernameValEl) usernameValEl.textContent = savedUsername;
const usernameEl = document.getElementById('accountUsername');
const usernameCredEl = document.getElementById('accountUsernameCred');
if (usernameEl) usernameEl.textContent = savedUsername;
if (usernameCredEl) usernameCredEl.textContent = savedUsername;
// A successful change starts a fresh 7-day lockout on the server, so the
// cooldown banner and cached account data are already stale. Refresh
// immediately so the lock shows before the user re-enters edit mode,
// mirroring the refresh-then-fallback pattern the 2FA flows use. If the
// refresh fails, patch the cache by hand so the UI stays correct:
// non-admins get the full 7-day lock, admins are exempt from it.
const refreshed = await loadAccountData();
if (!refreshed && window._accountData) {
window._accountData.username = savedUsername;
// A no-op save (server answers unchanged:true) starts no lockout, so
// only a real change earns the fabricated 7-day fallback lock here.
if (!window._accountData.isAdmin && !data.unchanged) {
window._accountData.usernameChangeCooldown = 7 * 24 * 60 * 60 * 1000;
}
renderAccountData(window._accountData);
}
usernameCancelBtn?.click();
} catch (err) {
alert(err.message);
} finally {
usernameSaveBtn.disabled = false;
}
});
const statusEditBtn = document.getElementById('statusEditBtn');
const statusModal = document.getElementById('statusModal');
const statusModalClose = document.getElementById('statusModalClose');
const statusCancelBtn = document.getElementById('statusCancelBtn');
const statusSaveBtn = document.getElementById('statusSaveBtn');
const statusInput = document.getElementById('statusInput');
const statusDuration = document.getElementById('statusDuration');
const statusError = document.getElementById('statusError');
const statusTextEl = document.getElementById('accountStatusText');
statusEditBtn?.addEventListener('click', () => {
if (statusInput) statusInput.value = statusTextEl?.textContent || '';
statusModal?.classList.add('show');
});
statusModalClose?.addEventListener('click', () => {
statusModal?.classList.remove('show');
});
statusCancelBtn?.addEventListener('click', () => {
statusModal?.classList.remove('show');
});
statusModal?.addEventListener('click', (e) => {
if (e.target === statusModal) statusModal.classList.remove('show');
});
statusSaveBtn?.addEventListener('click', async () => {
const text = statusInput?.value?.trim() || 'Available';
const durationVal = statusDuration?.value;
const expiresAt = durationVal === 'never' ? null : Date.now() + parseInt(durationVal || '86400000');
statusSaveBtn.disabled = true;
if (statusError) statusError.classList.remove('show');
try {
const res = await fetch('/api/me/status', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ text, expiresAt })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Failed to update status');
if (statusTextEl) statusTextEl.textContent = text;
statusModal?.classList.remove('show');
} catch (err) {
if (statusError) {
statusError.textContent = err.message;
statusError.classList.add('show');
}
} finally {
statusSaveBtn.disabled = false;
}
});
accountBtn?.addEventListener('click', showAccountPage);
accountBackBtn?.addEventListener('click', hideAccountPage);
if (window.location.hash === '#account') {
showAccountPage();
}
window.addEventListener('hashchange', () => {
if (window.location.hash === '#account') {
showAccountPage();
} else {
hideAccountPage();
}
});
function activateAccountTab(tabName) {
const normalized = tabName === 'credentials' ? 'credentials' : 'info';
document.querySelectorAll('.account-tab').forEach((tab) => {
tab.classList.toggle('active', tab.dataset.accountTab === normalized);
});
document.querySelectorAll('.account-tab-content').forEach((content) => {
content.classList.remove('active');
});
const tabId = normalized === 'info' ? 'accountInfoTab' : 'accountCredentialsTab';
document.getElementById(tabId)?.classList.add('active');
}
document.querySelectorAll('.account-tab').forEach(tab => {
tab.addEventListener('click', () => {
activateAccountTab(tab.dataset.accountTab);
});
});
const twofaModal = document.getElementById('twofaModal');
const change2faBtn = document.getElementById('change2faBtn');
const twofaModalClose = document.getElementById('twofaModalClose');
const twofaCancelBtn = document.getElementById('twofaCancelBtn');
const twofaConfirmBtn = document.getElementById('twofaConfirmBtn');
const currentCodeInput = document.getElementById('currentCodeInput');
const newCodeInput = document.getElementById('newCodeInput');
const qrCodeSection = document.getElementById('qrCodeSection');
const confirmSection = document.getElementById('confirmSection');
const newQrCode = document.getElementById('newQrCode');
const newSecretDisplay = document.getElementById('newSecretDisplay');
const twofaError = document.getElementById('twofaError');
const twofaSuccess = document.getElementById('twofaSuccess');
const twofaStep1Text = document.getElementById('twofaStep1Text');
let pendingNewSecret = null;
let twoFaModalStep = 1;
function accountHas2FA() {
return !window._accountData || window._accountData.has2FA !== false;
}
// Always re-fetches /api/account: 2FA state can be changed from another tab
// (or another device evicting this session's state), leaving the cached
// window._accountData stale, and the credential modals configure their input
// mode from has2FA — so every open must confirm current state from the
// server. On a failed refresh the cached data stays in place, but no modal
// is opened that could be configured from stale state (fail-closed, matching
// the alert path in the callers).
async function ensureAccountData() {
return loadAccountData();
}
function setStepVisibility(input, visible) {
const step = input?.closest('.password-step, .email-step, .twofa-step');
if (step) step.style.display = visible ? '' : 'none';
}
function setStepNumber(input, number) {
const step = input?.closest('.password-step, .email-step, .twofa-step');
const badge = step?.querySelector('.password-step-num, .email-step-num, .twofa-step-num');
if (badge) badge.textContent = String(number);
}
function syncTwofaCard() {
const has2FA = accountHas2FA();
if (change2faBtn) {
change2faBtn.textContent = has2FA ? 'Change 2FA' : 'Enable 2FA';
}
}
function configureTwofaModalSecurity() {
const has2FA = accountHas2FA();
const title = twofaModal?.querySelector('.twofa-modal-title');
const subtitle = twofaModal?.querySelector('.twofa-modal-subtitle');
if (title) title.textContent = has2FA ? 'Change 2FA Code' : 'Enable 2FA';
if (subtitle) subtitle.textContent = has2FA ? 'Update your authenticator app' : 'Add an authenticator app to this account';
if (twofaStep1Text) {
twofaStep1Text.textContent = has2FA ? 'Enter your current 2FA code' : 'Enter your current password';
}
if (currentCodeInput) {
currentCodeInput.type = has2FA ? 'text' : 'password';
currentCodeInput.placeholder = has2FA ? '000000' : 'Current password';
currentCodeInput.maxLength = has2FA ? 6 : 1024;
currentCodeInput.inputMode = has2FA ? 'numeric' : '';
currentCodeInput.autocomplete = has2FA ? 'one-time-code' : 'current-password';
currentCodeInput.classList.toggle('twofa-password-input', !has2FA);
}
const twofaForgotLink = document.getElementById('twofaForgotLink');
if (twofaForgotLink) twofaForgotLink.style.display = has2FA ? '' : 'none';
}
function configurePasswordModalSecurity() {
const has2FA = accountHas2FA();
const passwordCodeInput = document.getElementById('password2faInput');
const passwordNewInput = document.getElementById('newPasswordInput');
const passwordConfirmInput = document.getElementById('confirmPasswordInput');
setStepVisibility(passwordCodeInput, has2FA);
setStepNumber(passwordNewInput, has2FA ? 3 : 2);
setStepNumber(passwordConfirmInput, has2FA ? 4 : 3);
const passwordForgotLink = document.getElementById('passwordForgotLink');
if (passwordForgotLink) passwordForgotLink.style.display = has2FA ? '' : 'none';
}
function configureEmailModalSecurity() {
const has2FA = accountHas2FA();
const emailCodeInput = document.getElementById('email2faInput');
const emailNewInput = document.getElementById('newEmailInput');
setStepVisibility(emailCodeInput, has2FA);
setStepNumber(emailNewInput, has2FA ? 3 : 2);
const emailForgotLink = document.getElementById('emailForgotLink');
if (emailForgotLink) emailForgotLink.style.display = has2FA ? '' : 'none';
}
function syncAccountSecurityUi() {
syncTwofaCard();
configureTwofaModalSecurity();
configurePasswordModalSecurity();
configureEmailModalSecurity();
}
function resetTwofaModal() {
twoFaModalStep = 1;
pendingNewSecret = null;
if (currentCodeInput) currentCodeInput.value = '';
if (newCodeInput) newCodeInput.value = '';
if (qrCodeSection) qrCodeSection.style.display = 'none';
if (confirmSection) confirmSection.style.display = 'none';
// The pending secret stays valid until the new code is confirmed, so the
// seed text and QR image must not linger in the DOM after the modal closes.
if (newQrCode) newQrCode.removeAttribute('src');
if (newSecretDisplay) newSecretDisplay.textContent = '';
if (twofaError) twofaError.classList.remove('show');
if (twofaSuccess) twofaSuccess.classList.remove('show');
if (twofaConfirmBtn) {
twofaConfirmBtn.textContent = accountHas2FA() ? 'Verify Current Code' : 'Verify Password';
twofaConfirmBtn.disabled = false;
twofaConfirmBtn.style.display = '';
}
if (twofaCancelBtn) twofaCancelBtn.textContent = 'Cancel';
const twofaStep1 = document.getElementById('twofaStep1');
if (twofaStep1) twofaStep1.style.display = '';
configureTwofaModalSecurity();
// The show-once recovery-codes step added by a successful 2FA confirm must
// not survive the reset: its codes are single-render secrets.
const twofaRecoveryCodesStep = document.getElementById('twofaRecoveryCodesStep');
if (twofaRecoveryCodesStep) twofaRecoveryCodesStep.style.display = 'none';
const twofaRecoveryCodesGrid = document.getElementById('twofaRecoveryCodesGrid');
if (twofaRecoveryCodesGrid) twofaRecoveryCodesGrid.innerHTML = '';
const qrStepNum = qrCodeSection?.querySelector('.twofa-step-num');
const confirmStepNum = confirmSection?.querySelector('.twofa-step-num');
if (qrStepNum) qrStepNum.textContent = '2';
if (confirmStepNum) confirmStepNum.textContent = '3';
}
function showTwofaError(msg) {
if (twofaError) {
twofaError.textContent = msg;
twofaError.classList.add('show');
}
}
// Credential changes sign out the account's other sessions server-side;
// tell the user so the eviction is visible rather than a surprise on the
// other devices.
function showSuccessWithEviction(el, baseText, data) {
if (!el) return;
const evicted = Number(data?.sessionsDestroyed || 0);
const notice = evicted > 0
? ` ${evicted} other session${evicted === 1 ? ' has' : 's have'} been signed out.`
: '';
const icon = el.querySelector('i');
el.textContent = baseText + notice;
if (icon) el.prepend(icon);
el.classList.add('show');
}
function hideTwofaError() {
if (twofaError) twofaError.classList.remove('show');
}
change2faBtn?.addEventListener('click', async () => {
change2faBtn.disabled = true;
try {
if (!(await ensureAccountData())) {
alert('Could not load your account settings. Please check your connection and reload the page, then try again.');
return;
}
resetTwofaModal();
twofaModal?.classList.add('show');
} finally {
change2faBtn.disabled = false;
}
});
twofaModalClose?.addEventListener('click', () => {
twofaModal?.classList.remove('show');
resetTwofaModal();
});
twofaCancelBtn?.addEventListener('click', () => {
twofaModal?.classList.remove('show');
resetTwofaModal();
});
twofaModal?.addEventListener('click', (e) => {
if (e.target === twofaModal) {
twofaModal.classList.remove('show');
resetTwofaModal();
}
});
const twofaSecretDisplayBox = document.querySelector('.twofa-secret-display');
if (newSecretDisplay) {
newSecretDisplay.addEventListener('mousedown', (e) => {
e.stopPropagation();
});
newSecretDisplay.addEventListener('selectstart', (e) => {
e.stopPropagation();
});
newSecretDisplay.addEventListener('click', () => {
try {
const sel = window.getSelection();
const range = document.createRange();
range.selectNodeContents(newSecretDisplay);
sel.removeAllRanges();
sel.addRange(range);
} catch (_) { }
});
}
if (twofaSecretDisplayBox) {
twofaSecretDisplayBox.addEventListener('mousedown', (e) => {
e.stopPropagation();
});
twofaSecretDisplayBox.addEventListener('selectstart', (e) => {
e.stopPropagation();
});
twofaSecretDisplayBox.addEventListener('click', (e) => {
if (e.target === twofaSecretDisplayBox && newSecretDisplay) {
try {
const sel = window.getSelection();
const range = document.createRange();
range.selectNodeContents(newSecretDisplay);
sel.removeAllRanges();
sel.addRange(range);
} catch (_) { }
}
});
}
twofaConfirmBtn?.addEventListener('click', async () => {
hideTwofaError();
if (twoFaModalStep === 1) {
const has2FA = accountHas2FA();
const currentCredential = currentCodeInput?.value.trim() || '';
if (has2FA && (!currentCredential || currentCredential.length !== 6 || !/^\d+$/.test(currentCredential))) {
showTwofaError('Please enter a valid 6-digit code');
return;
}
if (!has2FA && !currentCredential) {
showTwofaError('Please enter your current password');
return;
}
twofaConfirmBtn.disabled = true;
twofaConfirmBtn.textContent = 'Verifying...';
try {
const res = await fetch('/api/account/2fa/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(has2FA ? { currentCode: currentCredential } : { currentPassword: currentCredential })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Verification failed');
pendingNewSecret = data.newSecret;
if (newQrCode) newQrCode.src = data.qrCodeUrl;
if (newSecretDisplay) newSecretDisplay.textContent = data.newSecret;
if (qrCodeSection) qrCodeSection.style.display = 'block';
if (confirmSection) confirmSection.style.display = 'block';
twoFaModalStep = 2;
twofaConfirmBtn.textContent = 'Confirm New 2FA';
twofaConfirmBtn.disabled = false;
} catch (err) {
showTwofaError(err.message);
twofaConfirmBtn.textContent = accountHas2FA() ? 'Verify Current Code' : 'Verify Password';
twofaConfirmBtn.disabled = false;
}
} else if (twoFaModalStep === 2) {
const newCode = newCodeInput?.value.trim() || '';
if (!newCode || newCode.length !== 6 || !/^\d+$/.test(newCode)) {
showTwofaError('Please enter a valid 6-digit code from your new authenticator');
return;
}
twofaConfirmBtn.disabled = true;
twofaConfirmBtn.textContent = 'Updating...';
try {
const res = await fetch('/api/account/2fa/confirm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ newCode, newSecret: pendingNewSecret })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Failed to update 2FA');
// Newer servers hand back one-time recovery codes on every successful
// confirm. Show them as a show-once step instead of the plain success
// state: the repurposed Cancel/Done button then closes the modal and
// resets it, matching the old close path. Older servers omit
// recoveryCodes and fall through to the unchanged behavior below.
if (Array.isArray(data.recoveryCodes) && data.recoveryCodes.length > 0) {
renderRecoveryCodesGrid('twofaRecoveryCodesGrid', data.recoveryCodes);
const twofaStep1 = document.getElementById('twofaStep1');
if (twofaStep1) twofaStep1.style.display = 'none';
if (qrCodeSection) qrCodeSection.style.display = 'none';
if (confirmSection) confirmSection.style.display = 'none';
const twofaRecoveryCodesStep = document.getElementById('twofaRecoveryCodesStep');
if (twofaRecoveryCodesStep) twofaRecoveryCodesStep.style.display = 'block';
hideTwofaError();
if (twofaSuccess) twofaSuccess.classList.remove('show');
if (window._accountData) window._accountData.has2FA = true;
syncAccountSecurityUi();
if (twofaConfirmBtn) twofaConfirmBtn.style.display = 'none';
if (twofaCancelBtn) twofaCancelBtn.textContent = 'Done';
twoFaModalStep = 3;
return;
}
if (twofaSuccess) showSuccessWithEviction(twofaSuccess, '2FA has been successfully updated!', data);
if (window._accountData) window._accountData.has2FA = true;
syncAccountSecurityUi();
twofaConfirmBtn.style.display = 'none';
if (twofaCancelBtn) twofaCancelBtn.textContent = 'Done';
setTimeout(() => {
twofaModal?.classList.remove('show');
resetTwofaModal();
}, 2000);
} catch (err) {
showTwofaError(err.message);
twofaConfirmBtn.textContent = 'Confirm New 2FA';
twofaConfirmBtn.disabled = false;
}
}
});
currentCodeInput?.addEventListener('input', (e) => {
if (accountHas2FA()) {
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
}
});
newCodeInput?.addEventListener('input', (e) => {
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
});
const passwordModal = document.getElementById('passwordModal');
const changePasswordBtn = document.getElementById('changePasswordBtn');
const passwordModalClose = document.getElementById('passwordModalClose');
const passwordCancelBtn = document.getElementById('passwordCancelBtn');
const passwordConfirmBtn = document.getElementById('passwordConfirmBtn');
const currentPasswordInput = document.getElementById('currentPasswordInput');
const password2faInput = document.getElementById('password2faInput');
const newPasswordInput = document.getElementById('newPasswordInput');
const confirmPasswordInput = document.getElementById('confirmPasswordInput');
const passwordStep1 = document.getElementById('passwordStep1');
const passwordStep2 = document.getElementById('passwordStep2');
const passwordError = document.getElementById('passwordError');
const passwordSuccess = document.getElementById('passwordSuccess');
let passwordModalStep = 1;
// Set when the modal was entered through the recovery flow instead of a
// verified current password, so a lapsed step-up can be detected on submit.
let passwordModalFromRecovery = false;
function resetPasswordModal() {
passwordModalStep = 1;
passwordModalFromRecovery = false;
if (currentPasswordInput) currentPasswordInput.value = '';
if (password2faInput) password2faInput.value = '';
if (newPasswordInput) newPasswordInput.value = '';
if (confirmPasswordInput) confirmPasswordInput.value = '';
if (passwordStep1) passwordStep1.style.display = 'block';
if (passwordStep2) passwordStep2.style.display = 'none';
if (passwordError) passwordError.classList.remove('show');
if (passwordSuccess) passwordSuccess.classList.remove('show');
if (passwordConfirmBtn) {
passwordConfirmBtn.textContent = 'Verify';
passwordConfirmBtn.disabled = false;
passwordConfirmBtn.style.display = '';
}
if (passwordCancelBtn) passwordCancelBtn.textContent = 'Cancel';
configurePasswordModalSecurity();
}
function showPasswordError(msg) {
if (passwordError) {
passwordError.textContent = msg;
passwordError.classList.add('show');
}
}
function hidePasswordError() {
if (passwordError) passwordError.classList.remove('show');
}
// Walk the modal back to step 1 when a step-1 factor no longer holds at step
// 2 (a lapsed recovery step-up, or a 2FA code that rolled over or was
// consumed between steps). Typed values are kept so nothing needs retyping,
// but the 2FA code is cleared: re-verification must use a fresh one.
function restorePasswordStep1(message) {
passwordModalFromRecovery = false;
passwordModalStep = 1;
if (password2faInput) password2faInput.value = '';
if (passwordStep1) passwordStep1.style.display = 'block';
if (passwordStep2) passwordStep2.style.display = 'none';
configurePasswordModalSecurity();
if (passwordConfirmBtn) {
passwordConfirmBtn.textContent = 'Verify';
passwordConfirmBtn.disabled = false;
}
if (message) showPasswordError(message);
}
changePasswordBtn?.addEventListener('click', async () => {
changePasswordBtn.disabled = true;
try {
if (!(await ensureAccountData())) {
alert('Could not load your account settings. Please check your connection and reload the page, then try again.');
return;
}
resetPasswordModal();
passwordModal?.classList.add('show');
} finally {
changePasswordBtn.disabled = false;
}
});
// Reset on close so typed secrets never linger in the hidden DOM; the
// reset is idempotent, so a double reset from the success timer is safe.
passwordModalClose?.addEventListener('click', () => {
passwordModal?.classList.remove('show');
resetPasswordModal();
});
passwordCancelBtn?.addEventListener('click', () => {
passwordModal?.classList.remove('show');
resetPasswordModal();
});
passwordModal?.addEventListener('click', (e) => {
if (e.target === passwordModal) {
passwordModal.classList.remove('show');
resetPasswordModal();
}
});
passwordConfirmBtn?.addEventListener('click', async () => {
hidePasswordError();
if (passwordModalStep === 1) {
const currentPw = currentPasswordInput?.value || '';
const code = password2faInput?.value.trim() || '';
if (!currentPw) {
showPasswordError('Please enter your current password');
return;
}
if (accountHas2FA() && (!code || code.length !== 6 || !/^\d+$/.test(code))) {
showPasswordError('Please enter a valid 6-digit 2FA code');
return;
}
passwordConfirmBtn.disabled = true;
passwordConfirmBtn.textContent = 'Verifying...';
try {
const res = await fetch('/api/account/password/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ currentPassword: currentPw, twoFactorCode: accountHas2FA() ? code : '' })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Verification failed');
passwordStep1.style.display = 'none';
passwordStep2.style.display = 'block';
passwordModalStep = 2;
passwordConfirmBtn.textContent = 'Change Password';
passwordConfirmBtn.disabled = false;
} catch (err) {
showPasswordError(err.message);
passwordConfirmBtn.textContent = 'Verify';
passwordConfirmBtn.disabled = false;
}
} else if (passwordModalStep === 2) {
const newPw = newPasswordInput?.value || '';
const confirmPw = confirmPasswordInput?.value || '';
if (!newPw || newPw.length < 8) {
showPasswordError('Password must be at least 8 characters');
return;
}
if (newPw !== confirmPw) {
showPasswordError('Passwords do not match');
return;
}
passwordConfirmBtn.disabled = true;
passwordConfirmBtn.textContent = 'Updating...';
try {
const res = await fetch('/api/account/password/change', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
currentPassword: currentPasswordInput?.value || '',
twoFactorCode: accountHas2FA() ? (password2faInput?.value.trim() || '') : '',
newPassword: newPw
})
});
const data = await res.json();
if (!res.ok) {
// Any 403 at step 2 means a step-1 factor no longer holds: the TOTP
// window rolled over or the code was consumed elsewhere, the current
// password changed in another session, or the recovery step-up
// expired (which the server may also report as an ordinary
// missing/incorrect password). The "Invalid 2FA code format" 400 is
// the same dead end in the other direction: 2FA was enabled in
// another session after the modal was configured from the cached
// has2FA, so no code was sent at all. Return to step 1, where those
// inputs live, or every retry would resend the same dead values.
if (res.status === 403 || data.error === 'Current password is required' || (res.status === 400 && data.error === 'Invalid 2FA code format')) {
if (passwordModalFromRecovery) {
restorePasswordStep1(data.error || 'Recovery verification expired. Please verify a recovery code again.');
} else if (data.error === 'Incorrect 2FA code') {
restorePasswordStep1('Your 2FA code is no longer valid. Please enter a fresh code and verify again.');
} else if (data.error === 'Invalid 2FA code format') {
const refreshed = await ensureAccountData();
if (!refreshed && window._accountData) {
// The 400 itself proves 2FA is on: seed the cached flag so the
// walk-back below re-reveals the step-1 2FA row instead of
// leaving it hidden.
window._accountData.has2FA = true;
syncAccountSecurityUi();
}
restorePasswordStep1('Two-factor authentication was enabled on your account. Enter a current 6-digit code along with your password.');
} else {
restorePasswordStep1(data.error || 'Verification failed. Please verify again.');
}
return;
}
throw new Error(data.error || 'Failed to change password');
}
if (passwordSuccess) showSuccessWithEviction(passwordSuccess, 'Password has been successfully changed!', data);
passwordConfirmBtn.style.display = 'none';
if (passwordCancelBtn) passwordCancelBtn.textContent = 'Done';
setTimeout(() => {
passwordModal?.classList.remove('show');
resetPasswordModal();
}, 2000);
} catch (err) {
showPasswordError(err.message);
passwordConfirmBtn.textContent = 'Change Password';
passwordConfirmBtn.disabled = false;
}
}
});
password2faInput?.addEventListener('input', (e) => {
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
});
document.querySelectorAll('.password-toggle-eye').forEach(btn => {
const targetId = btn.dataset.target;
const input = document.getElementById(targetId);
if (input) {
input.addEventListener('input', () => {
btn.style.display = input.value.length > 0 ? 'block' : 'none';
});
btn.addEventListener('click', () => {
const isPassword = input.type === 'password';
input.type = isPassword ? 'text' : 'password';
btn.querySelector('i').className = isPassword ? 'fa-solid fa-eye-slash' : 'fa-solid fa-eye';
});
}
});
const emailModal = document.getElementById('emailModal');
const changeEmailBtn = document.getElementById('changeEmailBtn');
const emailModalClose = document.getElementById('emailModalClose');
const emailCancelBtn = document.getElementById('emailCancelBtn');
const emailConfirmBtn = document.getElementById('emailConfirmBtn');
const emailPasswordInput = document.getElementById('emailPasswordInput');
const email2faInput = document.getElementById('email2faInput');
const newEmailInput = document.getElementById('newEmailInput');
const emailStep1 = document.getElementById('emailStep1');
const emailStep2 = document.getElementById('emailStep2');
const emailError = document.getElementById('emailError');
const emailSuccess = document.getElementById('emailSuccess');
let emailModalStep = 1;
// Recovery-flow marker, mirroring passwordModalFromRecovery.
let emailModalFromRecovery = false;
function resetEmailModal() {
emailModalStep = 1;
emailModalFromRecovery = false;
if (emailPasswordInput) emailPasswordInput.value = '';
if (email2faInput) email2faInput.value = '';
if (newEmailInput) newEmailInput.value = '';
if (emailStep1) emailStep1.style.display = 'block';
if (emailStep2) emailStep2.style.display = 'none';
if (emailError) emailError.classList.remove('show');
if (emailSuccess) emailSuccess.classList.remove('show');
if (emailConfirmBtn) {
emailConfirmBtn.textContent = 'Verify';
emailConfirmBtn.disabled = false;
emailConfirmBtn.style.display = '';
}
if (emailCancelBtn) emailCancelBtn.textContent = 'Cancel';
configureEmailModalSecurity();
}
function showEmailError(msg) {
if (emailError) {
emailError.textContent = msg;
emailError.classList.add('show');
}
}
function hideEmailError() {
if (emailError) emailError.classList.remove('show');
}
// Walk the modal back to step 1 when a step-1 factor no longer holds at step
// 2 (a lapsed recovery step-up, or a 2FA code that rolled over or was
// consumed between steps). Typed values are kept so nothing needs retyping,
// but the 2FA code is cleared: re-verification must use a fresh one.
function restoreEmailStep1(message) {
emailModalFromRecovery = false;
emailModalStep = 1;
if (email2faInput) email2faInput.value = '';
if (emailStep1) emailStep1.style.display = 'block';
if (emailStep2) emailStep2.style.display = 'none';
configureEmailModalSecurity();
if (emailConfirmBtn) {
emailConfirmBtn.textContent = 'Verify';
emailConfirmBtn.disabled = false;
}
if (message) showEmailError(message);
}
changeEmailBtn?.addEventListener('click', async () => {
changeEmailBtn.disabled = true;
try {
if (!(await ensureAccountData())) {
alert('Could not load your account settings. Please check your connection and reload the page, then try again.');
return;
}
resetEmailModal();
emailModal?.classList.add('show');
} finally {
changeEmailBtn.disabled = false;
}
});
// Reset on close so typed secrets never linger in the hidden DOM; the
// reset is idempotent, so a double reset from the success timer is safe.
emailModalClose?.addEventListener('click', () => {
emailModal?.classList.remove('show');
resetEmailModal();
});
emailCancelBtn?.addEventListener('click', () => {
emailModal?.classList.remove('show');
resetEmailModal();
});
emailModal?.addEventListener('click', (e) => {
if (e.target === emailModal) {
emailModal.classList.remove('show');
resetEmailModal();
}
});
emailConfirmBtn?.addEventListener('click', async () => {
hideEmailError();
if (emailModalStep === 1) {
const currentPw = emailPasswordInput?.value || '';
const code = email2faInput?.value.trim() || '';
if (!currentPw) {
showEmailError('Please enter your password');
return;
}
if (accountHas2FA() && (!code || code.length !== 6 || !/^\d+$/.test(code))) {
showEmailError('Please enter a valid 6-digit 2FA code');
return;
}
emailConfirmBtn.disabled = true;
emailConfirmBtn.textContent = 'Verifying...';
try {
const res = await fetch('/api/account/email/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ currentPassword: currentPw, twoFactorCode: accountHas2FA() ? code : '' })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Verification failed');
emailStep1.style.display = 'none';
emailStep2.style.display = 'block';
emailModalStep = 2;
emailConfirmBtn.textContent = 'Change Email';
emailConfirmBtn.disabled = false;
} catch (err) {
showEmailError(err.message);
emailConfirmBtn.textContent = 'Verify';
emailConfirmBtn.disabled = false;
}
} else if (emailModalStep === 2) {
const newEmail = newEmailInput?.value.trim() || '';
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!newEmail || !emailRegex.test(newEmail)) {
showEmailError('Please enter a valid email address');
return;
}
emailConfirmBtn.disabled = true;
emailConfirmBtn.textContent = 'Updating...';
try {
const res = await fetch('/api/account/email/change', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
currentPassword: emailPasswordInput?.value || '',
twoFactorCode: accountHas2FA() ? (email2faInput?.value.trim() || '') : '',
newEmail: newEmail
})
});
const data = await res.json();
if (!res.ok) {
// Any 403 at step 2 means a step-1 factor no longer holds: the TOTP
// window rolled over or the code was consumed elsewhere, the current
// password changed in another session, or the recovery step-up
// expired (which the server may also report as an ordinary
// missing/incorrect password). The "Invalid 2FA code format" 400 is
// the same dead end in the other direction: 2FA was enabled in
// another session after the modal was configured from the cached
// has2FA, so no code was sent at all. Return to step 1, where those
// inputs live, or every retry would resend the same dead values.
if (res.status === 403 || data.error === 'Password is required' || (res.status === 400 && data.error === 'Invalid 2FA code format')) {
if (emailModalFromRecovery) {
restoreEmailStep1(data.error || 'Recovery verification expired. Please verify a recovery code again.');
} else if (data.error === 'Incorrect 2FA code') {
restoreEmailStep1('Your 2FA code is no longer valid. Please enter a fresh code and verify again.');
} else if (data.error === 'Invalid 2FA code format') {
const refreshed = await ensureAccountData();
if (!refreshed && window._accountData) {
// The 400 itself proves 2FA is on: seed the cached flag so the
// walk-back below re-reveals the step-1 2FA row instead of
// leaving it hidden.
window._accountData.has2FA = true;
syncAccountSecurityUi();
}
restoreEmailStep1('Two-factor authentication was enabled on your account. Enter a current 6-digit code along with your password.');
} else {
restoreEmailStep1(data.error || 'Verification failed. Please verify again.');
}
return;
}
throw new Error(data.error || 'Failed to change email');
}
if (emailSuccess) showSuccessWithEviction(emailSuccess, 'Email has been successfully changed!', data);
emailConfirmBtn.style.display = 'none';
if (emailCancelBtn) emailCancelBtn.textContent = 'Done';
const accountEmailEl = document.getElementById('accountEmail');
const accountEmailValueEl = document.getElementById('accountEmailValue');
const accountEmailCredEl = document.getElementById('accountEmailCred');
if (accountEmailEl) accountEmailEl.textContent = newEmail;
if (accountEmailValueEl) accountEmailValueEl.textContent = newEmail;
if (accountEmailCredEl) accountEmailCredEl.textContent = newEmail;
setTimeout(() => {
emailModal?.classList.remove('show');
resetEmailModal();
}, 2000);
} catch (err) {
showEmailError(err.message);
emailConfirmBtn.textContent = 'Change Email';
emailConfirmBtn.disabled = false;
}
}
});
email2faInput?.addEventListener('input', (e) => {
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
});
document.querySelectorAll('.email-toggle-eye').forEach(btn => {
const targetId = btn.dataset.target;
const input = document.getElementById(targetId);
if (input) {
input.addEventListener('input', () => {
btn.style.display = input.value.length > 0 ? 'block' : 'none';
});
btn.addEventListener('click', () => {
const isPassword = input.type === 'password';
input.type = isPassword ? 'text' : 'password';
btn.querySelector('i').className = isPassword ? 'fa-solid fa-eye-slash' : 'fa-solid fa-eye';
});
}
});
const recoveryModal = document.getElementById('recoveryModal');
const recoveryModalClose = document.getElementById('recoveryModalClose');
const recoveryCancelBtn = document.getElementById('recoveryCancelBtn');
const recoveryConfirmBtn = document.getElementById('recoveryConfirmBtn');
const recoveryCodeInput = document.getElementById('recoveryCodeInput');
const recoveryError = document.getElementById('recoveryError');
let recoveryReturnTo = null;
function showRecoveryError(msg) {
if (recoveryError) {
recoveryError.textContent = msg;
recoveryError.classList.add('show');
}
}
function hideRecoveryError() {
if (recoveryError) recoveryError.classList.remove('show');
}
function resetRecoveryModal() {
if (recoveryCodeInput) recoveryCodeInput.value = '';
hideRecoveryError();
if (recoveryConfirmBtn) {
recoveryConfirmBtn.textContent = 'Verify Code';
recoveryConfirmBtn.disabled = false;
}
recoveryReturnTo = null;
}
function openRecoveryModal(returnTo) {
resetRecoveryModal();
recoveryReturnTo = returnTo;
recoveryModal?.classList.add('show');
}
async function openAccountFlow(flow) {
await showAccountPage();
activateAccountTab('credentials');
switch (flow) {
case 'change_password':
// The caller (dashboard-assistant.js) ignores the return value, so the
// gate runs detached: the modal only opens once /api/account has
// confirmed current 2FA state.
ensureAccountData().then((ok) => {
if (ok) {
resetPasswordModal();
passwordModal?.classList.add('show');
} else {
alert('Could not load your account settings. Please check your connection and reload the page, then try again.');
}
});
return true;
case 'change_email':
ensureAccountData().then((ok) => {
if (ok) {
resetEmailModal();
emailModal?.classList.add('show');
} else {
alert('Could not load your account settings. Please check your connection and reload the page, then try again.');
}
});
return true;
case 'change_2fa':
ensureAccountData().then((ok) => {
if (ok) {
resetTwofaModal();
twofaModal?.classList.add('show');
} else {
alert('Could not load your account settings. Please check your connection and reload the page, then try again.');
}
});
return true;
case 'recover_password':
// Same gate as the change_* flows: /api/account must confirm current
// 2FA state before anything opens, because an account without 2FA has
// no recovery codes to enter — the recovery-code modal must not even
// appear for it (the server would 403 the submitted code anyway, but
// non-2FA users must not be shown recovery-code UI at all).
ensureAccountData().then((ok) => {
if (!ok) {
alert('Could not load your account settings. Please check your connection and reload the page, then try again.');
return;
}
if (!accountHas2FA()) {
alert('Recovery codes are available once two-factor authentication is enabled on your account.');
return;
}
openRecoveryModal('password');
});
return true;
case 'recover_email':
ensureAccountData().then((ok) => {
if (!ok) {
alert('Could not load your account settings. Please check your connection and reload the page, then try again.');
return;
}
if (!accountHas2FA()) {
alert('Recovery codes are available once two-factor authentication is enabled on your account.');
return;
}
openRecoveryModal('email');
});
return true;
case 'recover_2fa':
ensureAccountData().then((ok) => {
if (!ok) {
alert('Could not load your account settings. Please check your connection and reload the page, then try again.');
return;
}
if (!accountHas2FA()) {
alert('Recovery codes are available once two-factor authentication is enabled on your account.');
return;
}
openRecoveryModal('twofa');
});
return true;
default:
return false;
}
}
window.ADPanelDashboardAccount = {
showAccountPage,
hideAccountPage,
activateAccountTab,
openAccountFlow,
};
document.getElementById('twofaForgotLink')?.addEventListener('click', () => {
twofaModal?.classList.remove('show');
resetTwofaModal();
openRecoveryModal('twofa');
});
document.getElementById('passwordForgotLink')?.addEventListener('click', () => {
passwordModal?.classList.remove('show');
resetPasswordModal();
openRecoveryModal('password');
});
document.getElementById('emailForgotLink')?.addEventListener('click', () => {
emailModal?.classList.remove('show');
resetEmailModal();
openRecoveryModal('email');
});
// Reset on close so typed secrets never linger in the hidden DOM; the
// reset is idempotent, so a double reset from the success timer is safe.
recoveryModalClose?.addEventListener('click', () => {
recoveryModal?.classList.remove('show');
resetRecoveryModal();
});
recoveryCancelBtn?.addEventListener('click', () => {
recoveryModal?.classList.remove('show');
resetRecoveryModal();
});
recoveryModal?.addEventListener('click', (e) => {
if (e.target === recoveryModal) {
recoveryModal.classList.remove('show');
resetRecoveryModal();
}
});
recoveryCodeInput?.addEventListener('input', (e) => {
e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 8);
});
recoveryConfirmBtn?.addEventListener('click', async () => {
hideRecoveryError();
const code = recoveryCodeInput?.value.trim().toUpperCase() || '';
if (!code || code.length !== 8) {
showRecoveryError('Please enter a valid 8-character recovery code');
return;
}
recoveryConfirmBtn.disabled = true;
recoveryConfirmBtn.textContent = 'Verifying...';
try {
const res = await fetch('/api/account/recovery/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ recoveryCode: code })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Invalid recovery code');
recoveryModal?.classList.remove('show');
if (recoveryReturnTo === 'twofa') {
try {
const genRes = await fetch('/api/account/2fa/generate-recovery', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
});
const genData = await genRes.json();
if (!genRes.ok) throw new Error(genData.error || 'Failed to generate new 2FA');
resetTwofaModal();
pendingNewSecret = genData.newSecret;
if (newQrCode) newQrCode.src = genData.qrCodeUrl;
if (newSecretDisplay) newSecretDisplay.textContent = genData.newSecret;
const twofaStep1 = document.getElementById('twofaStep1');
if (twofaStep1) twofaStep1.style.display = 'none';
if (qrCodeSection) qrCodeSection.style.display = 'block';
if (confirmSection) confirmSection.style.display = 'block';
const qrStepNum = qrCodeSection?.querySelector('.twofa-step-num');
const confirmStepNum = confirmSection?.querySelector('.twofa-step-num');
if (qrStepNum) qrStepNum.textContent = '1';
if (confirmStepNum) confirmStepNum.textContent = '2';
twoFaModalStep = 2;
if (twofaConfirmBtn) twofaConfirmBtn.textContent = 'Confirm New 2FA';
twofaModal?.classList.add('show');
} catch (err) {
alert('Failed to generate 2FA: ' + err.message);
}
} else if (recoveryReturnTo === 'password') {
resetPasswordModal();
if (passwordStep1) passwordStep1.style.display = 'none';
if (passwordStep2) passwordStep2.style.display = 'block';
document.getElementById('passwordForgotLink').style.display = 'none';
passwordModalStep = 2;
passwordModalFromRecovery = true;
if (passwordConfirmBtn) passwordConfirmBtn.textContent = 'Change Password';
passwordModal?.classList.add('show');
} else if (recoveryReturnTo === 'email') {
resetEmailModal();
if (emailStep1) emailStep1.style.display = 'none';
if (emailStep2) emailStep2.style.display = 'block';
document.getElementById('emailForgotLink').style.display = 'none';
emailModalStep = 2;
emailModalFromRecovery = true;
if (emailConfirmBtn) emailConfirmBtn.textContent = 'Change Email';
emailModal?.classList.add('show');
}
// resetRecoveryModal() nulls recoveryReturnTo, which the chain above
// reads, so it must run only after the follow-on modal is opened.
resetRecoveryModal();
} catch (err) {
showRecoveryError(err.message);
recoveryConfirmBtn.textContent = 'Verify Code';
recoveryConfirmBtn.disabled = false;
}
});
// --- Regenerate Recovery Codes modal (Account Settings → Security) ---
// Shared renderer for the show-once codes grids (this modal and the 2FA
// confirm success step, which is defined earlier in this scope and reaches
// this declaration through hoisting). Every code is escaped before render.
function renderRecoveryCodesGrid(gridId, codes) {
const grid = document.getElementById(gridId);
if (!grid) return;
grid.innerHTML = (Array.isArray(codes) ? codes : []).map((code, idx) => `
<div style="background: rgba(0,0,0,0.2); padding: 12px 16px; border-radius: 8px; font-family: 'SF Mono', Monaco, monospace; font-size: 14px; letter-spacing: 2px; text-align: center; color: #10b981;">
${idx + 1}. ${escapeHtml(code)}
</div>
`).join('');
}
const regenRecoveryModal = document.getElementById('regenRecoveryModal');
const regenerateRecoveryBtn = document.getElementById('regenerateRecoveryBtn');
const regenRecoveryCloseBtn = document.getElementById('regenRecoveryCloseBtn');
const regenRecoveryCancelBtn = document.getElementById('regenRecoveryCancelBtn');
const regenRecoveryConfirmBtn = document.getElementById('regenRecoveryConfirmBtn');
const regenRecoveryDoneBtn = document.getElementById('regenRecoveryDoneBtn');
const regenRecoveryPasswordInput = document.getElementById('regenRecoveryPasswordInput');
const regenRecoveryTotpInput = document.getElementById('regenRecoveryTotpInput');
const regenRecoveryError = document.getElementById('regenRecoveryError');
const regenRecoveryPasswordStep = document.getElementById('regenRecoveryPasswordStep');
const regenRecoveryTotpStep = document.getElementById('regenRecoveryTotpStep');
const regenRecoveryCodesStep = document.getElementById('regenRecoveryCodesStep');
const regenRecoveryCodesGrid = document.getElementById('regenRecoveryCodesGrid');
// Which step the modal sits on: password -> totp -> codes. Unlike the old
// single-input mode duality, each step owns a dedicated field, so this flag
// only exists so Confirm knows which endpoint to hit; showRegenRecoveryStep()
// is its only writer, keeping it and the DOM in lockstep.
let regenRecoveryStep = 'password';
function showRegenRecoveryError(msg) {
if (regenRecoveryError) {
regenRecoveryError.textContent = msg;
regenRecoveryError.classList.add('show');
}
}
function hideRegenRecoveryError() {
if (regenRecoveryError) regenRecoveryError.classList.remove('show');
}
// Single transition point: flips the three steps, drops the error, and moves
// the cursor into the newly visible input. Errors are hidden on every
// transition because a message belongs to the step it was raised on; a
// caller that wants an error on the new step re-raises it right after.
function showRegenRecoveryStep(step) {
regenRecoveryStep = step;
if (regenRecoveryPasswordStep) regenRecoveryPasswordStep.style.display = step === 'password' ? '' : 'none';
if (regenRecoveryTotpStep) regenRecoveryTotpStep.style.display = step === 'totp' ? '' : 'none';
if (regenRecoveryCodesStep) regenRecoveryCodesStep.style.display = step === 'codes' ? '' : 'none';
hideRegenRecoveryError();
if (step === 'password') regenRecoveryPasswordInput?.focus();
else if (step === 'totp') regenRecoveryTotpInput?.focus();
}
function resetRegenRecoveryModal() {
// Both fields are cleared (not just the visible one): a password must
// never linger in the hidden DOM, and a half-typed TOTP code left over
// from an abandoned attempt would sail straight past validation on the
// next run. The step state resets with the DOM so every open starts at
// step 1 no matter how the modal was dismissed (close, cancel, Done,
// overlay click, Escape).
if (regenRecoveryPasswordInput) regenRecoveryPasswordInput.value = '';
if (regenRecoveryTotpInput) regenRecoveryTotpInput.value = '';
if (regenRecoveryCodesGrid) regenRecoveryCodesGrid.innerHTML = '';
showRegenRecoveryStep('password');
if (regenRecoveryConfirmBtn) {
regenRecoveryConfirmBtn.textContent = 'Confirm';
regenRecoveryConfirmBtn.disabled = false;
regenRecoveryConfirmBtn.style.display = '';
}
if (regenRecoveryCancelBtn) regenRecoveryCancelBtn.style.display = '';
if (regenRecoveryDoneBtn) regenRecoveryDoneBtn.style.display = 'none';
}
regenerateRecoveryBtn?.addEventListener('click', async () => {
regenerateRecoveryBtn.disabled = true;
try {
if (!(await ensureAccountData())) {
alert('Could not load your account settings. Please check your connection and reload the page, then try again.');
return;
}
resetRegenRecoveryModal();
regenRecoveryModal?.classList.add('show');
regenRecoveryPasswordInput?.focus();
} finally {
regenerateRecoveryBtn.disabled = false;
}
});
// Reset on close so typed credentials and rendered codes never linger in the
// hidden DOM; the reset is idempotent, so a double reset is safe.
regenRecoveryCloseBtn?.addEventListener('click', () => {
regenRecoveryModal?.classList.remove('show');
resetRegenRecoveryModal();
});
regenRecoveryCancelBtn?.addEventListener('click', () => {
regenRecoveryModal?.classList.remove('show');
resetRegenRecoveryModal();
});
regenRecoveryDoneBtn?.addEventListener('click', () => {
regenRecoveryModal?.classList.remove('show');
resetRegenRecoveryModal();
});
regenRecoveryModal?.addEventListener('click', (e) => {
if (e.target === regenRecoveryModal) {
regenRecoveryModal.classList.remove('show');
resetRegenRecoveryModal();
}
});
// The other credential modals have no global Escape handling; scope the
// Escape close to this overlay so it never fights the recovery/password
// modals stacked in the same page.
document.addEventListener('keydown', (e) => {
if (e.key !== 'Escape') return;
if (!regenRecoveryModal?.classList.contains('show')) return;
regenRecoveryModal.classList.remove('show');
resetRegenRecoveryModal();
});
// Only the TOTP field is sanitised; the password field keeps whatever the
// user (or the browser's autofill) types — filtering it could silently
// corrupt a valid password and would also fight credential managers.
regenRecoveryTotpInput?.addEventListener('input', (e) => {
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
});
// STEP 2 completion, called from the TOTP step with the typed 6-digit code.
// The server always demands a live second factor, so there is no password-
// only completion to fall back to. On failure it routes the UI itself — back
// to step 1 for a missing/expired password grant, inline error otherwise —
// and re-enables Confirm; it resolves true only once the codes are on
// screen.
async function completeRegenRecovery(body) {
const res = await fetch('/api/account/2fa/regenerate-recovery-codes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(body)
});
let data = null;
try {
data = await res.json();
} catch (_) {
data = null;
}
if (res.ok && data && Array.isArray(data.recoveryCodes) && data.recoveryCodes.length > 0) {
renderRecoveryCodesGrid('regenRecoveryCodesGrid', data.recoveryCodes);
showRegenRecoveryStep('codes');
if (regenRecoveryConfirmBtn) regenRecoveryConfirmBtn.style.display = 'none';
if (regenRecoveryCancelBtn) regenRecoveryCancelBtn.style.display = 'none';
if (regenRecoveryDoneBtn) regenRecoveryDoneBtn.style.display = '';
return true;
}
// The password grant from step 1 is missing or expired (server restart,
// password changed in between): the only way forward is step 1 again, so
// both fields are cleared — the old grant chain is broken and a fresh
// password must be typed. This re-clear on a forced step change is the
// deliberate counterpart to the wrong-password retry in the step-1 branch
// below, which keeps its text for editing.
if (data && (data.code === 'password-required' || data.code === 'password-stale')) {
if (regenRecoveryPasswordInput) regenRecoveryPasswordInput.value = '';
if (regenRecoveryTotpInput) regenRecoveryTotpInput.value = '';
showRegenRecoveryStep('password');
showRegenRecoveryError(data.error || 'Please verify your password again');
regenRecoveryConfirmBtn.disabled = false;
regenRecoveryConfirmBtn.textContent = 'Confirm';
return false;
}
// A code-less 403: "Incorrect 2FA code" (wrong TOTP) or the grant-claim
// failure ("expired or already used") from the server's grant path (only
// reachable when a live recovery grant from another flow sits on the
// session). Either way a rejected TOTP is discarded rather than kept for
// editing, so the retype starts clean instead of inviting a one-digit
// nudge on a known-bad code.
if (res.status === 403 && data && !data.code) {
if (regenRecoveryTotpInput) regenRecoveryTotpInput.value = '';
regenRecoveryTotpInput?.focus();
showRegenRecoveryError((data && data.error) || 'Incorrect 2FA code');
regenRecoveryConfirmBtn.disabled = false;
regenRecoveryConfirmBtn.textContent = 'Confirm';
return false;
}
// Remaining contract failures (2fa-required, malformed code, 2fa-disabled,
// 429 rate limit, 401, unparseable body) all surface the server's error
// text inline and leave the modal on its current step for a retry.
showRegenRecoveryError((data && data.error) || 'Failed to regenerate recovery codes');
regenRecoveryConfirmBtn.disabled = false;
regenRecoveryConfirmBtn.textContent = 'Confirm';
return false;
}
regenRecoveryConfirmBtn?.addEventListener('click', async () => {
hideRegenRecoveryError();
// One button, two duties: the tracked step decides which endpoint Confirm
// talks to, so the button can never send a credential to the wrong stage.
if (regenRecoveryStep === 'password') {
const currentPassword = regenRecoveryPasswordInput?.value || '';
if (!currentPassword) {
showRegenRecoveryError('Please enter your current password');
return;
}
regenRecoveryConfirmBtn.disabled = true;
regenRecoveryConfirmBtn.textContent = 'Verifying...';
try {
const res = await fetch('/api/account/2fa/regenerate-recovery-codes/verify-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ currentPassword })
});
let data = null;
try {
data = await res.json();
} catch (_) {
data = null;
}
if (res.ok && data && data.ok) {
// Password accepted: the completion step ALWAYS demands a live
// second factor — even for an account whose stored-code inventory
// is empty — so advance to step 2 and hand the button back for the
// second confirmation. A legacy zero-codes user without a working
// authenticator stops at that step; that is the approved terminal
// state, and the admin reset / break-glass CLI paths are theirs.
showRegenRecoveryStep('totp');
regenRecoveryConfirmBtn.disabled = false;
regenRecoveryConfirmBtn.textContent = 'Confirm';
return;
}
// Expired session is called out explicitly because reloading is the
// only fix and the server's bare "Not authenticated" would not say so.
if (res.status === 401) {
showRegenRecoveryError('Your session has expired. Please reload the page.');
regenRecoveryConfirmBtn.disabled = false;
regenRecoveryConfirmBtn.textContent = 'Confirm';
return;
}
// Wrong password (403), 2fa-disabled, rate limit or an unparseable
// body: surface the server's text and stay on step 1. The typed
// password is deliberately kept — a mistyped character can be edited
// in place, and it is only wiped when the flow forces a fresh step-1
// grant (see completeRegenRecovery).
showRegenRecoveryError((data && data.error) || 'Failed to verify your password');
regenRecoveryConfirmBtn.disabled = false;
regenRecoveryConfirmBtn.textContent = 'Confirm';
} catch (err) {
showRegenRecoveryError(err.message);
regenRecoveryConfirmBtn.disabled = false;
regenRecoveryConfirmBtn.textContent = 'Confirm';
}
return;
}
if (regenRecoveryStep === 'totp') {
const twoFactorCode = regenRecoveryTotpInput?.value.trim() || '';
if (!/^\d{6}$/.test(twoFactorCode)) {
showRegenRecoveryError('Please enter a valid 6-digit code');
return;
}
regenRecoveryConfirmBtn.disabled = true;
regenRecoveryConfirmBtn.textContent = 'Verifying...';
try {
await completeRegenRecovery({ twoFactorCode });
} catch (err) {
showRegenRecoveryError(err.message);
regenRecoveryConfirmBtn.disabled = false;
regenRecoveryConfirmBtn.textContent = 'Confirm';
}
}
});
// The create-server wizard lives on the settings page; opening it from the
// dashboard just navigates there.
function openCreate() {
window.location.href = '/settings?panel=servers&create=server';
}
window.ADPanelDashboardCreate = {
openCreateModal() {
openCreate();
return true;
},
};
// Navbar Create pill: expand to a pill on hover/focus, collapse back to a
// circle on leave. Driven by JS so the collapse animation always plays.
const navCreateBtn = document.getElementById('createBtn');
if (navCreateBtn) {
const openPill = () => navCreateBtn.classList.add('is-open');
const closePill = () => navCreateBtn.classList.remove('is-open');
navCreateBtn.addEventListener('mouseenter', openPill);
navCreateBtn.addEventListener('mouseleave', closePill);
navCreateBtn.addEventListener('focus', openPill);
navCreateBtn.addEventListener('blur', closePill);
}
// Brand logo fallback: swap to the server-rendered logo if the branding
// image fails to load. The complete/naturalWidth check catches failures
// that fired before this deferred script ran.
const brandLogo = document.querySelector('.nav-brand__logo');
if (brandLogo) {
let logoFallbackUsed = false;
const useLogoFallback = () => {
if (logoFallbackUsed) return;
logoFallbackUsed = true;
brandLogo.src = '/auth-assets/logo';
};
brandLogo.addEventListener('error', useLogoFallback);
if (brandLogo.complete && brandLogo.naturalWidth === 0) useLogoFallback();
}
});
const serverStartTime = Number(document.body.dataset.serverStartTime) || Date.now();
const uptimeDisplay = document.getElementById('uptimeDisplay');
function formatTime(ms) {
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
return `${hours}h ${minutes}m ${seconds}s`;
}
function updateUptime() {
if (uptimeDisplay) {
const now = Date.now();
uptimeDisplay.textContent = formatTime(now - serverStartTime);
}
}
setInterval(updateUptime, 1000);
updateUptime();
class DashboardStatusManager {
constructor() {
this.socket = null;
this.serverCards = new Map();
this.statuses = new Map();
this.connected = false;
}
init() {
document.querySelectorAll('[data-bot-card]').forEach(card => {
const name = card.dataset.name;
if (name) this.serverCards.set(name.toLowerCase(), card);
});
if (this.serverCards.size === 0) return;
const adoptSharedSocket = () => {
if (!window._dashResourceSocket) return false;
this.socket = window._dashResourceSocket;
this.connected = this.socket.connected;
this._attachListeners();
if (this.connected) this.subscribe();
return true;
};
// dashboard.js is loaded with `defer`, so init() runs before the
// DOMContentLoaded handler above creates window._dashResourceSocket —
// consulting it here always missed and opened a second, permanent
// connection on top of the resource socket. Decide after
// DOMContentLoaded instead: that handler registered its listener first,
// so the shared socket exists by then. The dedicated-socket fallback
// stays for pages where the resource socket was never created.
if (document.readyState === 'loading' || document.readyState === 'interactive') {
document.addEventListener('DOMContentLoaded', () => {
if (!adoptSharedSocket()) this.connectSocket();
}, { once: true });
} else if (!adoptSharedSocket()) {
this.connectSocket();
}
}
connectSocket() {
if (!window.io) return;
this.socket = window.io({
transports: ['websocket'],
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000
});
this._attachListeners();
}
_attachListeners() {
if (!this.socket) return;
this.socket.on('connect', () => {
this.connected = true;
this.subscribe();
});
this.socket.on('disconnect', () => {
this.connected = false;
});
this.socket.on('dashboard:initial', (data) => {
if (data.statuses) {
Object.entries(data.statuses).forEach(([name, status]) => {
this.updateServerCard(name, status);
});
}
});
this.socket.on('server:status', (data) => {
this.updateServerCard(data.name, data);
});
this.socket.on('node:status', (data) => {
this.updateNodeIndicators(data.id, data);
});
}
subscribe() {
const serverNames = Array.from(this.serverCards.keys());
// The server caps dashboard:subscribe at 500 names per call
// (slice(0, 500)), and the card registry grows with infinite scroll —
// chunk so every card's rooms stay joined. Each call answers with its
// own dashboard:initial, and the handler merges them by name.
for (let i = 0; i < serverNames.length; i += 500) {
this.socket.emit('dashboard:subscribe', { bots: serverNames.slice(i, i + 500) });
}
}
// Register cards appended after page load (infinite scroll). Without this
// they are missing from serverCards, so every server:status event for them
// is dropped in updateServerCard and their badges stay frozen at the REST
// fetch values.
registerCards(root) {
const scope = root && typeof root.querySelectorAll === 'function' ? root : document;
const fresh = [];
scope.querySelectorAll('[data-bot-card]').forEach(card => {
const name = card.dataset.name;
if (!name) return;
const key = name.toLowerCase();
if (this.serverCards.has(key)) return;
this.serverCards.set(key, card);
fresh.push(key);
});
if (!fresh.length) return;
// Join the dashboard rooms for the new cards only: the server answers
// with dashboard:initial scoped to these names, which backfills their
// current status. Re-emitting the full list on every page append would
// re-push statuses for every known server. Chunked at the server's
// 500-name dashboard:subscribe cap.
if (this.socket && this.connected) {
for (let i = 0; i < fresh.length; i += 500) {
this.socket.emit('dashboard:subscribe', { bots: fresh.slice(i, i + 500) });
}
}
// Live resource stats ride on the shared resource socket, but only while
// the bulk subscription is active — a hidden tab has unsubscribed, and
// the next visibilitychange/connect re-subscription re-reads the DOM and
// picks the new cards up anyway.
if (window.__dashResourceBridge && window.__dashResourceBridge.isActive()) {
window.__dashResourceBridge.subscribe(fresh);
}
}
updateServerCard(name, status) {
const cardName = String(name || '').toLowerCase();
const card = this.serverCards.get(cardName);
if (!card) return;
this.statuses.set(cardName, status);
const statusEl = card.querySelector('.bot-card__status');
if (statusEl) {
const normalized = this.normalizeStatus(status.status);
// An unrecognized status ('unknown', 'installing', ...) carries no
// authoritative container state, so it must not rewrite the chip —
// same policy as updateCardFromResourceData (resources:data). Node
// outages broadcast status 'unknown' on both channels; rewriting here
// while that handler kept the prior chip made the same event paint one
// card gray and leave its neighbour green/red depending on which socket
// delivered it. The offline overlay below surfaces the outage either way.
if (normalized !== null) {
const allStatusClasses = ['status-online', 'status-stopped', 'status-unknown'];
card.classList.remove(...allStatusClasses);
statusEl.classList.remove(...allStatusClasses);
if (normalized === 'online') {
card.classList.add('status-online');
statusEl.classList.add('status-online');
} else {
card.classList.add('status-stopped');
statusEl.classList.add('status-stopped');
}
}
}
if ('nodeOnline' in status && typeof window.updateNodeOfflineStatus === 'function') {
window.updateNodeOfflineStatus(name, status.nodeOnline === true);
}
}
updateNodeIndicators(nodeId, status) {
const isOnline = status && (status.online === true || status.online === 1);
const targetId = String(nodeId || '').toLowerCase().trim();
if (!targetId) return;
document.querySelectorAll('.bot-card[data-node-id]').forEach(card => {
const cardNodeId = String(card.getAttribute('data-node-id') || '').toLowerCase().trim();
if (!cardNodeId) return;
if (cardNodeId === targetId) {
const name = card.dataset.name;
if (name && typeof window.updateNodeOfflineStatus === 'function') {
window.updateNodeOfflineStatus(name, isOnline);
}
}
});
}
normalizeStatus(status) {
const raw = String(status || '').toLowerCase();
if (['online', 'running', 'up', 'healthy'].some(t => raw.includes(t))) return 'online';
if (raw.includes('unknown')) return null;
if (['offline', 'exited', 'stopped', 'down', 'dead', 'error'].some(t => raw.includes(t))) return 'stopped';
if (!raw) return 'stopped';
return null;
}
destroy() {
if (this.socket) {
this.socket.emit('dashboard:unsubscribe');
}
}
}
window.dashboardStatus = new DashboardStatusManager();
window.dashboardStatus.init();
(function initDashboardInfiniteScroll() {
const grid = document.querySelector('.bot-grid[data-bot-grid]');
const sentinel = document.getElementById('infiniteScrollSentinel');
const loader = document.getElementById('dashInfiniteLoader');
if (!grid || !sentinel) return;
let isFetching = false;
function renderBotCard(bot) {
const statusClass = bot.status === 'online' || bot.status === 'running'
? 'status-online' : (bot.status === 'stopped' || bot.status === 'exited' ? 'status-stopped' : 'status-unknown');
const nodeOffline = bot.nodeOnline === false;
const card = document.createElement('article');
card.className = `bot-card ${statusClass}${nodeOffline ? ' node-offline is-offline' : ''}`;
card.setAttribute('data-bot-card', '');
card.setAttribute('data-name', (bot.name || '').toLowerCase());
card.setAttribute('data-display-name', (bot.displayName || '').toLowerCase());
card.setAttribute('data-node-id', bot.nodeId || '');
card.setAttribute('data-href', `/server/${bot.name}`);
card.innerHTML = `
<div class="bot-card__icon-box">
<svg class="bot-card__server-icon" aria-hidden="true" style="width:24px;height:24px;"><use href="#icon-servercard-icon"/></svg>
</div>
<div class="bot-card__name-container">
<h3 class="bot-card__name">${escapeHtml(bot.displayName || bot.name)}</h3>
<button class="bot-card__pin-btn" type="button" aria-label="Pin Server">
<svg class="bot-card__pin-img bot-card__pin-img--pinned" aria-hidden="true" style="width:14px;height:14px;"><use href="#icon-pinned-icon"/></svg>
<svg class="bot-card__pin-img bot-card__pin-img--unpinned" aria-hidden="true" style="width:14px;height:14px;"><use href="#icon-unpinned-icon"/></svg>
</button>
</div>
<div class="bot-card__stats">
<div class="bot-card__stat">
<span class="bot-card__stat-icon bot-card__stat-icon--memory">
<svg class="bot-card__stat-img" aria-hidden="true" style="width:16px;height:16px;"><use href="#icon-ram-icon"/></svg>
</span>
<span class="bot-card__stat-chip">
<span class="bot-card__stat-value bot-card__stat-value--memory">
${bot.memory && bot.memory.label ? escapeHtml(bot.memory.label.split('/')[0].trim()) : '0 MB'}
</span>
</span>
</div>
<div class="bot-card__stat">
<span class="bot-card__stat-icon bot-card__stat-icon--cpu">
<svg class="bot-card__stat-img" aria-hidden="true" style="width:16px;height:16px;"><use href="#icon-cpu-icon"/></svg>
</span>
<span class="bot-card__stat-chip">
<span class="bot-card__stat-value bot-card__stat-value--cpu">
${bot.cpu ? escapeHtml(bot.cpu) : '0%'}
</span>
</span>
</div>
<div class="bot-card__stat">
<span class="bot-card__stat-icon bot-card__stat-icon--disk">
<svg class="bot-card__stat-img" aria-hidden="true" style="width:16px;height:16px;"><use href="#icon-storage-icon"/></svg>
</span>
<span class="bot-card__stat-chip">
<span class="bot-card__stat-value bot-card__stat-value--disk">
${bot.disk && bot.disk.label ? escapeHtml(bot.disk.label.split('/')[0].trim()) : '0 MB'}
</span>
</span>
</div>
<div class="bot-card__uptime-wrapper" style="display: ${bot.status === 'online' || bot.status === 'running' ? 'flex' : 'none'};">
<span class="bot-card__stat-icon bot-card__stat-icon--uptime">
<i class="fa-solid fa-clock"></i>
</span>
<span class="bot-card__stat-chip">
<span class="bot-card__stat-value bot-card__uptime-value">${escapeHtml(formatUptimeShort(bot.uptime))}</span>
</span>
</div>
</div>
<div class="bot-card__offline" data-offline-overlay>
<svg class="offline-alert-icon" aria-hidden="true" style="width:18px;height:18px;"><use href="#icon-alert-icon"/></svg>
<div class="offline-text">Can't establish connection to the server</div>
</div>
`;
card.addEventListener('click', (e) => {
if (e.target.closest('.bot-card__pin-btn')) return;
window.location.href = `/server/${bot.name}`;
});
return card;
}
async function loadNextPage() {
if (isFetching) return;
const hasMore = grid.dataset.hasMore === 'true';
if (!hasMore) return;
const currentPage = parseInt(grid.dataset.page || '1', 10);
const nextPage = currentPage + 1;
const limit = parseInt(grid.dataset.limit || '20', 10);
const search = grid.dataset.search || '';
isFetching = true;
if (loader) loader.style.display = 'block';
try {
const res = await fetch(`/api/dashboard/servers?page=${nextPage}&limit=${limit}&search=${encodeURIComponent(search)}`);
if (!res.ok) throw new Error('HTTP ' + res.status);
const data = await res.json();
if (data && data.success && Array.isArray(data.bots)) {
data.bots.forEach(bot => {
const cardEl = renderBotCard(bot);
grid.appendChild(cardEl);
});
if (data.bots.length) {
// Merge the appended cards into the pinned-first/alphabetical order
// the first page was sorted with (window.updateCardOrder is exposed
// by the inline dashboard script). Without this, page 2+ cards
// append in backend order, never join the sort, and a later pin
// click would suddenly re-sort the whole list.
try {
if (typeof window.updateCardOrder === 'function') window.updateCardOrder();
} catch (err) {
console.warn('[infinite-scroll] Failed to reorder appended cards:', err);
}
// Wire the freshly rendered cards into the live status and
// resource subscriptions; otherwise no server:status or
// resources:data event ever reaches them.
try {
window.dashboardStatus?.registerCards(grid);
} catch (err) {
console.warn('[infinite-scroll] Failed to register cards for live updates:', err);
}
}
grid.dataset.page = String(data.pagination.page);
grid.dataset.hasMore = data.pagination.hasMore ? 'true' : 'false';
}
} catch (err) {
console.error('[infinite-scroll] Error fetching next batch:', err);
} finally {
isFetching = false;
if (loader) loader.style.display = 'none';
}
}
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
loadNextPage();
}
});
}, { rootMargin: '300px' });
observer.observe(sentinel);
})();