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
+15 -270
View File
@@ -18,6 +18,10 @@ async function api(path, { method = 'GET', body } = {}) {
});
const data = await res.json().catch(() => ({}));
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}).`);
error.payload = data;
error.status = res.status;
@@ -73,251 +77,17 @@ function field(label, name, value = '', type = 'text') {
<input name="${name}" type="${type}" value="${esc(value)}"></label>`;
}
function loginError(message) {
const el = $('#login-error');
el.textContent = message;
el.hidden = !message;
/* ------------------------------------------------------------ session */
// Signing in happens on /admin/login, a page of its own. If the session is gone
// or expires mid-use, go back there rather than trying to render a form here.
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 () => {
await api('/logout', { method: 'POST' });
location.reload();
await api('/logout', { method: 'POST' }).catch(() => {});
toLogin();
});
/* ---------------------------------------------------------------- tabs */
@@ -1188,36 +958,11 @@ function renderAccount(status) {
async function boot() {
const session = await api('/session');
if (!session.admin) {
$('#login').hidden = false;
$('#console').hidden = true;
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;
}
// The server redirects an unauthenticated /admin to the login page, so reaching
// here without a session means it lapsed between the page load and this call.
if (!session.admin || session.mustChangePassword) return toLogin();
me = { ...session.user, domainRule: session.domainRule };
$('#login').hidden = true;
$('#console').hidden = false;
$('#site-name').textContent = session.siteName;
document.title = `Admin — ${session.siteName}`;
$$('.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');
})();