SurfSense/surfsense_backend/app/services/turnstile_service.py
DESKTOP-RTLN3BA\$punk ff4e0f9b62
Some checks are pending
Build and Push Docker Images / tag_release (push) Waiting to run
Build and Push Docker Images / build (./surfsense_backend, ./surfsense_backend/Dockerfile, backend, surfsense-backend, ubuntu-24.04-arm, linux/arm64, arm64) (push) Blocked by required conditions
Build and Push Docker Images / build (./surfsense_backend, ./surfsense_backend/Dockerfile, backend, surfsense-backend, ubuntu-latest, linux/amd64, amd64) (push) Blocked by required conditions
Build and Push Docker Images / build (./surfsense_web, ./surfsense_web/Dockerfile, web, surfsense-web, ubuntu-24.04-arm, linux/arm64, arm64) (push) Blocked by required conditions
Build and Push Docker Images / build (./surfsense_web, ./surfsense_web/Dockerfile, web, surfsense-web, ubuntu-latest, linux/amd64, amd64) (push) Blocked by required conditions
Build and Push Docker Images / create_manifest (backend, surfsense-backend) (push) Blocked by required conditions
Build and Push Docker Images / create_manifest (web, surfsense-web) (push) Blocked by required conditions
feat: no login experience and prem tokens
2026-04-15 17:02:00 -07:00

52 lines
1.6 KiB
Python

"""Cloudflare Turnstile CAPTCHA verification service."""
from __future__ import annotations
import logging
import httpx
from app.config import config
logger = logging.getLogger(__name__)
TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
async def verify_turnstile_token(token: str, remote_ip: str | None = None) -> bool:
"""Verify a Turnstile response token with Cloudflare.
Returns True when the token is valid and the challenge was solved by a
real user. Returns False (never raises) on network errors or invalid
tokens so callers can treat it as a simple boolean gate.
"""
if not config.TURNSTILE_ENABLED:
return True
secret = config.TURNSTILE_SECRET_KEY
if not secret:
logger.warning("TURNSTILE_SECRET_KEY is not set; skipping verification")
return True
payload: dict[str, str] = {
"secret": secret,
"response": token,
}
if remote_ip:
payload["remoteip"] = remote_ip
try:
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.post(TURNSTILE_VERIFY_URL, data=payload)
resp.raise_for_status()
data = resp.json()
success = data.get("success", False)
if not success:
logger.info(
"Turnstile verification failed: %s",
data.get("error-codes", []),
)
return bool(success)
except Exception:
logger.exception("Turnstile verification request failed")
return False