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