if (typeof globalThis === "undefined") window.globalThis = window; // White-label brand name (set inline in page
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 ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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 = ` `.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) => `