60 lines
1.7 KiB
Python
60 lines
1.7 KiB
Python
import base64
|
|
import hashlib
|
|
import hmac
|
|
import secrets
|
|
import time
|
|
|
|
ID_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789"
|
|
|
|
|
|
def now_ms() -> int:
|
|
return int(time.time() * 1000)
|
|
|
|
|
|
def new_id(n: int = 8) -> str:
|
|
return "".join(secrets.choice(ID_ALPHABET) for _ in range(n))
|
|
|
|
|
|
def new_key() -> str:
|
|
return secrets.token_urlsafe(24)
|
|
|
|
|
|
def sha(s: str) -> str:
|
|
return hashlib.sha256(s.encode()).hexdigest()
|
|
|
|
|
|
def check_key(given: str | None, stored_hash: str) -> bool:
|
|
if not given:
|
|
return False
|
|
return hmac.compare_digest(sha(given), stored_hash)
|
|
|
|
|
|
def current_slot(interval_ms: int, at_ms: int | None = None) -> int:
|
|
return (at_ms if at_ms is not None else now_ms()) // interval_ms
|
|
|
|
|
|
def _pass_mac(secret: bytes, poll_id: str, slot: int) -> str:
|
|
# 50 bits in qr alphanumeric charset (base32 upper), the code lives ~15 s and is checked online only
|
|
d = hmac.new(secret, f"pass:{poll_id}:{slot}".encode(), hashlib.sha256).digest()
|
|
return base64.b32encode(d[:7]).decode()[:10]
|
|
|
|
|
|
def make_pass(secret: bytes, poll_id: str, slot: int) -> str:
|
|
return f"{slot}-{_pass_mac(secret, poll_id, slot)}"
|
|
|
|
|
|
def verify_pass(secret: bytes, poll_id: str, token: str, rotate_ms: int, grace_ms: int) -> int | None:
|
|
"""camera app code from the entry qr: slot if authentic and shown less than rotate + grace ago"""
|
|
try:
|
|
slot_s, mac = token.upper().split("-", 1)
|
|
slot = int(slot_s)
|
|
# compare_digest raises on non ascii str
|
|
if not hmac.compare_digest(mac.encode(), _pass_mac(secret, poll_id, slot).encode()):
|
|
return None
|
|
except (ValueError, AttributeError):
|
|
return None
|
|
age = now_ms() - slot * rotate_ms
|
|
if age < 0 or age > rotate_ms + grace_ms:
|
|
return None
|
|
return slot
|