File size: 2,923 Bytes
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//! Byparr sidecar client for Cloudflare Turnstile solving
//!
//! Byparr (modern successor to FlareSolverr) is a containerized FastAPI
//! server that runs a real browser engine (Camoufox) internally and
//! returns cookies + rendered HTML after passing Cloudflare challenges.
//!
//! This module talks to the Byparr sidecar when the crawler hits a
//! Cloudflare challenge it can't bypass with TLS tricks alone.

#![allow(dead_code)]

use anyhow::{Context, Result};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Response from Byparr's /v1 endpoint
#[derive(Debug, Deserialize)]
pub struct ByparrResponse {
    pub solution: ByparrSolution,
    pub status: String,
    pub message: String,
}

#[derive(Debug, Deserialize)]
pub struct ByparrSolution {
    pub url: String,
    pub status: u16,
    pub headers: Option<Vec<(String, String)>>,
    pub response: String,
    pub cookies: Option<Vec<Cookie>>,
    pub ua: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Cookie {
    pub name: String,
    pub value: String,
    pub domain: Option<String>,
    pub path: Option<String>,
}

/// Client for the Byparr/FlareSolverr sidecar
pub struct ByparrClient {
    base_url: String,
    http: Client,
}

impl ByparrClient {
    /// Create a new Byparr client pointing at the sidecar
    pub fn new(base_url: &str) -> Self {
        Self {
            base_url: base_url.trim_end_matches('/').to_string(),
            http: Client::builder()
                .timeout(Duration::from_secs(120))
                .build()
                .expect("Failed to build Byparr HTTP client"),
        }
    }

    /// Ask Byparr to fetch a URL, solving any Cloudflare challenge.
    /// Returns the rendered HTML + cookies on success.
    pub async fn fetch(&self, url: &str) -> Result<ByparrSolution> {
        let req = serde_json::json!({
            "cmd": "request.get",
            "url": url,
            "maxTimeout": 90000
        });

        let resp = self
            .http
            .post(format!("{}/v1", self.base_url))
            .json(&req)
            .send()
            .await
            .context("Failed to reach Byparr sidecar")?;

        let byparr: ByparrResponse = resp
            .json()
            .await
            .context("Failed to parse Byparr response")?;

        if byparr.status != "ok" {
            anyhow::bail!(
                "Byparr failed: {} (message: {})",
                byparr.status,
                byparr.message
            );
        }

        Ok(byparr.solution)
    }

    /// Check if the Byparr sidecar is reachable
    pub async fn health_check(&self) -> bool {
        match self.http.get(format!("{}/v1", self.base_url)).send().await {
            Ok(r) => r.status().is_success() || r.status() == 405, // 405 = method not allowed on GET (expected)
            Err(_) => false,
        }
    }
}