Visitor sign in kiosk: multi-site, badge printing, WWCC expiry warnings, admin accounts with 2FA

This commit is contained in:
2026-08-31 15:16:09 +10:00
parent 14678e13e8
commit a011587d66
9 changed files with 631 additions and 507 deletions
+2 -75
View File
@@ -4,87 +4,14 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin — visitor sign in</title> <title>Admin — visitor sign in</title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/css/admin.css"> <link rel="stylesheet" href="/css/admin.css">
</head> </head>
<body> <body>
<!-- ------------------------------------------------------------ login --> <!-- ------------------------------------------------------------ login -->
<div id="login" class="auth" hidden>
<div class="auth-card">
<header class="auth-head">
<button type="button" class="auth-back" id="auth-back" hidden aria-label="Go back">&#8592;</button>
<div class="auth-rail" id="auth-rail" hidden></div>
<h1 id="auth-title">Visitor admin</h1>
<p class="auth-sub" id="auth-subtitle"></p>
</header>
<div class="auth-body" id="auth-body">
<form class="auth-screen" id="step-password">
<label>
<span>Email address</span>
<input type="email" id="login-email" autocomplete="username" autocapitalize="none">
</label>
<label>
<span>Password</span>
<input type="password" id="login-password" autocomplete="current-password">
</label>
<p class="hint" id="domain-rule" hidden></p>
<button type="submit">Continue</button>
</form>
<form class="auth-screen" id="step-2fa" hidden>
<div id="twofa-setup" hidden>
<img id="twofa-qr" alt="Two factor setup QR code" width="180" height="180">
<details class="auth-details">
<summary>Can't scan it?</summary>
<p class="hint">Enter this key in your authenticator app by hand:</p>
<p><code id="twofa-secret"></code></p>
</details>
</div>
<label>
<span id="twofa-label">6 digit code</span>
<input id="twofa-code" inputmode="numeric" autocomplete="one-time-code" maxlength="12">
</label>
<button type="submit">Verify</button>
</form>
<div class="auth-screen" id="step-recovery" hidden>
<ul class="recovery" id="recovery-list"></ul>
<div class="auth-row">
<button type="button" class="secondary" id="recovery-copy">Copy codes</button>
<button type="button" id="recovery-done">I've saved them</button>
</div>
</div>
<form class="auth-screen" id="step-newpassword" hidden>
<label>
<span>Current password</span>
<input type="password" id="pw-current" autocomplete="current-password">
</label>
<label>
<span>New password</span>
<input type="password" id="pw-new" autocomplete="new-password">
</label>
<label>
<span>New password again</span>
<input type="password" id="pw-again" autocomplete="new-password">
</label>
<p class="hint">At least 12 characters, with upper and lower case and a number.</p>
<button type="submit">Save and continue</button>
</form>
<div class="auth-screen" id="step-setup" hidden>
<p class="hint" id="setup-message"></p>
</div>
</div>
<p class="err" id="login-error" hidden></p>
</div>
<p class="auth-foot">Created by: Jess Rogerson (yelling commands at Claude.AI)</p>
</div>
<!-- ---------------------------------------------------------- console --> <!-- ---------------------------------------------------------- console -->
<div id="console" hidden> <div id="console">
<header class="topbar"> <header class="topbar">
<strong id="site-name">Visitor admin</strong> <strong id="site-name">Visitor admin</strong>
<nav> <nav>
-160
View File
@@ -294,163 +294,3 @@ tr.row-bad td { background: #fdf0f2; }
word-break: break-all; word-break: break-all;
} }
#system-body h3 { margin-bottom: 14px; } #system-body h3 { margin-bottom: 14px; }
/* ============================================================ sign in ==
The sign in flow is a series of small pages, not one long form. Each screen
gets the same fixed-width card, its own title, and an animated height change
so moving between them reads as turning a page.
===================================================================== */
.auth {
display: grid;
place-items: center;
align-content: center;
min-height: 100vh;
padding: 24px 20px 40px;
}
.auth-card {
width: min(400px, 100%);
padding: 28px 30px 30px;
background: var(--card);
border-radius: 3px;
border-top: 5px solid var(--deep);
box-shadow: 0 12px 34px rgba(22, 32, 43, 0.1);
}
.auth-head { position: relative; margin-bottom: 22px; }
.auth-head h1 { font-size: 22px; margin: 0 0 6px; }
.auth-sub { margin: 0; color: var(--muted); font-size: 14px; line-height: 1.5; }
.auth-back {
position: absolute;
top: -4px;
right: 0;
width: 34px;
height: 34px;
border: 1px solid var(--rule);
border-radius: 3px;
background: transparent;
color: var(--muted);
font-size: 16px;
line-height: 1;
}
.auth-back:hover { background: var(--paper); color: var(--ink); }
/* Progress through the sequence, only shown when there is more than one page. */
.auth-rail {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 14px;
font-size: 12.5px;
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.auth-rail i {
display: block;
width: 22px;
height: 3px;
border-radius: 2px;
background: var(--rule);
}
.auth-rail i.done { background: var(--deep); }
.auth-rail span { margin-left: 5px; }
.auth-body {
overflow: hidden;
transition: height 220ms cubic-bezier(0.4, 0, 0.2, 1);
}
.auth-screen { display: block; }
.auth-screen.entering { animation: auth-in 240ms cubic-bezier(0.2, 0, 0.2, 1); }
@keyframes auth-in {
from { opacity: 0; transform: translateX(14px); }
to { opacity: 1; transform: none; }
}
@media (prefers-reduced-motion: reduce) {
.auth-body { transition: none; }
.auth-screen.entering { animation: none; }
}
.auth-screen label { display: block; }
.auth-screen label span {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 14px;
}
.auth-screen input {
width: 100%;
padding: 11px 12px;
border: 1px solid var(--rule);
border-radius: 3px;
margin-bottom: 16px;
background: #fff;
color: var(--ink);
}
.auth-screen button[type="submit"],
.auth-screen > button,
.auth-row button {
width: 100%;
padding: 12px;
border: 1px solid var(--deep);
border-radius: 3px;
background: var(--deep);
color: #fff;
font-weight: 600;
}
.auth-screen button[disabled] { opacity: 0.6; cursor: progress; }
.auth-screen .hint { margin: -4px 0 16px; font-size: 13.5px; }
.auth-row { display: flex; gap: 10px; }
.auth-row .secondary {
border-color: var(--rule);
background: transparent;
color: var(--ink);
font-weight: 400;
}
#twofa-qr {
display: block;
margin: 0 auto 14px;
border: 1px solid var(--rule);
border-radius: 3px;
}
#twofa-code {
letter-spacing: 0.32em;
text-align: center;
font-size: 22px;
font-variant-numeric: tabular-nums;
}
.auth-details { margin: 0 0 18px; font-size: 13.5px; }
.auth-details summary { cursor: pointer; color: var(--muted); }
.auth-details .hint { margin: 10px 0 6px; }
.auth-details code { word-break: break-all; display: inline-block; }
.recovery {
list-style: none;
margin: 0 0 16px;
padding: 14px;
border: 1px solid var(--rule);
border-radius: 3px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px 14px;
font-family: ui-monospace, Menlo, Consolas, monospace;
font-size: 14px;
}
.err {
margin: 18px 0 0;
padding: 11px 13px;
border-left: 4px solid var(--alert);
background: #fbeaed;
color: var(--ink);
font-size: 14px;
}
.auth-foot { margin: 20px 0 0; color: var(--muted); font-size: 12.5px; text-align: center; }
+199
View File
@@ -0,0 +1,199 @@
:root {
--paper: #e7ecf0;
--card: #ffffff;
--ink: #16202b;
--muted: #5d6b7a;
--rule: #d4dce3;
--deep: #0b4f4a;
--alert: #96162f;
}
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
background: var(--paper);
color: var(--ink);
font-family: "Segoe UI", system-ui, Roboto, "Helvetica Neue", Arial, sans-serif;
font-size: 15px;
line-height: 1.5;
display: grid;
place-items: center;
align-content: center;
padding: 24px 20px 40px;
}
button, input { font: inherit; }
button { cursor: pointer; }
:focus-visible { outline: 3px solid var(--deep); outline-offset: 2px; }
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0 0 0 0);
white-space: nowrap;
border: 0;
}
/* ---------------------------------------------------------------- card */
.auth-card {
width: min(400px, 100%);
padding: 26px 30px 30px;
background: var(--card);
border-radius: 3px;
border-top: 5px solid var(--deep);
box-shadow: 0 12px 34px rgba(22, 32, 43, 0.1);
}
.auth-head { position: relative; margin-bottom: 20px; }
.auth-site {
margin: 0 0 14px;
font-size: 12.5px;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--muted);
}
.auth-head h1 { font-size: 22px; font-weight: 620; letter-spacing: -0.015em; margin: 0 0 6px; }
.auth-sub { margin: 0; color: var(--muted); font-size: 14px; }
.auth-back {
position: absolute;
top: -2px;
right: 0;
width: 34px;
height: 34px;
border: 1px solid var(--rule);
border-radius: 3px;
background: transparent;
color: var(--muted);
font-size: 16px;
line-height: 1;
}
.auth-back:hover { background: var(--paper); color: var(--ink); }
.auth-rail {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 14px;
font-size: 12.5px;
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.auth-rail i { display: block; width: 22px; height: 3px; border-radius: 2px; background: var(--rule); }
.auth-rail i.done { background: var(--deep); }
.auth-rail span { margin-left: 5px; }
/* A floor under the body means most steps occupy the same box, so moving between
them swaps content rather than visibly growing the card. */
.auth-body { min-height: 232px; }
.auth-screen { display: block; }
.auth-screen.entering { animation: screen-in 200ms cubic-bezier(0.2, 0, 0.2, 1); }
@keyframes screen-in {
from { opacity: 0; transform: translateX(12px); }
to { opacity: 1; transform: none; }
}
@media (prefers-reduced-motion: reduce) {
.auth-screen.entering { animation: none; }
}
/* -------------------------------------------------------------- fields */
.auth-screen label { display: block; }
.auth-screen label span {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 14px;
}
.auth-screen input {
width: 100%;
padding: 11px 12px;
border: 1px solid var(--rule);
border-radius: 3px;
margin-bottom: 16px;
background: #fff;
color: var(--ink);
}
.auth-screen button[type="submit"],
.auth-screen > button,
.auth-row button {
width: 100%;
padding: 12px;
border: 1px solid var(--deep);
border-radius: 3px;
background: var(--deep);
color: #fff;
font-weight: 600;
}
.auth-screen button[disabled] { opacity: 0.6; cursor: progress; }
.auth-screen .hint { margin: -4px 0 16px; font-size: 13.5px; color: var(--muted); }
.auth-row { display: flex; gap: 10px; }
.auth-row .secondary {
border-color: var(--rule);
background: transparent;
color: var(--ink);
font-weight: 400;
}
#twofa-qr { display: block; margin: 0 auto 14px; border: 1px solid var(--rule); border-radius: 3px; }
#twofa-code {
letter-spacing: 0.32em;
text-align: center;
font-size: 22px;
font-variant-numeric: tabular-nums;
}
.auth-details { margin: 0 0 18px; font-size: 13.5px; }
.auth-details summary { cursor: pointer; color: var(--muted); }
.auth-details .hint { margin: 10px 0 6px; }
code {
font-family: ui-monospace, Menlo, Consolas, monospace;
font-size: 13px;
background: var(--paper);
padding: 2px 6px;
border-radius: 2px;
word-break: break-all;
}
.recovery {
list-style: none;
margin: 0 0 16px;
padding: 14px;
border: 1px solid var(--rule);
border-radius: 3px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px 14px;
font-family: ui-monospace, Menlo, Consolas, monospace;
font-size: 14px;
}
.err {
margin: 18px 0 0;
padding: 11px 13px;
border-left: 4px solid var(--alert);
background: #fbeaed;
font-size: 14px;
}
.auth-foot {
display: flex;
flex-direction: column;
gap: 6px;
align-items: center;
margin: 20px 0 0;
color: var(--muted);
font-size: 12.5px;
text-align: center;
}
.auth-foot a { color: var(--muted); text-decoration: underline; text-underline-offset: 3px; }
+8
View File
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="Visitor sign in">
<rect width="32" height="32" rx="5" fill="#0b4f4a"/>
<!-- a visitor badge: clip at the top, portrait below -->
<rect x="13" y="5" width="6" height="3" rx="1" fill="#8fd6c9"/>
<rect x="7" y="9" width="18" height="18" rx="2.5" fill="#ffffff"/>
<circle cx="16" cy="15.5" r="3.1" fill="#0b4f4a"/>
<path d="M10.4 24.2c0-3.1 2.5-5.2 5.6-5.2s5.6 2.1 5.6 5.2z" fill="#0b4f4a"/>
</svg>

