"""Support access codes (APPS_PLATFORM D-16, plan step 1.10). Standard library only. Used by the backend (routers/auth.py) AND by the builder's tool tools/support_code.py, which loads this file by path, so keep it free of backend imports. master key (builder only, %USERPROFILE%\\.xenia\\support_master_key.txt) └─ site secret = HMAC-SHA256(master, "xenia-support-site:" + site_id) -> hex, in the site .env as SUPPORT_SECRET └─ code = base32(HMAC-SHA256(site secret, "xenia-support:" + site_id + ":" + challenge))[:10] The site shows a random 8-character challenge (stored server-side for 15 min, single use); the builder runs the tool with the site id and the challenge and reads back the code. Works offline at the site: nothing but the two HMACs is needed. A code made for another site never verifies (different secret, and the site id is in the message). The test suite and tests/e2e (JS) re-implement these two functions; tests/test_support.py pins a known vector so the implementations can't drift apart. """ from __future__ import annotations import base64 import hashlib import hmac import secrets CHALLENGE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # read aloud / typed: no 0/O, 1/I CHALLENGE_LEN = 8 CODE_LEN = 10 def site_secret(master_key: str, site_id: str) -> str: return hmac.new(master_key.strip().encode(), f"xenia-support-site:{site_id}".encode(), hashlib.sha256).hexdigest() def normalize_challenge(challenge: str) -> str: return "".join(ch for ch in challenge.upper() if ch.isalnum()) def normalize_code(code: str) -> str: # base32 (A-Z, 2-7): people read 0 as O, 1 as I and 8 as B s = "".join(ch for ch in code.upper() if ch.isalnum()) return s.translate(str.maketrans({"0": "O", "1": "I", "8": "B"})) def code_for(secret: str, site_id: str, challenge: str) -> str: msg = f"xenia-support:{site_id}:{normalize_challenge(challenge)}".encode() digest = hmac.new(secret.strip().encode(), msg, hashlib.sha256).digest() return base64.b32encode(digest).decode()[:CODE_LEN] def new_challenge() -> str: return "".join(secrets.choice(CHALLENGE_ALPHABET) for _ in range(CHALLENGE_LEN)) def group(s: str, size: int) -> str: """"ABCDEFGH" -> "ABCD-EFGH" (for display; input is normalized anyway).""" return "-".join(s[i:i + size] for i in range(0, len(s), size))