fix(ui): keep recovery codes on screen and report failed logout

While one-time codes are visible the 401 redirect is suppressed and a
beforeunload guard is active until the done button. MFA buttons follow the
account state. A failed logout shows an error instead of looking successful.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 21:03:27 -03:00
1 parent 348e61ca95
commit 513741e403
5 files changed
+60 -8

No files matched your search

+40 -4
View File
@@ -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;
+14 -4
View File
@@ -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') {
+4
View File
@@ -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',
+1
View File
@@ -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.',
+1
View File
@@ -70,6 +70,7 @@
<button id="refreshBtn" type="button" class="btn">Atualizar status</button>
<button id="settingsBtn" type="button" class="icon-btn" aria-label="Configurações" title="Configurações">⚙</button>
<span id="topUser" class="mono user-chip"></span>
<span id="logoutStatus" class="form-error" role="alert" hidden></span>
<button id="logoutBtn" type="button" class="btn">Sair</button>
</div>
</header>