use std::sync::Arc;
use async_trait::async_trait;
use serde_json::Value;
use crate::config::DriverConfig;
use crate::contracts::CaptchaDriver;
use crate::provider_client::{ask_provider, check_hostname, interpret};
use crate::result::VerificationResult;
const ENDPOINT: &str = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
#[derive(Debug, Clone)]
pub struct TurnstileDriver {
config: DriverConfig,
expected_action: Option<String>,
}
impl TurnstileDriver {
pub fn new(config: DriverConfig) -> Self {
Self {
config,
expected_action: None,
}
}
}
#[async_trait]
impl CaptchaDriver for TurnstileDriver {
fn name(&self) -> &str {
"turnstile"
}
async fn verify(&self, token: &str, ip: Option<&str>) -> VerificationResult {
let Some(data) = ask_provider(ENDPOINT, &self.config.secret, token, ip).await else {
return VerificationResult::failure("unreachable");
};
let result = VerificationResult {
score: None,
..interpret(&data)
};
if result.success
&& let Some(expected) = &self.expected_action
&& data.get("action").and_then(Value::as_str) != Some(expected.as_str())
{
return result.refused("action-mismatch");
}
check_hostname(result, &data)
}
fn site_key(&self) -> String {
self.config.key.clone()
}
fn script_url(&self) -> String {
"https://challenges.cloudflare.com/turnstile/v0/api.js".to_owned()
}
fn response_field(&self) -> String {
"cf-turnstile-response".to_owned()
}
fn expecting_action(&self, action: Option<&str>) -> Option<Arc<dyn CaptchaDriver>> {
Some(Arc::new(Self {
config: self.config.clone(),
expected_action: action.map(str::to_owned),
}))
}
}