Files
dashcaddy/status/js/totp-auth.js
T
Hermes 923ce8c300
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled
DC-049 auth gate UI: pluggable provider selector + email challenge
New module status/js/auth-gate.js owns the Caddy ?auth=required flow.
On load it queries GET /api/v1/auth/login/methods to discover which
AuthProviders are configured. Three branches:

  * 0 providers  → legacy TOTP overlay (delegates to window._showTotpOverlay)
  * 1 provider (totp only) → legacy TOTP overlay (delegates, no UI change)
  * 2+ providers → provider selector with 'Sign in with …' buttons

Email provider challenge is a single email input + 'Send sign-in link'
button. POST to /api/v1/auth/login/email/initiate. On success the UI
shows 'check the server logs' message if deliveredVia == 'dev-console'
(production hosts without SMTP fall back gracefully) or 'check your
inbox' when SMTP is configured.

TOTP button just calls window.location.reload() — simplest path because
totp-auth.js wires the 6-digit input handlers at module-load time, and
a reload re-runs all IIFEs with the original markup. Same behavior as
the legacy single-provider path.

Coordination with totp-auth.js: auth-gate.js sets window.__dc_049_handled
= true at IIFE entry. totp-auth.js's top-level ?auth=required check
reads that flag and skips its own UI when set — eliminates the flicker
in multi-provider installs. Single-provider installs still work because
the legacy code path is unchanged (auth-gate delegates to it).

Bundle order in build.js: auth-gate.js BEFORE totp-auth.js so the flag
is set in time.

Webpack-style bundle markers verified offline: __dc_049_handled,
auth-gate-email-input, provider-btn, _showAuthGate, totp_redirect all
present in dist/core.js (now 20 files, 248KB raw / 153KB min). New SW
cache hash dashcaddy-shell-680e230383 (was 743f9c17b0).
2026-07-20 02:17:12 -07:00

144 lines
5.3 KiB
JavaScript

// ===== TOTP AUTHENTICATION GATE =====
(function() {
function updateTotpLogo() {
const card = document.querySelector('.totp-card');
if (!card) return;
const bg = getComputedStyle(card).backgroundColor;
const m = bg.match(/\d+/g);
if (!m) return;
const lum = (0.299 * +m[0] + 0.587 * +m[1] + 0.114 * +m[2]) / 255;
const dark = card.querySelector('.totp-logo-dark');
const light = card.querySelector('.totp-logo-light');
if (dark) dark.style.display = lum > 0.5 ? 'none' : '';
if (light) light.style.display = lum > 0.5 ? '' : 'none';
}
function showTotpOverlay() {
const overlay = document.getElementById('totp-overlay');
if (overlay) {
overlay.classList.add('show');
setTimeout(updateTotpLogo, 50);
const firstInput = overlay.querySelector('.totp-digits input');
if (firstInput) setTimeout(() => firstInput.focus(), 100);
}
// Refresh the "Lost access?" recovery link visibility based on server state.
// Hides itself if TOTP is healthy; shows if unreadable/corrupt. The user
// can still click it even when healthy — but the panel will explain there's
// no recovery needed. Cheaper than gating it.
if (typeof window._refreshRecoveryLink === 'function') {
window._refreshRecoveryLink();
}
}
function hideTotpOverlay() {
const overlay = document.getElementById('totp-overlay');
if (overlay) overlay.classList.remove('show');
}
// Setup digit input UX
const container = document.getElementById('totp-digits');
if (container) {
const inputs = container.querySelectorAll('input');
inputs.forEach((input, idx) => {
input.addEventListener('input', (e) => {
const val = e.target.value.replace(/\D/g, '');
e.target.value = val.slice(0, 1);
if (val && idx < inputs.length - 1) inputs[idx + 1].focus();
const code = Array.from(inputs).map(i => i.value).join('');
if (code.length === 6) submitTotpCode(code);
});
input.addEventListener('keydown', (e) => {
if (e.key === 'Backspace' && !e.target.value && idx > 0) {
inputs[idx - 1].focus();
inputs[idx - 1].value = '';
}
});
input.addEventListener('paste', (e) => {
e.preventDefault();
const pasted = (e.clipboardData.getData('text') || '').replace(/\D/g, '');
if (pasted.length >= 6) {
inputs.forEach((inp, i) => { inp.value = pasted[i] || ''; });
inputs[5].focus();
submitTotpCode(pasted.slice(0, 6));
}
});
});
}
async function submitTotpCode(code) {
const errorEl = document.getElementById('totp-error');
errorEl.textContent = 'Verifying...';
errorEl.className = 'totp-error verifying';
try {
const res = await secureFetch('/api/v1/totp/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code })
});
const data = await res.json();
if (data.success) {
errorEl.textContent = '';
// Update cached CSRF token from TOTP response (server rotates it on login)
if (data.csrfToken) {
csrfToken = data.csrfToken;
}
hideTotpOverlay();
// Check if redirected here from another service
const redirect = safeSessionGet('totp_redirect');
if (redirect) {
try { sessionStorage.removeItem('totp_redirect'); } catch (_) {}
window.location.href = redirect;
return;
}
// Initialize dashboard
if (typeof window.initializeDashboard === 'function') {
window.initializeDashboard();
}
} else {
errorEl.textContent = data.error || 'Invalid code';
errorEl.className = 'totp-error';
const inputs = document.querySelectorAll('#totp-digits input');
inputs.forEach(i => { i.value = ''; });
inputs[0]?.focus();
}
} catch (e) {
errorEl.textContent = 'Connection error';
errorEl.className = 'totp-error';
}
}
// Handle ?auth=required redirect from Caddy SSO.
// DC-049: if the auth-gate module will handle this (multi-provider
// installs), skip our TOTP-only branch entirely. Single-provider
// TOTP-only installs continue to use this path because auth-gate.js
// delegates back to window._showTotpOverlay().
const __dc_049_skip = !!(window.__dc_049_handled);
if (!__dc_049_skip && urlParams.get('auth') === 'required') {
const returnUrl = urlParams.get('return');
if (returnUrl) {
// Validate redirect URL: must be same-origin or hostname must end with our TLD
// (prevents open redirect via includes() bypass like evil.com?q=.sami)
try {
const parsed = new URL(returnUrl, window.location.origin);
const hostname = parsed.hostname;
const isSameOrigin = parsed.origin === window.location.origin;
const tldSuffix = SITE.tld.startsWith('.') ? SITE.tld : '.' + SITE.tld;
const isOurTld = hostname.endsWith(tldSuffix) || hostname === tldSuffix.substring(1);
if (isSameOrigin || isOurTld) {
safeSessionSet('totp_redirect', returnUrl);
}
} catch (_) {
// Invalid URL — reject redirect
}
}
// Clean URL
window.history.replaceState({}, '', window.location.pathname);
}
window._showTotpOverlay = showTotpOverlay;
})();