feat(manager): v2 sign-in (login modes, support access, license notice) and an unlock endpoint for the lock screen

Platform-v2 step 2.6b:
- backend: POST /api/auth/unlock {pin|password} checks the CURRENT session's
  user and keeps the session (no new login/token); 5 wrong tries end it
  (auth.wrong_pin with attempts_left, then auth.session_ended); bootstrap
  gains `login` (manager_mode, autofill_username, support)
- manager LoginPage rewritten on @xenia/ui + i18n: client "manager", password
  or PIN pad per setting, remembered/only account card, support access panel
  (challenge -> code -> 4 h session, not remembered as an account), notice
  when the license runs the free tier (expired/inactive/locked/clock/unverified)
- lock screen on /api/auth/unlock with the shared PinPad
- @xenia/ui PinPad: variable length (minLength/maxLength, OK key, Enter)
- e2e manager.mjs: 33 checks (+ lockout after 5 wrong PINs, PIN login mode,
  support access with a wrong then right code)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 22:17:09 +02:00
co-authored by Claude Opus 5.5
parent df57fd1552
commit 49a412d748
22 changed files with 574 additions and 475 deletions
+1 -1
View File
@@ -171,7 +171,7 @@ Design tokens are CSS variables prefixed `--x-` (`packages/ui/src/tokens.css`),
New UI text goes into `packages/i18n/locales/en/<ns>.json` first, then `el` (same keys, same `{{placeholders}}`), and is shown with `t()` from `@xenia/i18n` (`useTranslation`, re-exported). Dates and times are shown only through `useFormat()` (`formatTime`, `formatDateTime`, `formatDate`, `formatRelative`), which use the venue zone from bootstrap; money with `formatMoney`, numbers with `formatNumber`; typed numbers are read with `parseNumber` (comma or dot). Business dates (`YYYY-MM-DD`) go to `formatDate` as they are. `npm test -w @xenia/i18n` runs `scripts/check-i18n.mjs`, which fails on keys missing in English, placeholder mismatches, and `toLocale…String()` / `new Intl.DateTimeFormat(` without `timeZone` in new code (`packages/*`, `terminal/`); it warns for missing Greek. The v1 apps' Greek strings convert in phases 4 and 6. The `@xenia/ui` components get their texts from `<UiLabelsProvider labels={useUiLabels()}>` at the app root.
**CS-18. Frontends talk to the backend through `@xenia/api` and read access from bootstrap** (branch `platform-v2`, D-7, D-10, §9).
An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. The app root is `<AccessProvider client token i18n>`: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand).
An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. Lock screens never log in again: they call `POST /api/auth/unlock {pin}` with the current session (same token; 5 wrong PINs end the session); manager sign-in sends `client: "manager"` and reads its mode from bootstrap `login`. The app root is `<AccessProvider client token i18n>`: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand).
**CS-15. Support access is a challenge code, never a password** (branch `platform-v2`, D-16).
There is no master account. A site's `SUPPORT_SECRET` (env only) comes from `tools/support_code.py --site-secret <SITE_ID>`, derived from the builder's master key in `%USERPROFILE%\.xenia\support_master_key.txt` (outside the repo, back it up). The derivation lives in `local_backend/core/support_codes.py` (stdlib only, the tool loads it by path) and is re-implemented for the e2e suites in `tests/e2e/lib/support.mjs`; `tests/test_support.py` pins a vector both must match. The e2e backends log in through support access (`login()` in `lib/proc.mjs`).
+1
View File
@@ -62,6 +62,7 @@ CODES: dict[str, tuple[int, str]] = {
"auth.username_required": (422, "Enter your username."),
"auth.client_not_allowed": (403, "This account can't use the {client} app."),
"auth.session_not_found": (404, "Session not found."),
"auth.wrong_pin": (401, "Wrong PIN. {attempts_left} tries left before you are signed out."),
"auth.support_not_configured": (503, "Support access isn't set up on this site."),
"auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."),
"auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."),
+14 -1
View File
@@ -1,7 +1,8 @@
"""Platform endpoints (APPS_PLATFORM §4.1, §7.2, §9): /api/platform/...
GET /bootstrap what every frontend loads first: venue (name, tz, language,
currency), the effective modules, and, if logged in, the user,
currency), the effective modules, the license state, the login
settings a login screen needs, and, if logged in, the user,
their language and permission keys. Works without login (login
screens need the venue language and zone).
GET /modules the full catalogue with each module's state (logged in).
@@ -75,6 +76,16 @@ def _module_out(m, enabled: dict, effective: frozenset) -> dict:
}
def _login_info(db: Session) -> dict:
from config import settings as cfg
from core import sessions
return {
"manager_mode": sessions.manager_login_mode(db), # password | pin
"autofill_username": _setting(db, "security.autofill_username", "true") == "true",
"support": bool(cfg.SUPPORT_SECRET and cfg.SITE_ID), # "Support access" is offered
}
@router.get("/bootstrap", dependencies=[Depends(public())])
def bootstrap(
request: Request,
@@ -98,6 +109,8 @@ def bootstrap(
},
"modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective],
"license": {"mode": entitlements.current().mode, "reason": entitlements.current().reason},
# what a login screen needs before anyone is signed in (plan step 2.6b)
"login": _login_info(db),
"languages": list(i18n.SUPPORTED_LANGUAGES),
"user": None,
"language": i18n.venue_language(),
+40
View File
@@ -3,6 +3,7 @@ from core.access.check import holds
from core.access.queries import holders_filter
import bcrypt
import logging
import threading
from typing import Optional
import jwt
@@ -143,6 +144,45 @@ def refresh(credentials: HTTPAuthorizationCredentials = Depends(bearer), db: Ses
return TokenResponse(access_token=make_token(user, payload["sid"]), user=UserOut.model_validate(user))
# ── Unlock (plan step 2.6b) ──────────────────────────────────────────────────
# The manager's lock screen (and later the apps' own) checks the PIN of the user who owns
# the CURRENT session, and keeps that session: no new login, no new token, so the
# single-session rules never see a second login. After UNLOCK_MAX_FAILURES wrong tries
# the session is ended (someone is guessing on an unattended screen).
UNLOCK_MAX_FAILURES = 5
_unlock_failures: dict[str, int] = {} # sid -> wrong tries since the last success
_unlock_lock = threading.Lock()
class UnlockRequest(_PydanticBase):
pin: Optional[str] = None
password: Optional[str] = None
@router.post("/unlock")
def unlock(body: UnlockRequest, request: Request, db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
"""POST {pin} (or {password}) with the session's own token. 200 {user} = unlocked.
Wrong: 401 auth.wrong_pin {attempts_left}; the last allowed miss ends the session
(401 auth.session_ended)."""
sid = getattr(request.state, "xenia_sid", None)
if _check_secret(user, body.pin, body.password, db):
with _unlock_lock:
_unlock_failures.pop(sid, None)
return {"user": UserOut.model_validate(user)}
with _unlock_lock:
failures = _unlock_failures.get(sid, 0) + 1
_unlock_failures[sid] = failures
if failures >= UNLOCK_MAX_FAILURES:
with _unlock_lock:
_unlock_failures.pop(sid, None)
sessions.end(db, sid, "unlock_failed")
_logger.warning("auth.unlock: too many wrong PINs, session ended user=%s", user.id)
raise XeniaError("auth.session_ended")
raise XeniaError("auth.wrong_pin", attempts_left=UNLOCK_MAX_FAILURES - failures)
@router.post("/logout", dependencies=[Depends(public())])
def logout(credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer),
token: Optional[str] = None, db: Session = Depends(get_db)):
+74
View File
@@ -0,0 +1,74 @@
"""Lock-screen unlock (plan step 2.6b): the session's own PIN, the same session kept,
too many wrong tries end the session; the login settings in bootstrap."""
from routers import auth as auth_router
TEST_PIN = "1234"
def err(r):
return r.json()["error"]["code"]
def test_right_pin_unlocks_and_keeps_the_session(client, make_user, login):
user = make_user("store_manager")
headers = login(user)
r = client.post("/api/auth/unlock", json={"pin": TEST_PIN}, headers=headers)
assert r.status_code == 200, r.text
assert r.json()["user"]["id"] == user.id
assert "access_token" not in r.json() # no new token, no new session
assert client.get("/api/auth/me", headers=headers).status_code == 200
def test_password_also_unlocks(client, make_user, login):
from tests.conftest import TEST_PASSWORD
headers = login(make_user("store_manager"))
assert client.post("/api/auth/unlock", json={"password": TEST_PASSWORD}, headers=headers).status_code == 200
def test_wrong_pin_counts_down_then_ends_the_session(client, make_user, login):
headers = login(make_user("store_manager"))
left = []
for _ in range(auth_router.UNLOCK_MAX_FAILURES - 1):
r = client.post("/api/auth/unlock", json={"pin": "0000"}, headers=headers)
assert r.status_code == 401 and err(r) == "auth.wrong_pin"
left.append(r.json()["error"]["params"]["attempts_left"])
assert left == list(range(auth_router.UNLOCK_MAX_FAILURES - 1, 0, -1))
assert client.get("/api/auth/me", headers=headers).status_code == 200, "still signed in before the last try"
r = client.post("/api/auth/unlock", json={"pin": "0000"}, headers=headers)
assert r.status_code == 401 and err(r) == "auth.session_ended"
assert err(client.get("/api/auth/me", headers=headers)) == "auth.session_ended"
def test_a_success_resets_the_count(client, make_user, login):
headers = login(make_user("store_manager"))
for _ in range(auth_router.UNLOCK_MAX_FAILURES - 1):
client.post("/api/auth/unlock", json={"pin": "0000"}, headers=headers)
assert client.post("/api/auth/unlock", json={"pin": TEST_PIN}, headers=headers).status_code == 200
r = client.post("/api/auth/unlock", json={"pin": "0000"}, headers=headers)
assert r.json()["error"]["params"]["attempts_left"] == auth_router.UNLOCK_MAX_FAILURES - 1
def test_the_pin_is_the_session_owners(client, make_user, login):
import bcrypt
other = make_user("store_manager", pin_hash=bcrypt.hashpw(b"5678", bcrypt.gensalt(4)).decode())
headers = login(other) # another user's PIN (1234) must not unlock it
assert err(client.post("/api/auth/unlock", json={"pin": TEST_PIN}, headers=headers)) == "auth.wrong_pin"
def test_needs_a_session(client):
assert client.post("/api/auth/unlock", json={"pin": TEST_PIN}).status_code in (401, 403)
def test_bootstrap_has_the_login_settings(client, db):
from models.settings import PosSettings
b = client.get("/api/platform/bootstrap").json()
assert b["login"]["manager_mode"] == "password"
assert b["login"]["autofill_username"] is True
assert b["login"]["support"] in (True, False)
row = db.query(PosSettings).filter(PosSettings.key == "auth.manager_login_mode").first()
if row is None:
db.add(PosSettings(key="auth.manager_login_mode", value="pin"))
else:
row.value = "pin"
db.commit()
assert client.get("/api/platform/bootstrap").json()["login"]["manager_mode"] == "pin"
+27 -90
View File
@@ -12,10 +12,11 @@ import PhoneListener from '../components/PhoneListener'
import { useTranslation } from '@xenia/i18n'
import { pageFor } from '../shell/nav'
import RouteGuard from '../shell/RouteGuard'
import { errorMessage, isError } from '@xenia/api'
import { PinPad } from '@xenia/ui'
export const LicenseContext = createContext(null)
const DIGITS = ['1','2','3','4','5','6','7','8','9','','0','⌫']
// ─── Page title / breadcrumb (from shell/nav.js) ─────────────────────────────
@@ -127,102 +128,38 @@ function LicenseBanner({ license }) {
// ─── Lock Screen ──────────────────────────────────────────────────────────────
function LockScreen({ username, displayName, onUnlock, onLogout }) {
const [pin, setPin] = useState('')
// The lock screen checks the PIN of the user who owns THIS session (POST /api/auth/unlock,
// plan step 2.6b): no new login, no new token. Five wrong tries end the session.
function LockScreen({ displayName, onUnlock, onLogout }) {
const { t } = useTranslation('manager')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
function pressDigit(d) {
if (loading) return
if (d === '⌫') { setPin(p => p.slice(0, -1)); setError(''); return }
if (d === '') return
if (pin.length >= 6) return
setPin(p => p + d)
}
async function submitPin(usedPin) {
if (usedPin.length < 4) return
setError('')
setLoading(true)
async function tryPin(pin) {
try {
// A wrong PIN is a 401: say "Wrong PIN" instead of the session-ended logout
const { data } = await client.post('/api/auth/login', { username, pin: usedPin }, { xenia: { ignoreUnauthorized: true } })
if (!data.user.perm_access_dashboard) {
setError('Not a manager account.')
setPin('')
return
}
onUnlock(data.user, data.access_token)
} catch {
setError('Wrong PIN')
setPin('')
} finally {
setLoading(false)
const { data } = await client.post('/api/auth/unlock', { pin }, { xenia: { ignoreUnauthorized: true } })
setError('')
onUnlock(data.user)
return true
} catch (err) {
if (isError(err, 'auth.session_ended')) { onLogout(); return true }
setError(errorMessage(err, t))
return false
}
}
useEffect(() => {
if (pin.length === 4) submitPin(pin)
}, [pin])
useEffect(() => {
function onKeyDown(e) {
if (loading) return
if (e.key >= '0' && e.key <= '9') pressDigit(e.key)
else if (e.key === 'Backspace') pressDigit('⌫')
}
window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onKeyDown)
}, [pin, loading])
return (
<div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/80 backdrop-blur-md">
<div className="bg-white rounded-2xl shadow-2xl p-8 w-full max-w-xs text-center space-y-5">
<div className="space-y-1">
<div className="flex justify-center">
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-slate-100">
<Lock className="h-6 w-6 text-slate-500" />
<div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/80 backdrop-blur-md" data-testid="lock-screen">
<div className="bg-surface rounded-dialog shadow-overlay p-8 w-full max-w-xs text-center grid gap-4">
<div className="grid gap-1 justify-items-center">
<div className="flex h-12 w-12 items-center justify-center rounded-card bg-surface-2">
<Lock className="h-6 w-6 text-ink-3" />
</div>
<p className="text-body-lg font-bold text-ink">{t('lock.title')}</p>
<p className="text-label text-ink-2">{displayName}</p>
</div>
<p className="text-[15px] font-bold text-slate-900">Locked</p>
<p className="text-[13px] text-slate-500">{displayName}</p>
</div>
<div className="space-y-3">
<div className="flex justify-center gap-3">
{Array.from({ length: 4 }).map((_, i) => (
<div key={i} className={`w-3.5 h-3.5 rounded-full border-2 transition-colors ${
i < pin.length ? 'bg-sky-500 border-sky-500' : 'border-slate-300'
}`} />
))}
</div>
<div className="grid grid-cols-3 gap-2">
{DIGITS.map((d, i) => (
<button
key={i}
type="button"
onClick={() => pressDigit(d)}
disabled={d === '' || loading}
className={`h-12 rounded-xl text-lg font-semibold transition-colors ${
d === '' ? 'invisible'
: d === '⌫' ? 'bg-slate-100 hover:bg-slate-200 text-slate-600'
: 'bg-slate-100 hover:bg-sky-100 active:bg-sky-200 text-slate-800'
} disabled:opacity-50`}
>
{d}
</button>
))}
</div>
</div>
{error && <p className="text-[12px] text-rose-500">{error}</p>}
{loading && <p className="text-[12px] text-slate-400">Verifying…</p>}
<button
onClick={onLogout}
className="text-[12px] text-slate-400 hover:text-slate-600 transition-colors"
>
Sign out instead
<PinPad minLength={4} maxLength={8} error={error || undefined} onComplete={tryPin} />
<button onClick={onLogout} className="text-label text-ink-3 hover:text-ink-2 transition-colors">
{t('lock.signOutInstead')}
</button>
</div>
</div>
@@ -289,8 +226,8 @@ export default function AppLayout() {
navigate('/login', { replace: true, state: { manualLogout: true } })
}
function handleUnlock(u, t) {
unlock(u, t)
function handleUnlock(u) {
unlock(u)
lastActivityRef.current = Date.now()
}
+199 -327
View File
@@ -1,363 +1,235 @@
import { useState, useEffect, useRef } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { User, Lock, KeyRound } from 'lucide-react'
// Manager sign-in on v2 rules (plan step 2.6b, APPS_PLATFORM D-8, D-16).
// - POST /api/auth/login {client: "manager", …}: the login mode comes from settings via the
// platform bootstrap (`login.manager_mode`: password | pin); managers are never let in by
// username only (D-8).
// - Support access: a challenge code read to Xenia support, their answer opens a 4-hour
// support session (D-16, CS-15). Offered when the site has a SUPPORT_SECRET.
// - The license state is shown before sign-in (the venue then runs the free tier).
import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { KeyRound, LifeBuoy, ArrowLeft, ShieldAlert } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useAccess } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Field, Input, PinPad, Spinner } from '@xenia/ui'
import useAuthStore from '../store/authStore'
import client from '../api/client'
import Button from '../ui/Button'
import { LabelledInput } from '../ui/Input'
const DIGITS = ['1','2','3','4','5','6','7','8','9','','0','⌫']
function PinDots({ length, filled }) {
return (
<div className="flex justify-center gap-3 py-2">
{Array.from({ length }).map((_, i) => (
<div key={i} className={`w-3.5 h-3.5 rounded-full border-2 transition-colors ${
i < filled ? 'bg-sky-500 border-sky-500' : 'border-slate-300'
}`} />
))}
</div>
)
}
function PinPad({ pin, onChange, disabled }) {
function press(d) {
if (disabled) return
if (d === '⌫') { onChange(p => p.slice(0, -1)); return }
if (d === '') return
if (pin.length >= 6) return
onChange(p => p + d)
}
return (
<div className="grid grid-cols-3 gap-3">
{DIGITS.map((d, i) => (
<button
key={i}
type="button"
onClick={() => press(d)}
disabled={d === '' || disabled}
className={`h-14 rounded-xl text-xl font-semibold transition-colors ${
d === ''
? 'invisible'
: d === '⌫'
? 'bg-slate-100 hover:bg-slate-200 text-slate-600'
: 'bg-slate-100 hover:bg-sky-100 active:bg-sky-200 text-slate-800'
} disabled:opacity-50`}
>
{d}
</button>
))}
</div>
)
}
// ─── Manager picker (multi-manager + login=none) ──────────────────────────────
function ManagerPicker({ managers, onSelect }) {
return (
<div className="space-y-3">
<div className="space-y-1">
<h1 className="text-xl font-bold text-slate-900">Select account</h1>
<p className="text-[13px] text-slate-500">Choose your manager account to continue.</p>
</div>
<div className="space-y-2">
{managers.map(m => (
<button
key={m.id}
onClick={() => onSelect(m)}
className="w-full flex items-center gap-3 rounded-xl border border-slate-200 bg-white p-4 text-left transition hover:border-sky-300 hover:bg-sky-50 active:bg-sky-100"
>
<div className="flex h-9 w-9 items-center justify-center rounded-full bg-sky-100 text-sky-700 font-semibold text-[13px] flex-shrink-0">
{(m.full_name || m.username).charAt(0).toUpperCase()}
</div>
<div>
<p className="text-[13px] font-semibold text-slate-800">{m.full_name || m.username}</p>
<p className="text-[12px] text-slate-400">{m.username}</p>
</div>
</button>
))}
</div>
</div>
)
}
// ─── Main login page ──────────────────────────────────────────────────────────
const LOGIN = { xenia: { ignoreUnauthorized: true } } // a wrong password is a 401: show it, don't "log out"
export default function LoginPage() {
const [settings, setSettings] = useState(null)
const [managers, setManagers] = useState([])
const [loadingInit, setLoadingInit] = useState(true)
const [selectedManager, setSelectedManager] = useState(null)
const [manualMode, setManualMode] = useState(false)
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [pin, setPin] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const { login } = useAuthStore()
const { t } = useTranslation('manager')
const { venue, login: loginInfo, license } = useAccess()
const login = useAuthStore(s => s.login)
const savedUsername = useAuthStore(s => s.savedUsername)
const navigate = useNavigate()
const location = useLocation()
const autoLoginAttempted = useRef(false)
// manualLogout comes either from nav state (logout button) or sessionStorage (auto-logout)
const manualLogout = location.state?.manualLogout === true
|| sessionStorage.getItem('pos_manual_logout') === 'true'
const [managers, setManagers] = useState(null) // null = still loading (decides the account card)
const [manual, setManual] = useState(false)
const [support, setSupport] = useState(false)
// Write to sessionStorage when nav state says manualLogout, clear it on successful login
useEffect(() => {
if (location.state?.manualLogout) {
sessionStorage.setItem('pos_manual_logout', 'true')
}
client.get('/api/auth/managers', LOGIN).then(r => setManagers(r.data)).catch(() => setManagers([]))
}, [])
// Load security config + manager list in parallel (both public, no auth needed)
useEffect(() => {
Promise.all([
client.get('/api/setup/security-config').catch(() => ({ data: { login_method: 'password', autofill_username: true } })),
client.get('/api/auth/managers').catch(() => ({ data: [] })),
]).then(([configRes, managersRes]) => {
setSettings(configRes.data)
setManagers(managersRes.data)
}).finally(() => setLoadingInit(false))
}, [])
// The account to sign in to without typing a username: the last one used on this browser,
// or the only manager there is (when the venue allows the autofill).
const single = loginInfo?.autofill_username && managers?.length === 1 ? managers[0].username : null
const account = manual ? null : (savedUsername || single)
const known = managers?.find(m => m.username === account)
const loginMethod = settings?.login_method ?? 'password'
const autofill = settings?.autofill_username !== false
const singleManager = managers.length === 1 ? managers[0] : null
// Suppressed in manual mode so the free-text input is shown instead
const effectiveUsername = manualMode ? null
: (selectedManager?.username || (autofill && singleManager ? singleManager.username : null))
// Auto-login: none method + single manager → attempt exactly once, skip if manual logout
useEffect(() => {
if (!loadingInit && loginMethod === 'none' && singleManager && !manualLogout && !autoLoginAttempted.current) {
autoLoginAttempted.current = true
handleAutoLogin(singleManager.username)
}
}, [loadingInit, loginMethod, singleManager])
function clearManualLogoutFlag() {
sessionStorage.removeItem('pos_manual_logout')
}
async function handleAutoLogin(uname) {
setLoading(true)
try {
const { data } = await client.post('/api/auth/login-no-auth', { username: uname }, { xenia: { ignoreUnauthorized: true } })
if (!data.user.perm_access_dashboard) { setLoading(false); return }
clearManualLogoutFlag()
login(data.user, data.access_token)
function signedIn(data, { remember = true } = {}) {
login(data.user, data.access_token, { remember })
navigate('/dashboard', { replace: true })
} catch {
setLoading(false)
}
}
async function handleSubmit(e) {
e?.preventDefault()
const uname = effectiveUsername || username.trim()
if (!uname) return
if (loginMethod === 'password' && !password) return
if (loginMethod === 'pin' && pin.length < 4) return
const notice = license?.mode === 'free' && license.reason ? t(`license.${license.reason}`, { defaultValue: '' }) : ''
setError('')
setLoading(true)
try {
const body = { username: uname }
if (loginMethod === 'password') body.password = password
else if (loginMethod === 'pin') body.pin = pin
// A wrong password is a 401: show it here instead of the session-ended logout
const { data } = await client.post('/api/auth/login', body, { xenia: { ignoreUnauthorized: true } })
if (!data.user.perm_access_dashboard) {
setError('This account does not have manager access.')
setPin('')
setPassword('')
return
}
clearManualLogoutFlag()
login(data.user, data.access_token)
navigate('/dashboard', { replace: true })
} catch (err) {
setError(err.response?.data?.detail || 'Invalid credentials')
setPin('')
setPassword('')
} finally {
setLoading(false)
}
}
// Auto-submit on 4-digit PIN entry
useEffect(() => {
if (loginMethod === 'pin' && pin.length === 4) handleSubmit()
}, [pin])
// Show spinner while loading OR while auto-login is in progress (none mode, not manual logout)
if (loadingInit || (loginMethod === 'none' && singleManager && !manualLogout && !manualMode)) {
return (
<div className="min-h-screen bg-slate-50 flex items-center justify-center">
<div className="w-6 h-6 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
<div className="min-h-screen bg-canvas flex items-center justify-center p-4">
<div className="w-full max-w-sm">
<div className="bg-surface rounded-dialog shadow-overlay border border-line p-8">
<div className="flex flex-col items-center text-center mb-6">
<div className="flex h-12 w-12 items-center justify-center rounded-card bg-accent text-accent-fg mb-3">
{support ? <LifeBuoy size={22} /> : <KeyRound size={22} />}
</div>
<h1 className="text-title font-semibold text-ink" data-testid="login-title">{support ? t('support.title') : t('login.title')}</h1>
<p className="text-body text-ink-2 mt-0.5">{venue?.name || t('login.subtitle')}</p>
</div>
{notice && (
<div className="flex gap-2 rounded-control bg-warning-soft text-warning-ink text-label p-3 mb-5" role="status" data-testid="license-notice">
<ShieldAlert size={16} className="shrink-0 mt-0.5" />
<span>{notice}</span>
</div>
)}
{managers === null && !support
? <div className="flex justify-center py-6"><Spinner /></div>
: support
? <SupportAccess onSignedIn={data => signedIn(data, { remember: false })} onBack={() => setSupport(false)} />
: (
<PasswordOrPin
mode={loginInfo?.manager_mode || 'password'}
account={account}
accountName={known?.full_name}
onOtherAccount={() => setManual(true)}
onSignedIn={signedIn}
/>
)}
</div>
{!support && loginInfo?.support && (
<div className="text-center mt-4">
<button type="button" className="text-label text-ink-3 hover:text-ink-2 underline-offset-2 hover:underline" onClick={() => setSupport(true)}>
{t('login.supportLink')}
</button>
</div>
)}
</div>
</div>
)
}
// Multi-manager + none method: show picker first
const needsPicker = loginMethod === 'none' && managers.length > 1 && !selectedManager
function PasswordOrPin({ mode, account, accountName, onOtherAccount, onSignedIn }) {
const { t } = useTranslation('manager')
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const user = account || username.trim()
async function send(secret) {
setError('')
try {
const { data } = await client.post('/api/auth/login', { client: 'manager', username: user, ...secret }, LOGIN)
onSignedIn(data)
return true
} catch (err) {
setError(errorMessage(err, t))
return false
}
}
async function submitPassword(e) {
e.preventDefault()
if (!user || !password || busy) return
setBusy(true)
const ok = await send({ password })
setBusy(false)
if (!ok) setPassword('')
}
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-sky-50 flex items-center justify-center p-4">
<div className="w-full max-w-sm">
<div className="bg-white rounded-2xl shadow-xl shadow-slate-200/60 border border-slate-100 p-8">
{needsPicker ? (
<ManagerPicker managers={managers} onSelect={m => { setSelectedManager(m); handleAutoLogin(m.username) }} />
) : (
<form onSubmit={handleSubmit} className="space-y-5">
<div className="text-center space-y-1">
<div className="flex justify-center mb-3">
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-sky-500">
<KeyRound className="h-6 w-6 text-white" />
<div className="grid gap-4" data-testid="login-form">
{account
? (
<div className="flex items-center gap-3 rounded-control border border-line bg-surface-2 px-4 py-3" data-testid="login-account">
<div className="flex h-9 w-9 items-center justify-center rounded-full bg-accent-soft text-accent-ink font-semibold text-label shrink-0">
{(accountName || account).slice(0, 1).toUpperCase()}
</div>
<div className="min-w-0 flex-1">
<div className="text-body font-medium text-ink truncate">{accountName || account}</div>
{accountName && <div className="text-caption text-ink-3 truncate">{account}</div>}
</div>
<h1 className="text-xl font-bold text-slate-900">Sign In</h1>
<p className="text-[13px] text-slate-500">
{loginMethod === 'password' ? 'Enter your username and password'
: loginMethod === 'pin' ? 'Enter your username and PIN'
: 'Select your account'}
</p>
</div>
{/* Username section */}
{manualMode ? (
<LabelledInput
icon={User}
placeholder="Username"
value={username}
onChange={e => setUsername(e.target.value)}
autoComplete="off"
autoFocus
/>
) : effectiveUsername ? (
<div className="space-y-1">
<div className="flex items-center gap-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-sky-100 text-sky-700 font-semibold text-[12px] flex-shrink-0">
{effectiveUsername.charAt(0).toUpperCase()}
</div>
<div>
<p className="text-[13px] font-medium text-slate-700">{effectiveUsername}</p>
<p className="text-[11px] text-slate-400">Manager</p>
</div>
</div>
<button
type="button"
onClick={() => { setManualMode(true); setSelectedManager(null); setUsername(''); setPassword(''); setPin(''); setError('') }}
className="text-[11px] text-slate-400 hover:text-sky-600 transition-colors w-full text-right pr-1"
>
Sign in as different account
<button type="button" className="text-label text-accent-ink hover:underline shrink-0" onClick={onOtherAccount}>
{t('login.otherAccount')}
</button>
</div>
) : managers.length > 0 ? (
<div className="space-y-2">
{managers.map(m => (
<button
key={m.id}
type="button"
onClick={() => setUsername(m.username)}
className={`w-full flex items-center gap-3 rounded-xl border p-3 text-left transition ${
username === m.username
? 'border-sky-400 bg-sky-50'
: 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'
}`}
>
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-sky-100 text-sky-700 font-semibold text-[12px] flex-shrink-0">
{(m.full_name || m.username).charAt(0).toUpperCase()}
</div>
<div>
<p className="text-[13px] font-medium text-slate-800">{m.full_name || m.username}</p>
<p className="text-[11px] text-slate-400">{m.username}</p>
</div>
</button>
))}
<button
type="button"
onClick={() => { setManualMode(true); setUsername(''); setPassword(''); setPin(''); setError('') }}
className="text-[11px] text-slate-400 hover:text-sky-600 transition-colors w-full text-right pr-1"
>
Sign in as different account
</button>
</div>
) : (
<LabelledInput
icon={User}
placeholder="Username"
value={username}
onChange={e => setUsername(e.target.value)}
autoComplete="off"
autoFocus
)
: (
<Field label={t('login.username')}>
<Input value={username} onChange={e => setUsername(e.target.value)} autoComplete="username" autoCapitalize="none" autoFocus />
</Field>
)}
{mode === 'pin'
? (
<div className={user ? '' : 'opacity-50 pointer-events-none'}>
<PinPad
minLength={4}
maxLength={8}
title={t('login.pin')}
error={error || undefined}
captureKeyboard={!!account}
onComplete={pin => send({ pin })}
/>
)}
{/* Password input */}
{loginMethod === 'password' && (
<LabelledInput
icon={Lock}
placeholder="Password"
value={password}
onChange={e => setPassword(e.target.value)}
type="password"
autoComplete="current-password"
autoFocus={!!effectiveUsername}
/>
)}
{/* PIN pad */}
{loginMethod === 'pin' && (
<div className="space-y-3">
<PinDots length={4} filled={pin.length} />
<PinPad pin={pin} onChange={setPin} disabled={loading} />
</div>
)}
{error && <p className="text-center text-[13px] text-rose-500">{error}</p>}
{/* None mode: just a Log In button */}
{loginMethod === 'none' && (
<Button
type="button"
variant="primary"
disabled={loading || (!effectiveUsername && !username.trim())}
className="w-full justify-center py-3"
onClick={() => handleAutoLogin(effectiveUsername || username.trim())}
>
{loading ? 'Signing in…' : 'Log In'}
</Button>
)}
{/* Password mode: submit button */}
{loginMethod === 'password' && (
<Button
type="submit"
variant="primary"
disabled={loading || (!effectiveUsername && !username.trim()) || !password}
className="w-full justify-center py-3"
>
{loading ? 'Signing in…' : 'Sign In'}
</Button>
)}
{/* PIN mode: auto-submits, show verifying text */}
{loading && loginMethod === 'pin' && (
<p className="text-center text-[13px] text-slate-400">Verifying…</p>
)}
)
: (
<form onSubmit={submitPassword} className="grid gap-4">
<Field label={t('login.password')} error={error || undefined}>
<Input type="password" value={password} onChange={e => setPassword(e.target.value)} autoComplete="current-password" autoFocus={!!account} />
</Field>
<Button type="submit" block loading={busy} disabled={!user || !password}>{t('login.signIn')}</Button>
</form>
)}
</div>
)
}
<p className="text-center text-[11px] text-slate-400 mt-4">Xenia POS · Manager Dashboard</p>
function SupportAccess({ onSignedIn, onBack }) {
const { t } = useTranslation('manager')
const f = useFormat()
const [challenge, setChallenge] = useState(null)
const [code, setCode] = useState('')
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const latest = useRef(0) // only the newest request may show its code (no stale challenge on screen)
async function newChallenge() {
const id = ++latest.current
setError('')
setCode('')
try {
const { data } = await client.post('/api/auth/support/challenge', null, LOGIN)
if (id === latest.current) setChallenge(data)
} catch (err) {
if (id !== latest.current) return
setChallenge(null)
setError(errorMessage(err, t))
}
}
useEffect(() => {
newChallenge()
return () => { latest.current++ } // unmounted (or React dev's double mount): ignore the answer
}, []) // eslint-disable-line react-hooks/exhaustive-deps
async function verify(e) {
e.preventDefault()
if (!challenge || !code.trim() || busy) return
setBusy(true)
setError('')
try {
const { data } = await client.post('/api/auth/support/verify', { challenge: challenge.challenge, code: code.trim() }, LOGIN)
onSignedIn(data)
} catch (err) {
setError(errorMessage(err, t))
} finally {
setBusy(false)
}
}
return (
<form onSubmit={verify} className="grid gap-4">
<p className="text-body text-ink-2 text-center">{t('support.intro')}</p>
{challenge && (
<div className="text-center">
<div className="text-caption text-ink-3 mb-1">{t('support.challenge')}</div>
<div className="font-mono text-display tracking-widest text-ink select-all" data-testid="support-challenge">{challenge.challenge}</div>
<div className="text-caption text-ink-3 mt-1">{t('support.expires', { time: f.formatTime(challenge.expires_at) })}</div>
</div>
)}
<Field label={t('support.answer')} error={error || undefined}>
<Input value={code} onChange={e => setCode(e.target.value)} autoCapitalize="characters" autoComplete="off" spellCheck={false} disabled={!challenge} />
</Field>
<Button type="submit" block loading={busy} disabled={!challenge || !code.trim()}>{t('support.verify')}</Button>
<div className="flex justify-between text-label">
<button type="button" className="inline-flex items-center gap-1 text-ink-3 hover:text-ink-2" onClick={onBack}>
<ArrowLeft size={14} /> {t('support.back')}
</button>
<button type="button" className="text-accent-ink hover:underline" onClick={newChallenge}>{t('support.newChallenge')}</button>
</div>
</form>
)
}
+7 -6
View File
@@ -6,11 +6,12 @@ const useAuthStore = create((set) => ({
savedUsername: localStorage.getItem('manager_username') || null,
locked: sessionStorage.getItem('manager_locked') === 'true',
login(user, token) {
// remember=false: don't offer this account on the next sign-in (support sessions)
login(user, token, { remember = true } = {}) {
localStorage.setItem('manager_token', token)
localStorage.setItem('manager_username', user.username)
if (remember) localStorage.setItem('manager_username', user.username)
sessionStorage.removeItem('manager_locked')
set({ user, token, savedUsername: user.username, locked: false })
set(s => ({ user, token, savedUsername: remember ? user.username : s.savedUsername, locked: false }))
},
// Restores user after a page refresh without touching the lock state.
@@ -31,10 +32,10 @@ const useAuthStore = create((set) => ({
set({ locked: true })
},
unlock(user, token) {
localStorage.setItem('manager_token', token)
// The same session continues (POST /api/auth/unlock): no new token
unlock(user) {
sessionStorage.removeItem('manager_locked')
set({ user, token, locked: false })
set({ user, locked: false })
},
updateUser(updatedUser) {
+1
View File
@@ -48,6 +48,7 @@ export function AccessProvider({
venue: d.venue,
user: d.user,
license: d.license,
login: d.login,
languages: d.languages,
language: d.language,
modules: new Set((d.modules || []).map(m => m.key)),
+2 -1
View File
@@ -31,7 +31,8 @@
"moreInfo": "Περισσότερες πληροφορίες",
"notifications": "Ειδοποιήσεις",
"backspace": "Διαγραφή",
"pinProgress": "{{count}} από {{total}} ψηφία"
"pinProgress": "{{count}} από {{total}} ψηφία",
"submit": "OK"
},
"override": {
"title": "Έγκριση υπευθύνου",
+2 -1
View File
@@ -35,7 +35,8 @@
"session_not_found": "Η σύνδεση δεν βρέθηκε.",
"support_not_configured": "Η πρόσβαση υποστήριξης δεν έχει ρυθμιστεί σε αυτό το κατάστημα.",
"support_code_invalid": "Ο κωδικός υποστήριξης είναι λάθος ή έχει λήξει. Ζητήστε νέο κωδικό πρόκλησης.",
"support_rate_limited": "Πολλές αιτήσεις υποστήριξης. Περιμένετε λίγα λεπτά και δοκιμάστε ξανά."
"support_rate_limited": "Πολλές αιτήσεις υποστήριξης. Περιμένετε λίγα λεπτά και δοκιμάστε ξανά.",
"wrong_pin": "Λάθος PIN. Απομένουν {{attempts_left}} προσπάθειες πριν αποσυνδεθείτε."
},
"device": {
"revoked": "Αυτή η συσκευή αφαιρέθηκε. Κάντε ξανά σύζευξη.",
+31
View File
@@ -46,5 +46,36 @@
"edit": "Επεξεργασία προφίλ",
"signOut": "Αποσύνδεση",
"language": "Γλώσσα"
},
"login": {
"title": "Σύνδεση",
"subtitle": "Πίνακας διαχείρισης",
"username": "Όνομα χρήστη",
"password": "Κωδικός",
"pin": "PIN",
"signIn": "Σύνδεση",
"otherAccount": "Άλλος λογαριασμός",
"supportLink": "Πρόσβαση υποστήριξης"
},
"support": {
"title": "Πρόσβαση υποστήριξης",
"intro": "Διαβάστε αυτόν τον κωδικό στην υποστήριξη της Xenia. Θα σας δώσουν έναν κωδικό πίσω.",
"challenge": "Κωδικός για την υποστήριξη",
"answer": "Κωδικός της υποστήριξης",
"verify": "Άνοιγμα συνεδρίας υποστήριξης",
"newChallenge": "Νέος κωδικός",
"back": "Πίσω στη σύνδεση",
"expires": "Ο κωδικός ισχύει μέχρι τις {{time}}."
},
"license": {
"expired": "Η άδεια έχει λήξει. Το κατάστημα λειτουργεί με τη δωρεάν έκδοση μέχρι την ανανέωση: κάποιες λειτουργίες είναι κλειστές.",
"inactive": "Η άδεια δεν είναι ενεργή. Το κατάστημα λειτουργεί με τη δωρεάν έκδοση: κάποιες λειτουργίες είναι κλειστές.",
"locked": "Ο πάροχος κλείδωσε την άδεια του καταστήματος. Λειτουργεί με τη δωρεάν έκδοση: κάποιες λειτουργίες είναι κλειστές.",
"clock": "Το ρολόι του server γύρισε πίσω, οπότε η άδεια δεν μπορεί να ελεγχθεί. Διορθώστε την ημερομηνία και ώρα του server ή συνδέστε τον στο internet.",
"unverified": "Η άδεια δεν έχει ελεγχθεί ακόμα (δεν υπάρχει σύνδεση με τον server αδειών). Προς το παρόν λειτουργεί η δωρεάν έκδοση."
},
"lock": {
"title": "Κλειδωμένο",
"signOutInstead": "Αποσύνδεση"
}
}
+2 -1
View File
@@ -31,7 +31,8 @@
"moreInfo": "More info",
"notifications": "Notifications",
"backspace": "Delete",
"pinProgress": "{{count}} of {{total}} digits entered"
"pinProgress": "{{count}} of {{total}} digits entered",
"submit": "OK"
},
"override": {
"title": "Manager approval",
+2 -1
View File
@@ -35,7 +35,8 @@
"session_not_found": "Session not found.",
"support_not_configured": "Support access isn't set up on this site.",
"support_code_invalid": "That support code is wrong or has expired. Ask for a new challenge.",
"support_rate_limited": "Too many support challenges. Wait a few minutes and try again."
"support_rate_limited": "Too many support challenges. Wait a few minutes and try again.",
"wrong_pin": "Wrong PIN. {{attempts_left}} tries left before you are signed out."
},
"device": {
"revoked": "This device was removed. Pair it again.",
+31
View File
@@ -46,5 +46,36 @@
"edit": "Edit profile",
"signOut": "Sign out",
"language": "Language"
},
"login": {
"title": "Sign in",
"subtitle": "Manager dashboard",
"username": "Username",
"password": "Password",
"pin": "PIN",
"signIn": "Sign in",
"otherAccount": "Use another account",
"supportLink": "Support access"
},
"support": {
"title": "Support access",
"intro": "Read this code to Xenia support. They will give you a code back.",
"challenge": "Code for support",
"answer": "Support's code",
"verify": "Open support session",
"newChallenge": "New code",
"back": "Back to sign in",
"expires": "This code is valid until {{time}}."
},
"license": {
"expired": "The license has expired. This venue runs the free version until it's renewed: some features are off.",
"inactive": "The license isn't active. This venue runs the free version: some features are off.",
"locked": "The license provider locked this venue. It runs the free version: some features are off.",
"clock": "The server's clock went back in time, so the license can't be trusted. Fix the server's date and time or connect it to the internet.",
"unverified": "The license hasn't been verified yet (no connection to the license server). This venue runs the free version for now."
},
"lock": {
"title": "Locked",
"signOutInstead": "Sign out instead"
}
}
+1
View File
@@ -34,6 +34,7 @@ export function useUiLabels() {
moreInfo: t('ui.moreInfo'),
notifications: t('ui.notifications'),
backspace: t('ui.backspace'),
submit: t('ui.submit'),
pinProgress: (count, total) => t('ui.pinProgress', { count, total }),
}), [t, language]) // eslint-disable-line react-hooks/exhaustive-deps
}
+2
View File
@@ -193,6 +193,8 @@
.x-pinpad__key:focus-visible { outline: none; box-shadow: var(--x-focus-ring); }
.x-pinpad__key:disabled { opacity: 0.5; cursor: not-allowed; }
.x-pinpad__key--backspace { background: transparent; color: var(--x-ink-2); }
.x-pinpad__key--submit { background: var(--x-accent); color: var(--x-accent-fg); }
.x-pinpad__key--submit:hover:not(:disabled) { background: var(--x-accent-strong); }
@keyframes x-shake {
20% { transform: translateX(-8px); } 40% { transform: translateX(7px); }
60% { transform: translateX(-5px); } 80% { transform: translateX(3px); }
+38 -17
View File
@@ -1,32 +1,40 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { cx } from '../internal/cx.js'
import { Spinner } from './Spinner.jsx'
import { nextPin, pinAction } from './pin.js'
import { canSubmit, nextPin, pinAction } from './pin.js'
import { useLabels } from './labels.js'
const KEYS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', null, '0', 'Backspace']
const KEYS_VARIABLE = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'Enter', '0', 'Backspace']
/**
* Numeric PIN entry: dots + a 3×4 keypad, also driven by the physical keyboard.
*
* <PinPad length={4} onComplete={async pin => { await unlock(pin) }} />
*
* onComplete(pin) runs when `length` digits are in. If it returns a promise the pad
* Fixed length (`length`, default 4): onComplete(pin) runs as soon as `length` digits are in.
* Variable length (`minLength` + `maxLength`, e.g. PINs of 4–8 digits): an OK key (and the
* Enter key) submits once at least `minLength` digits are in.
*
* If onComplete returns a promise the pad
* shows a spinner until it settles. If it throws / rejects (or returns false), the pad
* shakes, shows `error` text if given, and clears for another try. On success it clears too.
*
* error: text under the dots (e.g. "Wrong PIN"); a change of it also shakes the pad.
* captureKeyboard (default true): digits/Backspace typed anywhere go to the pad,
* except while the user is typing in a field.
* backspaceLabel / progressLabel(n, length) override the UiLabelsProvider texts.
* backspaceLabel / submitLabel / progressLabel(n, length) override the UiLabelsProvider texts.
*/
export function PinPad({
length = 4, onComplete, onChange, disabled = false, error, title,
captureKeyboard = true, backspaceLabel, progressLabel, className,
length = 4, minLength, maxLength, onComplete, onChange, disabled = false, error, title,
captureKeyboard = true, backspaceLabel, submitLabel, progressLabel, className,
}) {
const labels = useLabels()
const backspaceText = backspaceLabel ?? labels.backspace
const submitText = submitLabel ?? labels.submit
const progress = progressLabel ?? labels.pinProgress
const variable = minLength != null && maxLength != null
const max = variable ? maxLength : length
const [value, setValue] = useState('')
const [busy, setBusy] = useState(false)
const [shake, setShake] = useState(0)
@@ -61,12 +69,16 @@ export function PinPad({
const { value: current, busy: isBusy, disabled: isDisabled } = latest.current
const action = pinAction(key)
if (!action || isBusy || isDisabled) return
const next = nextPin(current, action, length)
if (action.type === 'submit') {
if (variable && canSubmit(current, minLength)) submit(current)
return
}
const next = nextPin(current, action, max)
if (next === current) return
setValue(next)
onChange?.(next)
if (next.length === length) submit(next)
}, [length, onChange, submit])
if (!variable && next.length === max) submit(next)
}, [variable, minLength, max, onChange, submit])
useEffect(() => {
if (!captureKeyboard) return
@@ -74,38 +86,47 @@ export function PinPad({
if (e.ctrlKey || e.metaKey || e.altKey) return
const t = e.target
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
if (pinAction(e.key)) { e.preventDefault(); press(e.key) }
const action = pinAction(e.key)
if (!action || (action.type === 'submit' && !variable)) return // Enter only means "OK" in variable mode
e.preventDefault()
press(e.key)
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [captureKeyboard, press])
}, [captureKeyboard, press, variable])
return (
<div className={cx('x-pinpad', disabled && 'x-pinpad--disabled', className)}>
{title && <div className="x-pinpad__title">{title}</div>}
{/* Re-keyed on every failed attempt and on every new error text, which replays the shake */}
<div key={`${shake}:${error || ''}`} className={cx('x-pinpad__dots', (shake > 0 || error) && 'x-pinpad__dots--shake')} aria-hidden="true">
{Array.from({ length }, (_, i) => (
{Array.from({ length: variable ? Math.max(minLength, value.length) : max }, (_, i) => (
<span key={i} className={cx('x-pinpad__dot', i < value.length && 'x-pinpad__dot--filled', error && 'x-pinpad__dot--error')} />
))}
</div>
<div className="x-visually-hidden" aria-live="polite">{progress(value.length, length)}</div>
<div className="x-visually-hidden" aria-live="polite">{progress(value.length, variable ? minLength : max)}</div>
<div className="x-pinpad__status">
{busy ? <Spinner size="sm" /> : error ? <span className="x-pinpad__error" role="alert">{error}</span> : null}
</div>
<div className="x-pinpad__keys">
{KEYS.map(k => k === null
{(variable ? KEYS_VARIABLE : KEYS).map(k => k === null
? <span key="blank" aria-hidden="true" />
: (
<button
key={k}
type="button"
className={cx('x-pinpad__key', k === 'Backspace' && 'x-pinpad__key--backspace')}
className={cx('x-pinpad__key', k === 'Backspace' && 'x-pinpad__key--backspace', k === 'Enter' && 'x-pinpad__key--submit')}
onClick={() => press(k)}
disabled={disabled || busy}
aria-label={k === 'Backspace' ? backspaceText : undefined}
disabled={disabled || busy || (k === 'Enter' && !canSubmit(value, minLength))}
aria-label={k === 'Backspace' ? backspaceText : k === 'Enter' ? submitText : undefined}
>
{k === 'Backspace'
{k === 'Enter'
? (
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M5 12.5l4.5 4.5L19 7.5" />
</svg>
)
: k === 'Backspace'
? (
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M21 5H9l-6 7 6 7h12a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1z" /><path d="M17 9l-6 6M11 9l6 6" />
+1
View File
@@ -12,6 +12,7 @@ export const DEFAULT_LABELS = {
moreInfo: 'More info',
notifications: 'Notifications',
backspace: 'Delete',
submit: 'OK',
pinProgress: (n, total) => `${n} of ${total} digits entered`,
}
+6
View File
@@ -4,9 +4,15 @@
export function pinAction(key) {
if (/^[0-9]$/.test(key)) return { type: 'digit', digit: key }
if (key === 'Backspace' || key === 'Delete') return { type: 'backspace' }
if (key === 'Enter') return { type: 'submit' }
return null
}
/** Variable-length mode: may this value be submitted? */
export function canSubmit(value, minLength) {
return value.length >= minLength
}
/**
* Next PIN value. Digits are ignored once `length` is reached; backspace on an
* empty PIN is a no-op; 'clear' empties it.
+11 -2
View File
@@ -1,12 +1,13 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { nextPin, pinAction } from '../src/components/pin.js'
import { canSubmit, nextPin, pinAction } from '../src/components/pin.js'
test('keys map to actions', () => {
assert.deepEqual(pinAction('7'), { type: 'digit', digit: '7' })
assert.deepEqual(pinAction('Enter'), { type: 'submit' })
assert.deepEqual(pinAction('Backspace'), { type: 'backspace' })
assert.deepEqual(pinAction('Delete'), { type: 'backspace' })
for (const k of ['a', 'Enter', 'Escape', ' ', '12', '']) assert.equal(pinAction(k), null, k)
for (const k of ['a', 'Escape', ' ', '12', '']) assert.equal(pinAction(k), null, k)
})
test('digits stop at the length', () => {
@@ -21,3 +22,11 @@ test('backspace and clear', () => {
assert.equal(nextPin('123', { type: 'clear' }, 4), '')
assert.equal(nextPin('12', null, 4), '12')
})
test('variable length: submit only from minLength, digits stop at maxLength', () => {
assert.equal(canSubmit('123', 4), false)
assert.equal(canSubmit('1234', 4), true)
let v = ''
for (const k of '1234567890') v = nextPin(v, pinAction(k), 8)
assert.equal(v, '12345678')
})
+69 -15
View File
@@ -11,6 +11,7 @@ import path from 'node:path'
import { chromium } from 'playwright'
import { BROWSER_CHANNEL, CS, OUT, reporter, sleep } from './lib/env.mjs'
import { killTree, startBackend, waitHttp } from './lib/proc.mjs'
import { SUPPORT_MASTER, codeFor, siteSecret } from './lib/support.mjs'
const PORT = 5186
const APP = `http://localhost:${PORT}`
@@ -38,14 +39,13 @@ const loginApi = (username, secret) => api('POST', '/api/auth/login', { body: {
async function uiLogin(page, password) {
await page.goto(`${APP}/login`)
await page.waitForFunction(() => document.body.innerText.includes('Sign In'), null, { timeout: 60_000 })
const other = page.getByText('Sign in as different account')
if (await other.count()) { await other.click(); await sleep(300) }
const user = page.locator('input:not([type=password])').first()
if (await user.count()) await user.fill('manager')
await page.locator('input[type=password]').fill(password)
await page.getByRole('button', { name: 'Sign In' }).click()
await page.getByTestId('login-form').waitFor({ timeout: 60_000 })
if (!(await page.getByTestId('login-account').count())) await page.getByLabel('Username').fill('manager')
await page.getByLabel('Password').fill(password)
await page.getByRole('button', { name: 'Sign in', exact: true }).click()
}
const typePin = async (page, pin) => { for (const d of pin) { await page.keyboard.type(d); await sleep(80) } await page.keyboard.press('Enter') }
const setSetting = (token, key, value) => api('PUT', `/api/settings/${key}`, { token, body: { value } })
try {
await waitHttp(`${APP}/`)
@@ -61,12 +61,13 @@ try {
await page.evaluate(() => { window.__noReload = true })
await sleep(1500)
r.check('bootstrap loaded before login (anonymous)', bootstraps[0] === 'anonymous', bootstraps.join(','))
await page.screenshot({ path: path.join(OUT, 'manager-login-wrong-password.png') })
r.check('wrong password: error shown, page not reloaded',
await page.getByText('Wrong username or password').count() > 0 && await page.evaluate(() => window.__noReload === true))
// ── Right password: dashboard, bootstrap again with the session ────────────
await page.locator('input[type=password]').fill('password')
await page.getByRole('button', { name: 'Sign In' }).click()
await page.getByLabel('Password').fill('password')
await page.getByRole('button', { name: 'Sign in', exact: true }).click()
await page.waitForURL(u => u.pathname === '/dashboard', { timeout: 15_000 }).catch(() => {})
await sleep(1500)
r.check('login → /dashboard', new URL(page.url()).pathname === '/dashboard', page.url())
@@ -112,13 +113,17 @@ try {
await sleep(1500)
await page.locator('header button').filter({ has: page.locator('svg.lucide-lock') }).first().click()
await sleep(600)
for (const d of '0000') { await page.keyboard.type(d); await sleep(120) }
const tokenBeforeLock = await page.evaluate(() => localStorage.getItem('manager_token'))
await typePin(page, '0000')
await sleep(1500)
r.check('lock: wrong PIN → "Wrong PIN", still signed in',
await page.getByText('Wrong PIN').count() > 0 && !!(await page.evaluate(() => localStorage.getItem('manager_token'))) && new URL(page.url()).pathname === '/dashboard')
for (const d of '1234') { await page.keyboard.type(d); await sleep(120) }
await page.screenshot({ path: path.join(OUT, 'manager-lock-wrong-pin.png') })
r.check('lock: wrong PIN → "Wrong PIN. 4 tries left…", still signed in',
await page.getByTestId('lock-screen').getByText('Wrong PIN. 4 tries left').count() === 1 && !!(await page.evaluate(() => localStorage.getItem('manager_token'))) && new URL(page.url()).pathname === '/dashboard')
await typePin(page, '1234')
await sleep(2000)
r.check('lock: right PIN unlocks', await page.getByText('Locked').count() === 0 && new URL(page.url()).pathname === '/dashboard')
r.check('lock: right PIN unlocks the SAME session (token unchanged)',
await page.getByTestId('lock-screen').count() === 0 && new URL(page.url()).pathname === '/dashboard'
&& await page.evaluate(() => localStorage.getItem('manager_token')) === tokenBeforeLock)
// ── A module turned off: /kds shows the "turned off" screen ────────────────
const mgr = await page.evaluate(() => localStorage.getItem('manager_token'))
@@ -131,10 +136,59 @@ try {
await sleep(2000)
r.check('kds on again → the KDS renders', await page.locator('.x-empty__title').count() === 0)
// ── 2.6b: five wrong PINs on the lock screen end the session ───────────────
await page.goto(`${APP}/dashboard`)
await sleep(1500)
await page.locator('header button').filter({ has: page.locator('svg.lucide-lock') }).first().click()
await sleep(500)
for (let i = 0; i < 5; i++) { await typePin(page, '0000'); await sleep(900) }
await page.waitForURL(u => u.pathname === '/login', { timeout: 10_000 }).catch(() => {})
const endedToken = mgr
r.check('lock: 5 wrong PINs → signed out', new URL(page.url()).pathname === '/login' && !(await page.evaluate(() => localStorage.getItem('manager_token'))), page.url())
r.check('…and that session is really over on the server', await api('GET', '/api/auth/me', { token: endedToken }).then(() => false, e => e.message.includes('401')))
// ── 2.6b: PIN login mode ───────────────────────────────────────────────────
const owner = await loginApi('manager', { password: 'password', client: 'manager' })
await setSetting(owner, 'auth.manager_login_mode', 'pin')
await page.goto(`${APP}/login`)
await page.getByTestId('login-form').waitFor()
if (!(await page.getByTestId('login-account').count())) await page.getByLabel('Username').fill('manager')
r.check('pin mode: the login shows a PIN pad, no password field', await page.locator('.x-pinpad').count() === 1 && await page.getByLabel('Password').count() === 0)
await page.locator('.x-pinpad').getByRole('button', { name: '1', exact: true }).click()
for (const d of '234') await page.locator('.x-pinpad').getByRole('button', { name: d, exact: true }).click()
await page.locator('.x-pinpad').getByRole('button', { name: 'OK' }).click()
await page.waitForURL(u => u.pathname === '/dashboard', { timeout: 10_000 }).catch(() => {})
r.check('pin mode: PIN → /dashboard', new URL(page.url()).pathname === '/dashboard', page.url())
await setSetting(owner, 'auth.manager_login_mode', 'password')
const mgr2 = await page.evaluate(() => localStorage.getItem('manager_token'))
await page.evaluate(() => { localStorage.removeItem('manager_token') })
await page.goto('about:blank') // leave first: the open page would redirect itself on the 401
await api('POST', '/api/auth/logout', { token: mgr2 })
// ── 2.6b: support access from the login screen ─────────────────────────────
await page.goto(`${APP}/login`)
await page.getByTestId('login-title').waitFor()
await page.getByRole('button', { name: 'Support access' }).click()
const challenge = (await page.getByTestId('support-challenge').textContent({ timeout: 10_000 })).trim()
await page.screenshot({ path: path.join(OUT, 'manager-support-access.png') })
r.check('support: a challenge code is shown', /^[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(challenge), challenge)
await page.getByLabel("Support's code").fill('WRONGCODE1')
await page.getByRole('button', { name: 'Open support session' }).click()
await sleep(1000)
r.check('support: a wrong code is refused with a message', await page.getByText('That support code is wrong').count() === 1)
await page.getByLabel("Support's code").fill(codeFor(siteSecret(SUPPORT_MASTER, 'test-site-1'), 'test-site-1', challenge))
await page.getByRole('button', { name: 'Open support session' }).click()
await page.waitForURL(u => u.pathname === '/dashboard', { timeout: 10_000 }).catch(() => {})
r.check('support: the right code opens a session', new URL(page.url()).pathname === '/dashboard', page.url())
await page.evaluate(() => { localStorage.removeItem('manager_token') })
await uiLogin(page, 'password')
await page.waitForURL(u => u.pathname === '/dashboard', { timeout: 10_000 }).catch(() => {})
const mgr3 = await page.evaluate(() => localStorage.getItem('manager_token'))
// ── Session ended elsewhere: the next request logs out ─────────────────────
await page.goto(`${APP}/dashboard`)
await sleep(1500)
await api('POST', '/api/auth/logout', { token: mgr })
await api('POST', '/api/auth/logout', { token: mgr3 })
await sidebar.getByText('Reports').first().click()
await sidebar.getByText('Today').first().click()
await page.waitForURL(u => u.pathname === '/login', { timeout: 10_000 }).catch(() => {})