feat(auth): login, MFA and account screens
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
67cf62b536
commit
42892cb37f
10 files changed
+1226
-13
No files matched your search
@@ -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();
|
||||||
|
}
|
||||||
@@ -699,3 +699,69 @@ html[data-theme="light"] .host-detail-row td { background: rgba(20, 58, 64, 0.03
|
|||||||
.legend { display: none; }
|
.legend { display: none; }
|
||||||
.top-actions { justify-content: flex-start; }
|
.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; }
|
||||||
+64
-7
@@ -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 SVG_NS = 'http://www.w3.org/2000/svg';
|
||||||
const $ = (selector) => document.querySelector(selector);
|
const $ = (selector) => document.querySelector(selector);
|
||||||
@@ -53,6 +54,8 @@ const state = {
|
|||||||
expandedHosts: new Set(),
|
expandedHosts: new Set(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let session = { username: '', role: '', csrf: '' };
|
||||||
|
|
||||||
const VIEW_META = {
|
const VIEW_META = {
|
||||||
overview: {
|
overview: {
|
||||||
title: 'Visão geral',
|
title: 'Visão geral',
|
||||||
@@ -70,6 +73,10 @@ const VIEW_META = {
|
|||||||
title: 'Análise',
|
title: 'Análise',
|
||||||
sub: 'Ingestão de logs Zeek e relatório da execução',
|
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';
|
let themePreference = localStorage.getItem('acaua-theme') || 'auto';
|
||||||
@@ -1237,11 +1244,44 @@ function applyViewMeta() {
|
|||||||
document.title = `${t(meta.title)} · Acauã`;
|
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 = {}) {
|
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(() => ({}));
|
const body = await response.json().catch(() => ({}));
|
||||||
if (!response.ok) throw new Error(body.error || response.statusText);
|
if (response.ok) return body;
|
||||||
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 = {}) {
|
async function call(command, args = {}) {
|
||||||
@@ -1315,6 +1355,7 @@ async function refreshAll() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function analyzeDataset() {
|
async function analyzeDataset() {
|
||||||
|
if (session.role !== 'admin') return;
|
||||||
const path = datasetPath.value.trim();
|
const path = datasetPath.value.trim();
|
||||||
if (!path) {
|
if (!path) {
|
||||||
output.textContent = t('Nenhum dataset selecionado.');
|
output.textContent = t('Nenhum dataset selecionado.');
|
||||||
@@ -1336,7 +1377,9 @@ async function analyzeDataset() {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
reportSummary.hidden = true;
|
reportSummary.hidden = true;
|
||||||
reportStatus.textContent = '—';
|
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;
|
$('#gotoAlerts').hidden = true;
|
||||||
$('#gotoHosts').hidden = true;
|
$('#gotoHosts').hidden = true;
|
||||||
$('#openReport').hidden = true;
|
$('#openReport').hidden = true;
|
||||||
@@ -1417,6 +1460,7 @@ function showView(target, { updateHash = true } = {}) {
|
|||||||
if (target === 'overview') renderCharts();
|
if (target === 'overview') renderCharts();
|
||||||
if (target === 'alerts') renderAlerts();
|
if (target === 'alerts') renderAlerts();
|
||||||
if (target === 'hosts') renderHosts();
|
if (target === 'hosts') renderHosts();
|
||||||
|
if (target === 'account' && session.csrf) refreshAccount();
|
||||||
window.scrollTo({ top: 0, behavior: 'instant' });
|
window.scrollTo({ top: 0, behavior: 'instant' });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1425,10 +1469,23 @@ function initViewFromHash() {
|
|||||||
return VIEW_META[target] ? target : 'overview';
|
return VIEW_META[target] ? target : 'overview';
|
||||||
}
|
}
|
||||||
|
|
||||||
function init() {
|
async function init() {
|
||||||
applyTheme(themePreference);
|
applyTheme(themePreference);
|
||||||
langSel.value = localStorage.getItem('acaua-lang') || 'auto';
|
langSel.value = localStorage.getItem('acaua-lang') || 'auto';
|
||||||
setLang(langSel.value);
|
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') || '';
|
datasetPath.value = localStorage.getItem('acaua-last-path') || '';
|
||||||
state.view = initViewFromHash();
|
state.view = initViewFromHash();
|
||||||
showView(state.view, { updateHash: false });
|
showView(state.view, { updateHash: false });
|
||||||
@@ -1592,4 +1649,4 @@ function init() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
init();
|
init().catch((error) => console.error(error));
|
||||||
@@ -166,4 +166,138 @@ export const EN = {
|
|||||||
'Hosts por score de fusão': 'Hosts by fusion score',
|
'Hosts por score de fusão': 'Hosts by fusion score',
|
||||||
'Distribuição de alertas por pilar': 'Alert distribution per pillar',
|
'Distribuição de alertas por pilar': 'Alert distribution per pillar',
|
||||||
'Filtrar por pilar': 'Filter by 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',
|
||||||
};
|
};
|
||||||
@@ -47,6 +47,50 @@ export function tr(text) {
|
|||||||
return lead + out + trail;
|
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();
|
const original = new WeakMap();
|
||||||
let observer = null;
|
let observer = null;
|
||||||
|
|
||||||
|
|||||||
+179
-1
@@ -36,6 +36,10 @@
|
|||||||
<span class="nav-icon">⌁</span>
|
<span class="nav-icon">⌁</span>
|
||||||
<span><span class="nav-label">Análise</span><span class="nav-sub">dataset Zeek</span></span>
|
<span><span class="nav-label">Análise</span><span class="nav-sub">dataset Zeek</span></span>
|
||||||
</button>
|
</button>
|
||||||
|
<button type="button" class="nav-item" data-target="account">
|
||||||
|
<span class="nav-icon">◉</span>
|
||||||
|
<span><span class="nav-label">Conta</span><span class="nav-sub">senha, MFA e tokens</span></span>
|
||||||
|
</button>
|
||||||
<button type="button" class="nav-item" data-target="settings">
|
<button type="button" class="nav-item" data-target="settings">
|
||||||
<span class="nav-icon">⚙</span>
|
<span class="nav-icon">⚙</span>
|
||||||
<span><span class="nav-label">Configurações</span><span class="nav-sub">idioma e tema</span></span>
|
<span><span class="nav-label">Configurações</span><span class="nav-sub">idioma e tema</span></span>
|
||||||
@@ -65,6 +69,8 @@
|
|||||||
<span id="lastUpdated" class="mono last-updated">—</span>
|
<span id="lastUpdated" class="mono last-updated">—</span>
|
||||||
<button id="refreshBtn" type="button" class="btn">Atualizar status</button>
|
<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>
|
<button id="settingsBtn" type="button" class="icon-btn" aria-label="Configurações" title="Configurações">⚙</button>
|
||||||
|
<span id="topUser" class="mono user-chip"></span>
|
||||||
|
<button id="logoutBtn" type="button" class="btn">Sair</button>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -264,7 +270,9 @@
|
|||||||
<span id="reportStatus" class="panel-tag">—</span>
|
<span id="reportStatus" class="panel-tag">—</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="field-row">
|
<p id="analysisLocked" class="notice notice-warn analysis-locked" hidden><span>Só administradores podem executar análises. Você ainda pode ler os resultados.</span></p>
|
||||||
|
|
||||||
|
<div id="analysisForm" class="field-row">
|
||||||
<label class="field">
|
<label class="field">
|
||||||
<span>Diretório de logs</span>
|
<span>Diretório de logs</span>
|
||||||
<input id="datasetPath" type="text" placeholder="/var/log/zeek/current" autocomplete="off" spellcheck="false">
|
<input id="datasetPath" type="text" placeholder="/var/log/zeek/current" autocomplete="off" spellcheck="false">
|
||||||
@@ -295,6 +303,160 @@
|
|||||||
</section>
|
</section>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="view" id="account" hidden>
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head">
|
||||||
|
<div>
|
||||||
|
<h2>Sua conta</h2>
|
||||||
|
<p class="hint"><span id="accountUser" class="mono"></span> · <span id="accountRole"></span></p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="account-grid">
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head"><div>
|
||||||
|
<h2>Trocar a senha</h2>
|
||||||
|
<p class="hint">Pelo menos 12 caracteres. As outras sessões da conta são encerradas.</p>
|
||||||
|
</div></div>
|
||||||
|
<form id="passwordForm" class="form-stack">
|
||||||
|
<label class="field"><span>Senha atual</span>
|
||||||
|
<input id="pwCurrent" type="password" autocomplete="current-password" required></label>
|
||||||
|
<label class="field"><span>Nova senha</span>
|
||||||
|
<input id="pwNew" type="password" autocomplete="new-password" minlength="12" required></label>
|
||||||
|
<label class="field"><span>Repita a nova senha</span>
|
||||||
|
<input id="pwRepeat" type="password" autocomplete="new-password" minlength="12" required></label>
|
||||||
|
<p id="pwStatus" role="status" hidden></p>
|
||||||
|
<div><button type="submit" class="btn primary">Trocar a senha</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head"><div>
|
||||||
|
<h2>MFA</h2>
|
||||||
|
<p id="mfaPolicy" class="hint"></p>
|
||||||
|
</div></div>
|
||||||
|
<p id="mfaStatus" role="status" hidden></p>
|
||||||
|
<div id="mfaActions" class="secret-actions">
|
||||||
|
<button id="mfaStart" type="button" class="btn">Cadastrar MFA</button>
|
||||||
|
<button id="mfaDisable" type="button" class="btn danger" hidden>Desativar MFA</button>
|
||||||
|
</div>
|
||||||
|
<form id="mfaEnroll" class="form-stack" hidden>
|
||||||
|
<p class="hint">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.</p>
|
||||||
|
<img id="mfaQr" class="qr" alt="QR do cadastro de MFA">
|
||||||
|
<label class="field"><span>Chave manual</span>
|
||||||
|
<input id="mfaKey" class="mono" type="text" readonly></label>
|
||||||
|
<label class="field"><span>Código de 6 dígitos</span>
|
||||||
|
<input id="mfaCode" type="text" inputmode="numeric" autocomplete="one-time-code" required></label>
|
||||||
|
<div><button type="submit" class="btn primary">Confirmar cadastro</button></div>
|
||||||
|
</form>
|
||||||
|
<div id="mfaRecovery" class="form-stack" hidden>
|
||||||
|
<p class="notice notice-warn"><span>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 <strong>próximo</strong> código (até 30 s) ou use um código de recuperação.</span></p>
|
||||||
|
<pre id="mfaRecoveryCodes" class="secret-box"></pre>
|
||||||
|
<div class="secret-actions">
|
||||||
|
<button id="mfaRecoveryCopy" type="button" class="btn">Copiar</button>
|
||||||
|
<button id="mfaRecoveryDownload" type="button" class="btn">Baixar</button>
|
||||||
|
<button id="mfaRecoveryDone" type="button" class="btn primary">Já guardei, ir para o login</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head"><div>
|
||||||
|
<h2>Sessões</h2>
|
||||||
|
<p class="hint">Inclui esta sessão: encerrá-la leva de volta ao login.</p>
|
||||||
|
</div></div>
|
||||||
|
<p id="sessionStatus" role="status" hidden></p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="data-table">
|
||||||
|
<thead><tr><th scope="col">Início</th><th scope="col">Último uso</th><th scope="col">Expira</th><th scope="col"><span class="sr-only">Ações</span></th></tr></thead>
|
||||||
|
<tbody id="sessionRows"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head"><div>
|
||||||
|
<h2>Tokens de API</h2>
|
||||||
|
<p class="hint">O valor do token só aparece na criação. Validade de até 365 dias.</p>
|
||||||
|
</div></div>
|
||||||
|
<form id="tokenForm" class="form-inline">
|
||||||
|
<label class="field"><span>Nome</span>
|
||||||
|
<input id="tokenName" type="text" autocomplete="off" spellcheck="false" required></label>
|
||||||
|
<label class="field compact"><span>Escopo</span>
|
||||||
|
<select id="tokenScope">
|
||||||
|
<option value="read">Leitura</option>
|
||||||
|
<option id="tokenScopeAdmin" value="admin">Administração</option>
|
||||||
|
</select></label>
|
||||||
|
<label class="field compact"><span>Dias de validade</span>
|
||||||
|
<input id="tokenDays" type="number" min="1" max="365" value="90" required></label>
|
||||||
|
<button type="submit" class="btn primary">Criar token</button>
|
||||||
|
</form>
|
||||||
|
<p id="tokenStatus" role="status" hidden></p>
|
||||||
|
<div id="tokenOnce" class="form-stack" hidden>
|
||||||
|
<p class="notice notice-warn"><span>Copie este token agora: ele não aparece de novo.</span></p>
|
||||||
|
<pre id="tokenValue" class="secret-box"></pre>
|
||||||
|
<div class="secret-actions">
|
||||||
|
<button id="tokenCopy" type="button" class="btn">Copiar</button>
|
||||||
|
<button id="tokenDownload" type="button" class="btn">Baixar</button>
|
||||||
|
<button id="tokenDone" type="button" class="btn primary">Já guardei</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="data-table">
|
||||||
|
<thead><tr><th scope="col">Nome</th><th scope="col">Escopo</th><th scope="col">Expira</th><th scope="col"><span class="sr-only">Ações</span></th></tr></thead>
|
||||||
|
<tbody id="tokenRows"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div id="adminPanels" hidden>
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head"><div>
|
||||||
|
<h2>Contas e papéis</h2>
|
||||||
|
<p class="hint">Criar, excluir ou mudar o papel de uma conta pede sua senha e seu código.</p>
|
||||||
|
</div></div>
|
||||||
|
<form id="userForm" class="form-inline">
|
||||||
|
<label class="field"><span>Usuário</span>
|
||||||
|
<input id="userName" type="text" autocomplete="off" spellcheck="false" required></label>
|
||||||
|
<label class="field"><span>Senha inicial</span>
|
||||||
|
<input id="userPass" type="password" autocomplete="new-password" minlength="12" required></label>
|
||||||
|
<label class="field compact"><span>Papel</span>
|
||||||
|
<select id="userRole">
|
||||||
|
<option value="analyst">Analista</option>
|
||||||
|
<option value="admin">Administrador</option>
|
||||||
|
</select></label>
|
||||||
|
<button type="submit" class="btn primary">Criar conta</button>
|
||||||
|
</form>
|
||||||
|
<p id="userStatus" role="status" hidden></p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="data-table">
|
||||||
|
<thead><tr><th scope="col">Usuário</th><th scope="col">Papel</th><th scope="col">MFA</th><th scope="col">Criada em</th><th scope="col"><span class="sr-only">Ações</span></th></tr></thead>
|
||||||
|
<tbody id="userRows"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head">
|
||||||
|
<div>
|
||||||
|
<h2>Auditoria</h2>
|
||||||
|
<p class="hint">Os 100 eventos mais recentes.</p>
|
||||||
|
</div>
|
||||||
|
<button id="auditRefresh" type="button" class="btn">Atualizar</button>
|
||||||
|
</div>
|
||||||
|
<p id="auditStatus" role="status" hidden></p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="data-table">
|
||||||
|
<thead><tr><th scope="col">Quando</th><th scope="col">Ação</th><th scope="col">Quem</th><th scope="col">IP</th><th scope="col">Êxito</th><th scope="col">Detalhe</th></tr></thead>
|
||||||
|
<tbody id="auditRows"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<footer class="foot">
|
<footer class="foot">
|
||||||
<span>Acauã · pré-lançamento</span>
|
<span>Acauã · pré-lançamento</span>
|
||||||
<span class="mono">MIT OR Apache-2.0</span>
|
<span class="mono">MIT OR Apache-2.0</span>
|
||||||
@@ -330,6 +492,22 @@
|
|||||||
</form>
|
</form>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
|
<dialog id="reauthDlg" aria-labelledby="reauthTitle">
|
||||||
|
<form id="reauthForm">
|
||||||
|
<div class="dialog-head"><h2 id="reauthTitle">Confirme sua identidade</h2></div>
|
||||||
|
<p class="hint">Esta ação pede sua senha e, se o MFA estiver ativo, um código. Depois ela continua sozinha.</p>
|
||||||
|
<p id="reauthError" role="alert" hidden></p>
|
||||||
|
<label class="field"><span>Senha</span>
|
||||||
|
<input id="reauthPass" type="password" autocomplete="current-password" required></label>
|
||||||
|
<label class="field"><span>Código MFA ou de recuperação</span>
|
||||||
|
<input id="reauthCode" type="text" autocomplete="one-time-code" spellcheck="false"></label>
|
||||||
|
<menu>
|
||||||
|
<button type="button" id="reauthCancel" class="btn">Cancelar</button>
|
||||||
|
<button type="submit" class="btn primary">Confirmar</button>
|
||||||
|
</menu>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
<script type="module" src="/app.js"></script>
|
<script type="module" src="/app.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Entrar · Acauã</title>
|
||||||
|
<link rel="icon" href="/logo.png">
|
||||||
|
<link rel="stylesheet" href="/app.css">
|
||||||
|
</head>
|
||||||
|
<body class="auth-page">
|
||||||
|
<main class="auth-shell">
|
||||||
|
<div class="brand auth-brand">
|
||||||
|
<img class="logo" src="/logo.png" alt="">
|
||||||
|
<div>
|
||||||
|
<strong>Acauã</strong>
|
||||||
|
<small>caça a ameaças em rede</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="panel auth-card">
|
||||||
|
<p id="authError" class="form-error" role="alert" hidden></p>
|
||||||
|
|
||||||
|
<form id="stSetup" class="auth-step" hidden>
|
||||||
|
<h1>Configuração inicial</h1>
|
||||||
|
<p class="hint">Nenhum administrador existe ainda. O código de configuração está no log do contêiner (<code>docker compose logs acaua</code>) e vale por 1 hora; ao reiniciar o serviço, um novo código é gerado se o anterior tiver expirado.</p>
|
||||||
|
<label class="field"><span>Código de configuração</span>
|
||||||
|
<input id="setupCode" type="text" autocomplete="off" spellcheck="false" required></label>
|
||||||
|
<label class="field"><span>Usuário administrador</span>
|
||||||
|
<input id="setupUser" type="text" autocomplete="username" spellcheck="false" required></label>
|
||||||
|
<label class="field"><span>Senha</span>
|
||||||
|
<input id="setupPass" type="password" autocomplete="new-password" minlength="12" required></label>
|
||||||
|
<p class="hint">Pelo menos 12 caracteres. Em seguida você cadastra o MFA, obrigatório para administradores.</p>
|
||||||
|
<button type="submit" class="btn primary">Criar administrador</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<form id="stLogin" class="auth-step" hidden>
|
||||||
|
<h1>Entrar</h1>
|
||||||
|
<label class="field"><span>Usuário</span>
|
||||||
|
<input id="loginUser" type="text" autocomplete="username" spellcheck="false" required></label>
|
||||||
|
<label class="field"><span>Senha</span>
|
||||||
|
<input id="loginPass" type="password" autocomplete="current-password" required></label>
|
||||||
|
<button type="submit" class="btn primary">Entrar</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<form id="stMfa" class="auth-step" hidden>
|
||||||
|
<h1>Código de verificação</h1>
|
||||||
|
<p class="hint">Digite o código de 6 dígitos do aplicativo autenticador ou um código de recuperação.</p>
|
||||||
|
<p id="mfaNext" class="notice notice-warn" hidden>
|
||||||
|
<span>O código usado no cadastro já foi gasto. Para concluir o login, espere o <strong>próximo</strong> código (até 30 s) ou use um código de recuperação.</span>
|
||||||
|
</p>
|
||||||
|
<p id="mfaCountdown" class="hint" hidden></p>
|
||||||
|
<label class="field"><span>Código</span>
|
||||||
|
<input id="mfaCode" type="text" autocomplete="one-time-code" spellcheck="false" required></label>
|
||||||
|
<button type="submit" class="btn primary">Verificar</button>
|
||||||
|
<button type="button" class="link-btn" data-restart>Voltar ao login</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<form id="stEnroll" class="auth-step" hidden>
|
||||||
|
<h1>Cadastrar MFA</h1>
|
||||||
|
<p class="hint">Escaneie o QR no aplicativo autenticador ou digite a chave manual. Depois, informe o código gerado.</p>
|
||||||
|
<img id="enrollQr" class="qr" alt="QR do cadastro de MFA">
|
||||||
|
<label class="field"><span>Chave manual</span>
|
||||||
|
<input id="enrollKey" class="mono" type="text" readonly></label>
|
||||||
|
<label class="field"><span>Código de 6 dígitos</span>
|
||||||
|
<input id="enrollCode" type="text" inputmode="numeric" autocomplete="one-time-code" required></label>
|
||||||
|
<button type="submit" class="btn primary">Confirmar cadastro</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div id="stRecovery" class="auth-step" hidden>
|
||||||
|
<h1>Códigos de recuperação</h1>
|
||||||
|
<p class="notice notice-warn"><span>Guarde estes códigos agora: eles só aparecem esta vez e cada um funciona uma única vez.</span></p>
|
||||||
|
<pre id="recoveryCodes" class="secret-box"></pre>
|
||||||
|
<div class="secret-actions">
|
||||||
|
<button id="recoveryCopy" type="button" class="btn">Copiar</button>
|
||||||
|
<button id="recoveryDownload" type="button" class="btn">Baixar</button>
|
||||||
|
</div>
|
||||||
|
<button id="recoveryDone" type="button" class="btn primary">Já guardei os códigos</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form id="stPassword" class="auth-step" hidden>
|
||||||
|
<h1>Trocar a senha</h1>
|
||||||
|
<p class="hint">Esta conta precisa de uma senha nova antes de continuar.</p>
|
||||||
|
<label class="field"><span>Senha atual</span>
|
||||||
|
<input id="pwCurrent" type="password" autocomplete="current-password" required></label>
|
||||||
|
<label class="field"><span>Nova senha</span>
|
||||||
|
<input id="pwNew" type="password" autocomplete="new-password" minlength="12" required></label>
|
||||||
|
<label class="field"><span>Repita a nova senha</span>
|
||||||
|
<input id="pwRepeat" type="password" autocomplete="new-password" minlength="12" required></label>
|
||||||
|
<button type="submit" class="btn primary">Trocar a senha e entrar</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="auth-prefs">
|
||||||
|
<label class="field compact"><span>Idioma</span>
|
||||||
|
<select id="langSel">
|
||||||
|
<option value="auto">Auto</option>
|
||||||
|
<option value="pt">Português</option>
|
||||||
|
<option value="en">English</option>
|
||||||
|
</select></label>
|
||||||
|
<label class="field compact"><span>Tema</span>
|
||||||
|
<select id="themeSel">
|
||||||
|
<option value="auto">Auto</option>
|
||||||
|
<option value="light">Claro</option>
|
||||||
|
<option value="dark">Escuro</option>
|
||||||
|
</select></label>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
<script type="module" src="/login.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
// Public page: imports only the other public files. The pending token lives in
|
||||||
|
// this module's memory and nowhere else.
|
||||||
|
import { setLang, tr, serverMessage } from './i18n.js';
|
||||||
|
|
||||||
|
const $ = (selector) => document.querySelector(selector);
|
||||||
|
const STEPS = ['stSetup', 'stLogin', 'stMfa', 'stEnroll', 'stRecovery', 'stPassword'];
|
||||||
|
const errorBox = $('#authError');
|
||||||
|
|
||||||
|
let pending = null;
|
||||||
|
let setupRequired = false;
|
||||||
|
let countdown = null;
|
||||||
|
|
||||||
|
function showError(text) {
|
||||||
|
errorBox.textContent = text;
|
||||||
|
errorBox.hidden = !text;
|
||||||
|
}
|
||||||
|
|
||||||
|
function show(step) {
|
||||||
|
showError('');
|
||||||
|
for (const id of STEPS) document.getElementById(id).hidden = id !== step;
|
||||||
|
document.getElementById(step).querySelector('input:not([readonly])')?.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function post(path, body, headers = {}) {
|
||||||
|
const response = await fetch(path, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', ...headers },
|
||||||
|
body: JSON.stringify(body ?? {}),
|
||||||
|
});
|
||||||
|
const data = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = new Error(serverMessage(data.error || response.statusText));
|
||||||
|
error.retryAfter = response.headers.get('Retry-After');
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function explain(error) {
|
||||||
|
if (!error.retryAfter) return error.message;
|
||||||
|
return `${error.message} ${tr('Tente de novo em {n} s.').replace('{n}', error.retryAfter)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs a form action, showing a failure and keeping the button from doubling it. */
|
||||||
|
function onSubmit(form, action) {
|
||||||
|
form.addEventListener('submit', async (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const button = form.querySelector('button[type="submit"]');
|
||||||
|
button.disabled = true;
|
||||||
|
showError('');
|
||||||
|
try {
|
||||||
|
await action();
|
||||||
|
} catch (error) {
|
||||||
|
showError(explain(error));
|
||||||
|
} finally {
|
||||||
|
button.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function restart(notice = '') {
|
||||||
|
pending = null;
|
||||||
|
stopCountdown();
|
||||||
|
for (const input of document.querySelectorAll('input:not(#loginUser)')) input.value = '';
|
||||||
|
show(setupRequired ? 'stSetup' : 'stLogin');
|
||||||
|
showError(notice);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopCountdown() {
|
||||||
|
if (countdown) window.clearInterval(countdown);
|
||||||
|
countdown = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function startCountdown() {
|
||||||
|
const out = $('#mfaCountdown');
|
||||||
|
const tick = () => {
|
||||||
|
const left = 30 - (Math.floor(Date.now() / 1000) % 30);
|
||||||
|
out.textContent = tr('Próximo código em {n} s.').replace('{n}', String(left));
|
||||||
|
};
|
||||||
|
stopCountdown();
|
||||||
|
out.hidden = false;
|
||||||
|
tick();
|
||||||
|
countdown = window.setInterval(tick, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function beginEnroll() {
|
||||||
|
const data = await post('/api/auth/enroll/start', {}, { 'X-Acaua-Pending': pending });
|
||||||
|
$('#enrollQr').src = `data:image/png;base64,${data.qr_png_base64}`;
|
||||||
|
$('#enrollKey').value = data.manual_key;
|
||||||
|
$('#enrollCode').value = '';
|
||||||
|
show('stEnroll');
|
||||||
|
}
|
||||||
|
|
||||||
|
function advance(reply) {
|
||||||
|
if (reply.step === 'session') {
|
||||||
|
location.replace('/');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pending = reply.pending;
|
||||||
|
if (reply.step === 'mfa_required') {
|
||||||
|
$('#mfaCode').value = '';
|
||||||
|
$('#mfaNext').hidden = true;
|
||||||
|
$('#mfaCountdown').hidden = true;
|
||||||
|
show('stMfa');
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
if (reply.step === 'mfa_enroll_required') return beginEnroll();
|
||||||
|
if (reply.step === 'password_change_required') {
|
||||||
|
show('stPassword');
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
throw new Error(serverMessage('internal error'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function showRecovery(codes) {
|
||||||
|
$('#recoveryCodes').textContent = codes.join('\n');
|
||||||
|
show('stRecovery');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copySecret(button, text) {
|
||||||
|
const label = button.textContent;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
button.textContent = tr('Copiado');
|
||||||
|
window.setTimeout(() => { button.textContent = label; }, 1400);
|
||||||
|
} catch {
|
||||||
|
showError(tr('Não foi possível copiar. Selecione o texto e copie à mão.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function download(name, text) {
|
||||||
|
const url = URL.createObjectURL(new Blob([`${text}\n`], { type: 'text/plain' }));
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = name;
|
||||||
|
link.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyTheme(pref) {
|
||||||
|
const light = window.matchMedia('(prefers-color-scheme: light)').matches;
|
||||||
|
document.documentElement.dataset.theme = pref === 'auto' ? (light ? 'light' : 'dark') : pref;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindPrefs() {
|
||||||
|
const lang = $('#langSel');
|
||||||
|
const theme = $('#themeSel');
|
||||||
|
lang.value = localStorage.getItem('acaua-lang') || 'auto';
|
||||||
|
theme.value = localStorage.getItem('acaua-theme') || 'auto';
|
||||||
|
setLang(lang.value);
|
||||||
|
applyTheme(theme.value);
|
||||||
|
lang.addEventListener('change', () => {
|
||||||
|
localStorage.setItem('acaua-lang', lang.value);
|
||||||
|
setLang(lang.value);
|
||||||
|
});
|
||||||
|
theme.addEventListener('change', () => {
|
||||||
|
localStorage.setItem('acaua-theme', theme.value);
|
||||||
|
applyTheme(theme.value);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function init() {
|
||||||
|
bindPrefs();
|
||||||
|
|
||||||
|
onSubmit($('#stSetup'), async () => {
|
||||||
|
pending = (await post('/api/auth/bootstrap', {
|
||||||
|
code: $('#setupCode').value.trim(),
|
||||||
|
username: $('#setupUser').value,
|
||||||
|
password: $('#setupPass').value,
|
||||||
|
})).pending;
|
||||||
|
setupRequired = false;
|
||||||
|
$('#loginUser').value = $('#setupUser').value;
|
||||||
|
$('#setupPass').value = '';
|
||||||
|
await beginEnroll();
|
||||||
|
});
|
||||||
|
|
||||||
|
onSubmit($('#stLogin'), async () => {
|
||||||
|
const reply = await post('/api/auth/login', {
|
||||||
|
username: $('#loginUser').value,
|
||||||
|
password: $('#loginPass').value,
|
||||||
|
});
|
||||||
|
await advance(reply);
|
||||||
|
$('#loginPass').value = '';
|
||||||
|
});
|
||||||
|
|
||||||
|
onSubmit($('#stMfa'), async () => {
|
||||||
|
const reply = await post('/api/auth/mfa', { pending, code: $('#mfaCode').value.trim() });
|
||||||
|
stopCountdown();
|
||||||
|
await advance(reply);
|
||||||
|
});
|
||||||
|
|
||||||
|
onSubmit($('#stEnroll'), async () => {
|
||||||
|
const reply = await post(
|
||||||
|
'/api/auth/enroll/confirm',
|
||||||
|
{ code: $('#enrollCode').value.trim() },
|
||||||
|
{ 'X-Acaua-Pending': pending },
|
||||||
|
);
|
||||||
|
showRecovery(reply.recovery_codes);
|
||||||
|
});
|
||||||
|
|
||||||
|
onSubmit($('#stPassword'), async () => {
|
||||||
|
if ($('#pwNew').value !== $('#pwRepeat').value) throw new Error(tr('As senhas não coincidem.'));
|
||||||
|
await post('/api/auth/password-change-required', {
|
||||||
|
ticket: pending,
|
||||||
|
current: $('#pwCurrent').value,
|
||||||
|
new: $('#pwNew').value,
|
||||||
|
});
|
||||||
|
location.replace('/');
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll('[data-restart]').forEach((button) => {
|
||||||
|
button.addEventListener('click', () => restart());
|
||||||
|
});
|
||||||
|
|
||||||
|
$('#recoveryCopy').addEventListener('click', (event) => {
|
||||||
|
copySecret(event.currentTarget, $('#recoveryCodes').textContent);
|
||||||
|
});
|
||||||
|
$('#recoveryDownload').addEventListener('click', () => {
|
||||||
|
download('acaua-codigos-de-recuperacao.txt', $('#recoveryCodes').textContent);
|
||||||
|
});
|
||||||
|
$('#recoveryDone').addEventListener('click', () => {
|
||||||
|
$('#recoveryCodes').textContent = '';
|
||||||
|
$('#mfaCode').value = '';
|
||||||
|
$('#mfaNext').hidden = false;
|
||||||
|
startCountdown();
|
||||||
|
show('stMfa');
|
||||||
|
});
|
||||||
|
|
||||||
|
const state = await fetch('/api/auth/state').then((r) => r.json());
|
||||||
|
if (state.authenticated) {
|
||||||
|
location.replace('/');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setupRequired = state.setup_required;
|
||||||
|
restart();
|
||||||
|
}
|
||||||
|
|
||||||
|
init().catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
showError(serverMessage('internal error'));
|
||||||
|
});
|
||||||
@@ -301,11 +301,16 @@ async fn unknown_paths_answer_exactly_like_protected_ones() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn public_route_without_an_asset_is_404_and_assets_are_served() {
|
async fn every_public_asset_is_served() {
|
||||||
let (_d, _a, app) = fresh(Transport::Local);
|
let (_d, _a, app) = fresh(Transport::Local);
|
||||||
let r = send(&app, empty(Method::GET, "/login.html")).await;
|
for path in [
|
||||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
"/login.html",
|
||||||
for path in ["/app.css", "/logo.png", "/i18n.js", "/i18n-en.js"] {
|
"/login.js",
|
||||||
|
"/app.css",
|
||||||
|
"/logo.png",
|
||||||
|
"/i18n.js",
|
||||||
|
"/i18n-en.js",
|
||||||
|
] {
|
||||||
let r = send(&app, empty(Method::GET, path)).await;
|
let r = send(&app, empty(Method::GET, path)).await;
|
||||||
assert_eq!(r.status, StatusCode::OK, "{path}");
|
assert_eq!(r.status, StatusCode::OK, "{path}");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -257,7 +257,7 @@ function rustLabels(source, file) {
|
|||||||
const uiFiles = readdirSync(join(root, 'apps/gui/ui'))
|
const uiFiles = readdirSync(join(root, 'apps/gui/ui'))
|
||||||
.filter((f) => f.endsWith('.js') && f !== 'i18n-en.js' && f !== 'vendor')
|
.filter((f) => f.endsWith('.js') && f !== 'i18n-en.js' && f !== 'vendor')
|
||||||
.map((f) => join(root, 'apps/gui/ui', f));
|
.map((f) => join(root, 'apps/gui/ui', f));
|
||||||
uiFiles.push(join(root, 'apps/gui/ui/index.html'));
|
uiFiles.push(join(root, 'apps/gui/ui/index.html'), join(root, 'apps/gui/ui/login.html'));
|
||||||
|
|
||||||
const rustFiles = [
|
const rustFiles = [
|
||||||
'crates/acaua-core/src/error.rs',
|
'crates/acaua-core/src/error.rs',
|
||||||
|
|||||||
Reference in new issue
Block a user