"""One-time codes from an authenticator app (TOTP, RFC 6238), for dashboard sign-in. `llmhost install-otp` makes a secret, shows it as a QR code to pair the app(s), and once a code checks out stores it in ~/.config/llm-host/otp_secret (0600). The dashboard then accepts a current code wherever it asks for the API key. Stdlib only. The parameters are the ones every authenticator app defaults to -- SHA-1, 6 digits, 30 seconds -- since some apps ignore anything else in the pairing link. """ import base64 import hashlib import hmac import secrets import struct import threading import time import urllib.parse from collections import deque STEP = 30 DIGITS = 6 WINDOW = 1 # accept the previous and next step too: clocks drift MAX_FAILURES = 5 # wrong codes allowed in FAIL_WINDOW before codes are refused FAIL_WINDOW = 300 ISSUER = "llm-host" def new_secret() -> str: return base64.b32encode(secrets.token_bytes(20)).decode().rstrip("=") def _key(secret_b32: str) -> bytes: s = secret_b32.strip().replace(" ", "").upper() return base64.b32decode(s + "=" * (-len(s) % 8)) def code_at(secret_b32: str, t: float, digits=DIGITS, step=STEP) -> str: counter = int(t // step) h = hmac.new(_key(secret_b32), struct.pack(">Q", counter), hashlib.sha1).digest() o = h[-1] & 0x0F n = (struct.unpack(">I", h[o:o + 4])[0] & 0x7FFFFFFF) % 10 ** digits return str(n).zfill(digits) def pairing_uri(secret_b32: str, account: str) -> str: label = urllib.parse.quote(f"{ISSUER}:{account}", safe=":@") q = urllib.parse.urlencode({"secret": secret_b32, "issuer": ISSUER, "algorithm": "SHA1", "digits": DIGITS, "period": STEP}) return f"otpauth://totp/{label}?{q}" def grouped(secret_b32: str) -> str: """The secret in groups of four, for typing into an app that can't scan.""" return " ".join(secret_b32[i:i + 4] for i in range(0, len(secret_b32), 4)) def matching_step(secret_b32: str, code: str, now=None): """The time step `code` belongs to (within the drift window), or None.""" code = "".join(ch for ch in str(code) if ch.isdigit()) if len(code) != DIGITS: return None now = time.time() if now is None else now base = int(now // STEP) for step in range(base - WINDOW, base + WINDOW + 1): if hmac.compare_digest(code_at(secret_b32, step * STEP), code): return step return None class Verifier: """Checks dashboard sign-in codes: each code works once, and after MAX_FAILURES wrong ones within FAIL_WINDOW, every code is refused until the window passes. The limit is global rather than per address because behind a tunnel every request comes from the same place; at worst a guesser locks codes out for a few minutes, and the API key still works.""" def __init__(self, secret_b32: str, clock=time.time): self.secret = secret_b32 self.clock = clock self.lock = threading.Lock() self.used_step = None self.failures = deque() def locked_for(self) -> int: now = self.clock() with self.lock: while self.failures and now - self.failures[0] > FAIL_WINDOW: self.failures.popleft() if len(self.failures) >= MAX_FAILURES: return int(FAIL_WINDOW - (now - self.failures[0])) + 1 return 0 def check(self, code: str) -> str: """"ok", "locked" or "wrong".""" if self.locked_for(): return "locked" now = self.clock() step = matching_step(self.secret, code, now) with self.lock: if step is not None and (self.used_step is None or step > self.used_step): self.used_step = step return "ok" self.failures.append(now) return "wrong"