import os import secrets from pathlib import Path def get_token_path(): app_data = os.environ.get("JARVIS_APP_DATA_DIR", "data") return Path(app_data) / "auth.token" def get_or_create_master_token() -> str: """Single source of truth for the API auth token. Cloud (HF Space): JARVIS_CLOUD_TOKEN is injected as a Space secret — the container filesystem is ephemeral, so a generated file token would rotate on every restart and no client could ever pair with it. Local: falls back to a persisted random token on disk (localhost requests are additionally exempted by the middleware, so this only gates LAN clients). """ env_token = os.environ.get("JARVIS_CLOUD_TOKEN", "").strip() if env_token: return env_token path = get_token_path() if not path.parent.exists(): path.parent.mkdir(parents=True, exist_ok=True) if path.exists(): with open(path, "r") as f: return f.read().strip() # Generate a new secure token token = secrets.token_hex(32) with open(path, "w") as f: f.write(token) return token def verify_master_token(token: str) -> bool: """Verifies a given token against the master token.""" # Strip potential 'Bearer ' prefix if token.startswith("Bearer "): token = token[7:] return secrets.compare_digest(token, get_or_create_master_token())