Skip to main content

eoka_protocol/sidecar/
params.rs

1use super::*;
2
3#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
4#[serde(deny_unknown_fields)]
5pub struct Empty {}
6
7dto!(LaunchParams {
8    #[serde(default = "default_headless")] headless: bool,
9    user_agent: Option<String>, timezone: Option<String>,
10    #[schemars(range(min = 1, max = 2147483647))] viewport_width: Option<u32>,
11    #[schemars(range(min = 1, max = 2147483647))] viewport_height: Option<u32>,
12    user_data_dir: Option<String>, proxy: Option<ProxyParams>,
13    executable_path: Option<String>, runtime_dir: Option<String>,
14    #[serde(default = "default_sandbox")] sandbox: bool,
15    #[serde(default)] aggressive_cdp_evasion: bool,
16    #[serde(default)] geo_align: bool,
17    #[serde(default)] extra_args: Vec<String>,
18    #[schemars(schema_with = "optional_positive_scale_schema")]
19    device_scale_factor: Option<f64>,
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    auto_solve_cloudflare: Option<CloudflareAutoSolve>,
22});
23dto!(ProxyParams { server: String, username: Option<String>, password: Option<String> });
24fn default_headless() -> bool {
25    true
26}
27
28fn default_sandbox() -> bool {
29    true
30}
31
32pub(super) fn positive_scale_schema(_: &mut SchemaGenerator) -> Schema {
33    json!({"type":"number","exclusiveMinimum":0})
34        .try_into()
35        .unwrap()
36}
37
38fn optional_positive_scale_schema(_: &mut SchemaGenerator) -> Schema {
39    json!({"type":["number","null"],"exclusiveMinimum":0})
40        .try_into()
41        .unwrap()
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
45#[serde(rename_all = "camelCase", deny_unknown_fields)]
46pub struct ConnectParams {
47    pub ws_endpoint: String,
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub auto_solve_cloudflare: Option<CloudflareAutoSolve>,
50}
51
52impl ConnectParams {
53    pub fn validate(&self) -> Result<(), ServerError> {
54        self.auto_solve_cloudflare
55            .as_ref()
56            .map_or(Ok(()), CloudflareAutoSolve::validate)
57    }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
61#[serde(rename_all = "lowercase")]
62pub enum BrowserOwnership {
63    Owned,
64    Borrowed,
65}
66
67dto!(BrowserSessionResult {
68    ownership: BrowserOwnership,
69    browser_version: String,
70});
71pub fn validate_viewport(width: u32, height: u32, scale: f64) -> Result<(), ServerError> {
72    if width == 0 || height == 0 || width > i32::MAX as u32 || height > i32::MAX as u32 {
73        return Err(ServerError::invalid_params(
74            "viewport dimensions must be positive and no greater than 2147483647",
75        ));
76    }
77    if !scale.is_finite() || scale <= 0.0 {
78        return Err(ServerError::invalid_params(
79            "deviceScaleFactor must be finite and positive",
80        ));
81    }
82    Ok(())
83}
84
85impl LaunchParams {
86    pub fn validate(&self) -> Result<(), ServerError> {
87        if self.viewport_width.is_some() != self.viewport_height.is_some() {
88            return Err(ServerError::invalid_params(
89                "viewportWidth and viewportHeight must be provided together",
90            ));
91        }
92        validate_viewport(
93            self.viewport_width.unwrap_or(1),
94            self.viewport_height.unwrap_or(1),
95            self.device_scale_factor.unwrap_or(1.0),
96        )?;
97        for (name, path) in [
98            ("userDataDir", self.user_data_dir.as_deref()),
99            ("executablePath", self.executable_path.as_deref()),
100            ("runtimeDir", self.runtime_dir.as_deref()),
101        ] {
102            if path.is_some_and(|path| !std::path::Path::new(path).is_absolute()) {
103                return Err(ServerError::invalid_params(format!(
104                    "{name} must be an absolute path",
105                )));
106            }
107        }
108        if let Some(auto_solve) = &self.auto_solve_cloudflare {
109            auto_solve.validate()?;
110        }
111        Ok(())
112    }
113}
114dto!(NewPageParams { url: Option<String> });
115
116dto!(PageIdParams { page_id: String });
117dto!(CloudflareAutoSolve {
118    #[serde(default = "default_cloudflare_interval_ms")]
119    #[schemars(range(min = 100, max = 60000))]
120    interval_ms: u64,
121    #[serde(default = "default_turnstile_timeout_ms")]
122    #[schemars(range(min = 1, max = 120000))]
123    timeout_ms: u64,
124});
125impl CloudflareAutoSolve {
126    pub fn validate(&self) -> Result<(), ServerError> {
127        if !(100..=60_000).contains(&self.interval_ms) {
128            return Err(ServerError::invalid_params(
129                "autoSolveCloudflare.intervalMs must be between 100 and 60000",
130            ));
131        }
132        validate_turnstile_timeout(self.timeout_ms)
133    }
134}
135fn validate_turnstile_timeout(timeout_ms: u64) -> Result<(), ServerError> {
136    if timeout_ms == 0 || timeout_ms > 120_000 {
137        return Err(ServerError::invalid_params(
138            "timeoutMs must be between 1 and 120000",
139        ));
140    }
141    Ok(())
142}
143fn default_turnstile_timeout_ms() -> u64 {
144    30_000
145}
146fn default_cloudflare_interval_ms() -> u64 {
147    500
148}
149dto!(RestoreStateParams {
150    page_id: String,
151    state: BrowserState
152});
153dto!(SolveCaptchaParams {
154    page_id: String, api_key: String,
155    #[schemars(regex(pattern = "^recaptcha_v2_enterprise$"))] captcha_type: String,
156    #[schemars(regex(pattern = "^anti_captcha_proxyless$"))] captcha_mode: String,
157    #[serde(rename = "websiteURL")] website_url: String,
158    website_key: String,
159    #[serde(default)] enterprise_payload: Option<Value>,
160    #[serde(default)] api_domain: Option<String>,
161    #[serde(default)] callback: Option<String>,
162});
163
164#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
165pub struct SessionCookie {
166    pub name: String,
167    pub value: String,
168    pub domain: String,
169    pub path: String,
170    pub secure: bool,
171    pub http_only: bool,
172    pub same_site: Option<String>,
173    pub expires: Option<f64>,
174}
175dto!(BrowserState {
176    cookies: Vec<SessionCookie>,
177    #[serde(default)] local_storage: HashMap<String, String>,
178    #[serde(default)] session_storage: HashMap<String, String>,
179    user_agent: String, url: String,
180});
181
182impl From<eoka::BrowserState> for BrowserState {
183    fn from(state: eoka::BrowserState) -> Self {
184        Self {
185            cookies: state
186                .cookies
187                .into_iter()
188                .map(|cookie| SessionCookie {
189                    name: cookie.name,
190                    value: cookie.value,
191                    domain: cookie.domain,
192                    path: cookie.path,
193                    secure: cookie.secure,
194                    http_only: cookie.http_only,
195                    same_site: cookie.same_site,
196                    expires: cookie.expires,
197                })
198                .collect(),
199            local_storage: state.local_storage,
200            session_storage: state.session_storage,
201            user_agent: state.user_agent,
202            url: state.url,
203        }
204    }
205}
206impl From<BrowserState> for eoka::BrowserState {
207    fn from(state: BrowserState) -> Self {
208        Self {
209            cookies: state
210                .cookies
211                .into_iter()
212                .map(|cookie| eoka::SessionCookie {
213                    name: cookie.name,
214                    value: cookie.value,
215                    domain: cookie.domain,
216                    path: cookie.path,
217                    secure: cookie.secure,
218                    http_only: cookie.http_only,
219                    same_site: cookie.same_site,
220                    expires: cookie.expires,
221                })
222                .collect(),
223            local_storage: state.local_storage,
224            session_storage: state.session_storage,
225            user_agent: state.user_agent,
226            url: state.url,
227        }
228    }
229}
230
231dto!(NewPageResult { page_id: String });
232dto!(Tab {
233    id: String,
234    title: String,
235    url: String
236});
237dto!(TabsResult { tabs: Vec<Tab> });
238dto!(CloseTabResult { #[serde(skip_serializing_if = "Option::is_none")] cleanup_error: Option<String> });
239dto!(CaptureStateResult {
240    state: BrowserState
241});
242
243#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
244pub struct CaptchaInjection {
245    pub kind: String,
246    pub updated_count: usize,
247    pub created: Vec<String>,
248    pub callbacks: Vec<String>,
249    pub errors: Vec<String>,
250    #[serde(rename = "solverUserAgent", skip_serializing_if = "Option::is_none")]
251    pub solver_user_agent: Option<String>,
252}
253dto!(SolveCaptchaResult {
254    injection: CaptchaInjection
255});
256
257macro_rules! action_params {
258    ($name:ident { $($(#[$attr:meta])* $field:ident: $ty:ty),* }) => {
259        dto!($name {
260            page_id: String,
261            #[serde(rename = "operation_id")] operation_id: String,
262            #[serde(default)] options: crate::ActionOptions,
263            $($(#[$attr])* $field: $ty),*
264        });
265    };
266}
267action_params!(ActionPerformParams {
268    action: crate::Action
269});
270dto!(AgentObserveParams {
271    page_id: String,
272    #[serde(flatten)]
273    args: crate::AgentObserveArgs
274});
275dto!(AgentStepParams {
276    page_id: String,
277    #[serde(flatten)]
278    args: crate::AgentStepArgs
279});