diff --git a/apps/gui/ui/account.js b/apps/gui/ui/account.js index 024a622..0782d03 100644 --- a/apps/gui/ui/account.js +++ b/apps/gui/ui/account.js @@ -155,6 +155,34 @@ async function changePassword(event) { }, tr('Senha trocada. As outras sessões foram encerradas.')); } +/** True while one-time recovery codes are on screen and not yet confirmed. */ +let holdingCodes = false; + +export function holdingOneTimeCodes() { + return holdingCodes; +} + +function warnBeforeLeaving(event) { + event.preventDefault(); + event.returnValue = ''; +} + +function holdCodes() { + holdingCodes = true; + window.addEventListener('beforeunload', warnBeforeLeaving); +} + +function releaseCodes() { + holdingCodes = false; + window.removeEventListener('beforeunload', warnBeforeLeaving); +} + +/** The buttons follow the account: disabling needs an analyst with MFA on. */ +function showMfaState() { + $('#mfaStart').textContent = session.mfa_enabled ? 'Cadastrar MFA de novo' : 'Ativar MFA'; + $('#mfaDisable').hidden = session.role === 'admin' || !session.mfa_enabled; +} + function bindMfa() { const status = $('#mfaStatus'); $('#mfaStart').addEventListener('click', () => attempt(status, async () => { @@ -172,6 +200,8 @@ function bindMfa() { method: 'POST', body: { code: $('#mfaCode').value.trim() }, })); + // This session has just ended, and the page must not leave with the codes. + holdCodes(); $('#mfaEnroll').hidden = true; $('#mfaQr').removeAttribute('src'); $('#mfaKey').value = ''; @@ -188,11 +218,17 @@ function bindMfa() { status, }); // Activation ended every session of this user, this one included. - $('#mfaRecoveryDone').addEventListener('click', () => location.replace('/login.html')); + $('#mfaRecoveryDone').addEventListener('click', () => { + releaseCodes(); + location.replace('/login.html'); + }); $('#mfaDisable').addEventListener('click', () => { if (!window.confirm(tr('Desativar o MFA desta conta?'))) return; - attempt(status, () => withReauth(() => api('/api/auth/mfa/disable', { method: 'POST', body: {} })), - tr('MFA desativado.')); + attempt(status, async () => { + await withReauth(() => api('/api/auth/mfa/disable', { method: 'POST', body: {} })); + session.mfa_enabled = false; + showMfaState(); + }, tr('MFA desativado.')); }); } @@ -366,7 +402,7 @@ export function initAccount(client, current) { $('#mfaPolicy').textContent = admin ? 'O MFA é obrigatório para administradores. Cadastrar de novo troca o segredo e os códigos de recuperação.' : 'O MFA é opcional para analistas. Cadastrar de novo troca o segredo e os códigos de recuperação.'; - $('#mfaDisable').hidden = admin; + showMfaState(); $('#tokenScopeAdmin').hidden = !admin; $('#tokenScopeAdmin').disabled = !admin; $('#adminPanels').hidden = !admin; diff --git a/apps/gui/ui/app.js b/apps/gui/ui/app.js index a324dfc..f2171ff 100644 --- a/apps/gui/ui/app.js +++ b/apps/gui/ui/app.js @@ -1,5 +1,5 @@ import { setLang, tr, LOC, currentLang, serverMessage } from './i18n.js'; -import { initAccount, refreshAccount } from './account.js'; +import { initAccount, refreshAccount, holdingOneTimeCodes } from './account.js'; const SVG_NS = 'http://www.w3.org/2000/svg'; const $ = (selector) => document.querySelector(selector); @@ -1245,7 +1245,8 @@ function applyViewMeta() { } function goToLogin() { - location.replace('/login.html'); + // Recovery codes on screen exist nowhere else: their "done" button leaves. + if (!holdingOneTimeCodes()) location.replace('/login.html'); // The page is leaving: callers must not go on to render a failure. return new Promise(() => {}); } @@ -1277,10 +1278,19 @@ function accountApi(path, { method = 'GET', body } = {}) { } async function logout() { + // On failure the session is still alive: looking signed out would be a lie. + const button = $('#logoutBtn'); + const status = $('#logoutStatus'); + status.hidden = true; + button.disabled = true; try { await fetchJson('/api/auth/logout', { method: 'POST' }); + await goToLogin(); + } catch (error) { + status.textContent = `${tr('Não foi possível sair; a sessão continua ativa.')} ${error.message}`; + status.hidden = false; } finally { - location.replace('/login.html'); + button.disabled = false; } } @@ -1478,7 +1488,7 @@ async function init() { await goToLogin(); return; } - session = { username: auth.username, role: auth.role, csrf: auth.csrf }; + session = { username: auth.username, role: auth.role, csrf: auth.csrf, mfa_enabled: auth.mfa_enabled }; $('#topUser').textContent = session.username; $('#logoutBtn').addEventListener('click', logout); if (session.role !== 'admin') { diff --git a/apps/gui/ui/i18n-en.js b/apps/gui/ui/i18n-en.js index 1c3737a..aa79fd8 100644 --- a/apps/gui/ui/i18n-en.js +++ b/apps/gui/ui/i18n-en.js @@ -181,6 +181,10 @@ export const EN = { 'Pelo menos 12 caracteres. As outras sessões da conta são encerradas.': 'At least 12 characters. The account\'s other sessions are ended.', 'Cadastrar MFA': 'Enroll MFA', 'Desativar MFA': 'Disable MFA', + 'Ativar MFA': 'Enable MFA', + 'O MFA não está ativo nesta conta.': 'MFA is not enabled on this account.', + 'Cadastrar MFA de novo': 'Enroll MFA again', + 'Não foi possível sair; a sessão continua ativa.': 'Could not sign out; the session is still active.', 'Escaneie o QR no aplicativo autenticador ou digite a chave manual. Depois, informe o código gerado. Ao confirmar, todas as suas sessões terminam e você entra de novo.': 'Scan the QR with your authenticator app or type the manual key, then enter the generated code. Confirming ends all your sessions and you sign in again.', 'Escaneie o QR no aplicativo autenticador ou digite a chave manual. Depois, informe o código gerado.': 'Scan the QR with your authenticator app or type the manual key, then enter the generated code.', 'QR do cadastro de MFA': 'MFA enrollment QR', diff --git a/apps/gui/ui/i18n.js b/apps/gui/ui/i18n.js index 0f87058..7e8605d 100644 --- a/apps/gui/ui/i18n.js +++ b/apps/gui/ui/i18n.js @@ -56,6 +56,7 @@ const SERVER_MESSAGES = { 'invalid setup code': 'Código de configuração inválido.', 'the last administrator must remain': 'O último administrador precisa continuar existindo.', 'MFA is mandatory for administrators': 'O MFA é obrigatório para administradores.', + 'MFA is not enabled': 'O MFA não está ativo nesta conta.', 'no enrollment in progress': 'Nenhum cadastro de MFA em andamento.', 'username is already in use': 'Este nome de usuário já está em uso.', 'not found': 'Não encontrado.', diff --git a/apps/gui/ui/index.html b/apps/gui/ui/index.html index 5061325..938763a 100644 --- a/apps/gui/ui/index.html +++ b/apps/gui/ui/index.html @@ -70,6 +70,7 @@ +