- sanitizer XSS serveur (markdown + page de partage) [BUG-021/022] - rate-limit/lockout MFA [BUG-023] - isolation vaults par segments [BUG-024] - caps regex ReDoS [BUG-025] - SSRF webhooks + secrets externalises [BUG-026] - rotation/revocation des jetons [BUG-027] - politique de mot de passe + invalidation sessions [BUG-028] - verrous users.json [BUG-029] - IP reelle dans les audits [BUG-030] - rate-limit par compte [BUG-031] - symlinks hors vault ignores [BUG-032] - recherche simple via inverted index [BUG-033] - token en memoire + cookie HttpOnly, CSP durcie [BUG-034] Tests: pytest 961 passed / 6 skipped, ruff 0, mypy 0, frontend vert.
1309 lines
47 KiB
JavaScript
1309 lines
47 KiB
JavaScript
/* ObsiGate — Authentication: API helper, AuthManager, login form, AdminPanel */
|
|
import { state } from './state.js';
|
|
import { safeCreateIcons } from './utils.js';
|
|
import { showToast, closeHeaderMenu } from './ui.js';
|
|
import { t, getLocale, setLocale } from './i18n.js';
|
|
import { showWelcome } from './viewer.js';
|
|
|
|
// ── Global logout handler for header dropdown onclick ────────────────────
|
|
// Defined at module top level so it's always available, even if
|
|
// renderUserMenu() hasn't been called yet.
|
|
// Uses a getter to lazy-resolve AuthManager (defined later in this module).
|
|
window.handleLogout = () => {
|
|
AuthManager.logout();
|
|
};
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// API helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/**
|
|
* Fetch JSON from an API endpoint with optional AbortSignal support.
|
|
* Surfaces errors to the user via toast instead of silently failing.
|
|
*
|
|
* @param {string} path - API URL path.
|
|
* @param {object} [opts] - Fetch options (may include signal).
|
|
* @returns {Promise<any>} Parsed JSON response.
|
|
*/
|
|
async function api(path, opts) {
|
|
var res;
|
|
try {
|
|
// Inject auth header if authenticated
|
|
const authHeaders = AuthManager.getAuthHeaders();
|
|
const mergedOpts = opts || {};
|
|
// Auto-set Content-Type for JSON bodies
|
|
if (mergedOpts.body && typeof mergedOpts.body === "string" && !mergedOpts.headers?.["Content-Type"]) {
|
|
mergedOpts.headers = { ...mergedOpts.headers, "Content-Type": "application/json" };
|
|
}
|
|
if (authHeaders) {
|
|
mergedOpts.headers = { ...mergedOpts.headers, ...authHeaders };
|
|
}
|
|
mergedOpts.credentials = "include";
|
|
res = await fetch(path, mergedOpts);
|
|
} catch (err) {
|
|
if (err.name === "AbortError") throw err; // let callers handle abort
|
|
showToast(t("auth.network_error"), "error");
|
|
throw err;
|
|
}
|
|
if (res.status === 401 && AuthManager._authEnabled) {
|
|
// Token expired — try refresh
|
|
try {
|
|
await AuthManager.refreshAccessToken();
|
|
// Retry the request with new token
|
|
const retryHeaders = AuthManager.getAuthHeaders();
|
|
const retryOpts = opts || {};
|
|
retryOpts.headers = { ...retryOpts.headers, ...retryHeaders };
|
|
retryOpts.credentials = "include";
|
|
res = await fetch(path, retryOpts);
|
|
} catch (refreshErr) {
|
|
AuthManager.clearSession();
|
|
AuthManager.showLoginScreen();
|
|
throw new Error("Session expirée");
|
|
}
|
|
}
|
|
if (!res.ok) {
|
|
var detail = "";
|
|
try {
|
|
var body = await res.json();
|
|
detail = body.detail || "";
|
|
} catch (_) {
|
|
/* no json body */
|
|
}
|
|
showToast(detail || "Erreur API : " + res.status, "error");
|
|
throw new Error(detail || "API error: " + res.status);
|
|
}
|
|
return res.json();
|
|
}
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// AuthManager — Authentication state & token management
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const AuthManager = {
|
|
ACCESS_TOKEN_KEY: "obsigate_access_token",
|
|
TOKEN_EXPIRY_KEY: "obsigate_token_expiry",
|
|
USER_KEY: "obsigate_user",
|
|
_authEnabled: false,
|
|
// BUG-034: the access token is kept in memory only. The server also sets it
|
|
// as an HttpOnly cookie, so a page reload re-authenticates via /api/auth/refresh
|
|
// without ever exposing the token to JavaScript-readable storage.
|
|
_accessToken: null,
|
|
|
|
// ── Token storage (in-memory + HttpOnly cookie) ────────────────
|
|
|
|
saveToken(tokenData) {
|
|
const expiresAt = Date.now() + tokenData.expires_in * 1000;
|
|
this._accessToken = tokenData.access_token;
|
|
// Clear any token persisted by an older build (XSS-readable).
|
|
try { sessionStorage.removeItem(this.ACCESS_TOKEN_KEY); } catch (e) { /* ignore */ }
|
|
sessionStorage.setItem(this.TOKEN_EXPIRY_KEY, expiresAt.toString());
|
|
if (tokenData.user) {
|
|
sessionStorage.setItem(this.USER_KEY, JSON.stringify(tokenData.user));
|
|
}
|
|
},
|
|
|
|
getToken() {
|
|
return this._accessToken;
|
|
},
|
|
|
|
hasSession() {
|
|
return !!this._accessToken || !!sessionStorage.getItem(this.TOKEN_EXPIRY_KEY);
|
|
},
|
|
|
|
getUser() {
|
|
const raw = sessionStorage.getItem(this.USER_KEY);
|
|
return raw ? JSON.parse(raw) : null;
|
|
},
|
|
|
|
isTokenExpired() {
|
|
const expiry = sessionStorage.getItem(this.TOKEN_EXPIRY_KEY);
|
|
if (!expiry) return true;
|
|
// Renew 60s before expiration
|
|
return Date.now() > parseInt(expiry) - 60000;
|
|
},
|
|
|
|
clearSession() {
|
|
this._accessToken = null;
|
|
try { sessionStorage.removeItem(this.ACCESS_TOKEN_KEY); } catch (e) { /* ignore */ }
|
|
sessionStorage.removeItem(this.TOKEN_EXPIRY_KEY);
|
|
sessionStorage.removeItem(this.USER_KEY);
|
|
},
|
|
|
|
getAuthHeaders() {
|
|
const token = this.getToken();
|
|
if (!token || !this._authEnabled) return null;
|
|
return { Authorization: "Bearer " + token };
|
|
},
|
|
|
|
// ── API calls ──────────────────────────────────────────────────
|
|
|
|
async login(username, password, rememberMe) {
|
|
const response = await fetch("/api/auth/login", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
credentials: "include",
|
|
body: JSON.stringify({ username, password, remember_me: rememberMe || false }),
|
|
});
|
|
if (!response.ok) {
|
|
const err = await response.json();
|
|
throw new Error(err.detail || "Erreur de connexion");
|
|
}
|
|
const data = await response.json();
|
|
// If MFA is required, return the MFA challenge instead of saving token
|
|
if (data.mfa_required) {
|
|
return data;
|
|
}
|
|
this.saveToken(data);
|
|
return data.user;
|
|
},
|
|
|
|
async verifyMfa(username, code, rememberMe) {
|
|
const response = await fetch("/api/auth/mfa/totp/verify", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
credentials: "include",
|
|
body: JSON.stringify({ username, code, remember_me: rememberMe || false }),
|
|
});
|
|
if (!response.ok) {
|
|
const err = await response.json();
|
|
throw new Error(err.detail || "Code invalide");
|
|
}
|
|
const data = await response.json();
|
|
this.saveToken(data);
|
|
return data.user;
|
|
},
|
|
|
|
async verifyRecovery(username, recoveryCode) {
|
|
const response = await fetch("/api/auth/mfa/recovery", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
credentials: "include",
|
|
body: JSON.stringify({ username, recovery_code: recoveryCode }),
|
|
});
|
|
if (!response.ok) {
|
|
const err = await response.json();
|
|
throw new Error(err.detail || "Code invalide");
|
|
}
|
|
const data = await response.json();
|
|
this.saveToken(data);
|
|
return data.user;
|
|
},
|
|
|
|
// ── WebAuthn (ROADMAP #64) ─────────────────────────────────────────
|
|
|
|
async webauthnLoginOptions(username) {
|
|
const resp = await fetch("/api/auth/mfa/webauthn/options", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
credentials: "include",
|
|
body: JSON.stringify({ username }),
|
|
});
|
|
if (!resp.ok) throw new Error((await resp.json()).detail || "WebAuthn indisponible");
|
|
return await resp.json();
|
|
},
|
|
|
|
async verifyWebauthn(username, credential, rememberMe) {
|
|
const response = await fetch("/api/auth/mfa/webauthn/verify", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
credentials: "include",
|
|
body: JSON.stringify({ username, credential, remember_me: rememberMe || false }),
|
|
});
|
|
if (!response.ok) {
|
|
const err = await response.json();
|
|
throw new Error(err.detail || "Vérification WebAuthn échouée");
|
|
}
|
|
const data = await response.json();
|
|
this.saveToken(data);
|
|
return data.user;
|
|
},
|
|
|
|
async webauthnRegisterOptions() {
|
|
return await api("/api/auth/mfa/webauthn/register/options", { method: "POST" });
|
|
},
|
|
|
|
async webauthnRegister(credential, label) {
|
|
return await api("/api/auth/mfa/webauthn/register", {
|
|
method: "POST",
|
|
body: JSON.stringify({ credential, label }),
|
|
});
|
|
},
|
|
|
|
async webauthnCredentials() {
|
|
return await api("/api/auth/mfa/webauthn/credentials");
|
|
},
|
|
|
|
async webauthnRemove(credentialId, password) {
|
|
return await api("/api/auth/mfa/webauthn/credentials/remove", {
|
|
method: "POST",
|
|
body: JSON.stringify({ credential_id: credentialId, password }),
|
|
});
|
|
},
|
|
|
|
// ── MFA Setup API calls ──────────────────────────────────────────
|
|
|
|
async getMfaStatus() {
|
|
const resp = await api("/api/auth/mfa/status");
|
|
return resp;
|
|
},
|
|
|
|
async mfaSetup() {
|
|
return await api("/api/auth/mfa/totp/setup", { method: "POST" });
|
|
},
|
|
|
|
async mfaEnable(code) {
|
|
return await api("/api/auth/mfa/totp/enable", {
|
|
method: "POST",
|
|
body: JSON.stringify({ code }),
|
|
});
|
|
},
|
|
|
|
async mfaDisable(password, code) {
|
|
return await api("/api/auth/mfa/totp/disable", {
|
|
method: "POST",
|
|
body: JSON.stringify({ password, code }),
|
|
});
|
|
},
|
|
|
|
async logout() {
|
|
try {
|
|
const token = this.getToken();
|
|
await fetch("/api/auth/logout", {
|
|
method: "POST",
|
|
headers: token ? { Authorization: "Bearer " + token } : {},
|
|
credentials: "include",
|
|
});
|
|
} catch (e) {
|
|
/* continue even if API fails */
|
|
}
|
|
this.clearSession();
|
|
this.showLoginScreen();
|
|
},
|
|
|
|
async refreshAccessToken() {
|
|
const response = await fetch("/api/auth/refresh", {
|
|
method: "POST",
|
|
credentials: "include",
|
|
});
|
|
if (!response.ok) {
|
|
this.clearSession();
|
|
throw new Error("Session expirée");
|
|
}
|
|
const data = await response.json();
|
|
const expiry = Date.now() + data.expires_in * 1000;
|
|
this._accessToken = data.access_token;
|
|
try { sessionStorage.removeItem(this.ACCESS_TOKEN_KEY); } catch (e) { /* ignore */ }
|
|
sessionStorage.setItem(this.TOKEN_EXPIRY_KEY, expiry.toString());
|
|
return data.access_token;
|
|
},
|
|
|
|
// ── UI controls ────────────────────────────────────────────────
|
|
|
|
showLoginScreen() {
|
|
const app = document.getElementById("app");
|
|
const login = document.getElementById("login-screen");
|
|
if (app) app.classList.add("hidden");
|
|
if (login) {
|
|
login.classList.remove("hidden");
|
|
const usernameInput = document.getElementById("login-username");
|
|
if (usernameInput) usernameInput.focus();
|
|
}
|
|
},
|
|
|
|
showApp() {
|
|
const login = document.getElementById("login-screen");
|
|
const app = document.getElementById("app");
|
|
if (login) login.classList.add("hidden");
|
|
if (app) app.classList.remove("hidden");
|
|
this.renderUserMenu();
|
|
},
|
|
|
|
renderUserMenu() {
|
|
const user = this.getUser();
|
|
const userMenu = document.getElementById("user-menu");
|
|
if (!userMenu) return;
|
|
if (!user || !this._authEnabled) {
|
|
userMenu.innerHTML = "";
|
|
return;
|
|
}
|
|
userMenu.innerHTML = '<span class="user-display-name">' + (user.display_name || user.username) + "</span>" + '<button class="btn-logout" id="logout-btn" title="' + t('auth.logout_title') + '" onclick="window.handleLogout()"><i data-lucide="log-out" style="width:14px;height:14px"></i></button>';
|
|
safeCreateIcons();
|
|
|
|
const logoutBtn = document.getElementById("logout-btn");
|
|
if (logoutBtn) logoutBtn.addEventListener("click", () => AuthManager.logout());
|
|
|
|
const adminRow = document.getElementById("admin-menu-row");
|
|
if (adminRow) {
|
|
if (user.role === "admin") {
|
|
adminRow.classList.remove("hidden");
|
|
// Important: use an inline function to ensure we don't bind multiple identical listeners on rerenders, or clean up before
|
|
adminRow.onclick = () => {
|
|
closeHeaderMenu();
|
|
window.location.href = "/admin.html";
|
|
};
|
|
} else {
|
|
adminRow.classList.add("hidden");
|
|
}
|
|
}
|
|
},
|
|
|
|
// ── Initialization ──────────────────────────────────────────────
|
|
|
|
async checkAuthStatus() {
|
|
try {
|
|
const res = await fetch("/api/auth/status");
|
|
const data = await res.json();
|
|
this._authEnabled = data.auth_enabled;
|
|
return data;
|
|
} catch (e) {
|
|
this._authEnabled = false;
|
|
return { auth_enabled: false };
|
|
}
|
|
},
|
|
|
|
async initAuth() {
|
|
const status = await this.checkAuthStatus();
|
|
if (!status.auth_enabled) {
|
|
// Auth disabled — show app immediately
|
|
this.showApp();
|
|
return true;
|
|
}
|
|
|
|
// Auth enabled — check for existing session
|
|
if (this.hasSession() && !this.isTokenExpired()) {
|
|
this.showApp();
|
|
return true;
|
|
}
|
|
|
|
// Try silent refresh
|
|
try {
|
|
await this.refreshAccessToken();
|
|
// Fetch user info
|
|
const token = this.getToken();
|
|
const res = await fetch("/api/auth/me", {
|
|
headers: { Authorization: "Bearer " + token },
|
|
credentials: "include",
|
|
});
|
|
if (res.ok) {
|
|
const user = await res.json();
|
|
sessionStorage.setItem(this.USER_KEY, JSON.stringify(user));
|
|
this.showApp();
|
|
return true;
|
|
}
|
|
} catch (e) {
|
|
/* silent refresh failed */
|
|
}
|
|
|
|
// No valid session — show login
|
|
this.showLoginScreen();
|
|
return false;
|
|
},
|
|
};
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Post-login setup (shared between normal login and MFA login)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
async function _onLoginSuccess() {
|
|
AuthManager.showApp();
|
|
|
|
// Re-sync language from server now that we're authenticated
|
|
try {
|
|
const resp = await fetch('/api/auth/me', { credentials: 'include' });
|
|
if (resp.ok) {
|
|
const user = await resp.json();
|
|
if (user.language && user.language !== getLocale()) {
|
|
await setLocale(user.language);
|
|
}
|
|
}
|
|
} catch (e) { /* non-bloquant */ }
|
|
|
|
// Load app data after successful login
|
|
try {
|
|
const { loadVaults, loadTags } = await import('./sidebar.js');
|
|
await Promise.all([loadVaults(), loadTags()]);
|
|
const { IndexUpdateManager } = await import('./sync.js');
|
|
IndexUpdateManager.connect();
|
|
const { syncFileIndexFromServer } = await import('./offline.js');
|
|
syncFileIndexFromServer();
|
|
showWelcome();
|
|
} catch (err) {
|
|
console.error("Failed to load data after login:", err);
|
|
}
|
|
}
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// MFA Challenge UI (TOTP code input during login)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// base64url <-> ArrayBuffer helpers for WebAuthn (ROADMAP #64)
|
|
function _b64urlToBuf(s) {
|
|
const pad = "=".repeat((4 - (s.length % 4)) % 4);
|
|
const b = (s + pad).replace(/-/g, "+").replace(/_/g, "/");
|
|
const raw = atob(b);
|
|
return Uint8Array.from(raw, (c) => c.charCodeAt(0));
|
|
}
|
|
|
|
function _bufToB64url(buf) {
|
|
const bytes = new Uint8Array(buf);
|
|
let s = "";
|
|
for (const c of bytes) s += String.fromCharCode(c);
|
|
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
}
|
|
|
|
async function runWebauthnCeremony(optionsJson) {
|
|
const pkOptions = {
|
|
challenge: _b64urlToBuf(optionsJson.challenge),
|
|
timeout: optionsJson.timeout || 60000,
|
|
rpId: optionsJson.rpId,
|
|
userVerification: optionsJson.userVerification || "preferred",
|
|
allowCredentials: (optionsJson.allowCredentials || []).map((c) => ({
|
|
type: c.type || "public-key",
|
|
id: _b64urlToBuf(c.id),
|
|
transports: c.transports,
|
|
})),
|
|
};
|
|
const cred = await navigator.credentials.get({ publicKey: pkOptions });
|
|
if (!cred) throw new Error(t("mfa.webauthn_cancelled"));
|
|
return {
|
|
id: cred.id,
|
|
rawId: _bufToB64url(cred.rawId),
|
|
type: cred.type,
|
|
response: {
|
|
clientDataJSON: _bufToB64url(cred.response.clientDataJSON),
|
|
authenticatorData: _bufToB64url(cred.response.authenticatorData),
|
|
signature: _bufToB64url(cred.response.signature),
|
|
userHandle: cred.response.userHandle ? _bufToB64url(cred.response.userHandle) : "",
|
|
},
|
|
};
|
|
}
|
|
|
|
async function runWebauthnRegistration() {
|
|
const resp = await AuthManager.webauthnRegisterOptions();
|
|
const o = resp.options;
|
|
const pkOptions = {
|
|
rp: { id: o.rpId || o.rp.id, name: o.rp.name },
|
|
challenge: _b64urlToBuf(o.challenge),
|
|
user: {
|
|
id: _b64urlToBuf(o.user.id),
|
|
name: o.user.name,
|
|
displayName: o.user.displayName,
|
|
},
|
|
pubKeyCredParams: o.pubKeyCredParams,
|
|
timeout: o.timeout || 60000,
|
|
authenticatorSelection: o.authenticatorSelection || undefined,
|
|
attestation: "none",
|
|
};
|
|
const cred = await navigator.credentials.create({ publicKey: pkOptions });
|
|
if (!cred) throw new Error(t("mfa.webauthn_cancelled"));
|
|
const credential = {
|
|
id: cred.id,
|
|
rawId: _bufToB64url(cred.rawId),
|
|
type: cred.type,
|
|
response: {
|
|
clientDataJSON: _bufToB64url(cred.response.clientDataJSON),
|
|
attestationObject: _bufToB64url(cred.response.attestationObject),
|
|
},
|
|
};
|
|
if (cred.response.getTransports) {
|
|
credential.response.transports = Array.from(cred.response.getTransports());
|
|
}
|
|
return credential;
|
|
}
|
|
|
|
function _startWebauthnLogin(mfaSection, username, rememberMe) {
|
|
const btn = mfaSection.querySelector("#mfa-webauthn-btn");
|
|
const errorEl = mfaSection.querySelector("#mfa-error");
|
|
if (btn) btn.disabled = true;
|
|
if (errorEl) errorEl.classList.add("hidden");
|
|
|
|
(async () => {
|
|
try {
|
|
const resp = await AuthManager.webauthnLoginOptions(username);
|
|
if (resp.mfa_method !== "webauthn" || !resp.options) {
|
|
throw new Error(t("mfa.webauthn_no_key"));
|
|
}
|
|
const credential = await runWebauthnCeremony(resp.options);
|
|
await AuthManager.verifyWebauthn(username, credential, rememberMe);
|
|
mfaSection.classList.add("hidden");
|
|
const loginForm = document.getElementById("login-form");
|
|
if (loginForm) loginForm.classList.remove("hidden");
|
|
await _onLoginSuccess();
|
|
} catch (err) {
|
|
if (errorEl) {
|
|
errorEl.textContent = err.message || String(err);
|
|
errorEl.classList.remove("hidden");
|
|
}
|
|
} finally {
|
|
if (btn) btn.disabled = false;
|
|
}
|
|
})();
|
|
}
|
|
|
|
|
|
function showMfaChallenge(username, rememberMe, loginBtn, loginErrorEl, mfaMethod) {
|
|
const loginBox = document.querySelector(".login-box");
|
|
if (!loginBox) return;
|
|
|
|
// Hide the normal login form
|
|
const loginForm = document.getElementById("login-form");
|
|
if (loginForm) loginForm.classList.add("hidden");
|
|
|
|
// Create MFA challenge UI
|
|
let mfaSection = document.getElementById("mfa-challenge");
|
|
if (!mfaSection) {
|
|
mfaSection = document.createElement("div");
|
|
mfaSection.id = "mfa-challenge";
|
|
mfaSection.className = "mfa-challenge";
|
|
loginBox.appendChild(mfaSection);
|
|
}
|
|
|
|
// WebAuthn second factor: key prompt instead of TOTP code input
|
|
if (mfaMethod === "webauthn") {
|
|
mfaSection.innerHTML = `
|
|
<div class="mfa-icon">🔑</div>
|
|
<h3>${t('mfa.title')}</h3>
|
|
<p class="mfa-subtitle">${t('mfa.webauthn_prompt')}</p>
|
|
<p class="mfa-error hidden" id="mfa-error"></p>
|
|
<button type="button" class="btn-login" id="mfa-webauthn-btn">
|
|
<span class="btn-text">${t('mfa.webauthn_btn')}</span>
|
|
</button>
|
|
<div class="mfa-actions">
|
|
<button type="button" class="mfa-link-btn" id="mfa-use-recovery">${t('mfa.use_recovery')}</button>
|
|
<button type="button" class="mfa-link-btn" id="mfa-back-login">${t('mfa.back_to_login')}</button>
|
|
</div>
|
|
`;
|
|
mfaSection.classList.remove("hidden");
|
|
document.getElementById("mfa-webauthn-btn").addEventListener("click", () => {
|
|
_startWebauthnLogin(mfaSection, username, rememberMe);
|
|
});
|
|
document.getElementById("mfa-use-recovery").addEventListener("click", () => {
|
|
showRecoveryChallenge(username, rememberMe, loginForm, mfaSection);
|
|
});
|
|
document.getElementById("mfa-back-login").addEventListener("click", () => {
|
|
mfaSection.classList.add("hidden");
|
|
if (loginForm) loginForm.classList.remove("hidden");
|
|
});
|
|
// Auto-start the ceremony — the browser shows its own dialog
|
|
_startWebauthnLogin(mfaSection, username, rememberMe);
|
|
return;
|
|
}
|
|
|
|
mfaSection.innerHTML = `
|
|
<div class="mfa-icon">🔐</div>
|
|
<h3>${t('mfa.title')}</h3>
|
|
<p class="mfa-subtitle">${t('mfa.subtitle')}</p>
|
|
<form id="mfa-form">
|
|
<div class="mfa-code-input-group">
|
|
<input type="text" id="mfa-code" class="mfa-code-input" maxlength="6"
|
|
pattern="[0-9]{6}" inputmode="numeric" autocomplete="one-time-code"
|
|
placeholder="000000" autofocus required>
|
|
</div>
|
|
<p class="mfa-error hidden" id="mfa-error"></p>
|
|
<button type="submit" class="btn-login" id="mfa-verify-btn">
|
|
<span class="btn-text">${t('mfa.verify')}</span>
|
|
<span class="btn-spinner hidden">⏳</span>
|
|
</button>
|
|
</form>
|
|
<div class="mfa-actions">
|
|
<button type="button" class="mfa-link-btn" id="mfa-use-recovery">${t('mfa.use_recovery')}</button>
|
|
<button type="button" class="mfa-link-btn" id="mfa-back-login">${t('mfa.back_to_login')}</button>
|
|
</div>
|
|
`;
|
|
mfaSection.classList.remove("hidden");
|
|
|
|
const codeInput = document.getElementById("mfa-code");
|
|
codeInput.focus();
|
|
|
|
// Auto-submit when 6 digits entered
|
|
codeInput.addEventListener("input", () => {
|
|
codeInput.value = codeInput.value.replace(/[^0-9]/g, "");
|
|
if (codeInput.value.length === 6) {
|
|
document.getElementById("mfa-verify-btn").click();
|
|
}
|
|
});
|
|
|
|
// Handle MFA form submit
|
|
document.getElementById("mfa-form").addEventListener("submit", async (e) => {
|
|
e.preventDefault();
|
|
const code = codeInput.value.trim();
|
|
if (code.length !== 6) return;
|
|
|
|
const btn = document.getElementById("mfa-verify-btn");
|
|
const errorEl = document.getElementById("mfa-error");
|
|
btn.disabled = true;
|
|
btn.querySelector(".btn-spinner").classList.remove("hidden");
|
|
btn.querySelector(".btn-text").textContent = t('mfa.verifying');
|
|
errorEl.classList.add("hidden");
|
|
|
|
try {
|
|
await AuthManager.verifyMfa(username, code, rememberMe);
|
|
mfaSection.classList.add("hidden");
|
|
if (loginForm) loginForm.classList.remove("hidden");
|
|
await _onLoginSuccess();
|
|
} catch (err) {
|
|
errorEl.textContent = err.message;
|
|
errorEl.classList.remove("hidden");
|
|
codeInput.value = "";
|
|
codeInput.focus();
|
|
} finally {
|
|
btn.disabled = false;
|
|
btn.querySelector(".btn-spinner").classList.add("hidden");
|
|
btn.querySelector(".btn-text").textContent = t('mfa.verify');
|
|
}
|
|
});
|
|
|
|
// Switch to recovery code input
|
|
document.getElementById("mfa-use-recovery").addEventListener("click", () => {
|
|
showRecoveryChallenge(username, rememberMe, loginForm, mfaSection);
|
|
});
|
|
|
|
// Back to login
|
|
document.getElementById("mfa-back-login").addEventListener("click", () => {
|
|
mfaSection.classList.add("hidden");
|
|
if (loginForm) loginForm.classList.remove("hidden");
|
|
});
|
|
}
|
|
|
|
|
|
function showRecoveryChallenge(username, rememberMe, loginForm, mfaSection) {
|
|
mfaSection.innerHTML = `
|
|
<div class="mfa-icon">🔑</div>
|
|
<h3>${t('mfa.recovery_title')}</h3>
|
|
<p class="mfa-subtitle">${t('mfa.recovery_subtitle')}</p>
|
|
<form id="recovery-form">
|
|
<div class="mfa-code-input-group">
|
|
<input type="text" id="recovery-code" class="mfa-code-input recovery-input" maxlength="9"
|
|
autocomplete="off" placeholder="XXXX-XXXX" autofocus required>
|
|
</div>
|
|
<p class="mfa-error hidden" id="recovery-error"></p>
|
|
<button type="submit" class="btn-login" id="recovery-verify-btn">
|
|
<span class="btn-text">${t('mfa.verify')}</span>
|
|
<span class="btn-spinner hidden">⏳</span>
|
|
</button>
|
|
</form>
|
|
<div class="mfa-actions">
|
|
<button type="button" class="mfa-link-btn" id="recovery-use-totp">${t('mfa.use_totp')}</button>
|
|
<button type="button" class="mfa-link-btn" id="recovery-back-login">${t('mfa.back_to_login')}</button>
|
|
</div>
|
|
`;
|
|
|
|
const codeInput = document.getElementById("recovery-code");
|
|
codeInput.focus();
|
|
|
|
// Auto-format: insert dash after 4 chars
|
|
codeInput.addEventListener("input", () => {
|
|
let v = codeInput.value.replace(/[^a-zA-Z0-9]/g, "").toUpperCase();
|
|
if (v.length > 4) v = v.slice(0, 4) + "-" + v.slice(4, 8);
|
|
codeInput.value = v;
|
|
});
|
|
|
|
document.getElementById("recovery-form").addEventListener("submit", async (e) => {
|
|
e.preventDefault();
|
|
const code = codeInput.value.trim();
|
|
const btn = document.getElementById("recovery-verify-btn");
|
|
const errorEl = document.getElementById("recovery-error");
|
|
btn.disabled = true;
|
|
btn.querySelector(".btn-spinner").classList.remove("hidden");
|
|
btn.querySelector(".btn-text").textContent = t('mfa.verifying');
|
|
errorEl.classList.add("hidden");
|
|
|
|
try {
|
|
await AuthManager.verifyRecovery(username, code);
|
|
mfaSection.classList.add("hidden");
|
|
if (loginForm) loginForm.classList.remove("hidden");
|
|
await _onLoginSuccess();
|
|
} catch (err) {
|
|
errorEl.textContent = err.message;
|
|
errorEl.classList.remove("hidden");
|
|
codeInput.value = "";
|
|
codeInput.focus();
|
|
} finally {
|
|
btn.disabled = false;
|
|
btn.querySelector(".btn-spinner").classList.add("hidden");
|
|
btn.querySelector(".btn-text").textContent = t('mfa.verify');
|
|
}
|
|
});
|
|
|
|
document.getElementById("recovery-use-totp").addEventListener("click", () => {
|
|
showMfaChallenge(username, rememberMe, null, null);
|
|
});
|
|
|
|
document.getElementById("recovery-back-login").addEventListener("click", () => {
|
|
mfaSection.classList.add("hidden");
|
|
if (loginForm) loginForm.classList.remove("hidden");
|
|
});
|
|
}
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Login form handler
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function initLoginForm() {
|
|
const form = document.getElementById("login-form");
|
|
if (!form) return;
|
|
|
|
form.addEventListener("submit", async (e) => {
|
|
e.preventDefault();
|
|
const username = document.getElementById("login-username").value;
|
|
const password = document.getElementById("login-password").value;
|
|
const rememberMe = document.getElementById("remember-me").checked;
|
|
const errorEl = document.getElementById("login-error");
|
|
const btn = document.getElementById("login-btn");
|
|
|
|
btn.disabled = true;
|
|
btn.querySelector(".btn-spinner").classList.remove("hidden");
|
|
btn.querySelector(".btn-text").textContent = "Connexion...";
|
|
errorEl.classList.add("hidden");
|
|
|
|
try {
|
|
const result = await AuthManager.login(username, password, rememberMe);
|
|
// Check if MFA is required
|
|
if (result && result.mfa_required) {
|
|
showMfaChallenge(result.username, rememberMe, btn, errorEl, result.mfa_method);
|
|
return;
|
|
}
|
|
// Normal login success
|
|
await _onLoginSuccess();
|
|
safeCreateIcons();
|
|
} catch (err) {
|
|
errorEl.textContent = err.message;
|
|
errorEl.classList.remove("hidden");
|
|
document.getElementById("login-password").value = "";
|
|
document.getElementById("login-password").focus();
|
|
} finally {
|
|
btn.disabled = false;
|
|
btn.querySelector(".btn-spinner").classList.add("hidden");
|
|
btn.querySelector(".btn-text").textContent = "Se connecter";
|
|
}
|
|
});
|
|
|
|
// Toggle password visibility
|
|
const toggleBtn = document.getElementById("toggle-password");
|
|
if (toggleBtn) {
|
|
toggleBtn.addEventListener("click", () => {
|
|
const input = document.getElementById("login-password");
|
|
input.type = input.type === "password" ? "text" : "password";
|
|
});
|
|
}
|
|
}
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Admin Panel — User management (admin only)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const AdminPanel = {
|
|
_modal: null,
|
|
_allVaults: [],
|
|
|
|
show() {
|
|
this._createModal();
|
|
this._modal.classList.add("active");
|
|
this._loadUsers();
|
|
},
|
|
|
|
hide() {
|
|
if (this._modal) this._modal.classList.remove("active");
|
|
},
|
|
|
|
_createModal() {
|
|
if (this._modal) return;
|
|
this._modal = document.createElement("div");
|
|
this._modal.className = "editor-modal";
|
|
this._modal.id = "admin-modal";
|
|
this._modal.innerHTML = `
|
|
<div class="editor-container">
|
|
<div class="editor-header">
|
|
<div class="editor-title">⚙️ ${t('admin.title')}</div>
|
|
<div class="editor-actions">
|
|
<button class="editor-btn" id="admin-close" title="Fermer">
|
|
<i data-lucide="x" style="width:16px;height:16px"></i>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
<div class="editor-body" id="admin-body">
|
|
<div class="admin-toolbar">
|
|
<button class="btn-login" id="admin-add-user" style="font-size:0.85rem;padding:6px 16px;">${t('admin.new_user')}</button>
|
|
</div>
|
|
<div id="admin-users-list" class="admin-users-list"></div>
|
|
</div>
|
|
</div>
|
|
`;
|
|
document.body.appendChild(this._modal);
|
|
safeCreateIcons();
|
|
|
|
document.getElementById("admin-close").addEventListener("click", () => this.hide());
|
|
document.getElementById("admin-add-user").addEventListener("click", () => this._showUserForm(null));
|
|
},
|
|
|
|
async _loadUsers() {
|
|
try {
|
|
const users = await api("/api/auth/admin/users");
|
|
// Also load available vaults
|
|
try {
|
|
const vaultsData = await api("/api/vaults");
|
|
this._allVaults = vaultsData.map((v) => v.name);
|
|
} catch (e) {
|
|
this._allVaults = [];
|
|
}
|
|
this._renderUsers(users);
|
|
} catch (err) {
|
|
document.getElementById("admin-users-list").innerHTML = '<p style="color:var(--danger);padding:16px;">Erreur : ' + err.message + "</p>";
|
|
}
|
|
},
|
|
|
|
_renderUsers(users) {
|
|
const container = document.getElementById("admin-users-list");
|
|
if (!users.length) {
|
|
container.innerHTML = '<p style="padding:16px;color:var(--text-muted);">Aucun utilisateur.</p>';
|
|
return;
|
|
}
|
|
let html = '<table class="admin-table"><thead><tr>' +
|
|
'<th>' + t('admin.col_user') + '</th><th>' + t('admin.col_role') + '</th><th>' + t('admin.col_vaults') + '</th><th>' + t('admin.col_status') + '</th><th>' + t('admin.col_last_login') + '</th><th>' + t('admin.col_actions') + '</th>' +
|
|
'</tr></thead><tbody>';
|
|
users.forEach((u) => {
|
|
const vaults = u.vaults.includes("*") ? t('common.all') : u.vaults.join(", ") || t('common.none');
|
|
const status = u.active ? "✅" : "🔴";
|
|
const lastLogin = u.last_login ? new Date(u.last_login).toLocaleDateString(getLocale() === 'fr' ? 'fr-FR' : 'en-US', { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : t('common.never');
|
|
html +=
|
|
"<tr>" +
|
|
"<td><strong>" +
|
|
u.username +
|
|
"</strong>" +
|
|
(u.display_name && u.display_name !== u.username ? "<br><small>" + u.display_name + "</small>" : "") +
|
|
"</td>" +
|
|
'<td><span class="admin-role-badge admin-role-' +
|
|
u.role +
|
|
'">' +
|
|
u.role +
|
|
"</span></td>" +
|
|
'<td><span class="admin-vaults-text">' +
|
|
vaults +
|
|
"</span></td>" +
|
|
"<td>" +
|
|
status +
|
|
"</td>" +
|
|
"<td><small>" +
|
|
lastLogin +
|
|
"</small></td>" +
|
|
'<td class="admin-actions">' +
|
|
'<button class="admin-action-btn" data-action="edit" data-username="' +
|
|
u.username +
|
|
'" title="' + t('common.edit') + '">✏️</button>' +
|
|
'<button class="admin-action-btn danger" data-action="delete" data-username="' +
|
|
u.username +
|
|
'" title="' + t('common.delete') + '">🗑️</button>' +
|
|
"</td></tr>";
|
|
});
|
|
html += "</tbody></table>";
|
|
container.innerHTML = html;
|
|
|
|
// Bind action buttons
|
|
container.querySelectorAll('[data-action="edit"]').forEach((btn) => {
|
|
btn.addEventListener("click", () => {
|
|
const user = users.find((u) => u.username === btn.dataset.username);
|
|
if (user) this._showUserForm(user);
|
|
});
|
|
});
|
|
container.querySelectorAll('[data-action="delete"]').forEach((btn) => {
|
|
btn.addEventListener("click", () => this._deleteUser(btn.dataset.username));
|
|
});
|
|
},
|
|
|
|
_showUserForm(user) {
|
|
const isEdit = !!user;
|
|
const title = isEdit ? "Modifier : " + user.username : "Nouvel utilisateur";
|
|
const vaultCheckboxes = this._allVaults
|
|
.map((v) => {
|
|
const checked = user && (user.vaults.includes(v) || user.vaults.includes("*")) ? "checked" : "";
|
|
return '<label class="checkbox-label"><input type="checkbox" name="vault" value="' + v + '" ' + checked + "><span>" + v + "</span></label>";
|
|
})
|
|
.join("");
|
|
const allVaultsChecked = user && user.vaults.includes("*") ? "checked" : "";
|
|
|
|
// Create form modal overlay
|
|
const overlay = document.createElement("div");
|
|
overlay.className = "admin-form-overlay";
|
|
overlay.innerHTML = `
|
|
<div class="admin-form-card">
|
|
<h3>${title}</h3>
|
|
<form id="admin-user-form">
|
|
${!isEdit ? '<div class="form-group"><label>Nom d\'utilisateur</label><input type="text" name="username" required pattern="[a-zA-Z0-9_\-]{2,32}" placeholder="username"></div>' : ""}
|
|
<div class="form-group"><label>Nom affiché</label><input type="text" name="display_name" value="${isEdit ? user.display_name || "" : ""}"></div>
|
|
<div class="form-group"><label>${isEdit ? "Nouveau mot de passe (vide = inchangé)" : "Mot de passe"}</label><input type="password" name="password" ${!isEdit ? 'required minlength="8"' : ""} placeholder="${isEdit ? "Laisser vide pour ne pas changer" : "Min. 8 caractères"}"></div>
|
|
<div class="form-group"><label>Rôle</label><select name="role"><option value="user" ${isEdit && user.role === "user" ? "selected" : ""}>Utilisateur</option><option value="admin" ${isEdit && user.role === "admin" ? "selected" : ""}>Admin</option></select></div>
|
|
<div class="form-group">
|
|
<label>Vaults autorisées</label>
|
|
<div class="admin-vault-list">${vaultCheckboxes}</div>
|
|
<label class="checkbox-label" style="margin-top:8px;border-top:1px solid var(--border);padding-top:8px;"><input type="checkbox" id="admin-all-vaults" ${allVaultsChecked}><span><strong>Accès total</strong> (toutes les vaults, y compris futures)</span></label>
|
|
</div>
|
|
${isEdit ? '<div class="form-group"><label>Compte actif</label><label class="checkbox-label"><input type="checkbox" name="active" ' + (user.active ? "checked" : "") + "><span>Actif</span></label></div>" : ""}
|
|
<div class="admin-form-actions">
|
|
<button type="button" class="config-btn-secondary" id="admin-form-cancel">Annuler</button>
|
|
<button type="submit" class="btn-login" style="font-size:0.85rem;padding:6px 20px;">Enregistrer</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
`;
|
|
this._modal.appendChild(overlay);
|
|
|
|
document.getElementById("admin-form-cancel").addEventListener("click", () => overlay.remove());
|
|
|
|
document.getElementById("admin-user-form").addEventListener("submit", async (e) => {
|
|
e.preventDefault();
|
|
const form = e.target;
|
|
const allVaults = document.getElementById("admin-all-vaults").checked;
|
|
const selectedVaults = allVaults ? ["*"] : Array.from(form.querySelectorAll('input[name="vault"]:checked')).map((cb) => cb.value);
|
|
|
|
try {
|
|
if (isEdit) {
|
|
const updates = {
|
|
display_name: form.display_name.value || null,
|
|
role: form.role.value,
|
|
vaults: selectedVaults,
|
|
};
|
|
if (form.password.value) updates.password = form.password.value;
|
|
const activeCheckbox = form.querySelector('input[name="active"]');
|
|
if (activeCheckbox) updates.active = activeCheckbox.checked;
|
|
await api("/api/auth/admin/users/" + user.username, {
|
|
method: "PATCH",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(updates),
|
|
});
|
|
} else {
|
|
await api("/api/auth/admin/users", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
username: form.username.value,
|
|
password: form.password.value,
|
|
display_name: form.display_name.value || null,
|
|
role: form.role.value,
|
|
vaults: selectedVaults,
|
|
}),
|
|
});
|
|
}
|
|
overlay.remove();
|
|
this._loadUsers();
|
|
showToast(isEdit ? "Utilisateur modifié" : "Utilisateur créé", "success");
|
|
} catch (err) {
|
|
showToast(err.message, "error");
|
|
}
|
|
});
|
|
},
|
|
|
|
async _deleteUser(username) {
|
|
const currentUser = AuthManager.getUser();
|
|
if (currentUser && currentUser.username === username) {
|
|
showToast(t("auth.cannot_delete_self"), "error");
|
|
return;
|
|
}
|
|
if (!confirm("Supprimer l'utilisateur \"" + username + '" ?')) return;
|
|
try {
|
|
await api("/api/auth/admin/users/" + username, { method: "DELETE" });
|
|
this._loadUsers();
|
|
showToast(t("auth.user_deleted"), "success");
|
|
} catch (err) {
|
|
showToast(err.message, "error");
|
|
}
|
|
},
|
|
};
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// MFA Settings — Setup/Disable UI in the settings panel
|
|
// ---------------------------------------------------------------------------
|
|
|
|
async function initMfaSettings() {
|
|
const area = document.getElementById("mfa-setup-area");
|
|
const badge = document.getElementById("mfa-status-badge");
|
|
if (!area || !badge) return;
|
|
|
|
// Check current MFA status
|
|
let mfaEnabled = false;
|
|
try {
|
|
const status = await AuthManager.getMfaStatus();
|
|
mfaEnabled = status.mfa_enabled;
|
|
} catch (e) {
|
|
// Not logged in or error
|
|
return;
|
|
}
|
|
|
|
if (mfaEnabled) {
|
|
badge.textContent = t("mfa.enabled");
|
|
badge.className = "mfa-badge mfa-badge-on";
|
|
area.innerHTML = `
|
|
<p class="mfa-info-text" data-i18n="mfa.enabled_desc">${t("mfa.enabled_desc")}</p>
|
|
<button class="config-btn-secondary" id="mfa-disable-btn">${t("mfa.disable_btn")}</button>
|
|
<div id="mfa-disable-form-area"></div>
|
|
`;
|
|
document.getElementById("mfa-disable-btn").addEventListener("click", () => {
|
|
_showDisableMfaForm();
|
|
});
|
|
} else {
|
|
badge.textContent = t("mfa.disabled");
|
|
badge.className = "mfa-badge mfa-badge-off";
|
|
area.innerHTML = `
|
|
<p class="mfa-info-text" data-i18n="mfa.setup_desc">${t("mfa.setup_desc")}</p>
|
|
<button class="config-btn-primary" id="mfa-enable-btn">${t("mfa.enable_btn")}</button>
|
|
<div id="mfa-setup-flow-area"></div>
|
|
`;
|
|
document.getElementById("mfa-enable-btn").addEventListener("click", () => {
|
|
_startMfaSetup();
|
|
});
|
|
}
|
|
|
|
// WebAuthn security keys section (ROADMAP #64)
|
|
_renderWebauthnSection(area);
|
|
}
|
|
|
|
|
|
async function _renderWebauthnSection(container) {
|
|
if (!container || !window.PublicKeyCredential) return;
|
|
|
|
let keys = [];
|
|
try {
|
|
const resp = await AuthManager.webauthnCredentials();
|
|
keys = resp.credentials || [];
|
|
} catch (e) {
|
|
return; // auth disabled or endpoint unreachable — hide section
|
|
}
|
|
|
|
let section = document.getElementById("webauthn-settings");
|
|
if (!section) {
|
|
section = document.createElement("div");
|
|
section.id = "webauthn-settings";
|
|
section.className = "webauthn-settings";
|
|
container.appendChild(section);
|
|
}
|
|
|
|
const listHtml = keys.length
|
|
? `<ul class="webauthn-key-list">${keys.map((k) => `
|
|
<li class="webauthn-key-item">
|
|
<span class="webauthn-key-label">🔑 ${k.label || "Security key"}</span>
|
|
<span class="webauthn-key-meta">${(k.transports || []).join(", ") || "—"}</span>
|
|
<button class="config-btn-secondary config-btn-sm webauthn-key-remove"
|
|
data-id="${k.credential_id}">${t("mfa.webauthn_remove")}</button>
|
|
</li>`).join("")}</ul>`
|
|
: `<p class="mfa-info-text">${t("mfa.webauthn_none")}</p>`;
|
|
|
|
section.innerHTML = `
|
|
<h4 class="webauthn-title">${t("mfa.webauthn_title")}</h4>
|
|
<p class="mfa-info-text">${t("mfa.webauthn_desc")}</p>
|
|
${listHtml}
|
|
<div class="mfa-recovery-actions">
|
|
<button class="config-btn-primary" id="webauthn-add-btn">${t("mfa.webauthn_add")}</button>
|
|
</div>
|
|
<p class="mfa-error hidden" id="webauthn-error"></p>
|
|
<div id="webauthn-flow-area"></div>
|
|
`;
|
|
|
|
const errEl = section.querySelector("#webauthn-error");
|
|
document.getElementById("webauthn-add-btn").addEventListener("click", async () => {
|
|
errEl.classList.add("hidden");
|
|
try {
|
|
const credential = await runWebauthnRegistration();
|
|
const label = prompt(t("mfa.webauthn_label_prompt"), "Ma clé");
|
|
const result = await AuthManager.webauthnRegister(credential, label || "Security key");
|
|
if (result.recovery_codes && result.recovery_codes.length) {
|
|
_showRecoveryCodes(result.recovery_codes);
|
|
} else {
|
|
showToast(t("mfa.webauthn_added"), "success");
|
|
}
|
|
initMfaSettings();
|
|
} catch (err) {
|
|
errEl.textContent = err.message || String(err);
|
|
errEl.classList.remove("hidden");
|
|
}
|
|
});
|
|
|
|
section.querySelectorAll(".webauthn-key-remove").forEach((btn) => {
|
|
btn.addEventListener("click", async () => {
|
|
const password = prompt(t("mfa.webauthn_remove_confirm"));
|
|
if (password === null) return;
|
|
try {
|
|
await AuthManager.webauthnRemove(btn.dataset.id, password);
|
|
showToast(t("mfa.webauthn_removed"), "success");
|
|
initMfaSettings();
|
|
} catch (err) {
|
|
errEl.textContent = err.message || String(err);
|
|
errEl.classList.remove("hidden");
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
|
|
async function _startMfaSetup() {
|
|
const flowArea = document.getElementById("mfa-setup-flow-area");
|
|
if (!flowArea) return;
|
|
|
|
try {
|
|
const data = await AuthManager.mfaSetup();
|
|
flowArea.innerHTML = `
|
|
<div class="mfa-setup-card">
|
|
<h4>${t("mfa.scan_qr")}</h4>
|
|
<div class="mfa-qr-container">
|
|
<img id="mfa-qr-img" alt="QR Code" class="mfa-qr-code"
|
|
src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(data.otpauth_uri)}">
|
|
</div>
|
|
<details class="mfa-secret-details">
|
|
<summary>${t("mfa.manual_entry")}</summary>
|
|
<code class="mfa-secret-code">${data.secret}</code>
|
|
</details>
|
|
<div class="mfa-verify-section">
|
|
<label>${t("mfa.enter_code")}</label>
|
|
<input type="text" id="mfa-enable-code" class="mfa-code-input" maxlength="6"
|
|
pattern="[0-9]{6}" inputmode="numeric" placeholder="000000" autocomplete="one-time-code">
|
|
<button class="config-btn-primary" id="mfa-confirm-btn">${t("mfa.confirm_enable")}</button>
|
|
<p class="mfa-error hidden" id="mfa-enable-error"></p>
|
|
</div>
|
|
</div>
|
|
`;
|
|
|
|
const codeInput = document.getElementById("mfa-enable-code");
|
|
codeInput.addEventListener("input", () => {
|
|
codeInput.value = codeInput.value.replace(/[^0-9]/g, "");
|
|
});
|
|
|
|
document.getElementById("mfa-confirm-btn").addEventListener("click", async () => {
|
|
const code = codeInput.value.trim();
|
|
if (code.length !== 6) return;
|
|
|
|
const btn = document.getElementById("mfa-confirm-btn");
|
|
const errorEl = document.getElementById("mfa-enable-error");
|
|
btn.disabled = true;
|
|
btn.textContent = t("mfa.verifying");
|
|
errorEl.classList.add("hidden");
|
|
|
|
try {
|
|
const result = await AuthManager.mfaEnable(code);
|
|
// Show recovery codes
|
|
_showRecoveryCodes(result.recovery_codes);
|
|
} catch (err) {
|
|
errorEl.textContent = err.message;
|
|
errorEl.classList.remove("hidden");
|
|
codeInput.value = "";
|
|
codeInput.focus();
|
|
} finally {
|
|
btn.disabled = false;
|
|
btn.textContent = t("mfa.confirm_enable");
|
|
}
|
|
});
|
|
} catch (err) {
|
|
flowArea.innerHTML = `<p class="mfa-error">${err.message}</p>`;
|
|
}
|
|
}
|
|
|
|
|
|
function _showRecoveryCodes(codes) {
|
|
const flowArea = document.getElementById("mfa-setup-flow-area");
|
|
const area = document.getElementById("mfa-setup-area");
|
|
if (!flowArea) return;
|
|
|
|
const codesHtml = codes.map(c => `<code class="mfa-recovery-code">${c}</code>`).join("\n");
|
|
flowArea.innerHTML = `
|
|
<div class="mfa-recovery-card">
|
|
<h4>🔑 ${t("mfa.recovery_codes_title")}</h4>
|
|
<p class="mfa-warning">${t("mfa.recovery_codes_warning")}</p>
|
|
<div class="mfa-recovery-list" id="mfa-recovery-list">
|
|
${codesHtml}
|
|
</div>
|
|
<div class="mfa-recovery-actions">
|
|
<button class="config-btn-secondary" id="mfa-copy-codes">${t("mfa.copy_codes")}</button>
|
|
<button class="config-btn-secondary" id="mfa-download-codes">${t("mfa.download_codes")}</button>
|
|
<button class="config-btn-primary" id="mfa-codes-done">${t("mfa.done")}</button>
|
|
</div>
|
|
</div>
|
|
`;
|
|
|
|
document.getElementById("mfa-copy-codes").addEventListener("click", () => {
|
|
navigator.clipboard.writeText(codes.join("\n")).then(() => {
|
|
showToast(t("mfa.codes_copied"), "success");
|
|
});
|
|
});
|
|
|
|
document.getElementById("mfa-download-codes").addEventListener("click", () => {
|
|
const blob = new Blob([codes.join("\n")], { type: "text/plain" });
|
|
const url = URL.createObjectURL(blob);
|
|
const a = document.createElement("a");
|
|
a.href = url;
|
|
a.download = "obsigate-recovery-codes.txt";
|
|
a.click();
|
|
URL.revokeObjectURL(url);
|
|
});
|
|
|
|
document.getElementById("mfa-codes-done").addEventListener("click", () => {
|
|
// Refresh MFA settings display
|
|
initMfaSettings();
|
|
});
|
|
}
|
|
|
|
|
|
function _showDisableMfaForm() {
|
|
const formArea = document.getElementById("mfa-disable-form-area");
|
|
if (!formArea) return;
|
|
|
|
formArea.innerHTML = `
|
|
<div class="mfa-disable-card">
|
|
<h4>${t("mfa.disable_confirm_title")}</h4>
|
|
<p>${t("mfa.disable_confirm_desc")}</p>
|
|
<div class="form-group">
|
|
<label>${t("mfa.password_label")}</label>
|
|
<input type="password" id="mfa-disable-password" class="config-input" placeholder="${t('mfa.password_placeholder')}">
|
|
</div>
|
|
<div class="form-group">
|
|
<label>${t("mfa.totp_code_label")}</label>
|
|
<input type="text" id="mfa-disable-code" class="mfa-code-input" maxlength="6"
|
|
pattern="[0-9]{6}" inputmode="numeric" placeholder="000000">
|
|
</div>
|
|
<div class="mfa-disable-actions">
|
|
<button class="config-btn-secondary" id="mfa-disable-cancel">${t("common.cancel")}</button>
|
|
<button class="config-btn-danger" id="mfa-disable-confirm">${t("mfa.disable_confirm_btn")}</button>
|
|
</div>
|
|
<p class="mfa-error hidden" id="mfa-disable-error"></p>
|
|
</div>
|
|
`;
|
|
|
|
document.getElementById("mfa-disable-cancel").addEventListener("click", () => {
|
|
formArea.innerHTML = "";
|
|
});
|
|
|
|
document.getElementById("mfa-disable-confirm").addEventListener("click", async () => {
|
|
const password = document.getElementById("mfa-disable-password").value;
|
|
const code = document.getElementById("mfa-disable-code").value.trim();
|
|
const errorEl = document.getElementById("mfa-disable-error");
|
|
const btn = document.getElementById("mfa-disable-confirm");
|
|
|
|
if (!password || code.length !== 6) {
|
|
errorEl.textContent = t("mfa.fill_all_fields");
|
|
errorEl.classList.remove("hidden");
|
|
return;
|
|
}
|
|
|
|
btn.disabled = true;
|
|
btn.textContent = t("mfa.verifying");
|
|
errorEl.classList.add("hidden");
|
|
|
|
try {
|
|
await AuthManager.mfaDisable(password, code);
|
|
showToast(t("mfa.disabled_success"), "success");
|
|
initMfaSettings();
|
|
} catch (err) {
|
|
errorEl.textContent = err.message;
|
|
errorEl.classList.remove("hidden");
|
|
} finally {
|
|
btn.disabled = false;
|
|
btn.textContent = t("mfa.disable_confirm_btn");
|
|
}
|
|
});
|
|
}
|
|
|
|
|
|
export { api, AuthManager, initLoginForm, AdminPanel, initMfaSettings };
|