diff --git a/apps/gui/ui/account.js b/apps/gui/ui/account.js new file mode 100644 index 0000000..024a622 --- /dev/null +++ b/apps/gui/ui/account.js @@ -0,0 +1,378 @@ +// The "Conta" view. Everything from the server goes in through textContent. +import { tr, LOC } from './i18n.js'; + +const $ = (selector) => document.querySelector(selector); + +let api = null; +let session = { username: '', role: '' }; + +function el(tag, props = {}, children = []) { + const node = document.createElement(tag); + for (const [key, value] of Object.entries(props)) { + if (key === 'text') node.textContent = value; + else if (key === 'class') node.className = value; + else if (key === 'on') node.addEventListener('click', value); + else node.setAttribute(key, value); + } + for (const child of children) node.append(child); + return node; +} + +function when(unix) { + return unix ? new Date(unix * 1000).toLocaleString(LOC()) : '—'; +} + +function say(box, text, ok = false) { + box.textContent = text; + box.className = ok ? 'form-ok' : 'form-error'; + box.hidden = !text; +} + +function explain(error) { + if (!error.retryAfter) return error.message; + return `${error.message} ${tr('Tente de novo em {n} s.').replace('{n}', error.retryAfter)}`; +} + +function fillRows(body, rows, columns, emptyText) { + body.replaceChildren( + ...(rows.length + ? rows + : [el('tr', {}, [el('td', { colspan: String(columns), class: 'empty-cell', text: emptyText })])]), + ); +} + +// ---- Reauthentication ------------------------------------------------------ + +class ReauthCancelled extends Error {} + +function promptReauth() { + const dialog = $('#reauthDlg'); + const form = $('#reauthForm'); + const error = $('#reauthError'); + const password = $('#reauthPass'); + const code = $('#reauthCode'); + return new Promise((resolve, reject) => { + const finish = (confirmed) => { + form.removeEventListener('submit', submit); + $('#reauthCancel').removeEventListener('click', cancel); + dialog.removeEventListener('cancel', cancel); + password.value = ''; + code.value = ''; + dialog.close(); + if (confirmed) resolve(); + else reject(new ReauthCancelled()); + }; + const cancel = (event) => { + event.preventDefault(); + finish(false); + }; + const submit = async (event) => { + event.preventDefault(); + const button = form.querySelector('button[type="submit"]'); + button.disabled = true; + say(error, ''); + try { + await api('/api/auth/reauth', { + method: 'POST', + body: { password: password.value, code: code.value.trim() || null }, + }); + finish(true); + } catch (failure) { + say(error, explain(failure)); + } finally { + button.disabled = false; + } + }; + say(error, ''); + form.addEventListener('submit', submit); + $('#reauthCancel').addEventListener('click', cancel); + dialog.addEventListener('cancel', cancel); + dialog.showModal(); + password.focus(); + }); +} + +/** Runs a sensitive action, asking for password and code once if the server wants them. */ +async function withReauth(action) { + try { + return await action(); + } catch (error) { + if (error.code !== 'recent authentication required') throw error; + } + await promptReauth(); + return action(); +} + +/** Runs a panel's action and reports the outcome in its status line. */ +async function attempt(box, action, done = '') { + say(box, ''); + try { + await action(); + if (done) say(box, done, true); + } catch (error) { + if (!(error instanceof ReauthCancelled)) say(box, explain(error)); + } +} + +// ---- One-time secrets ------------------------------------------------------ + +function bindSecret({ box, copy, download, fileName, status }) { + copy.addEventListener('click', async () => { + const label = copy.textContent; + try { + await navigator.clipboard.writeText(box.textContent); + copy.textContent = tr('Copiado'); + window.setTimeout(() => { copy.textContent = label; }, 1400); + } catch { + say(status, tr('Não foi possível copiar. Selecione o texto e copie à mão.')); + } + }); + download.addEventListener('click', () => { + const url = URL.createObjectURL(new Blob([`${box.textContent}\n`], { type: 'text/plain' })); + const link = el('a', { href: url, download: fileName }); + link.click(); + URL.revokeObjectURL(url); + }); +} + +// ---- Own credentials ------------------------------------------------------- + +async function changePassword(event) { + event.preventDefault(); + const box = $('#pwStatus'); + const form = event.currentTarget; + if ($('#pwNew').value !== $('#pwRepeat').value) { + say(box, tr('As senhas não coincidem.')); + return; + } + await attempt(box, async () => { + await api('/api/auth/password', { + method: 'POST', + body: { current: $('#pwCurrent').value, new: $('#pwNew').value }, + }); + form.reset(); + await loadSessions(); + }, tr('Senha trocada. As outras sessões foram encerradas.')); +} + +function bindMfa() { + const status = $('#mfaStatus'); + $('#mfaStart').addEventListener('click', () => attempt(status, async () => { + const data = await withReauth(() => api('/api/auth/enroll/start', { method: 'POST', body: {} })); + $('#mfaQr').src = `data:image/png;base64,${data.qr_png_base64}`; + $('#mfaKey').value = data.manual_key; + $('#mfaCode').value = ''; + $('#mfaEnroll').hidden = false; + $('#mfaCode').focus(); + })); + $('#mfaEnroll').addEventListener('submit', (event) => { + event.preventDefault(); + attempt(status, async () => { + const reply = await withReauth(() => api('/api/auth/enroll/confirm', { + method: 'POST', + body: { code: $('#mfaCode').value.trim() }, + })); + $('#mfaEnroll').hidden = true; + $('#mfaQr').removeAttribute('src'); + $('#mfaKey').value = ''; + $('#mfaActions').hidden = true; + $('#mfaRecoveryCodes').textContent = reply.recovery_codes.join('\n'); + $('#mfaRecovery').hidden = false; + }); + }); + bindSecret({ + box: $('#mfaRecoveryCodes'), + copy: $('#mfaRecoveryCopy'), + download: $('#mfaRecoveryDownload'), + fileName: 'acaua-codigos-de-recuperacao.txt', + status, + }); + // Activation ended every session of this user, this one included. + $('#mfaRecoveryDone').addEventListener('click', () => 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.')); + }); +} + +// ---- Sessions and tokens --------------------------------------------------- + +async function loadSessions() { + const box = $('#sessionStatus'); + const list = await api('/api/auth/sessions'); + fillRows($('#sessionRows'), list.map((s) => el('tr', {}, [ + el('td', { text: when(s.created_at) }), + el('td', { text: when(s.last_seen) }), + el('td', { text: when(s.expires_at) }), + el('td', { class: 'row-actions' }, [el('button', { + type: 'button', + class: 'btn small danger', + text: 'Encerrar', + on: () => attempt(box, async () => { + await api('/api/auth/sessions', { method: 'DELETE', body: { id: s.id } }); + await loadSessions(); + }), + })]), + ])), 4, 'Nenhuma sessão ativa.'); +} + +async function loadTokens() { + const box = $('#tokenStatus'); + const list = await api('/api/auth/tokens'); + fillRows($('#tokenRows'), list.map((token) => el('tr', {}, [ + el('td', { class: 'mono', text: token.name }), + el('td', { text: token.scope === 'admin' ? 'Administração' : 'Leitura' }), + el('td', { text: when(token.expires_at) }), + el('td', { class: 'row-actions' }, [el('button', { + type: 'button', + class: 'btn small danger', + text: 'Revogar', + on: () => attempt(box, async () => { + await api('/api/auth/tokens', { method: 'DELETE', body: { id: token.id } }); + await loadTokens(); + }), + })]), + ])), 4, 'Nenhum token criado.'); +} + +function bindTokens() { + const status = $('#tokenStatus'); + $('#tokenForm').addEventListener('submit', (event) => { + event.preventDefault(); + const form = event.currentTarget; + attempt(status, async () => { + const days = Number($('#tokenDays').value); + const made = await withReauth(() => api('/api/auth/tokens', { + method: 'POST', + body: { + name: $('#tokenName').value, + scope: $('#tokenScope').value, + expires_at: Math.floor(Date.now() / 1000) + days * 86400, + }, + })); + form.reset(); + $('#tokenValue').textContent = made.token; + $('#tokenOnce').hidden = false; + await loadTokens(); + }); + }); + bindSecret({ + box: $('#tokenValue'), + copy: $('#tokenCopy'), + download: $('#tokenDownload'), + fileName: 'acaua-token.txt', + status, + }); + $('#tokenDone').addEventListener('click', () => { + $('#tokenValue').textContent = ''; + $('#tokenOnce').hidden = true; + }); +} + +// ---- Administration -------------------------------------------------------- + +function roleSelect(user) { + const select = el('select', { name: 'role', 'aria-label': 'Papel' }, [ + el('option', { value: 'analyst', text: 'Analista' }), + el('option', { value: 'admin', text: 'Administrador' }), + ]); + select.value = user.role; + select.addEventListener('change', () => attempt($('#userStatus'), async () => { + try { + await withReauth(() => api('/api/admin/users', { + method: 'PATCH', + body: { id: user.id, role: select.value }, + })); + } finally { + await loadUsers(); + } + })); + return select; +} + +async function loadUsers() { + const box = $('#userStatus'); + const list = await api('/api/admin/users'); + fillRows($('#userRows'), list.map((user) => el('tr', {}, [ + el('td', { class: 'mono', text: user.username }), + el('td', {}, [roleSelect(user)]), + el('td', { text: user.mfa_enabled ? 'Ativo' : 'Inativo' }), + el('td', { text: when(user.created_at) }), + el('td', { class: 'row-actions' }, [el('button', { + type: 'button', + class: 'btn small danger', + text: 'Excluir', + on: () => { + if (!window.confirm(tr('Excluir esta conta? As sessões e os tokens dela também acabam.'))) return; + attempt(box, async () => { + await withReauth(() => api('/api/admin/users', { method: 'DELETE', body: { id: user.id } })); + await loadUsers(); + }); + }, + })]), + ])), 5, 'Nenhuma conta.'); +} + +async function loadAudit() { + const list = await api('/api/admin/audit?limit=100'); + fillRows($('#auditRows'), list.slice().reverse().map((entry) => el('tr', {}, [ + el('td', { class: 'mono', text: entry.ts }), + el('td', { class: 'mono', text: entry.action }), + el('td', { class: 'mono', text: entry.actor ?? '—' }), + el('td', { class: 'mono', text: entry.ip ?? '—' }), + el('td', { text: entry.ok ? 'Sim' : 'Não' }), + el('td', { class: 'mono', text: entry.detail ?? '—' }), + ])), 6, 'Nenhum evento registrado.'); +} + +function bindAdmin() { + $('#userForm').addEventListener('submit', (event) => { + event.preventDefault(); + const form = event.currentTarget; + attempt($('#userStatus'), async () => { + await withReauth(() => api('/api/admin/users', { + method: 'POST', + body: { + username: $('#userName').value, + password: $('#userPass').value, + role: $('#userRole').value, + }, + })); + form.reset(); + await Promise.all([loadUsers(), loadAudit()]); + }, tr('Conta criada.')); + }); + $('#auditRefresh').addEventListener('click', () => attempt($('#auditStatus'), loadAudit)); +} + +// ---- Entry points ---------------------------------------------------------- + +export function refreshAccount() { + attempt($('#sessionStatus'), loadSessions); + attempt($('#tokenStatus'), loadTokens); + if (session.role === 'admin') { + attempt($('#userStatus'), loadUsers); + attempt($('#auditStatus'), loadAudit); + } +} + +export function initAccount(client, current) { + api = client; + session = current; + const admin = session.role === 'admin'; + $('#accountUser').textContent = session.username; + $('#accountRole').textContent = admin ? 'Administrador' : 'Analista'; + $('#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; + $('#tokenScopeAdmin').hidden = !admin; + $('#tokenScopeAdmin').disabled = !admin; + $('#adminPanels').hidden = !admin; + + $('#passwordForm').addEventListener('submit', changePassword); + bindMfa(); + bindTokens(); + if (admin) bindAdmin(); +} diff --git a/apps/gui/ui/app.css b/apps/gui/ui/app.css index dcc7ec2..063ead2 100644 --- a/apps/gui/ui/app.css +++ b/apps/gui/ui/app.css @@ -699,3 +699,69 @@ html[data-theme="light"] .host-detail-row td { background: rgba(20, 58, 64, 0.03 .legend { display: none; } .top-actions { justify-content: flex-start; } } + +/* ---- Login and account ---- */ +.auth-shell { width: min(460px, 100%); margin: 0 auto; padding: 40px 16px; display: grid; gap: 16px; } +.auth-brand { justify-content: center; } +.auth-card { margin-top: 0; } +.auth-step { display: grid; gap: 14px; } +.auth-step[hidden], .form-stack[hidden] { display: none; } +.auth-step h1 { font-size: 1.3rem; } +.auth-step .link-btn { justify-self: center; } +.auth-prefs { display: flex; justify-content: center; gap: 10px; } +.notice.notice-warn { margin: 0; } +.notice strong { white-space: normal; } +.form-error { + margin-bottom: 14px; + padding: 10px 12px; + border: 1px solid color-mix(in srgb, var(--danger) 45%, transparent); + border-radius: 10px; + color: var(--danger); + font-size: 0.84rem; +} +.form-ok { color: var(--accent); font-size: 0.84rem; } +.qr { justify-self: center; display: block; margin: 0 auto; width: 200px; height: 200px; padding: 8px; border-radius: 10px; background: #ffffff; image-rendering: pixelated; } +.secret-box { + margin: 0; + padding: 12px 14px; + border: 1px solid var(--line-strong); + border-radius: 10px; + background: var(--panel-solid); + color: var(--text); + font-family: var(--mono); + font-size: 0.84rem; + line-height: 1.7; + white-space: pre-wrap; + overflow-wrap: anywhere; + user-select: all; +} +.secret-actions { display: flex; gap: 8px; flex-wrap: wrap; } +.account-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; align-items: start; } +.account-grid > .panel { margin-top: 16px; } +.form-stack { display: grid; gap: 12px; } +.form-inline { display: flex; gap: 10px; align-items: flex-end; flex-wrap: wrap; margin-bottom: 14px; } +.form-inline .field { min-width: 150px; } +.data-table { width: 100%; border-collapse: collapse; } +.data-table th { + padding: 10px 12px; + color: var(--muted); + font-size: 0.68rem; + font-weight: 600; + letter-spacing: 0.08em; + text-align: left; + text-transform: uppercase; +} +.data-table td { padding: 10px 12px; border-top: 1px solid var(--line); font-size: 0.82rem; vertical-align: middle; overflow-wrap: break-word; } +.data-table select { padding: 6px 8px; } +.data-table .row-actions { text-align: right; white-space: nowrap; } +.btn.danger { color: var(--danger); } +.btn.danger:hover { border-color: var(--danger); } +.user-chip { color: var(--muted); font-size: 0.8rem; } +.analysis-locked { margin: 0 0 14px; } +@media (max-width: 1120px) { .account-grid { grid-template-columns: minmax(0, 1fr); } } +.notice[hidden], .field-row[hidden], .btn[hidden] { display: none; } +.empty-cell { color: var(--muted); } +.form-inline .field.compact > span { font-size: 0.74rem; } +html[data-theme="light"] .btn.primary { color: #ffffff; } +.panel [role="status"] { margin: 0 0 12px; } +#tokenOnce { margin-bottom: 14px; } diff --git a/apps/gui/ui/app.js b/apps/gui/ui/app.js index 1be03b0..a324dfc 100644 --- a/apps/gui/ui/app.js +++ b/apps/gui/ui/app.js @@ -1,4 +1,5 @@ -import { setLang, tr, LOC, currentLang } from './i18n.js'; +import { setLang, tr, LOC, currentLang, serverMessage } from './i18n.js'; +import { initAccount, refreshAccount } from './account.js'; const SVG_NS = 'http://www.w3.org/2000/svg'; const $ = (selector) => document.querySelector(selector); @@ -53,6 +54,8 @@ const state = { expandedHosts: new Set(), }; +let session = { username: '', role: '', csrf: '' }; + const VIEW_META = { overview: { title: 'Visão geral', @@ -70,6 +73,10 @@ const VIEW_META = { title: 'Análise', sub: 'Ingestão de logs Zeek e relatório da execução', }, + account: { + title: 'Conta', + sub: 'Senha, MFA, sessões e tokens', + }, }; let themePreference = localStorage.getItem('acaua-theme') || 'auto'; @@ -1237,11 +1244,44 @@ function applyViewMeta() { document.title = `${t(meta.title)} · Acauã`; } +function goToLogin() { + location.replace('/login.html'); + // The page is leaving: callers must not go on to render a failure. + return new Promise(() => {}); +} + async function fetchJson(path, options = {}) { - const response = await fetch(path, options); + const method = (options.method || 'GET').toUpperCase(); + const headers = { ...options.headers }; + if (method !== 'GET' && method !== 'HEAD') headers['X-Acaua-CSRF'] = session.csrf; + const response = await fetch(path, { ...options, headers }); const body = await response.json().catch(() => ({})); - if (!response.ok) throw new Error(body.error || response.statusText); - return body; + if (response.ok) return body; + // A wrong password in a form is also a 401, but must stay on the page. + if (response.status === 401 && body.error === 'authentication required') return goToLogin(); + const raw = body.error || response.statusText; + const error = new Error(serverMessage(raw)); + error.code = raw; + error.retryAfter = response.headers.get('Retry-After'); + throw error; +} + +/** `fetchJson` with a JSON body, for the account screen. */ +function accountApi(path, { method = 'GET', body } = {}) { + if (body === undefined) return fetchJson(path, { method }); + return fetchJson(path, { + method, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); +} + +async function logout() { + try { + await fetchJson('/api/auth/logout', { method: 'POST' }); + } finally { + location.replace('/login.html'); + } } async function call(command, args = {}) { @@ -1315,6 +1355,7 @@ async function refreshAll() { } async function analyzeDataset() { + if (session.role !== 'admin') return; const path = datasetPath.value.trim(); if (!path) { output.textContent = t('Nenhum dataset selecionado.'); @@ -1336,7 +1377,9 @@ async function analyzeDataset() { } catch (error) { reportSummary.hidden = true; reportStatus.textContent = '—'; - output.textContent = message('Falha na análise: {n}', error.message); + output.textContent = error.code === 'analysis failed' + ? error.message + : message('Falha na análise: {n}', error.message); $('#gotoAlerts').hidden = true; $('#gotoHosts').hidden = true; $('#openReport').hidden = true; @@ -1417,6 +1460,7 @@ function showView(target, { updateHash = true } = {}) { if (target === 'overview') renderCharts(); if (target === 'alerts') renderAlerts(); if (target === 'hosts') renderHosts(); + if (target === 'account' && session.csrf) refreshAccount(); window.scrollTo({ top: 0, behavior: 'instant' }); } @@ -1425,10 +1469,23 @@ function initViewFromHash() { return VIEW_META[target] ? target : 'overview'; } -function init() { +async function init() { applyTheme(themePreference); langSel.value = localStorage.getItem('acaua-lang') || 'auto'; setLang(langSel.value); + const auth = await fetch('/api/auth/state').then((response) => response.json()); + if (!auth.authenticated) { + await goToLogin(); + return; + } + session = { username: auth.username, role: auth.role, csrf: auth.csrf }; + $('#topUser').textContent = session.username; + $('#logoutBtn').addEventListener('click', logout); + if (session.role !== 'admin') { + $('#analysisForm').hidden = true; + $('#analysisLocked').hidden = false; + } + initAccount(accountApi, session); datasetPath.value = localStorage.getItem('acaua-last-path') || ''; state.view = initViewFromHash(); showView(state.view, { updateHash: false }); @@ -1592,4 +1649,4 @@ function init() { }; } -init(); +init().catch((error) => console.error(error)); diff --git a/apps/gui/ui/i18n-en.js b/apps/gui/ui/i18n-en.js index bef8ac1..1c3737a 100644 --- a/apps/gui/ui/i18n-en.js +++ b/apps/gui/ui/i18n-en.js @@ -166,4 +166,138 @@ export const EN = { 'Hosts por score de fusão': 'Hosts by fusion score', 'Distribuição de alertas por pilar': 'Alert distribution per pillar', 'Filtrar por pilar': 'Filter by pillar', + 'Entrar · Acauã': 'Sign in · Acauã', + 'Entrar': 'Sign in', + 'Sair': 'Sign out', + 'Conta': 'Account', + 'senha, MFA e tokens': 'password, MFA and tokens', + 'Senha, MFA, sessões e tokens': 'Password, MFA, sessions and tokens', + 'Sua conta': 'Your account', + 'Trocar a senha': 'Change password', + 'Senha atual': 'Current password', + 'Nova senha': 'New password', + 'Repita a nova senha': 'Repeat the new password', + 'Senha': 'Password', + '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', + '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', + 'Chave manual': 'Manual key', + 'Código de 6 dígitos': '6-digit code', + 'Confirmar cadastro': 'Confirm enrollment', + 'Guarde estes códigos agora: eles só aparecem esta vez e cada um funciona uma única vez. O código usado no cadastro já foi gasto: para entrar, espere o': 'Save these codes now: they appear only this once and each works a single time. The enrollment code is already spent: to sign in, wait for the', + 'próximo': 'next', + 'código (até 30 s) ou use um código de recuperação.': 'code (up to 30 s) or use a recovery code.', + 'Copiar': 'Copy', + 'Baixar': 'Download', + 'Já guardei, ir para o login': 'Saved, go to sign in', + 'Sessões': 'Sessions', + 'Inclui esta sessão: encerrá-la leva de volta ao login.': 'Includes this session: ending it returns you to sign in.', + 'Último uso': 'Last used', + 'Expira': 'Expires', + 'Ações': 'Actions', + 'Tokens de API': 'API tokens', + 'O valor do token só aparece na criação. Validade de até 365 dias.': 'The token value appears only at creation. Valid for up to 365 days.', + 'Nome': 'Name', + 'Escopo': 'Scope', + 'Leitura': 'Read', + 'Administração': 'Administration', + 'Dias de validade': 'Days valid', + 'Criar token': 'Create token', + 'Copie este token agora: ele não aparece de novo.': 'Copy this token now: it will not appear again.', + 'Já guardei': 'Saved', + 'Contas e papéis': 'Accounts and roles', + 'Criar, excluir ou mudar o papel de uma conta pede sua senha e seu código.': 'Creating, deleting or changing an account\'s role asks for your password and code.', + 'Usuário': 'Username', + 'Senha inicial': 'Initial password', + 'Papel': 'Role', + 'Analista': 'Analyst', + 'Administrador': 'Administrator', + 'Criar conta': 'Create account', + 'MFA': 'MFA', + 'Criada em': 'Created', + 'Auditoria': 'Audit', + 'Os 100 eventos mais recentes.': 'The 100 most recent events.', + 'Atualizar': 'Refresh', + 'Quando': 'When', + 'Ação': 'Action', + 'Quem': 'Who', + 'IP': 'IP', + 'Êxito': 'Success', + 'Detalhe': 'Detail', + 'Confirme sua identidade': 'Confirm your identity', + 'Esta ação pede sua senha e, se o MFA estiver ativo, um código. Depois ela continua sozinha.': 'This action asks for your password and, if MFA is active, a code. It then continues on its own.', + 'Código MFA ou de recuperação': 'MFA or recovery code', + 'Cancelar': 'Cancel', + 'Confirmar': 'Confirm', + 'Só administradores podem executar análises. Você ainda pode ler os resultados.': 'Only administrators can run analyses. You can still read the results.', + 'Não foi possível copiar. Selecione o texto e copie à mão.': 'Could not copy. Select the text and copy it by hand.', + 'As senhas não coincidem.': 'The passwords do not match.', + 'Senha trocada. As outras sessões foram encerradas.': 'Password changed. Your other sessions were ended.', + 'Desativar o MFA desta conta?': 'Disable MFA for this account?', + 'MFA desativado.': 'MFA disabled.', + 'Nenhuma sessão ativa.': 'No active sessions.', + 'Encerrar': 'End', + 'Revogar': 'Revoke', + 'Nenhum token criado.': 'No tokens created.', + 'Excluir': 'Delete', + 'Ativo': 'Active', + 'Inativo': 'Inactive', + 'Excluir esta conta? As sessões e os tokens dela também acabam.': 'Delete this account? Its sessions and tokens end too.', + 'Nenhuma conta.': 'No accounts.', + 'Sim': 'Yes', + 'Não': 'No', + 'Nenhum evento registrado.': 'No events recorded.', + 'Conta criada.': 'Account created.', + 'O MFA é obrigatório para administradores. Cadastrar de novo troca o segredo e os códigos de recuperação.': 'MFA is mandatory for administrators. Enrolling again replaces the secret and the recovery codes.', + 'O MFA é opcional para analistas. Cadastrar de novo troca o segredo e os códigos de recuperação.': 'MFA is optional for analysts. Enrolling again replaces the secret and the recovery codes.', + 'Tente de novo em {n} s.': 'Try again in {n} s.', + 'Próximo código em {n} s.': 'Next code in {n} s.', + 'Credenciais inválidas.': 'Invalid credentials.', + 'Muitas tentativas.': 'Too many attempts.', + 'A configuração inicial ainda não foi concluída.': 'Initial setup is not finished yet.', + 'Código de configuração inválido.': 'Invalid setup code.', + 'O último administrador precisa continuar existindo.': 'The last administrator must remain.', + 'O MFA é obrigatório para administradores.': 'MFA is mandatory for administrators.', + 'Nenhum cadastro de MFA em andamento.': 'No MFA enrollment in progress.', + 'Este nome de usuário já está em uso.': 'This username is already in use.', + 'Não encontrado.': 'Not found.', + 'É preciso confirmar sua identidade de novo.': 'You need to confirm your identity again.', + 'Sem permissão para esta ação.': 'You do not have permission for this action.', + 'Erro interno do serviço.': 'Internal service error.', + 'Sua sessão terminou. Entre de novo.': 'Your session ended. Sign in again.', + 'Sessão desatualizada. Recarregue a página.': 'Stale session. Reload the page.', + 'A análise falhou. Os detalhes ficam no log do servidor.': 'The analysis failed. Details are in the server log.', + 'Esta senha é comum demais.': 'This password is too common.', + 'A senha não pode repetir um único caractere.': 'The password must not repeat a single character.', + 'A senha não pode ter só dígitos.': 'The password must not be only digits.', + 'A nova senha precisa ser diferente da atual.': 'The new password must differ from the current one.', + 'O nome de usuário não pode ter dois-pontos nem caracteres de controle.': 'The username must not contain colons or control characters.', + 'O nome de usuário não pode começar nem terminar com espaço.': 'The username must not start or end with a space.', + 'A validade do token precisa estar no futuro e em até 365 dias.': 'The token expiry must be in the future and within 365 days.', + 'Esta conta já tem tokens de API demais.': 'This account already has too many API tokens.', + 'A senha precisa ter pelo menos {n} caracteres.': 'The password must have at least {n} characters.', + 'A senha pode ter no máximo {n} bytes.': 'The password can have at most {n} bytes.', + 'O nome de usuário precisa ter de 1 a {n} caracteres.': 'The username must have 1 to {n} characters.', + 'O nome do token precisa ter de 1 a {n} caracteres, sem caracteres de controle.': 'The token name must have 1 to {n} characters, without control characters.', + 'Configuração inicial': 'Initial setup', + 'Nenhum administrador existe ainda. O código de configuração está no log do contêiner (': 'No administrator exists yet. The setup code is in the container log (', + ') e vale por 1 hora; ao reiniciar o serviço, um novo código é gerado se o anterior tiver expirado.': ') and is valid for 1 hour; restarting the service generates a new code if the previous one expired.', + 'Código de configuração': 'Setup code', + 'Usuário administrador': 'Administrator username', + 'Pelo menos 12 caracteres. Em seguida você cadastra o MFA, obrigatório para administradores.': 'At least 12 characters. Next you enroll MFA, which is mandatory for administrators.', + 'Criar administrador': 'Create administrator', + 'Código de verificação': 'Verification code', + 'Digite o código de 6 dígitos do aplicativo autenticador ou um código de recuperação.': 'Enter the 6-digit code from your authenticator app or a recovery code.', + 'O código usado no cadastro já foi gasto. Para concluir o login, espere o': 'The enrollment code is already spent. To finish signing in, wait for the', + 'Código': 'Code', + 'Verificar': 'Verify', + 'Voltar ao login': 'Back to sign in', + 'Códigos de recuperação': 'Recovery codes', + 'Guarde estes códigos agora: eles só aparecem esta vez e cada um funciona uma única vez.': 'Save these codes now: they appear only this once and each works a single time.', + 'Já guardei os códigos': 'I saved the codes', + 'Esta conta precisa de uma senha nova antes de continuar.': 'This account needs a new password before continuing.', + 'Trocar a senha e entrar': 'Change password and sign in', }; diff --git a/apps/gui/ui/i18n.js b/apps/gui/ui/i18n.js index b44848c..0f87058 100644 --- a/apps/gui/ui/i18n.js +++ b/apps/gui/ui/i18n.js @@ -47,6 +47,50 @@ export function tr(text) { return lead + out + trail; } +// The server speaks fixed English messages; the interface shows them in the +// user's language. Unknown messages pass through as they came. +const SERVER_MESSAGES = { + 'invalid credentials': 'Credenciais inválidas.', + 'too many attempts': 'Muitas tentativas.', + 'setup required': 'A configuração inicial ainda não foi concluída.', + '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.', + '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.', + 'recent authentication required': 'É preciso confirmar sua identidade de novo.', + forbidden: 'Sem permissão para esta ação.', + 'internal error': 'Erro interno do serviço.', + 'authentication required': 'Sua sessão terminou. Entre de novo.', + 'invalid CSRF token': 'Sessão desatualizada. Recarregue a página.', + 'analysis failed': 'A análise falhou. Os detalhes ficam no log do servidor.', + 'password is too common': 'Esta senha é comum demais.', + 'password must not repeat a single character': 'A senha não pode repetir um único caractere.', + 'password must not be only digits': 'A senha não pode ter só dígitos.', + 'new password must differ from the current one': 'A nova senha precisa ser diferente da atual.', + "username must not contain ':' or control characters": 'O nome de usuário não pode ter dois-pontos nem caracteres de controle.', + 'username must not start or end with a space': 'O nome de usuário não pode começar nem terminar com espaço.', + 'token expiry must be in the future and within 365 days': 'A validade do token precisa estar no futuro e em até 365 dias.', + 'too many API tokens': 'Esta conta já tem tokens de API demais.', +}; +const SERVER_PATTERNS = [ + [/^password must be at least (\d+) characters$/, 'A senha precisa ter pelo menos {n} caracteres.'], + [/^password must be at most (\d+) bytes$/, 'A senha pode ter no máximo {n} bytes.'], + [/^username must have 1 to (\d+) characters$/, 'O nome de usuário precisa ter de 1 a {n} caracteres.'], + [/^token name must have 1 to (\d+) characters, without control characters$/, 'O nome do token precisa ter de 1 a {n} caracteres, sem caracteres de controle.'], +]; + +export function serverMessage(raw) { + const known = SERVER_MESSAGES[raw]; + if (known) return tr(known); + for (const [re, template] of SERVER_PATTERNS) { + const match = String(raw).match(re); + if (match) return tr(template).replace('{n}', match[1]); + } + return raw; +} + const original = new WeakMap(); let observer = null; diff --git a/apps/gui/ui/index.html b/apps/gui/ui/index.html index a6f851e..5061325 100644 --- a/apps/gui/ui/index.html +++ b/apps/gui/ui/index.html @@ -36,6 +36,10 @@ ⌁ Análisedataset Zeek + + + @@ -264,7 +270,9 @@ — -
+ + +