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}
176dto!(BrowserState {
177 cookies: Vec<SessionCookie>,
178 #[serde(default)] local_storage: HashMap<String, String>,
179 #[serde(default)] session_storage: HashMap<String, String>,
180 user_agent: String, url: String,
181});
182
183impl From<eoka::BrowserState> for BrowserState {
184 fn from(state: eoka::BrowserState) -> Self {
185 Self {
186 cookies: state
187 .cookies
188 .into_iter()
189 .map(|cookie| SessionCookie {
190 name: cookie.name,
191 value: cookie.value,
192 domain: cookie.domain,
193 path: cookie.path,
194 secure: cookie.secure,
195 http_only: cookie.http_only,
196 same_site: cookie.same_site,
197 expires: cookie.expires,
198 })
199 .collect(),
200 local_storage: state.local_storage,
201 session_storage: state.session_storage,
202 user_agent: state.user_agent,
203 url: state.url,
204 }
205 }
206}
207impl From<BrowserState> for eoka::BrowserState {
208 fn from(state: BrowserState) -> Self {
209 Self {
210 cookies: state
211 .cookies
212 .into_iter()
213 .map(|cookie| eoka::SessionCookie {
214 name: cookie.name,
215 value: cookie.value,
216 domain: cookie.domain,
217 path: cookie.path,
218 secure: cookie.secure,
219 http_only: cookie.http_only,
220 same_site: cookie.same_site,
221 expires: cookie.expires,
222 ..Default::default()
223 })
224 .collect(),
225 local_storage: state.local_storage,
226 session_storage: state.session_storage,
227 user_agent: state.user_agent,
228 url: state.url,
229 }
230 }
231}
232
233dto!(NewPageResult { page_id: String });
234dto!(Tab {
235 id: String,
236 title: String,
237 url: String
238});
239dto!(TabsResult { tabs: Vec<Tab> });
240dto!(CloseTabResult { #[serde(skip_serializing_if = "Option::is_none")] cleanup_error: Option<String> });
241dto!(CaptureStateResult {
242 state: BrowserState
243});
244
245#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
246pub struct CaptchaInjection {
247 pub kind: String,
248 pub updated_count: usize,
249 pub created: Vec<String>,
250 pub callbacks: Vec<String>,
251 pub errors: Vec<String>,
252 #[serde(rename = "solverUserAgent", skip_serializing_if = "Option::is_none")]
253 pub solver_user_agent: Option<String>,
254}
255dto!(SolveCaptchaResult {
256 injection: CaptchaInjection
257});
258
259macro_rules! action_params {
260 ($name:ident { $($(#[$attr:meta])* $field:ident: $ty:ty),* }) => {
261 dto!($name {
262 page_id: String,
263 #[serde(rename = "operation_id")] operation_id: String,
264 #[serde(default)] options: crate::ActionOptions,
265 $($(#[$attr])* $field: $ty),*
266 });
267 };
268}
269action_params!(ActionPerformParams {
270 action: crate::Action
271});
272dto!(AgentObserveParams {
273 page_id: String,
274 #[serde(flatten)]
275 args: crate::AgentObserveArgs
276});
277dto!(AgentStepParams {
278 page_id: String,
279 #[serde(flatten)]
280 args: crate::AgentStepArgs
281});