File size: 2,191 Bytes
fa2be82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""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."
    )