videogen/apps/api/app/services/turnstile.py
caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

61 lines
2.3 KiB
Python

"""Cloudflare Turnstile server-side verification.
Guards a public, no-sign-in endpoint (today: the anonymous reel preview,
``app.domains.reel_preview``) against scripted abuse without adding a second
account/session system. Soft-gated by configuration: until an operator
creates a real Turnstile widget and sets ``TURNSTILE_SECRET_KEY`` (owner-only,
needs a Cloudflare dashboard token scoped ``Account.Turnstile:Edit`` that this
box's existing DNS-only API token does not carry), :func:`verify_turnstile`
is a no-op that allows the request through -- the caller-IP fixed-window
limiter (:mod:`app.services.ratelimit`) is the sole abuse control in that mode.
Once the secret is set, a missing/invalid/expired token is rejected (fail
closed): a configured-but-unverified Turnstile is worse than none at all,
since it would look protected while doing nothing.
"""
from __future__ import annotations
import os
import requests
from loguru import logger
SITEVERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
_TIMEOUT_S = 5.0
_SECRET_ENV = "TURNSTILE_SECRET_KEY"
def turnstile_configured() -> bool:
"""Whether an operator has set a real secret key yet."""
return bool(os.environ.get(_SECRET_ENV, "").strip())
def verify_turnstile(token: str, remote_ip: str = "") -> bool:
"""Verify a ``cf-turnstile-response`` token via Cloudflare's siteverify.
Returns ``True`` when Turnstile is not configured yet (soft mode -- see
module docstring). Once configured, returns ``True`` only for a token
Cloudflare confirms as a real pass; any missing token, network error,
timeout or non-success response is treated as a failure (fail closed).
"""
secret = os.environ.get(_SECRET_ENV, "").strip()
if not secret:
return True
token = (token or "").strip()
if not token or len(token) > 2048:
return False
try:
resp = requests.post(
SITEVERIFY_URL,
data={"secret": secret, "response": token, "remoteip": remote_ip or ""},
timeout=_TIMEOUT_S,
)
data = resp.json()
except Exception as exc: # noqa: BLE001 - any transport/parse failure fails closed
logger.warning(f"turnstile: siteverify call failed: {type(exc).__name__}: {exc}")
return False
return bool(data.get("success"))
__all__ = ["turnstile_configured", "verify_turnstile"]