"""In-app password gate for the Face Swap + Extend Space. Gradio ``launch(auth=…)`` (HTTP basic / Login chrome) is unreliable on iPhone and behind the Hugging Face Spaces proxy — fields clear and never unlock. This module backs an **in-app** password Textbox + Unlock control instead. Env: ``SPACE_AUTH_PASSWORD`` (required). Aliases: ``GRADIO_PASSWORD``, ``AUTH_PASSWORD``. No username — mobile-friendly. """ from __future__ import annotations import hmac import os PASSWORD_ENV = "SPACE_AUTH_PASSWORD" PASSWORD_ALIASES = ("SPACE_AUTH_PASSWORD", "GRADIO_PASSWORD", "AUTH_PASSWORD") MISSING_PASSWORD_MESSAGE = ( f"Set Space secret `{PASSWORD_ENV}` (app unlock password), then Factory reboot. " "Gradio Login chrome is disabled; unlock is in-app only." ) WRONG_PASSWORD_MESSAGE = "Wrong password. Try again." LOCKED_MESSAGE = "Enter the Space password and tap **Unlock** before running Swap / Extend." def _first_env(*names: str, default: str = "") -> str: for name in names: value = (os.environ.get(name) or "").strip() if value: return value return default def auth_password() -> str: return _first_env(*PASSWORD_ALIASES, default="") def require_password_configured() -> None: """Fail closed before launch if the password secret is missing.""" if not auth_password(): raise RuntimeError(MISSING_PASSWORD_MESSAGE) def check_password(password: str | None) -> bool: """Constant-time compare against ``SPACE_AUTH_PASSWORD``.""" expected = auth_password() if not expected: return False got = (password or "").strip() return hmac.compare_digest(got, expected) def require_unlocked(state: dict | None) -> None: """Raise ``gr.Error`` if the session has not unlocked (blocks RunPod).""" import gradio as gr if not state or not state.get("unlocked"): raise gr.Error(LOCKED_MESSAGE) def auth_help_markdown() -> str: return ( "This Space is public, but **Unlock** with the owner password before " f"Swap / Extend (secret `{PASSWORD_ENV}`). The password box shows " "characters on purpose (iPhone-friendly). No Gradio Login page." )