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
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"