"""Shared legacy device proof verification; v2 adds binding/version checks.""" import hashlib import re import time from fastapi import HTTPException from .crypto import canonical, verified, verify_device async def device_owner(settings, redis, store, host, proof, purpose, payload): device = store.device(host) if not device or device["revoked"] or not device["owner"]: raise HTTPException(403, "active bound device required") try: key = verify_device(device["cert"], settings.ca_cert.read_bytes(), host) data = verified(proof, key) if (data["host_id"] != host or data["purpose"] != purpose or abs(time.time() - data["ts"]) > 90 or not re.fullmatch(r"[a-f0-9]{32}", data["nonce"]) or data["payload_hash"] != hashlib.sha256(canonical(payload)).hexdigest()): raise ValueError() except Exception: raise HTTPException(403, "invalid device request proof") from None if not await redis.set("hn:work-proof:" + host + ":" + data["nonce"], "1", nx=True, ex=180): raise HTTPException(409, "device request replayed") return device["owner"]