1use crate::error::{BrowserError, Result};
9use chromiumoxide::cdp::browser_protocol::browser::{
10 SetDownloadBehaviorBehavior, SetDownloadBehaviorParams,
11};
12use chromiumoxide::cdp::browser_protocol::emulation::SetPageScaleFactorParams;
13use chromiumoxide::cdp::browser_protocol::fetch::{
14 ContinueRequestParams, FailRequestParams, FulfillRequestParams, HeaderEntry, RequestId,
15};
16use chromiumoxide::cdp::browser_protocol::network::ErrorReason;
17use futures::future::BoxFuture;
18use serde::Serialize;
19use serde_json::Value;
20use std::path::PathBuf;
21use std::sync::Arc;
22use std::time::Duration;
23
24pub(crate) const INTERCEPTOR_TIMEOUT: Duration = Duration::from_secs(30);
26
27pub const MAX_EXCEPTIONS: usize = 200;
29
30#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
34pub enum InterceptStage {
35 Request,
37 Response,
39}
40
41#[derive(Clone, Debug, PartialEq, Serialize)]
43pub struct InterceptedRequest {
44 pub request_id: String,
46 pub url: String,
47 pub method: String,
48 pub headers: Vec<(String, String)>,
50 pub resource_type: String,
52 pub frame_id: String,
54 pub has_post_data: bool,
55 pub redirected_from: Option<String>,
58 pub stage: InterceptStage,
59 pub response_status: Option<i64>,
60 pub response_headers: Vec<(String, String)>,
61}
62
63impl InterceptedRequest {
64 pub fn is_redirect(&self) -> bool {
66 self.redirected_from.is_some()
67 }
68
69 pub fn header(&self, name: &str) -> Option<&str> {
71 self.headers
72 .iter()
73 .find(|(k, _)| k.eq_ignore_ascii_case(name))
74 .map(|(_, v)| v.as_str())
75 }
76
77 pub fn from_cdp_value(v: &Value) -> Option<Self> {
79 let request = v.get("request")?;
80 let text = |o: &Value, k: &str| o.get(k).and_then(Value::as_str).map(str::to_string);
81 let response_status = v.get("responseStatusCode").and_then(Value::as_i64);
82 let stage = if response_status.is_some() || v.get("responseErrorReason").is_some() {
83 InterceptStage::Response
84 } else {
85 InterceptStage::Request
86 };
87 Some(Self {
88 request_id: text(v, "requestId")?,
89 url: text(request, "url")?,
90 method: text(request, "method").unwrap_or_else(|| "GET".into()),
91 headers: request
92 .get("headers")
93 .map(header_object)
94 .unwrap_or_default(),
95 resource_type: text(v, "resourceType").unwrap_or_default(),
96 frame_id: text(v, "frameId").unwrap_or_default(),
97 has_post_data: request
98 .get("hasPostData")
99 .and_then(Value::as_bool)
100 .unwrap_or(false),
101 redirected_from: text(v, "redirectedRequestId"),
102 stage,
103 response_status,
104 response_headers: v
105 .get("responseHeaders")
106 .map(header_entries)
107 .unwrap_or_default(),
108 })
109 }
110}
111
112#[derive(Clone, Debug, Default, PartialEq)]
114pub struct ContinueOverrides {
115 pub url: Option<String>,
117 pub method: Option<String>,
118 pub headers: Option<Vec<(String, String)>>,
120 pub post_data: Option<Vec<u8>>,
121}
122
123#[derive(Clone, Copy, Debug, Eq, PartialEq)]
125pub enum InterceptFailure {
126 Failed,
127 Aborted,
128 AccessDenied,
129 ConnectionRefused,
130 NameNotResolved,
131 BlockedByClient,
132}
133
134impl InterceptFailure {
135 fn reason(self) -> ErrorReason {
136 match self {
137 Self::Failed => ErrorReason::Failed,
138 Self::Aborted => ErrorReason::Aborted,
139 Self::AccessDenied => ErrorReason::AccessDenied,
140 Self::ConnectionRefused => ErrorReason::ConnectionRefused,
141 Self::NameNotResolved => ErrorReason::NameNotResolved,
142 Self::BlockedByClient => ErrorReason::BlockedByClient,
143 }
144 }
145}
146
147#[derive(Clone, Debug, PartialEq)]
149pub enum InterceptDecision {
150 Continue,
152 ContinueWith(ContinueOverrides),
154 Fulfill {
156 status: u16,
157 headers: Vec<(String, String)>,
158 body: Vec<u8>,
159 phrase: Option<String>,
160 },
161 Fail(InterceptFailure),
163}
164
165pub type RequestInterceptor =
171 Arc<dyn Fn(InterceptedRequest) -> BoxFuture<'static, InterceptDecision> + Send + Sync>;
172
173#[derive(Debug)]
175pub(crate) enum PausedCommand {
176 Continue(ContinueRequestParams),
177 Fulfill(FulfillRequestParams),
178 Fail(FailRequestParams),
179}
180
181pub(crate) fn command_for(id: RequestId, decision: InterceptDecision) -> PausedCommand {
182 match decision {
183 InterceptDecision::Continue => PausedCommand::Continue(ContinueRequestParams::new(id)),
184 InterceptDecision::ContinueWith(o) => {
185 let mut p = ContinueRequestParams::new(id);
186 p.url = o.url;
187 p.method = o.method;
188 p.headers = o.headers.map(header_entries_out);
189 p.post_data = o.post_data.map(|b| base64(&b).into());
190 PausedCommand::Continue(p)
191 }
192 InterceptDecision::Fulfill {
193 status,
194 headers,
195 body,
196 phrase,
197 } => {
198 let mut p = FulfillRequestParams::new(id, i64::from(status));
199 p.response_headers = Some(header_entries_out(headers));
200 if !body.is_empty() {
201 p.body = Some(base64(&body).into());
202 }
203 p.response_phrase = phrase;
204 PausedCommand::Fulfill(p)
205 }
206 InterceptDecision::Fail(f) => PausedCommand::Fail(FailRequestParams::new(id, f.reason())),
207 }
208}
209
210pub(crate) async fn run_interceptor(
212 hook: &RequestInterceptor,
213 request: InterceptedRequest,
214 limit: Duration,
215) -> InterceptDecision {
216 match tokio::time::timeout(limit, hook(request)).await {
217 Ok(d) => d,
218 Err(_) => InterceptDecision::Fail(InterceptFailure::Failed),
219 }
220}
221
222#[derive(Clone, Debug, PartialEq, Serialize)]
226pub struct AxNode {
227 pub node_id: String,
228 pub ignored: bool,
229 pub role: Option<String>,
230 pub name: Option<String>,
231 pub description: Option<String>,
232 pub value: Option<Value>,
234 pub properties: Vec<(String, Value)>,
236 pub parent_id: Option<String>,
237 pub child_ids: Vec<String>,
238 pub backend_dom_node_id: Option<i64>,
240 pub frame_id: Option<String>,
241}
242
243impl AxNode {
244 pub fn property(&self, name: &str) -> Option<&Value> {
246 self.properties
247 .iter()
248 .find(|(k, _)| k == name)
249 .map(|(_, v)| v)
250 }
251}
252
253#[derive(Clone, Debug, PartialEq, Serialize)]
255pub struct AxSummary {
256 pub role: String,
257 pub name: String,
259 pub frame_id: String,
261}
262
263pub(crate) fn summarize_ax(nodes: &[AxNode]) -> Vec<AxSummary> {
265 nodes
266 .iter()
267 .filter(|n| !n.ignored)
268 .filter_map(|n| {
269 let role = n.role.as_ref().filter(|r| !r.is_empty())?;
270 Some(AxSummary {
271 role: role.clone(),
272 name: n.name.clone().unwrap_or_default(),
273 frame_id: n.frame_id.clone().unwrap_or_default(),
274 })
275 })
276 .collect()
277}
278
279pub(crate) fn parse_ax_tree(result: &Value) -> Vec<AxNode> {
281 let ax_value =
282 |n: &Value, k: &str| -> Option<Value> { n.get(k).and_then(|x| x.get("value")).cloned() };
283 let ax_text = |n: &Value, k: &str| -> Option<String> {
284 ax_value(n, k).and_then(|v| match v {
285 Value::String(s) => Some(s),
286 Value::Null => None,
287 other => Some(other.to_string()),
288 })
289 };
290 result
291 .get("nodes")
292 .and_then(Value::as_array)
293 .map(|nodes| {
294 nodes
295 .iter()
296 .filter_map(|n| {
297 Some(AxNode {
298 node_id: n.get("nodeId").and_then(Value::as_str)?.to_string(),
299 ignored: n.get("ignored").and_then(Value::as_bool).unwrap_or(false),
300 role: ax_text(n, "role"),
301 name: ax_text(n, "name"),
302 description: ax_text(n, "description"),
303 value: ax_value(n, "value"),
304 properties: n
305 .get("properties")
306 .and_then(Value::as_array)
307 .map(|ps| {
308 ps.iter()
309 .filter_map(|p| {
310 Some((
311 p.get("name")?.as_str()?.to_string(),
312 p.get("value")
313 .and_then(|v| v.get("value"))
314 .cloned()
315 .unwrap_or(Value::Null),
316 ))
317 })
318 .collect()
319 })
320 .unwrap_or_default(),
321 parent_id: n
322 .get("parentId")
323 .and_then(Value::as_str)
324 .map(str::to_string),
325 child_ids: n
326 .get("childIds")
327 .and_then(Value::as_array)
328 .map(|c| {
329 c.iter()
330 .filter_map(Value::as_str)
331 .map(str::to_string)
332 .collect()
333 })
334 .unwrap_or_default(),
335 backend_dom_node_id: n.get("backendDOMNodeId").and_then(Value::as_i64),
336 frame_id: n.get("frameId").and_then(Value::as_str).map(str::to_string),
337 })
338 })
339 .collect()
340 })
341 .unwrap_or_default()
342}
343
344#[derive(Clone, Debug, PartialEq, Serialize)]
348pub struct ExceptionFrame {
349 pub function_name: String,
350 pub url: String,
351 pub line: i64,
353 pub column: i64,
354}
355
356#[derive(Clone, Debug, PartialEq, Serialize)]
358pub struct PageException {
359 pub text: String,
361 pub description: Option<String>,
363 pub url: Option<String>,
364 pub line: i64,
365 pub column: i64,
366 pub timestamp_ms: f64,
368 pub stack: Vec<ExceptionFrame>,
369}
370
371impl PageException {
372 pub fn message(&self) -> &str {
374 self.description.as_deref().unwrap_or(&self.text)
375 }
376
377 pub fn from_cdp_value(v: &Value) -> Option<Self> {
379 let d = v.get("exceptionDetails")?;
380 Some(Self {
381 text: d.get("text").and_then(Value::as_str)?.to_string(),
382 description: d
383 .get("exception")
384 .and_then(|e| e.get("description"))
385 .and_then(Value::as_str)
386 .map(str::to_string),
387 url: d.get("url").and_then(Value::as_str).map(str::to_string),
388 line: d.get("lineNumber").and_then(Value::as_i64).unwrap_or(0),
389 column: d.get("columnNumber").and_then(Value::as_i64).unwrap_or(0),
390 timestamp_ms: v.get("timestamp").and_then(Value::as_f64).unwrap_or(0.0),
391 stack: d
392 .get("stackTrace")
393 .and_then(|s| s.get("callFrames"))
394 .and_then(Value::as_array)
395 .map(|frames| {
396 frames
397 .iter()
398 .map(|f| ExceptionFrame {
399 function_name: f
400 .get("functionName")
401 .and_then(Value::as_str)
402 .unwrap_or_default()
403 .to_string(),
404 url: f
405 .get("url")
406 .and_then(Value::as_str)
407 .unwrap_or_default()
408 .to_string(),
409 line: f.get("lineNumber").and_then(Value::as_i64).unwrap_or(0),
410 column: f.get("columnNumber").and_then(Value::as_i64).unwrap_or(0),
411 })
412 .collect()
413 })
414 .unwrap_or_default(),
415 })
416 }
417}
418
419pub(crate) fn page_scale_params(scale: f64) -> Result<SetPageScaleFactorParams> {
423 if !scale.is_finite() || scale <= 0.0 {
424 return Err(BrowserError::Invalid(format!(
425 "page scale must be a positive finite number, got {scale}"
426 )));
427 }
428 Ok(SetPageScaleFactorParams::new(scale))
429}
430
431#[derive(Clone, Debug, Eq, PartialEq)]
433pub enum DownloadBehavior {
434 Deny,
436 Allow { dir: PathBuf },
438 AllowAndName { dir: PathBuf },
440 Default,
442}
443
444pub(crate) fn download_params(behavior: &DownloadBehavior) -> Result<SetDownloadBehaviorParams> {
446 let dir_text = |dir: &PathBuf| -> Result<String> {
447 if !dir.is_absolute() {
448 return Err(BrowserError::Invalid(format!(
449 "download directory must be absolute: {}",
450 dir.display()
451 )));
452 }
453 if !dir.is_dir() {
454 return Err(BrowserError::Invalid(format!(
455 "download directory does not exist: {}",
456 dir.display()
457 )));
458 }
459 Ok(dir.to_string_lossy().into_owned())
460 };
461 Ok(match behavior {
462 DownloadBehavior::Deny => SetDownloadBehaviorParams::new(SetDownloadBehaviorBehavior::Deny),
463 DownloadBehavior::Default => {
464 SetDownloadBehaviorParams::new(SetDownloadBehaviorBehavior::Default)
465 }
466 DownloadBehavior::Allow { dir } => {
467 let mut p = SetDownloadBehaviorParams::new(SetDownloadBehaviorBehavior::Allow);
468 p.download_path = Some(dir_text(dir)?);
469 p
470 }
471 DownloadBehavior::AllowAndName { dir } => {
472 let mut p = SetDownloadBehaviorParams::new(SetDownloadBehaviorBehavior::AllowAndName);
473 p.download_path = Some(dir_text(dir)?);
474 p
475 }
476 })
477}
478
479fn header_object(v: &Value) -> Vec<(String, String)> {
483 v.as_object()
484 .map(|o| {
485 o.iter()
486 .map(|(k, v)| {
487 (
488 k.clone(),
489 v.as_str()
490 .map(str::to_string)
491 .unwrap_or_else(|| v.to_string()),
492 )
493 })
494 .collect()
495 })
496 .unwrap_or_default()
497}
498
499fn header_entries(v: &Value) -> Vec<(String, String)> {
501 v.as_array()
502 .map(|a| {
503 a.iter()
504 .filter_map(|h| {
505 Some((
506 h.get("name")?.as_str()?.to_string(),
507 h.get("value")?.as_str()?.to_string(),
508 ))
509 })
510 .collect()
511 })
512 .unwrap_or_default()
513}
514
515fn header_entries_out(h: Vec<(String, String)>) -> Vec<HeaderEntry> {
516 h.into_iter().map(|(n, v)| HeaderEntry::new(n, v)).collect()
517}
518
519pub(crate) fn base64(bytes: &[u8]) -> String {
521 const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
522 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
523 for c in bytes.chunks(3) {
524 let n = (u32::from(c[0]) << 16)
525 | (u32::from(*c.get(1).unwrap_or(&0)) << 8)
526 | u32::from(*c.get(2).unwrap_or(&0));
527 out.push(T[(n >> 18) as usize & 63] as char);
528 out.push(T[(n >> 12) as usize & 63] as char);
529 out.push(if c.len() > 1 {
530 T[(n >> 6) as usize & 63] as char
531 } else {
532 '='
533 });
534 out.push(if c.len() > 2 {
535 T[n as usize & 63] as char
536 } else {
537 '='
538 });
539 }
540 out
541}