const toast = globalThis.toast; const profileEditState = { editing: false, snapshot: { username: '', email: '' }, }; function byId(id) { return document.getElementById(id); } function setText(id, value) { const element = byId(id); if (element) element.textContent = value; } function setValue(id, value) { const element = byId(id); if (element) element.value = value; } function parseApiError(payload, fallback) { return payload?.error || payload?.message || payload?.data?.error || fallback; } function setButtonBusy(id, busy) { const button = byId(id); if (!button) return; button.disabled = !!busy; } function setMfaBadge(enabled) { const badge = byId('mfaBadge'); if (!badge) return; if (enabled) { badge.className = 'inline-flex items-center rounded-full border border-emerald-500/40 bg-emerald-500/15 px-3 py-1 text-xs font-semibold text-emerald-300'; badge.textContent = 'MFA Enabled'; return; } badge.className = 'inline-flex items-center rounded-full border border-amber-500/40 bg-amber-500/10 px-3 py-1 text-xs font-semibold text-amber-300'; badge.textContent = 'MFA Disabled'; } function resetTotpWizard() { const wizard = byId('totpWizard'); if (wizard) wizard.hidden = true; setValue('totpCode', ''); const manualLabel = byId('totpManualLabel'); if (manualLabel) manualLabel.hidden = true; setText('totpManualKey', ''); } function extractTotpSecret(otpauth) { try { const parsed = new URL(String(otpauth || '')); return parsed.searchParams.get('secret') || ''; } catch { return ''; } } function normalizeTotpCode(raw) { return String(raw || '') .replace(/\D+/g, '') .slice(0, 6); } function showBackupCodes(codes) { const panel = byId('backupCodesPanel'); const list = byId('backupCodesList'); if (!panel || !list || !Array.isArray(codes)) return; list.innerHTML = ''; codes.forEach(code => { const li = document.createElement('li'); li.textContent = code; list.appendChild(li); }); panel.hidden = false; } function hideBackupCodes() { const panel = byId('backupCodesPanel'); if (panel) panel.hidden = true; const list = byId('backupCodesList'); if (list) list.innerHTML = ''; } function hideBackupCodesRegenerateForm() { const form = byId('backupCodesRegenerateForm'); if (form) form.hidden = true; } async function loadBackupCodesStatus() { const manage = byId('backupCodesManage'); if (!manage) return; try { const response = await fetch('/api/security/totp/backup-codes/status'); const payload = await response.json().catch(() => ({})); if (!response.ok || !payload?.data?.mfaEnabled) { manage.hidden = true; return; } manage.hidden = false; const remaining = Number(payload.data.remaining) || 0; setText( 'backupCodesRemaining', `Backup codes: ${remaining} of 10 remaining.` + (remaining <= 2 ? ' Consider regenerating soon.' : '') ); } catch { manage.hidden = true; } } function normalizeProfileEntryValue(value) { return String(value || '').trim(); } function readProfileEntryInputs() { return { username: normalizeProfileEntryValue(byId('usernameInput')?.value), email: normalizeProfileEntryValue(byId('emailInput')?.value), }; } function applyProfileEntryInputs({ username = '', email = '' } = {}) { setValue('usernameInput', username); setValue('emailInput', email); } function profileEntryValuesEqual(a, b) { return ( normalizeProfileEntryValue(a?.username) === normalizeProfileEntryValue(b?.username) && normalizeProfileEntryValue(a?.email) === normalizeProfileEntryValue(b?.email) ); } function setProfileEditMode(editing, { restore = false } = {}) { const isEditing = Boolean(editing); const form = byId('editProfileForm'); if (form) form.hidden = !isEditing; if (!isEditing && restore) { applyProfileEntryInputs(profileEditState.snapshot); } const editButton = byId('editProfileButton'); if (editButton) editButton.disabled = isEditing; profileEditState.editing = isEditing; } async function fetchUserProfile({ silent = false } = {}) { if (!byId('profile-container')) return; try { const response = await fetch('/api/profile'); const payload = await response.json().catch(() => ({})); const user = payload?.data || payload?.profile || payload?.user || null; if (!response.ok || !user) { throw new Error(parseApiError(payload, 'Failed to load profile')); } const entries = { username: normalizeProfileEntryValue(user.username || 'Anonymous'), email: normalizeProfileEntryValue(user.email || 'Not set'), }; setText('username', entries.username); setText('email', entries.email); const profilePicture = byId('profilePicture'); if (profilePicture) { profilePicture.src = user.avatar_url || user.profilePicture || '/shared/images/default-avatar.svg'; } if (!profileEditState.editing) { applyProfileEntryInputs(entries); profileEditState.snapshot = entries; } const mfaEnabled = !!user.mfaEnabled; setMfaBadge(mfaEnabled); setText('mfaStatus', mfaEnabled ? 'TOTP is enabled on your account.' : 'TOTP is not enabled.'); const setup = byId('mfaSetup'); const disable = byId('mfaDisable'); if (setup) setup.hidden = mfaEnabled; if (disable) disable.hidden = !mfaEnabled; if (mfaEnabled) resetTotpWizard(); if (mfaEnabled) { await loadBackupCodesStatus(); } else { const manage = byId('backupCodesManage'); if (manage) manage.hidden = true; hideBackupCodesRegenerateForm(); } } catch (error) { if (!silent) { toast?.error?.(error?.message || 'Profile load error'); } } } function openProfileEdit() { if (profileEditState.editing) return; profileEditState.snapshot = { username: normalizeProfileEntryValue( byId('usernameInput')?.value || byId('username')?.textContent || '' ), email: normalizeProfileEntryValue( byId('emailInput')?.value || byId('email')?.textContent || '' ), }; applyProfileEntryInputs(profileEditState.snapshot); setProfileEditMode(true); byId('usernameInput')?.focus(); } function closeProfileEdit({ restore = true } = {}) { setProfileEditMode(false, { restore }); } async function saveProfileChanges() { const draft = readProfileEntryInputs(); if (profileEntryValuesEqual(draft, profileEditState.snapshot)) { closeProfileEdit({ restore: false }); return; } setButtonBusy('profileSaveBtn', true); setButtonBusy('profileCancelBtn', true); try { const response = await fetch('/api/profile', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(draft), }); const payload = await response.json().catch(() => ({})); if (!response.ok) { throw new Error(parseApiError(payload, 'Save failed')); } profileEditState.snapshot = draft; toast?.success?.('Profile updated'); closeProfileEdit({ restore: false }); await fetchUserProfile({ silent: true }); } catch (error) { toast?.error?.(error?.message || 'Save failed'); } finally { setButtonBusy('profileSaveBtn', false); setButtonBusy('profileCancelBtn', false); const editButton = byId('editProfileButton'); if (editButton) editButton.disabled = profileEditState.editing; } } async function changePassword() { const newPassword = byId('newPw')?.value || ''; if (!newPassword) { toast?.error?.('New password is required'); return; } setButtonBusy('btnChangePw', true); try { const response = await fetch('/api/profile/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ newPassword }), }); const payload = await response.json().catch(() => ({})); if (!response.ok) { throw new Error(parseApiError(payload, 'Change failed')); } toast?.success?.('Password updated'); setValue('newPw', ''); } catch (error) { toast?.error?.(error?.message || 'Change failed'); } finally { setButtonBusy('btnChangePw', false); } } async function startTotpSetup() { setButtonBusy('btnStartTotp', true); try { const response = await fetch('/api/security/totp/initiate'); const payload = await response.json().catch(() => ({})); if (!response.ok || !(payload?.data?.qr || payload?.data?.otpauth)) { throw new Error(parseApiError(payload, 'Failed to start TOTP')); } const wizard = byId('totpWizard'); const qrImage = byId('totpQr'); if (wizard) wizard.hidden = false; if (qrImage && payload?.data?.qr) qrImage.src = payload.data.qr; const secret = extractTotpSecret(payload?.data?.otpauth); if (secret) { setText('totpManualKey', secret); const manualLabel = byId('totpManualLabel'); if (manualLabel) manualLabel.hidden = false; } byId('totpCode')?.focus(); } catch (error) { toast?.error?.(error?.message || 'Failed to start TOTP'); } finally { setButtonBusy('btnStartTotp', false); } } async function verifyTotpSetup() { const token = normalizeTotpCode(byId('totpCode')?.value || ''); if (token.length !== 6) { toast?.error?.('Enter a valid 6-digit TOTP code'); return; } setButtonBusy('btnVerifyTotp', true); try { const response = await fetch('/api/security/totp/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }), }); const payload = await response.json().catch(() => ({})); if (!response.ok) { throw new Error(parseApiError(payload, 'Invalid code')); } toast?.success?.('MFA enabled'); resetTotpWizard(); if (Array.isArray(payload?.data?.backupCodes)) { showBackupCodes(payload.data.backupCodes); } await fetchUserProfile({ silent: true }); } catch (error) { toast?.error?.(error?.message || 'Invalid code'); } finally { setButtonBusy('btnVerifyTotp', false); } } async function regenerateBackupCodes() { setButtonBusy('btnConfirmRegenerateBackupCodes', true); try { const response = await fetch('/api/security/totp/backup-codes/regenerate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}), }); const payload = await response.json().catch(() => ({})); if (!response.ok) { throw new Error(parseApiError(payload, 'Failed to regenerate backup codes')); } toast?.success?.('Backup codes regenerated'); hideBackupCodesRegenerateForm(); if (Array.isArray(payload?.data?.backupCodes)) { showBackupCodes(payload.data.backupCodes); } await loadBackupCodesStatus(); } catch (error) { toast?.error?.(error?.message || 'Failed to regenerate backup codes'); } finally { setButtonBusy('btnConfirmRegenerateBackupCodes', false); } } async function disableTotp() { const token = normalizeTotpCode(window.prompt('Enter the current 6-digit authenticator code to disable MFA:') || ''); if (token.length !== 6) { toast?.error?.('Enter a valid 6-digit TOTP code'); return; } setButtonBusy('btnDisableTotp', true); try { const response = await fetch('/api/security/totp/disable', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }), }); const payload = await response.json().catch(() => ({})); if (!response.ok) { throw new Error(parseApiError(payload, 'Disable failed')); } toast?.success?.('MFA disabled'); await fetchUserProfile({ silent: true }); } catch (error) { toast?.error?.(error?.message || 'Disable failed'); } finally { setButtonBusy('btnDisableTotp', false); } } async function uploadAvatar() { const file = byId('avatarFile')?.files?.[0]; if (!file) { toast?.error?.('Choose an image'); return; } setButtonBusy('btnUploadAvatar', true); try { const formData = new FormData(); formData.append('avatar', file); const response = await fetch('/api/profile/avatar', { method: 'POST', body: formData }); const payload = await response.json().catch(() => ({})); if (!response.ok) { throw new Error(parseApiError(payload, 'Upload failed')); } toast?.success?.('Avatar updated'); await fetchUserProfile({ silent: true }); } catch (error) { toast?.error?.(error?.message || 'Upload failed'); } finally { setButtonBusy('btnUploadAvatar', false); } } function wireProfileEvents() { byId('editProfileButton')?.addEventListener('click', openProfileEdit); byId('editProfileForm')?.addEventListener('submit', event => { event.preventDefault(); saveProfileChanges(); }); byId('profileCancelBtn')?.addEventListener('click', () => closeProfileEdit({ restore: true })); byId('changePasswordForm')?.addEventListener('submit', event => { event.preventDefault(); changePassword(); }); byId('btnStartTotp')?.addEventListener('click', startTotpSetup); byId('btnVerifyTotp')?.addEventListener('click', verifyTotpSetup); byId('mfaDisableForm')?.addEventListener('submit', event => { event.preventDefault(); disableTotp(); }); byId('btnUploadAvatar')?.addEventListener('click', uploadAvatar); byId('btnDismissBackupCodes')?.addEventListener('click', hideBackupCodes); byId('btnCopyBackupCodes')?.addEventListener('click', async () => { const codes = Array.from(byId('backupCodesList')?.children || []).map(li => li.textContent); if (!codes.length) return; try { await navigator.clipboard.writeText(codes.join('\n')); toast?.success?.('Backup codes copied'); } catch { toast?.error?.('Could not copy — please copy manually'); } }); byId('btnRegenerateBackupCodes')?.addEventListener('click', () => { const form = byId('backupCodesRegenerateForm'); if (form) form.hidden = false; }); byId('btnCancelRegenerateBackupCodes')?.addEventListener('click', hideBackupCodesRegenerateForm); byId('backupCodesRegenerateForm')?.addEventListener('submit', event => { event.preventDefault(); regenerateBackupCodes(); }); byId('totpCode')?.addEventListener('keydown', event => { if (event.key === 'Enter') { event.preventDefault(); verifyTotpSetup(); } }); const profileImage = byId('profilePicture'); if (profileImage) { profileImage.addEventListener( 'error', () => { const fallbackSrc = profileImage.getAttribute('data-fallback-src'); if (fallbackSrc && profileImage.src !== fallbackSrc) profileImage.src = fallbackSrc; }, { once: true } ); } } document.addEventListener('DOMContentLoaded', () => { if (!byId('profile-container')) return; wireProfileEvents(); fetchUserProfile(); });