After

Width:  |  Height:  |  Size: 490 B

+1
View File
@@ -5,6 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#0b4f4a"> <meta name="theme-color" content="#0b4f4a">
<title>Visitor sign in</title> <title>Visitor sign in</title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/css/kiosk.css"> <link rel="stylesheet" href="/css/kiosk.css">
</head> </head>
<body> <body>
+15 -270
View File
@@ -18,6 +18,10 @@ async function api(path, { method = 'GET', body } = {}) {
}); });
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
if (!res.ok) { if (!res.ok) {
// The session lapsed or was signed out in another tab.
if (res.status === 401 || data.mustChangePassword) {
toLogin();
}
const error = new Error(data.error || `Request failed (${res.status}).`); const error = new Error(data.error || `Request failed (${res.status}).`);
error.payload = data; error.payload = data;
error.status = res.status; error.status = res.status;
@@ -73,251 +77,17 @@ function field(label, name, value = '', type = 'text') {
<input name="${name}" type="${type}" value="${esc(value)}"></label>`; <input name="${name}" type="${type}" value="${esc(value)}"></label>`;
} }
function loginError(message) { /* ------------------------------------------------------------ session */
const el = $('#login-error'); // Signing in happens on /admin/login, a page of its own. If the session is gone
el.textContent = message; // or expires mid-use, go back there rather than trying to render a form here.
el.hidden = !message;
function toLogin() {
window.location.href = '/admin/login';
} }
/* --------------------------------------------------------- auth screens */
// The sign in flow is a sequence of small pages rather than one form that grows
// as it goes. Each screen carries its own title and instruction, the header shows
// where you are in the sequence, and the card animates between the two heights so
// a tall screen like the QR code reads as a new page, not a form unfolding.
const AUTH_SCREENS = {
'step-password': {
title: 'Sign in',
subtitle: 'Use the email address your account was set up with.',
focus: '#login-email',
},
'step-2fa-verify': {
screen: 'step-2fa',
title: 'Two factor',
subtitle: 'Enter the current code from your authenticator app.',
focus: '#twofa-code',
back: 'restart',
},
'step-2fa-setup': {
screen: 'step-2fa',
title: 'Set up two factor',
subtitle: 'Scan this with Google Authenticator, Authy, 1Password or similar, then enter the code it shows.',
focus: '#twofa-code',
back: 'restart',
},
'step-recovery': {
title: 'Recovery codes',
subtitle: 'Each of these works once, if you ever lose the phone with your authenticator on it. Save them somewhere safe now — they are not shown again.',
},
'step-newpassword': {
title: 'Choose a password',
subtitle: 'Set one only you know before you continue.',
focus: '#pw-current',
},
'step-setup': {
title: 'Not set up yet',
subtitle: 'No admin account exists on this server.',
},
};
// Which screens this particular sign in will pass through, so the header can say
// "2 of 3" honestly rather than guessing.
let authFlow = ['step-password'];
let authCurrent = 'step-password';
function setAuthFlow(steps) {
authFlow = steps;
}
function renderAuthRail(key) {
const rail = $('#auth-rail');
const index = authFlow.indexOf(key);
if (authFlow.length < 2 || index < 0) {
rail.hidden = true;
return;
}
rail.hidden = false;
rail.innerHTML =
authFlow.map((_, i) => `<i class="${i <= index ? 'done' : ''}"></i>`).join('') +
`<span>Step ${index + 1} of ${authFlow.length}</span>`;
}
function loginStep(key) {
const meta = AUTH_SCREENS[key] || AUTH_SCREENS['step-password'];
const targetId = meta.screen || key;
const body = $('#auth-body');
const previousHeight = body.offsetHeight;
authCurrent = key;
$('#auth-title').textContent = meta.title;
$('#auth-subtitle').textContent = meta.subtitle || '';
$('#auth-subtitle').hidden = !meta.subtitle;
$('#auth-back').hidden = !meta.back;
renderAuthRail(key);
loginError('');
$$('.auth-screen').forEach((el) => {
el.hidden = el.id !== targetId;
el.classList.remove('entering');
});
const entering = document.getElementById(targetId);
entering.classList.add('entering');
// Animate between the old and new heights so the card feels like it is turning
// a page instead of jumping.
const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (!reduce && previousHeight) {
const nextHeight = body.scrollHeight;
body.style.height = `${previousHeight}px`;
requestAnimationFrame(() => {
body.style.height = `${nextHeight}px`;
});
body.addEventListener(
'transitionend',
() => {
body.style.height = '';
},
{ once: true }
);
}
const focusTarget = meta.focus ? $(meta.focus) : entering.querySelector('input');
if (focusTarget) setTimeout(() => focusTarget.focus(), 60);
}
$('#auth-back').addEventListener('click', async () => {
if ((AUTH_SCREENS[authCurrent] || {}).back === 'restart') {
await api('/logout', { method: 'POST' }).catch(() => {});
$('#twofa-code').value = '';
$('#login-password').value = '';
setAuthFlow(['step-password']);
loginStep('step-password');
}
});
/* ---------------------------------------------------------- login flow */
$('#step-password').addEventListener('submit', async (event) => {
event.preventDefault();
loginError('');
const button = event.target.querySelector('button[type="submit"]');
button.disabled = true;
try {
const result = await api('/login', {
method: 'POST',
body: { email: $('#login-email').value, password: $('#login-password').value },
});
handleLoginResult(result);
} catch (err) {
loginError(err.message);
} finally {
button.disabled = false;
}
});
function handleLoginResult(result) {
if (result.status === 'twoFactorSetup') {
$('#twofa-setup').hidden = false;
$('#twofa-qr').src = result.qr;
$('#twofa-secret').textContent = result.secret;
$('#twofa-label').textContent = '6 digit code from the app';
// Enrolling always adds a recovery codes page, and the server tells us whether a
// password change follows. Declaring the whole path now means the step counter
// never changes its total halfway through.
setAuthFlow([
'step-password',
'step-2fa-setup',
'step-recovery',
...(result.passwordChangeToFollow ? ['step-newpassword'] : []),
]);
loginStep('step-2fa-setup');
return;
}
if (result.status === 'twoFactorRequired') {
$('#twofa-setup').hidden = true;
$('#twofa-label').textContent = '6 digit code, or a recovery code';
setAuthFlow([
'step-password',
'step-2fa-verify',
...(result.passwordChangeToFollow ? ['step-newpassword'] : []),
]);
loginStep('step-2fa-verify');
return;
}
if (result.recoveryCodes) {
recoveryCodes = result.recoveryCodes;
$('#recovery-list').innerHTML = recoveryCodes.map((c) => `<li>${esc(c)}</li>`).join('');
$('#recovery-done').dataset.next = result.status;
if (result.status === 'passwordChangeRequired' && !authFlow.includes('step-newpassword')) {
setAuthFlow([...authFlow, 'step-newpassword']);
}
loginStep('step-recovery');
return;
}
if (result.status === 'passwordChangeRequired') {
if (!authFlow.includes('step-newpassword')) setAuthFlow([...authFlow, 'step-newpassword']);
loginStep('step-newpassword');
return;
}
if (result.usedRecoveryCode) {
toast(`Recovery code used. ${result.recoveryCodesLeft} left — reset two factor soon.`);
}
boot();
}
$('#step-2fa').addEventListener('submit', async (event) => {
event.preventDefault();
loginError('');
const button = event.target.querySelector('button[type="submit"]');
button.disabled = true;
try {
const result = await api('/login/2fa', { method: 'POST', body: { code: $('#twofa-code').value } });
$('#twofa-code').value = '';
handleLoginResult(result);
} catch (err) {
loginError(err.message);
$('#twofa-code').select();
} finally {
button.disabled = false;
}
});
let recoveryCodes = [];
$('#recovery-copy').addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(recoveryCodes.join('\n'));
toast('Recovery codes copied.');
} catch {
toast('Copying was blocked. Write them down instead.', true);
}
});
$('#recovery-done').addEventListener('click', () => {
if ($('#recovery-done').dataset.next === 'passwordChangeRequired') loginStep('step-newpassword');
else boot();
});
$('#step-newpassword').addEventListener('submit', async (event) => {
event.preventDefault();
loginError('');
if ($('#pw-new').value !== $('#pw-again').value) return loginError('The two new passwords differ.');
try {
await api('/account/password', {
method: 'POST',
body: { currentPassword: $('#pw-current').value, newPassword: $('#pw-new').value },
});
toast('Password updated.');
boot();
} catch (err) {
loginError(err.message);
}
});
$('#logout').addEventListener('click', async () => { $('#logout').addEventListener('click', async () => {
await api('/logout', { method: 'POST' }); await api('/logout', { method: 'POST' }).catch(() => {});
location.reload(); toLogin();
}); });
/* ---------------------------------------------------------------- tabs */ /* ---------------------------------------------------------------- tabs */
@@ -1188,36 +958,11 @@ function renderAccount(status) {
async function boot() { async function boot() {
const session = await api('/session'); const session = await api('/session');
if (!session.admin) { // The server redirects an unauthenticated /admin to the login page, so reaching
$('#login').hidden = false; // here without a session means it lapsed between the page load and this call.
$('#console').hidden = true; if (!session.admin || session.mustChangePassword) return toLogin();
if (session.domainRule) {
$('#domain-rule').textContent = `Use your ${session.domainRule} address.`;
$('#domain-rule').hidden = false;
}
if (session.setupNeeded) {
$('#setup-message').textContent =
'No admin accounts exist yet. Set ADMIN_BOOTSTRAP_EMAIL and ADMIN_BOOTSTRAP_PASSWORD in the .env file and restart the container to create the first one.';
setAuthFlow(['step-setup']);
loginStep('step-setup');
} else {
setAuthFlow(['step-password']);
loginStep('step-password');
}
return;
}
if (session.mustChangePassword) {
$('#login').hidden = false;
$('#console').hidden = true;
if (!authFlow.includes('step-newpassword')) setAuthFlow([...authFlow, 'step-newpassword']);
loginStep('step-newpassword');
return;
}
me = { ...session.user, domainRule: session.domainRule }; me = { ...session.user, domainRule: session.domainRule };
$('#login').hidden = true;
$('#console').hidden = false;
$('#site-name').textContent = session.siteName; $('#site-name').textContent = session.siteName;
document.title = `Admin — ${session.siteName}`; document.title = `Admin — ${session.siteName}`;
$$('.owner-only').forEach((el) => { $$('.owner-only').forEach((el) => {
+282
View File
@@ -0,0 +1,282 @@
/* Visitor sign in — admin login page.
*
* A page of its own, not a panel hidden inside the console. When it finishes it
* navigates to /admin, so the console loads fresh with no login markup in it.
*/
const $ = (sel) => document.querySelector(sel);
const $$ = (sel) => Array.from(document.querySelectorAll(sel));
const esc = (v) =>
String(v ?? '').replace(/[&<>"']/g, (c) =>
({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]
);
async function api(path, { method = 'GET', body } = {}) {
const res = await fetch(`/admin/api${path}`, {
method,
headers: body ? { 'Content-Type': 'application/json' } : undefined,
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || `Request failed (${res.status}).`);
return data;
}
function showError(message) {
const el = $('#login-error');
el.textContent = message || '';
el.hidden = !message;
}
/* ------------------------------------------------------------- screens */
const SCREENS = {
'step-password': {
title: 'Sign in',
subtitle: 'Use the email address your account was set up with.',
focus: '#login-email',
},
'step-2fa-verify': {
node: 'step-2fa',
title: 'Two factor',
subtitle: 'Enter the current code from your authenticator app.',
focus: '#twofa-code',
back: true,
},
'step-2fa-setup': {
node: 'step-2fa',
title: 'Set up two factor',
subtitle:
'Scan this with Google Authenticator, Authy, 1Password or similar, then enter the code it shows.',
focus: '#twofa-code',
back: true,
},
'step-recovery': {
title: 'Recovery codes',
subtitle:
'Each works once, if you lose the phone with your authenticator on it. Save them now — they are not shown again.',
},
'step-newpassword': {
title: 'Choose a password',
subtitle: 'Set one only you know before you continue.',
focus: '#pw-current',
},
'step-setup': {
title: 'Not set up yet',
subtitle: 'No admin account exists on this server.',
},
};
let flow = ['step-password'];
let currentKey = 'step-password';
let recoveryCodes = [];
function setFlow(steps) {
flow = steps;
}
function renderRail(key) {
const rail = $('#auth-rail');
const index = flow.indexOf(key);
if (flow.length < 2 || index < 0) {
rail.hidden = true;
return;
}
rail.hidden = false;
rail.innerHTML =
flow.map((_, i) => `<i class="${i <= index ? 'done' : ''}"></i>`).join('') +
`<span>Step ${index + 1} of ${flow.length}</span>`;
}
function goto(key) {
const meta = SCREENS[key] || SCREENS['step-password'];
const nodeId = meta.node || key;
currentKey = key;
$('#auth-title').textContent = meta.title;
$('#auth-subtitle').textContent = meta.subtitle || '';
$('#auth-subtitle').hidden = !meta.subtitle;
$('#auth-back').hidden = !meta.back;
renderRail(key);
showError('');
$$('.auth-screen').forEach((el) => {
el.hidden = el.id !== nodeId;
el.classList.remove('entering');
});
const entering = document.getElementById(nodeId);
void entering.offsetWidth; // restart the animation if the same node is reused
entering.classList.add('entering');
const focusTarget = meta.focus ? $(meta.focus) : entering.querySelector('input');
if (focusTarget) setTimeout(() => focusTarget.focus(), 50);
}
$('#auth-back').addEventListener('click', async () => {
if (!SCREENS[currentKey]?.back) return;
await api('/logout', { method: 'POST' }).catch(() => {});
$('#twofa-code').value = '';
$('#login-password').value = '';
setFlow(['step-password']);
goto('step-password');
});
/* ---------------------------------------------------------- the journey */
function handle(result) {
if (result.status === 'twoFactorSetup') {
$('#twofa-setup').hidden = false;
$('#twofa-qr').src = result.qr;
$('#twofa-secret').textContent = result.secret;
$('#twofa-label').textContent = '6 digit code from the app';
// Declared in full now, so the step counter never changes its total midway.
setFlow([
'step-password',
'step-2fa-setup',
'step-recovery',
...(result.passwordChangeToFollow ? ['step-newpassword'] : []),
]);
goto('step-2fa-setup');
return;
}
if (result.status === 'twoFactorRequired') {
$('#twofa-setup').hidden = true;
$('#twofa-label').textContent = '6 digit code, or a recovery code';
setFlow([
'step-password',
'step-2fa-verify',
...(result.passwordChangeToFollow ? ['step-newpassword'] : []),
]);
goto('step-2fa-verify');
return;
}
if (result.recoveryCodes) {
recoveryCodes = result.recoveryCodes;
$('#recovery-list').innerHTML = recoveryCodes.map((c) => `<li>${esc(c)}</li>`).join('');
$('#recovery-done').dataset.next = result.status;
goto('step-recovery');
return;
}
if (result.status === 'passwordChangeRequired') {
if (!flow.includes('step-newpassword')) setFlow([...flow, 'step-newpassword']);
goto('step-newpassword');
return;
}
done();
}
/** Leaves the login page entirely; the console loads as a fresh document. */
function done() {
window.location.href = '/admin';
}
$('#step-password').addEventListener('submit', async (event) => {
event.preventDefault();
showError('');
const button = event.target.querySelector('button[type="submit"]');
button.disabled = true;
try {
const email = $('#login-email').value.trim();
$('#pw-username').value = email;
handle(await api('/login', { method: 'POST', body: { email, password: $('#login-password').value } }));
} catch (err) {
showError(err.message);
} finally {
button.disabled = false;
}
});
$('#step-2fa').addEventListener('submit', async (event) => {
event.preventDefault();
showError('');
const button = event.target.querySelector('button[type="submit"]');
button.disabled = true;
try {
const result = await api('/login/2fa', { method: 'POST', body: { code: $('#twofa-code').value } });
$('#twofa-code').value = '';
handle(result);
} catch (err) {
showError(err.message);
$('#twofa-code').select();
} finally {
button.disabled = false;
}
});
$('#recovery-copy').addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(recoveryCodes.join('\n'));
$('#recovery-copy').textContent = 'Copied';
setTimeout(() => {
$('#recovery-copy').textContent = 'Copy codes';
}, 2500);
} catch {
showError('Copying was blocked by the browser. Write the codes down instead.');
}
});
$('#recovery-done').addEventListener('click', () => {
if ($('#recovery-done').dataset.next === 'passwordChangeRequired') goto('step-newpassword');
else done();
});
$('#step-newpassword').addEventListener('submit', async (event) => {
event.preventDefault();
showError('');
if ($('#pw-new').value !== $('#pw-again').value) {
return showError('The two new passwords do not match.');
}
const button = event.target.querySelector('button[type="submit"]');
button.disabled = true;
try {
await api('/account/password', {
method: 'POST',
body: { currentPassword: $('#pw-current').value, newPassword: $('#pw-new').value },
});
done();
} catch (err) {
showError(err.message);
} finally {
button.disabled = false;
}
});
/* ---------------------------------------------------------------- start */
(async function init() {
try {
const session = await api('/session');
$('#auth-site').textContent = session.siteName || 'Visitor admin';
document.title = `Sign in — ${session.siteName || 'visitor admin'}`;
if (session.domainRule) {
$('#domain-rule').textContent = `Use your ${session.domainRule} address.`;
$('#domain-rule').hidden = false;
}
if (session.admin && session.mustChangePassword) {
$('#pw-username').value = session.user?.email || '';
setFlow(['step-newpassword']);
goto('step-newpassword');
return;
}
if (session.admin) return done();
if (session.setupNeeded) {
$('#setup-message').textContent =
'Set ADMIN_BOOTSTRAP_EMAIL and ADMIN_BOOTSTRAP_PASSWORD in the .env file and restart the container to create the first account.';
setFlow(['step-setup']);
goto('step-setup');
return;
}
} catch {
/* the server is unreachable; the sign in page still renders */
}
goto('step-password');
})();
+96
View File
@@ -0,0 +1,96 @@
<!doctype html>
<html lang="en-AU">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Sign in — visitor admin</title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/css/login.css">
</head>
<body class="auth">
<div class="auth-card">
<header class="auth-head">
<button type="button" class="auth-back" id="auth-back" hidden aria-label="Go back">&#8592;</button>
<p class="auth-site" id="auth-site">Visitor admin</p>
<div class="auth-rail" id="auth-rail" hidden></div>
<h1 id="auth-title">Sign in</h1>
<p class="auth-sub" id="auth-subtitle"></p>
</header>
<div class="auth-body" id="auth-body">
<form class="auth-screen" id="step-password">
<label>
<span>Email address</span>
<input type="email" id="login-email" name="email" autocomplete="username" autocapitalize="none" required>
</label>
<label>
<span>Password</span>
<input type="password" id="login-password" name="password" autocomplete="current-password" required>
</label>
<p class="hint" id="domain-rule" hidden></p>
<button type="submit">Continue</button>
</form>
<form class="auth-screen" id="step-2fa" hidden>
<div id="twofa-setup" hidden>
<img id="twofa-qr" alt="Two factor setup QR code" width="180" height="180">
<details class="auth-details">
<summary>Can't scan it?</summary>
<p class="hint">Type this key into your authenticator app instead:</p>
<p><code id="twofa-secret"></code></p>
</details>
</div>
<label>
<span id="twofa-label">6 digit code</span>
<input id="twofa-code" name="code" inputmode="numeric" autocomplete="one-time-code" maxlength="12" required>
</label>
<button type="submit">Verify</button>
</form>
<div class="auth-screen" id="step-recovery" hidden>
<ul class="recovery" id="recovery-list"></ul>
<div class="auth-row">
<button type="button" class="secondary" id="recovery-copy">Copy codes</button>
<button type="button" id="recovery-done">I've saved them</button>
</div>
</div>
<form class="auth-screen" id="step-newpassword" hidden>
<!-- Hidden but present: password managers and screen readers need to know
which account the new password belongs to. -->
<input type="text" id="pw-username" name="username" autocomplete="username"
tabindex="-1" aria-hidden="true" class="visually-hidden" readonly>
<label>
<span>Current password</span>
<input type="password" id="pw-current" name="current-password" autocomplete="current-password" required>
</label>
<label>
<span>New password</span>
<input type="password" id="pw-new" name="new-password" autocomplete="new-password" required>
</label>
<label>
<span>New password again</span>
<input type="password" id="pw-again" name="confirm-password" autocomplete="new-password" required>
</label>
<p class="hint">At least 12 characters, with upper and lower case and a number.</p>
<button type="submit">Save and continue</button>
</form>
<div class="auth-screen" id="step-setup" hidden>
<p class="hint" id="setup-message"></p>
</div>
</div>
<p class="err" id="login-error" role="alert" hidden></p>
</div>
<p class="auth-foot">
<a href="/">Back to the kiosk</a>
<span>Created by: Jess Rogerson (yelling commands at Claude.AI)</span>
</p>
<script src="/js/login.js"></script>
</body>
</html>
+28 -2
View File
@@ -46,8 +46,34 @@ app.get('/healthz', (req, res) => {
res.json({ ok: true, onSite: db.prepare('SELECT COUNT(*) AS n FROM visits WHERE signed_out_at IS NULL').get().n }); res.json({ ok: true, onSite: db.prepare('SELECT COUNT(*) AS n FROM visits WHERE signed_out_at IS NULL').get().n });
}); });
app.use(express.static(publicDir, { extensions: ['html'] })); /* ------------------------------------------------------------ admin pages */
app.get('/admin', (req, res) => res.sendFile(path.join(publicDir, 'admin.html'))); // The console and the sign in screen are separate documents, so these must be
// declared before express.static or it would serve them itself and skip the
// redirect that keeps an unauthenticated browser off the console.
function sessionUser(req) {
if (!req.session?.adminUserId) return null;
const user = users.findById(req.session.adminUserId);
return user && user.active ? user : null;
}
app.get('/admin', (req, res) => {
const user = sessionUser(req);
if (!user || user.must_change_password) return res.redirect('/admin/login');
res.sendFile(path.join(publicDir, 'admin.html'));
});
app.get('/admin/login', (req, res) => {
const user = sessionUser(req);
if (user && !user.must_change_password) return res.redirect('/admin');
res.sendFile(path.join(publicDir, 'login.html'));
});
// Nobody should land on the raw filenames; keep one address per page.
app.get(['/admin.html', '/login.html'], (req, res) => res.redirect('/admin'));
app.use(express.static(publicDir, { extensions: ['html'], index: false }));
app.get('/favicon.ico', (req, res) => res.redirect(301, '/favicon.svg'));
app.use((req, res) => res.status(404).sendFile(path.join(publicDir, 'index.html'))); app.use((req, res) => res.status(404).sendFile(path.join(publicDir, 'index.html')));
app.use((err, req, res, next) => { app.use((err, req, res, next) => {