Files
Kelx/views/login.ejs
T
2026-11-30 16:32:37 +00:00

922 lines
39 KiB
Plaintext

<% const loginBackgroundType=(branding && branding.loginBackgroundType) ? branding.loginBackgroundType : 'video' ; const
loginBackgroundUrl='/auth-assets/background' ; const
loginBackgroundMimeType=(branding && branding.loginBackgroundMimeType) ? branding.loginBackgroundMimeType
: 'video/webm' ; const loginRequiresTwoFactor=typeof requiresTwoFactor !== 'undefined' && !!requiresTwoFactor; const
loginEmailValue=typeof loginEmail !== 'undefined' ? String(loginEmail || '') : ''; const
loginExternalCaptchaAvailable=typeof externalCaptchaAvailable !== 'undefined' ? !!externalCaptchaAvailable : !!useExternalCaptcha; const
loginCaptchaChallengeActive=!!useExternalCaptcha; %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sign in</title>
<meta name="robots" content="noindex, noarchive" />
<%# adpanel:login-dead-assets — the auth-page CSP is built with
includeGoogleFonts:false (index.js applyLoginPageSecurityHeaders), so
style-src never allowed fonts.googleapis.com: the Google Fonts links
below were hard-blocked dead weight and are not re-added here unless
the CSP flag flips too. %>
<link rel="preload" as="font" type="font/woff2" crossorigin
href="/vendor/fontawesome/webfonts/fa-solid-900.woff2">
<link rel="stylesheet" href="/vendor/fontawesome/css/all.min.css?v=6.7.2-subset">
<link id="favicon" rel="icon" type="<%= (branding && branding.faviconMimeType) ? branding.faviconMimeType : 'image/webp' %>" sizes="<%= (branding && branding.faviconMimeType === 'image/svg+xml') ? 'any' : '16x16' %>"
href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : (branding && branding.logoUrl ? branding.logoUrl : '/images/adpanel-dark.svg') %>" />
<link rel="alternate icon" type="<%= (branding && branding.faviconMimeType) ? branding.faviconMimeType : 'image/webp' %>" href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : (branding && branding.logoUrl ? branding.logoUrl : '/images/adpanel-dark.svg') %>" />
<% if (loginBackgroundType==='image' && loginBackgroundUrl) { %>
<link rel="preload" as="image" href="<%= loginBackgroundUrl %>" fetchpriority="high" />
<% } %>
<style nonce="<%= cspNonce %>">
<%- loginCss || "" %>
*,
*::before,
*::after {
-webkit-font-smoothing: antialiased !important;
-moz-osx-font-smoothing: grayscale !important;
text-rendering: optimizeLegibility !important;
font-synthesis: none !important;
}
.custom-login-input,
.custom-login-input::placeholder,
.access-btn-text:not(.access-btn-text--panel) {
font-weight: 400 !important;
font-synthesis: none !important;
}
.access-btn-text--panel {
font-weight: 600 !important;
font-size: 15.7px !important;
}
<% if (loginBackgroundType === 'image' && loginBackgroundUrl) { %>
body.login-body--image {
<% /* adpanel:login-css-escape-context — CSS-string context requires a CSS hex escape (\00003c), not the JS \u003c form used in the script context (~line 102): inside a CSS string \u escapes the letter "u" (u is not a hex digit), so a `<` would materialize as garbage text instead of an escaped codepoint — the two contexts deliberately differ. */ %>
background-image: url(<%- JSON.stringify(String(loginBackgroundUrl)).replace(/</g, '\\00003c') %>);
}
<% } %>
</style>
<script nonce="<%= cspNonce %>">
(function () {
const CHRISTMAS_IMG = '/auth-assets/christmas-logo';
function isChristmasPeriod() {
const now = new Date();
const month = now.getMonth();
const day = now.getDate();
return month === 11 && day >= 25 && day <= 28;
}
function applyChristmasTheme() {
if (!isChristmasPeriod()) return;
const favicon = document.getElementById('favicon') || document.querySelector('link[rel="icon"]');
if (favicon) favicon.href = CHRISTMAS_IMG;
document.querySelectorAll('img').forEach(img => {
// adpanel:login-dead-assets — the i.imgur.com legacy-CDN default-logo
// match was removed 2026-11 with the CDN-surface retirement: no
// runtime path on this page can produce that src any more. The
// ADPanel-owned default-logo match is the case-insensitive,
// basename-anchored test /(^|\/)adpanel-dark\.(svg|webp)(\?|$)/i,
// restored to life 2026-11: it themes BOTH shipped spellings of the
// default logo — the shipped remote-CDN .../adpanel-dark.svg logoUrl
// and the local /images/adpanel-dark.svg fallback (plus the
// /auth-assets/logo no-branding fallback leg below) — while an
// operator's custom upload is never clobbered. The anchors are
// load-bearing: an unanchored substring match also themed URLs that
// merely EMBED the default filename (e.g. .../logos/adpanel-dark.svg.png,
// or a proxy URL carrying the name as a query param), so the test
// requires the basename to begin after a / (or at string start) and
// end at string end or a query — any src whose basename is not
// exactly the ADPanel-owned default filename never matches. The old
// ADPanel-dark.webp-only includes() was dead against the shipped svg
// default: pre-fix the swap never fired on default-branding
// deployments.
if (img.src && (img.src.includes('/auth-assets/logo') || /(^|\/)adpanel-dark\.(svg|webp)(\?|$)/i.test(img.src))) {
img.src = CHRISTMAS_IMG;
}
});
}
document.addEventListener('DOMContentLoaded', applyChristmasTheme);
})();
</script>
<script nonce="<%= cspNonce %>">
(function() {
const isInput = e => e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable);
document.addEventListener('contextmenu', e => { if (!isInput(e)) e.preventDefault(); });
document.addEventListener('dragstart', e => { if (!isInput(e)) e.preventDefault(); });
document.addEventListener('selectstart', e => { if (!isInput(e)) e.preventDefault(); });
document.addEventListener('copy', e => { if (!isInput(e)) e.preventDefault(); });
document.addEventListener('cut', e => { if (!isInput(e)) e.preventDefault(); });
document.addEventListener('keydown', e => {
if (isInput(e)) return;
if ((e.ctrlKey || e.metaKey) && ['c', 'C', 'a', 'A', 's', 'S', 'u', 'U'].includes(e.key)) e.preventDefault();
});
})();
</script>
</head>
<body class="<%= [loginBackgroundType === 'image' && loginBackgroundUrl ? 'login-body--image' : '', loginRequiresTwoFactor ? 'login-has-2fa' : ''].filter(Boolean).join(' ') %>">
<div id="toastHost" class="toast-host" aria-live="polite" aria-atomic="true"></div>
<script nonce="<%= cspNonce %>">
(() => {
const msg = <%- JSON.stringify(String(error || "")).replace(/</g, "\\u003c") %>;
if (!msg) return;
const host = document.getElementById("toastHost");
if (!host) return;
function showToast(text, duration = 4500) {
const toast = document.createElement("div");
toast.className = "toast";
toast.innerHTML = `
<div class="toast-inner">
<div class="toast-msg"></div>
<div class="toast-bar"></div>
</div>
`;
toast.querySelector(".toast-msg").textContent = text;
host.appendChild(toast);
requestAnimationFrame(() => toast.classList.add("toast-show"));
const leaveAt = Math.max(0, duration - 320);
setTimeout(() => toast.classList.add("toast-hide"), leaveAt);
setTimeout(() => toast.remove(), duration + 450);
}
showToast(msg, 4500);
})();
</script>
<% if (loginBackgroundType==='video' ) { %>
<video id="bgVideo" autoplay muted loop playsinline preload="metadata" class="video">
<source src="<%= loginBackgroundUrl %>" type="<%= loginBackgroundMimeType %>" />
Your browser does not support instant-video.
</video>
<% } %>
<!-- Main Glassmorphic Container (Rectangle 193: 1099x509, #343434 40%, backdrop blur 25px, border-radius 42px, NO BOX SHADOW) -->
<div class="login-card">
<div class="login-left-side">
<%# adpanel:login-two-step-ux — the prompt state is DYNAMIC, not a
literal: the login CSS moves the submit button from this attribute
(top 180px while hidden, 263px once the 2FA row is revealed) and
the client controller keys every 2FA flip off it. The output tag
emits only the "true"/"false" VALUE — attribute markup must never
pass through an EJS output tag, which HTML-escapes its quotes —
and with no render data it defaults to "false": the row ships
hidden and appears only after the server has verified the
email+password pair and answered 401 { requires2FA: true }. %>
<form method="POST" action="/login" class="login-form" data-requires-two-factor="<%= loginRequiresTwoFactor ? 'true' : 'false' %>">
<input type="text" name="company" tabindex="-1" autocomplete="off" aria-hidden="true" hidden>
<input type="hidden" name="botProof" id="botProofInput" value="<%= botProofSeed || '' %>" autocomplete="off">
<input type="hidden" name="_csrf" value="<%= csrfToken %>" autocomplete="off">
<input type="hidden" name="captchaToken" id="captchaTokenInput" value="" />
<div class="login-form-content">
<!-- Email Field -->
<div class="field-item field-item--email">
<input class="custom-login-input" id="loginEmail" type="email" name="email" value="<%= loginEmailValue %>" placeholder="Email" autocomplete="email" required />
<div class="field-separator"></div>
</div>
<!-- Password Field -->
<div class="field-item field-item--password">
<input class="custom-login-input" id="loginPassword" type="password" name="password" placeholder="Password" autocomplete="current-password" required />
<%# adpanel:login-two-step-ux — attribute VALUES (not markup) may
pass through an EJS output tag: 'false'/'true' contain no
escapable characters, so the emission reaches the browser
intact in both render modes. The pre-campaign template's
bug was emitting whole-attribute markup (quotes) through a
output tag, which HTML-escaping turned into a broken
attribute. The row ships hidden; a no-JS challenge render
(requiresTwoFactor: true) bakes "false" directly, and the
controller's initial setTwoFactorRequired pass re-applies
the same state when JS runs. %>
<div class="field-separator sep-2fa" id="sepTwoFactor" aria-hidden="<%= loginRequiresTwoFactor ? 'false' : 'true' %>"></div>
</div>
<!-- 2FA Code Field -->
<%# adpanel:login-two-step-ux — the row state is baked from the
render data (hidden on a fresh page; visible only on the
post-password-match challenge render, so a no-JS 2FA user is
never stuck on an invisible required field) and the
controller's initial setTwoFactorRequired pass re-applies the
same state when JS runs. Value-only aria-hidden emission (see
the separator note above); the conditional emits the bare
words required/disabled. Placeholder is the owner-mandated
"2FA Code". %>
<div class="field-item field-item--2fa" id="loginTwoFactorField" aria-hidden="<%= loginRequiresTwoFactor ? 'false' : 'true' %>">
<input class="custom-login-input" type="text" name="code" id="loginTwoFactorCode" placeholder="2FA Code" maxlength="6" inputmode="numeric" autocomplete="one-time-code" <%= loginRequiresTwoFactor ? 'required' : 'disabled' %> />
</div>
<!-- Access Panel Button -->
<button type="submit" class="access-panel-btn">
<div class="access-btn-brand">
<span class="access-btn-text">Access</span>
<img class="access-btn-logo" src="<%= (branding && branding.logoUrl) ? branding.logoUrl : '/auth-assets/logo' %>" alt="<%= (branding && branding.appName) ? branding.appName : 'ADPanel' %> logo" draggable="false" />
<span class="access-btn-text access-btn-text--panel"><%= (branding && branding.appName) ? branding.appName.replace(/^AD/i, '') : 'Panel' %></span>
</div>
<%# adpanel:login-dead-assets — same-origin arrow: the inline
onerror fallback was dead under script-src-attr 'none', so the
arrow is served from 'self' instead.
Removed 2026-11: the access-btn-logo onerror attribute is gone
too — dead under script-src-attr 'none' (it could never fire),
so the inline-handler surface on this page stays empty; the
default-logo fallback lives in the src ternary above. %>
<img class="access-btn-arrow" src="/images/down-icon.svg" alt="arrow" draggable="false" />
</button>
</div>
</form>
</div>
<div class="login-right-side">
<h1 class="greeting-title" id="greetingTitle">Good Afternoon!</h1>
<p class="welcome-subtitle">Welcome to ADPanel! Manage your containers with ease.</p>
<div class="did-you-know-container">
<h2 class="did-you-know-title">Did you know?</h2>
<p class="did-you-know-text" id="didYouKnowText">ADPanel was first engineered to run on phones.</p>
<div class="carousel-indicators" id="carouselIndicators">
<button type="button" class="indicator-item" data-index="0" aria-label="Fact 1"><span class="indicator-fill"></span></button>
<button type="button" class="indicator-item" data-index="1" aria-label="Fact 2"><span class="indicator-fill"></span></button>
<button type="button" class="indicator-item" data-index="2" aria-label="Fact 3"><span class="indicator-fill"></span></button>
<button type="button" class="indicator-item" data-index="3" aria-label="Fact 4"><span class="indicator-fill"></span></button>
</div>
</div>
</div>
</div>
<!-- Captcha Modal -->
<div id="captchaModal" class="captcha-modal<%= loginCaptchaChallengeActive ? ' show' : '' %>"
data-provider="<%= (externalCaptchaProvider || 'recaptcha').toLowerCase() %>"
data-challenge="<%= loginCaptchaChallengeActive ? '1' : '0' %>"
aria-hidden="<%= loginCaptchaChallengeActive ? 'false' : 'true' %>">
<div class="captcha-modal__backdrop"></div>
<div class="captcha-modal__card">
<div class="captcha-modal__title">
<i class="fa-solid fa-shield-halved captcha-modal__title-icon"></i>Security Verification
</div>
<div class="captcha-modal__desc">Complete the challenge below to continue</div>
<div class="captcha-modal__widget">
<div id="recaptchaWidget" hidden></div>
<div id="cf-turnstile" hidden></div>
<div id="hcaptchaWidget" hidden></div>
</div>
</div>
</div>
<script nonce="<%= cspNonce %>">
(() => {
const cfg = {
enabled: <%- loginExternalCaptchaAvailable ? "true" : "false" %>,
required: <%- externalCaptchaAutoStart ? "true" : "false" %>,
provider: <%- JSON.stringify((externalCaptchaProvider || "recaptcha").toLowerCase()).replace(/</g, "\\u003c") %>,
siteKey: <%- JSON.stringify(externalCaptchaSiteKey || "").replace(/</g, "\\u003c") %>,
challengeActive: <%- loginCaptchaChallengeActive ? "true" : "false" %>,
};
const form = document.querySelector("form.login-form");
const modal = document.getElementById("captchaModal");
const tokenInput = document.getElementById("captchaTokenInput");
const recaptchaHost = document.getElementById("recaptchaWidget");
const turnstileHost = document.getElementById("cf-turnstile");
const hcaptchaHost = document.getElementById("hcaptchaWidget");
const statusEl = modal ? modal.querySelector(".captcha-modal__desc") : null;
const defaultStatusText = statusEl ? statusEl.textContent : "";
let recaptchaId = null;
let turnstileId = null;
let hcaptchaId = null;
let started = false;
let timeoutHandle = null;
function notify(text, duration = 4500) {
const host = document.getElementById("toastHost");
if (!host || !text) return;
const toast = document.createElement("div");
toast.className = "toast";
toast.innerHTML = '<div class="toast-inner"><div class="toast-msg"></div><div class="toast-bar"></div></div>';
toast.querySelector(".toast-msg").textContent = text;
host.appendChild(toast);
requestAnimationFrame(() => toast.classList.add("toast-show"));
setTimeout(() => toast.classList.add("toast-hide"), Math.max(0, duration - 320));
setTimeout(() => toast.remove(), duration + 450);
}
const disableForm = () => {
if (!form) return;
form.querySelectorAll("input:not([type=hidden]), button[type=submit]").forEach(el => { el.disabled = true; });
form.classList.add("login-form--blocked");
};
const enableForm = () => {
if (!form) return;
form.querySelectorAll("input, button").forEach(el => { el.disabled = false; });
// adpanel:login-two-step-ux — the bulk enable must not wake the 2FA
// row out of its hidden state: it stays disabled unless the form is
// actually in the server-confirmed prompt state.
const loginTwoFactorInput = document.getElementById("loginTwoFactorCode");
if (loginTwoFactorInput && form.dataset.requiresTwoFactor !== "true") {
loginTwoFactorInput.disabled = true;
}
form.classList.remove("login-form--blocked");
};
const showModal = () => {
if (modal) modal.classList.add("show");
disableForm();
};
const hideModal = () => {
if (modal) {
modal.classList.remove("show");
modal.dataset.challenge = "0";
modal.setAttribute("aria-hidden", "true");
}
enableForm();
if (timeoutHandle) {
clearTimeout(timeoutHandle);
timeoutHandle = null;
}
};
const resetStatus = () => {
if (statusEl) statusEl.textContent = defaultStatusText;
};
const markTimeout = () => {
if (statusEl) {
statusEl.textContent = "Captcha unavailable. Try again.";
}
};
const resetCaptchaWidget = () => {
tokenInput.value = "";
try {
if (recaptchaId !== null && window.grecaptcha && typeof window.grecaptcha.reset === "function") {
window.grecaptcha.reset(recaptchaId);
}
} catch { }
try {
if (turnstileId !== null && window.turnstile && typeof window.turnstile.reset === "function") {
window.turnstile.reset(turnstileId);
}
} catch { }
try {
if (hcaptchaId !== null && window.hcaptcha && typeof window.hcaptcha.reset === "function") {
window.hcaptcha.reset(hcaptchaId);
}
} catch { }
};
async function verifyCaptchaToken(token) {
if (!token || modal?.dataset.challenge !== "1") return;
tokenInput.value = token;
if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null; }
if (statusEl) statusEl.textContent = "Finalizing sign in...";
try {
const resp = await fetch("/api/captcha/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token }),
credentials: "same-origin",
});
const data = await resp.json().catch(() => ({}));
if (resp.ok && data.ok) {
if (data.redirect) {
window.location.href = data.redirect;
return;
}
hideModal();
if (data.unlocked) {
notify("Security verification complete. Continuing sign-in...", 4500);
const submitBtn = form ? form.querySelector('button[type="submit"]') : null;
if (submitBtn) submitBtn.disabled = true;
setTimeout(() => {
form.dispatchEvent(new Event("submit", { cancelable: true }));
}, 400);
}
return;
}
resetCaptchaWidget();
if (data.redirect) {
window.location.href = data.redirect;
return;
}
if (statusEl) statusEl.textContent = data.error || "Captcha verification failed. Try again.";
} catch {
resetCaptchaWidget();
if (statusEl) statusEl.textContent = "Network error. Try again.";
}
}
function renderRecaptcha() {
if (!cfg.enabled || recaptchaId !== null) return recaptchaId;
if (!window.grecaptcha || typeof window.grecaptcha.render !== "function") return null;
if (turnstileHost) turnstileHost.hidden = true;
if (hcaptchaHost) hcaptchaHost.hidden = true;
if (recaptchaHost) recaptchaHost.hidden = false;
recaptchaId = window.grecaptcha.render("recaptchaWidget", {
sitekey: cfg.siteKey,
size: "normal",
theme: "dark",
callback: verifyCaptchaToken,
"expired-callback": () => { tokenInput.value = ""; },
"error-callback": () => { tokenInput.value = ""; },
});
if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null; }
resetStatus();
return recaptchaId;
}
function ensureRecaptcha(attempt = 0) {
if (recaptchaId === null) renderRecaptcha();
if (recaptchaId !== null) return;
if (attempt < 50) setTimeout(() => ensureRecaptcha(attempt + 1), 200);
}
function renderTurnstile() {
if (!cfg.enabled || turnstileId !== null) return turnstileId;
if (!window.turnstile || typeof window.turnstile.render !== "function") return null;
if (recaptchaHost) recaptchaHost.hidden = true;
if (hcaptchaHost) hcaptchaHost.hidden = true;
if (turnstileHost) turnstileHost.hidden = false;
turnstileId = window.turnstile.render("#cf-turnstile", {
sitekey: cfg.siteKey,
size: "normal",
theme: "dark",
callback: verifyCaptchaToken,
"expired-callback": () => { tokenInput.value = ""; },
"error-callback": () => { tokenInput.value = ""; },
});
if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null; }
resetStatus();
return turnstileId;
}
function ensureTurnstile(attempt = 0) {
if (turnstileId === null) renderTurnstile();
if (turnstileId !== null) return;
if (attempt < 50) setTimeout(() => ensureTurnstile(attempt + 1), 200);
}
function renderHcaptcha() {
if (!cfg.enabled || hcaptchaId !== null) return hcaptchaId;
if (!window.hcaptcha || typeof window.hcaptcha.render !== "function") return null;
if (recaptchaHost) recaptchaHost.hidden = true;
if (turnstileHost) turnstileHost.hidden = true;
if (hcaptchaHost) hcaptchaHost.hidden = false;
hcaptchaId = window.hcaptcha.render("hcaptchaWidget", {
sitekey: cfg.siteKey,
size: "normal",
theme: "dark",
callback: verifyCaptchaToken,
"expired-callback": () => { tokenInput.value = ""; },
"error-callback": () => { tokenInput.value = ""; },
});
if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null; }
resetStatus();
return hcaptchaId;
}
function ensureHcaptcha(attempt = 0) {
if (hcaptchaId === null) renderHcaptcha();
if (hcaptchaId !== null) return;
if (attempt < 50) setTimeout(() => ensureHcaptcha(attempt + 1), 200);
}
function ensureActiveCaptchaWidget() {
if (!cfg.enabled || modal?.dataset.challenge !== "1") return;
if (["cloudflare", "turnstile", "cf"].includes(cfg.provider)) return ensureTurnstile();
if (["hcaptcha", "h"].includes(cfg.provider)) return ensureHcaptcha();
return ensureRecaptcha();
}
function startCaptchaFlow() {
started = true;
// Drop any token from a previous solve so a stale green checkmark
// can never mask an unfinished challenge on a later attempt.
if (modal) {
modal.dataset.challenge = "1";
modal.setAttribute("aria-hidden", "false");
}
showModal();
resetCaptchaWidget();
resetStatus();
if (timeoutHandle) clearTimeout(timeoutHandle);
timeoutHandle = setTimeout(markTimeout, 30000);
ensureActiveCaptchaWidget();
}
if (form) {
form.addEventListener("submit", (e) => {
if (modal && modal.dataset.challenge === "1") {
e.preventDefault();
e.stopImmediatePropagation();
if (cfg.enabled && !tokenInput.value) startCaptchaFlow();
return false;
}
}, true);
}
if (cfg.challengeActive) {
disableForm();
if (cfg.enabled && !started) startCaptchaFlow();
} else if (cfg.enabled && cfg.required && !started) {
startCaptchaFlow();
}
window.initRecaptcha = ensureActiveCaptchaWidget;
window.initTurnstile = ensureActiveCaptchaWidget;
window.initHcaptcha = ensureActiveCaptchaWidget;
window.__adStartCaptchaFlow = startCaptchaFlow;
})();
</script>
<!-- Login Form Submission & Dynamic 2FA Controller -->
<script nonce="<%= cspNonce %>">
(() => {
const form = document.querySelector("form.login-form");
if (!form || !window.fetch) return;
const twoFactorField = document.getElementById("loginTwoFactorField");
const twoFactorInput = document.getElementById("loginTwoFactorCode");
const sepTwoFactor = document.getElementById("sepTwoFactor");
const csrfInput = form.querySelector('input[name="_csrf"]');
const submitBtn = form.querySelector('button[type="submit"]');
const toastHost = document.getElementById("toastHost");
const emailInput = document.getElementById("loginEmail");
const passwordInput = document.getElementById("loginPassword");
function showLoginToast(text, duration = 4200) {
if (!toastHost || !text) return;
const toast = document.createElement("div");
toast.className = "toast";
toast.innerHTML = '<div class="toast-inner"><div class="toast-msg"></div><div class="toast-bar"></div></div>';
toast.querySelector(".toast-msg").textContent = text;
toastHost.appendChild(toast);
requestAnimationFrame(() => toast.classList.add("toast-show"));
setTimeout(() => toast.classList.add("toast-hide"), Math.max(0, duration - 320));
setTimeout(() => toast.remove(), duration + 450);
}
// adpanel:login-two-step-ux — the 2FA row is INVISIBLE until the
// server has verified the email+password pair: a 401
// { requires2FA: true } answer (sent only after the password matched)
// is the only thing that flips this state on, so a response's shape
// can never disclose 2FA enrollment before authentication. The
// initial pass below re-derives the state from the server render so a
// server-rendered prompt page comes up revealed.
function setTwoFactorRequired(required) {
form.dataset.requiresTwoFactor = required ? "true" : "false";
document.body?.classList.toggle("login-has-2fa", !!required);
if (twoFactorField) {
twoFactorField.setAttribute("aria-hidden", required ? "false" : "true");
}
if (sepTwoFactor) {
sepTwoFactor.setAttribute("aria-hidden", required ? "false" : "true");
}
if (twoFactorInput) {
twoFactorInput.required = !!required;
twoFactorInput.disabled = !required;
if (!required) twoFactorInput.value = "";
}
}
setTwoFactorRequired(form.dataset.requiresTwoFactor === "true");
// Email the current password/2FA prompt belongs to; any edit away from it
// invalidates both, so reset the form state (purely client-side).
let lastEmailValue = (emailInput?.value || "").trim();
function resetForEmailChange() {
const currentEmail = (emailInput?.value || "").trim();
if (currentEmail === lastEmailValue) return;
lastEmailValue = currentEmail;
if (passwordInput) passwordInput.value = "";
if (form.dataset.requiresTwoFactor === "true") setTwoFactorRequired(false);
}
emailInput?.addEventListener("input", resetForEmailChange);
emailInput?.addEventListener("change", resetForEmailChange);
twoFactorInput?.addEventListener("input", () => {
twoFactorInput.value = twoFactorInput.value.replace(/\D/g, "").slice(0, 6);
});
form.addEventListener("submit", async (e) => {
if (e.defaultPrevented) return;
e.preventDefault();
if (submitBtn) submitBtn.disabled = true;
let keepSubmitDisabled = false;
lastEmailValue = (emailInput?.value || "").trim();
try {
const body = new URLSearchParams(new FormData(form));
const res = await fetch(form.action || "/login", {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"X-Requested-With": "XMLHttpRequest",
},
credentials: "same-origin",
body,
});
const data = await res.json().catch(() => ({}));
if (data.csrfToken && csrfInput) csrfInput.value = data.csrfToken;
const botProofInput = form.querySelector('input[name="botProof"]');
if (data.botProofSeed && botProofInput) botProofInput.value = data.botProofSeed;
if (data.requires2FA) {
setTwoFactorRequired(true);
showLoginToast(data.error || "Enter your 2FA code to continue.");
setTimeout(() => {
twoFactorInput?.focus();
if (data.error && twoFactorInput?.value) {
twoFactorInput.select();
}
}, 40);
return;
}
if (data.captchaRequired) {
keepSubmitDisabled = true;
if (data.useExternalCaptcha && typeof window.__adStartCaptchaFlow === "function") {
window.__adStartCaptchaFlow();
} else {
window.location.reload();
}
return;
}
if (res.ok && data.ok) {
window.location.href = data.redirect || "/";
return;
}
if (res.status === 403 && !data.error) {
window.location.reload();
return;
}
showLoginToast(data.error || "Invalid credentials");
} catch (err) {
showLoginToast("Network error. Try again.");
} finally {
if (submitBtn && !keepSubmitDisabled) submitBtn.disabled = false;
}
});
})();
</script>
<% if (loginExternalCaptchaAvailable) { %>
<% if (["cloudflare","turnstile","cf"].includes((externalCaptchaProvider || "" ).toLowerCase())) { %>
<script nonce="<%= cspNonce %>"
src="https://challenges.cloudflare.com/turnstile/v0/api.js?onload=initTurnstile&render=explicit" async
defer></script>
<% } else if (["hcaptcha","h"].includes((externalCaptchaProvider || "" ).toLowerCase())) { %>
<script nonce="<%= cspNonce %>"
src="https://js.hcaptcha.com/1/api.js?onload=initHcaptcha&render=explicit" async
defer></script>
<% } else { %>
<script nonce="<%= cspNonce %>"
src="https://www.google.com/recaptcha/api.js?onload=initRecaptcha&render=explicit" async
defer></script>
<% } %>
<% } %>
<script nonce="<%= cspNonce %>">
document.addEventListener("DOMContentLoaded", () => {
const videoEl = document.getElementById("bgVideo");
if (!videoEl) return;
const tryPlay = () => {
const p = videoEl.play();
if (p && typeof p.then === "function") {
p.catch(() => {});
}
};
videoEl.addEventListener(
"canplay",
() => {
tryPlay();
},
{ once: true }
);
const resumeOnUserGesture = () => {
tryPlay();
window.removeEventListener("click", resumeOnUserGesture);
window.removeEventListener("keydown", resumeOnUserGesture);
window.removeEventListener("touchstart", resumeOnUserGesture);
};
window.addEventListener("click", resumeOnUserGesture);
window.addEventListener("keydown", resumeOnUserGesture);
window.addEventListener("touchstart", resumeOnUserGesture);
});
</script>
<script nonce="<%= cspNonce %>">
(function () {
var challengeActive = <%- loginCaptchaChallengeActive ? "true" : "false" %>;
if (!challengeActive) return;
var modal = document.getElementById("captchaModal");
var form = document.querySelector("form");
if (!modal) return;
if (form) {
form.addEventListener("submit", function (e) {
if (modal.dataset.challenge === "1") {
e.preventDefault();
e.stopImmediatePropagation();
return false;
}
}, true);
}
var restoring = false;
var observer = new MutationObserver(function () {
if (restoring) return;
var m = document.getElementById("captchaModal");
if (!m) {
restoring = true;
window.location.reload();
return;
}
if (m.dataset.challenge === "0") return;
if (!m.classList.contains("show")) m.classList.add("show");
var st = m.getAttribute("style") || "";
if (st && (st.indexOf("display") !== -1 || st.indexOf("visibility") !== -1 || st.indexOf("opacity") !== -1)) {
m.removeAttribute("style");
}
});
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["class", "style", "hidden"],
});
var integrityInterval = setInterval(function () {
var m = document.getElementById("captchaModal");
if (!m) {
clearInterval(integrityInterval);
window.location.reload();
return;
}
if (m.dataset.challenge === "0") {
clearInterval(integrityInterval);
observer.disconnect();
return;
}
if (!m.classList.contains("show")) m.classList.add("show");
var cs = getComputedStyle(m);
if (cs.display === "none" || cs.visibility === "hidden" || parseFloat(cs.opacity) < 0.5) {
m.removeAttribute("style");
m.classList.add("show");
}
if (form && m.dataset.challenge === "1") {
form.classList.add("login-form--blocked");
}
}, 800);
try {
var origRemove = modal.remove;
Object.defineProperty(modal, "remove", {
value: function () {
if (modal.dataset.challenge === "1") return;
return origRemove.call(this);
},
writable: false,
configurable: false,
});
} catch (ex) { }
try {
var origSetAttr = modal.setAttribute.bind(modal);
modal.setAttribute = function (name, value) {
if (modal.dataset.challenge !== "1") return origSetAttr(name, value);
if (name === "style" && typeof value === "string" && (/display\s*:\s*none|visibility\s*:\s*hidden|opacity\s*:\s*0/i).test(value)) return;
if (name === "class" && typeof value === "string" && !value.includes("show")) return;
if (name === "hidden") return;
return origSetAttr(name, value);
};
} catch (ex) { }
modal.addEventListener("contextmenu", function (e) { e.preventDefault(); });
})();
</script>
<script nonce="<%= cspNonce %>">
(function () {
'use strict';
/* 1. Dynamic Greeting based on Client Browser Local Time */
function updateGreeting() {
const titleEl = document.getElementById('greetingTitle');
if (!titleEl) return;
const hour = new Date().getHours();
let greeting = 'Good Afternoon!';
if (hour >= 5 && hour < 12) {
greeting = 'Good Morning!';
} else if (hour >= 12 && hour < 18) {
greeting = 'Good Afternoon!';
} else {
greeting = 'Good Evening!';
}
titleEl.textContent = greeting;
}
updateGreeting();
/* 2. Did You Know Carousel Engine (Pure GPU CSS Keyframes 8s + 120Hz Smooth + Alt-Tab Sync) */
const facts = [
'ADPanel was first engineered to run on phones.',
'ADPanel was first launched in 2025.',
"ADPanel was built to innovate panels' design in 2025.",
'ADPanel is built to be secure down to every bit, based on current threat knowledge.'
];
let currentIndex = 0;
const textEl = document.getElementById('didYouKnowText');
const indicatorsContainer = document.getElementById('carouselIndicators');
function setSlideText(index) {
if (!textEl) return;
textEl.classList.add('fade-out');
setTimeout(() => {
textEl.textContent = facts[index];
textEl.classList.remove('fade-out');
}, 200);
}
function goToSlide(index) {
if (!indicatorsContainer) return;
currentIndex = index % facts.length;
const buttons = indicatorsContainer.querySelectorAll('.indicator-item');
buttons.forEach((btn) => {
btn.classList.remove('active');
const fill = btn.querySelector('.indicator-fill');
if (fill) {
fill.style.animation = 'none';
void fill.offsetWidth; /* Force reflow to reset CSS keyframe animation state */
fill.style.animation = '';
}
});
const activeBtn = buttons[currentIndex];
if (activeBtn) {
activeBtn.classList.add('active');
const activeFill = activeBtn.querySelector('.indicator-fill');
if (activeFill) {
const onEnd = () => {
activeFill.removeEventListener('animationend', onEnd);
goToSlide(currentIndex + 1);
};
activeFill.addEventListener('animationend', onEnd, { once: true });
}
}
setSlideText(currentIndex);
}
/* Seamless Alt-Tab / Tab Switch handling via animationPlayState */
document.addEventListener('visibilitychange', () => {
if (!indicatorsContainer) return;
const activeFill = indicatorsContainer.querySelector('.indicator-item.active .indicator-fill');
if (activeFill) {
activeFill.style.animationPlayState = document.hidden ? 'paused' : 'running';
}
});
if (indicatorsContainer) {
indicatorsContainer.addEventListener('click', (e) => {
const btn = e.target.closest('.indicator-item');
if (!btn) return;
const idx = parseInt(btn.getAttribute('data-index'), 10);
if (!isNaN(idx)) {
goToSlide(idx);
}
});
}
/* Start engine */
goToSlide(0);
})();
</script>
</body>
</html>