chromiumoxide/handler/
network.rs

1use super::blockers::{
2    block_websites::block_xhr,
3    ignore_script_embedded, ignore_script_xhr, ignore_script_xhr_media,
4    intercept_manager::NetworkInterceptManager,
5    scripts::{
6        URL_IGNORE_SCRIPT_BASE_PATHS, URL_IGNORE_SCRIPT_STYLES_PATHS, URL_IGNORE_TRIE,
7        URL_IGNORE_TRIE_PATHS,
8    },
9    xhr::IGNORE_XHR_ASSETS,
10};
11use crate::auth::Credentials;
12use crate::cmd::CommandChain;
13use crate::handler::http::HttpRequest;
14use aho_corasick::AhoCorasick;
15use case_insensitive_string::CaseInsensitiveString;
16use chromiumoxide_cdp::cdp::browser_protocol::network::{
17    EmulateNetworkConditionsParams, EventLoadingFailed, EventLoadingFinished,
18    EventRequestServedFromCache, EventRequestWillBeSent, EventResponseReceived, Headers,
19    InterceptionId, RequestId, ResourceType, Response, SetCacheDisabledParams,
20    SetExtraHttpHeadersParams,
21};
22use chromiumoxide_cdp::cdp::browser_protocol::{
23    fetch::{
24        self, AuthChallengeResponse, AuthChallengeResponseResponse, ContinueRequestParams,
25        ContinueWithAuthParams, DisableParams, EventAuthRequired, EventRequestPaused,
26        RequestPattern,
27    },
28    network::SetBypassServiceWorkerParams,
29};
30use chromiumoxide_cdp::cdp::browser_protocol::{
31    network::EnableParams, security::SetIgnoreCertificateErrorsParams,
32};
33use chromiumoxide_types::{Command, Method, MethodId};
34use hashbrown::{HashMap, HashSet};
35use lazy_static::lazy_static;
36use reqwest::header::PROXY_AUTHORIZATION;
37use std::collections::VecDeque;
38use std::time::Duration;
39
40lazy_static! {
41    /// General patterns for popular libraries and resources
42    static ref JS_FRAMEWORK_ALLOW: Vec<&'static str> = vec![
43        "jquery",           // Covers jquery.min.js, jquery.js, etc.
44        "angular",
45        "react",            // Covers all React-related patterns
46        "vue",              // Covers all Vue-related patterns
47        "bootstrap",
48        "d3",
49        "lodash",
50        "ajax",
51        "application",
52        "app",              // Covers general app scripts like app.js
53        "main",
54        "index",
55        "bundle",
56        "vendor",
57        "runtime",
58        "polyfill",
59        "scripts",
60        "es2015.",
61        "es2020.",
62        "webpack",
63        "/wp-content/js/",  // Covers Wordpress content
64        // Verified 3rd parties for request
65        "https://m.stripe.network/",
66        "https://challenges.cloudflare.com/",
67        "https://www.google.com/recaptcha/api.js",
68        "https://google.com/recaptcha/api.js",
69        "https://js.stripe.com/",
70        "https://cdn.prod.website-files.com/", // webflow cdn scripts
71        "https://cdnjs.cloudflare.com/",        // cloudflare cdn scripts
72        "https://code.jquery.com/jquery-"
73    ];
74
75    /// Determine if a script should be rendered in the browser by name.
76    pub static ref ALLOWED_MATCHER: AhoCorasick = AhoCorasick::new(JS_FRAMEWORK_ALLOW.iter()).unwrap();
77
78    /// path of a js framework
79    pub static ref JS_FRAMEWORK_PATH: phf::Set<&'static str> = {
80        phf::phf_set! {
81            // Add allowed assets from JS_FRAMEWORK_ASSETS except the excluded ones
82            "_next/static/", "_astro/", "_app/immutable"
83        }
84    };
85
86    /// Ignore the content types.
87    pub static ref IGNORE_CONTENT_TYPES: phf::Set<&'static str> = phf::phf_set! {
88        "application/pdf",
89        "application/zip",
90        "application/x-rar-compressed",
91        "application/x-tar",
92        "image/png",
93        "image/jpeg",
94        "image/gif",
95        "image/bmp",
96        "image/svg+xml",
97        "video/mp4",
98        "video/x-msvideo",
99        "video/x-matroska",
100        "video/webm",
101        "audio/mpeg",
102        "audio/ogg",
103        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
104        "application/vnd.ms-excel",
105        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
106        "application/vnd.ms-powerpoint",
107        "application/vnd.openxmlformats-officedocument.presentationml.presentation",
108        "application/x-7z-compressed",
109        "application/x-rpm",
110        "application/x-shockwave-flash",
111        "application/rtf",
112    };
113
114    /// Ignore the resources for visual content types.
115    pub static ref IGNORE_VISUAL_RESOURCE_MAP: phf::Set<&'static str> = phf::phf_set! {
116        "Image",
117        "Media",
118        "Font"
119    };
120
121    /// Ignore the resources for visual content types.
122    pub static ref IGNORE_NETWORKING_RESOURCE_MAP: phf::Set<&'static str> = phf::phf_set! {
123        "CspViolationReport",
124        "Manifest",
125        "Other",
126        "Prefetch",
127        "Ping",
128    };
129
130    /// Case insenstive css matching
131    pub static ref CSS_EXTENSION: CaseInsensitiveString = CaseInsensitiveString::from("css");
132
133    /// The command chain.
134    pub static ref INIT_CHAIN: Vec<(std::borrow::Cow<'static, str>, serde_json::Value)>  = {
135        let enable = EnableParams::default();
136
137        if let Ok(c) = serde_json::to_value(&enable) {
138            vec![(enable.identifier(), c)]
139        } else {
140            vec![]
141        }
142    };
143
144    /// The command chain with https ignore.
145    pub static ref INIT_CHAIN_IGNORE_HTTP_ERRORS: Vec<(std::borrow::Cow<'static, str>, serde_json::Value)>  = {
146        let enable = EnableParams::default();
147        let mut v = vec![];
148        if let Ok(c) = serde_json::to_value(&enable) {
149            v.push((enable.identifier(), c));
150        }
151        let ignore = SetIgnoreCertificateErrorsParams::new(true);
152        if let Ok(ignored) = serde_json::to_value(&ignore) {
153            v.push((ignore.identifier(), ignored));
154        }
155
156        v
157    };
158
159    /// Enable the fetch intercept command
160    pub static ref ENABLE_FETCH: chromiumoxide_cdp::cdp::browser_protocol::fetch::EnableParams = {
161        fetch::EnableParams::builder()
162        .handle_auth_requests(true)
163        .pattern(RequestPattern::builder().url_pattern("*").build())
164        .build()
165    };
166}
167
168/// Determine if a redirect is true.
169pub(crate) fn is_redirect_status(status: i64) -> bool {
170    matches!(status, 301 | 302 | 303 | 307 | 308)
171}
172
173#[derive(Debug)]
174/// The base network manager.
175pub struct NetworkManager {
176    queued_events: VecDeque<NetworkEvent>,
177    ignore_httpserrors: bool,
178    requests: HashMap<RequestId, HttpRequest>,
179    // TODO put event in an Arc?
180    requests_will_be_sent: HashMap<RequestId, EventRequestWillBeSent>,
181    extra_headers: std::collections::HashMap<String, String>,
182    request_id_to_interception_id: HashMap<RequestId, InterceptionId>,
183    user_cache_disabled: bool,
184    attempted_authentications: HashSet<RequestId>,
185    credentials: Option<Credentials>,
186    // unused atm for remote connections, needs to be used for self launches.
187    user_request_interception_enabled: bool,
188    protocol_request_interception_enabled: bool,
189    offline: bool,
190    request_timeout: Duration,
191    // made_request: bool,
192    /// Ignore visuals (no pings, prefetching, and etc).
193    pub ignore_visuals: bool,
194    /// Block CSS stylesheets.
195    pub block_stylesheets: bool,
196    /// Block javascript that is not critical to rendering.
197    pub block_javascript: bool,
198    /// Block analytics from rendering
199    pub block_analytics: bool,
200    /// Only html from loading.
201    pub only_html: bool,
202    /// The custom intercept handle logic to run on the website.
203    pub intercept_manager: NetworkInterceptManager,
204    /// Track the amount of times the document reloaded.
205    pub document_reload_tracker: u8,
206    /// The initial target domain.
207    pub document_target_domain: String,
208}
209
210impl NetworkManager {
211    pub fn new(ignore_httpserrors: bool, request_timeout: Duration) -> Self {
212        Self {
213            queued_events: Default::default(),
214            ignore_httpserrors,
215            requests: Default::default(),
216            requests_will_be_sent: Default::default(),
217            extra_headers: Default::default(),
218            request_id_to_interception_id: Default::default(),
219            user_cache_disabled: false,
220            attempted_authentications: Default::default(),
221            credentials: None,
222            user_request_interception_enabled: false,
223            protocol_request_interception_enabled: false,
224            offline: false,
225            request_timeout,
226            ignore_visuals: false,
227            block_javascript: false,
228            block_stylesheets: false,
229            block_analytics: true,
230            only_html: false,
231            intercept_manager: NetworkInterceptManager::Unknown,
232            document_reload_tracker: 0,
233            document_target_domain: String::new(),
234        }
235    }
236
237    pub fn init_commands(&self) -> CommandChain {
238        let cmds = if self.ignore_httpserrors {
239            INIT_CHAIN_IGNORE_HTTP_ERRORS.clone()
240        } else {
241            INIT_CHAIN.clone()
242        };
243
244        CommandChain::new(cmds, self.request_timeout)
245    }
246
247    pub(crate) fn push_cdp_request<T: Command>(&mut self, cmd: T) {
248        let method = cmd.identifier();
249        if let Ok(params) = serde_json::to_value(cmd) {
250            self.queued_events
251                .push_back(NetworkEvent::SendCdpRequest((method, params)));
252        }
253    }
254
255    /// The next event to handle
256    pub fn poll(&mut self) -> Option<NetworkEvent> {
257        self.queued_events.pop_front()
258    }
259
260    pub fn extra_headers(&self) -> &std::collections::HashMap<String, String> {
261        &self.extra_headers
262    }
263
264    pub fn set_extra_headers(&mut self, headers: std::collections::HashMap<String, String>) {
265        self.extra_headers = headers;
266        self.extra_headers.remove(PROXY_AUTHORIZATION.as_str());
267        if let Ok(headers) = serde_json::to_value(&self.extra_headers) {
268            self.push_cdp_request(SetExtraHttpHeadersParams::new(Headers::new(headers)));
269        }
270    }
271
272    pub fn set_service_worker_enabled(&mut self, bypass: bool) {
273        self.push_cdp_request(SetBypassServiceWorkerParams::new(bypass));
274    }
275
276    pub fn set_request_interception(&mut self, enabled: bool) {
277        self.user_request_interception_enabled = enabled;
278        self.update_protocol_request_interception();
279    }
280
281    pub fn set_cache_enabled(&mut self, enabled: bool) {
282        let run = self.user_cache_disabled != !enabled;
283        self.user_cache_disabled = !enabled;
284        if run {
285            self.update_protocol_cache_disabled();
286        }
287    }
288
289    pub fn update_protocol_cache_disabled(&mut self) {
290        self.push_cdp_request(SetCacheDisabledParams::new(self.user_cache_disabled));
291    }
292
293    pub fn authenticate(&mut self, credentials: Credentials) {
294        self.credentials = Some(credentials);
295        self.update_protocol_request_interception()
296    }
297
298    fn update_protocol_request_interception(&mut self) {
299        let enabled = self.user_request_interception_enabled || self.credentials.is_some();
300
301        if enabled == self.protocol_request_interception_enabled {
302            return;
303        }
304
305        if enabled {
306            self.push_cdp_request(ENABLE_FETCH.clone())
307        } else {
308            self.push_cdp_request(DisableParams::default())
309        }
310    }
311
312    /// Url matches analytics that we want to ignore or trackers.
313    pub(crate) fn ignore_script(
314        &self,
315        url: &str,
316        block_analytics: bool,
317        intercept_manager: NetworkInterceptManager,
318    ) -> bool {
319        let mut ignore_script = block_analytics && URL_IGNORE_TRIE.contains_prefix(url);
320
321        if !ignore_script {
322            if let Some(index) = url.find("//") {
323                let pos = index + 2;
324
325                // Ensure there is something after `//`
326                if pos < url.len() {
327                    // Find the first slash after the `//`
328                    if let Some(slash_index) = url[pos..].find('/') {
329                        let base_path_index = pos + slash_index + 1;
330
331                        if url.len() > base_path_index {
332                            let new_url: &str = &url[base_path_index..];
333
334                            // ignore assets we do not need for frameworks
335                            if !ignore_script
336                                && intercept_manager == NetworkInterceptManager::Unknown
337                            {
338                                let hydration_file =
339                                    JS_FRAMEWORK_PATH.iter().any(|p| new_url.starts_with(p));
340
341                                // ignore astro paths
342                                if hydration_file && new_url.ends_with(".js") {
343                                    ignore_script = true;
344                                }
345                            }
346
347                            if !ignore_script
348                                && URL_IGNORE_SCRIPT_BASE_PATHS.contains_prefix(new_url)
349                            {
350                                ignore_script = true;
351                            }
352
353                            if !ignore_script
354                                && self.ignore_visuals
355                                && URL_IGNORE_SCRIPT_STYLES_PATHS.contains_prefix(new_url)
356                            {
357                                ignore_script = true;
358                            }
359                        }
360                    }
361                }
362            }
363        }
364
365        // fallback for file ending in analytics.js
366        if !ignore_script && block_analytics {
367            ignore_script = URL_IGNORE_TRIE_PATHS.contains_prefix(url);
368        }
369
370        ignore_script
371    }
372
373    /// Determine if the request should be skipped.
374    fn skip_xhr(
375        &self,
376        skip_networking: bool,
377        event: &EventRequestPaused,
378        network_event: bool,
379    ) -> bool {
380        // XHR check
381        if !skip_networking && network_event {
382            let request_url = event.request.url.as_str();
383
384            // check if part of ignore scripts.
385            let skip_analytics =
386                self.block_analytics && (ignore_script_xhr(request_url) || block_xhr(request_url));
387
388            if skip_analytics {
389                true
390            } else if self.block_stylesheets || self.ignore_visuals {
391                let block_css = self.block_stylesheets;
392                let block_media = self.ignore_visuals;
393
394                let mut block_request = false;
395
396                if let Some(position) = request_url.rfind('.') {
397                    let hlen = request_url.len();
398                    let has_asset = hlen - position;
399
400                    if has_asset >= 3 {
401                        let next_position = position + 1;
402
403                        if block_media
404                            && IGNORE_XHR_ASSETS.contains::<CaseInsensitiveString>(
405                                &request_url[next_position..].into(),
406                            )
407                        {
408                            block_request = true;
409                        } else if block_css {
410                            block_request =
411                                CaseInsensitiveString::from(request_url[next_position..].as_bytes())
412                                    .contains(&**CSS_EXTENSION)
413                        }
414                    }
415                }
416
417                if !block_request {
418                    block_request = ignore_script_xhr_media(request_url);
419                }
420
421                block_request
422            } else {
423                skip_networking
424            }
425        } else {
426            skip_networking
427        }
428    }
429
430    #[cfg(not(feature = "adblock"))]
431    pub fn on_fetch_request_paused(&mut self, event: &EventRequestPaused) {
432        use super::blockers::block_websites::block_website;
433
434        if !self.user_request_interception_enabled && self.protocol_request_interception_enabled {
435            self.push_cdp_request(ContinueRequestParams::new(event.request_id.clone()))
436        } else {
437            if let Some(network_id) = event.network_id.as_ref() {
438                if let Some(request_will_be_sent) =
439                    self.requests_will_be_sent.remove(network_id.as_ref())
440                {
441                    self.on_request(&request_will_be_sent, Some(event.request_id.clone().into()));
442                } else {
443                    let current_url = event.request.url.as_str();
444                    let javascript_resource = event.resource_type == ResourceType::Script;
445                    let document_resource = event.resource_type == ResourceType::Document;
446                    let network_resource = !document_resource
447                        && (event.resource_type == ResourceType::Xhr
448                            || event.resource_type == ResourceType::Fetch
449                            || event.resource_type == ResourceType::WebSocket);
450
451                    let skip_networking =
452                        IGNORE_NETWORKING_RESOURCE_MAP.contains(event.resource_type.as_ref());
453
454                    let skip_networking = skip_networking || self.document_reload_tracker >= 3;
455                    let mut replacer = None;
456
457                    if document_resource {
458                        if self.document_target_domain == current_url {
459                            // this will prevent the domain from looping (3 times is enough).
460                            self.document_reload_tracker += 1;
461                        } else if !self.document_target_domain.is_empty()
462                            && event.redirected_request_id.is_some()
463                        {
464                            let (http_document_replacement, mut https_document_replacement) =
465                                if self.document_target_domain.starts_with("http://") {
466                                    (
467                                        self.document_target_domain.replace("http://", "http//"),
468                                        self.document_target_domain.replace("http://", "https://"),
469                                    )
470                                } else {
471                                    (
472                                        self.document_target_domain.replace("https://", "https//"),
473                                        self.document_target_domain.replace("https://", "http://"),
474                                    )
475                                };
476
477                            let trailing = https_document_replacement.ends_with('/');
478
479                            if trailing {
480                                https_document_replacement.pop();
481                            }
482
483                            if https_document_replacement.ends_with('/') {
484                                https_document_replacement.pop();
485                            }
486
487                            let redirect_mask = format!(
488                                "{}{}",
489                                https_document_replacement, http_document_replacement
490                            );
491
492                            // handle redirect masking
493                            if current_url == redirect_mask {
494                                replacer = Some(if trailing {
495                                    format!("{}/", https_document_replacement)
496                                } else {
497                                    https_document_replacement
498                                });
499                            }
500                        }
501                        self.document_target_domain = event.request.url.clone();
502                    }
503
504                    let current_url = match &replacer {
505                        Some(r) => r,
506                        _ => &event.request.url,
507                    }
508                    .as_str();
509
510                    // main initial check
511                    let skip_networking = if !skip_networking {
512                        self.ignore_visuals
513                            && (IGNORE_VISUAL_RESOURCE_MAP.contains(event.resource_type.as_ref()))
514                            || self.block_stylesheets
515                                && ResourceType::Stylesheet == event.resource_type
516                            || self.block_javascript
517                                && javascript_resource
518                                && self.intercept_manager == NetworkInterceptManager::Unknown
519                                && !ALLOWED_MATCHER.is_match(current_url)
520                    } else {
521                        skip_networking
522                    };
523
524                    let skip_networking = if !skip_networking
525                        && (self.only_html || self.ignore_visuals)
526                        && (javascript_resource || document_resource)
527                    {
528                        ignore_script_embedded(current_url)
529                    } else {
530                        skip_networking
531                    };
532
533                    // analytics check
534                    let skip_networking = if !skip_networking && javascript_resource {
535                        self.ignore_script(
536                            current_url,
537                            self.block_analytics,
538                            self.intercept_manager,
539                        )
540                    } else {
541                        skip_networking
542                    };
543
544                    // XHR check
545                    let skip_networking = self.skip_xhr(skip_networking, &event, network_resource);
546
547                    // custom interception layer.
548                    let skip_networking = if !skip_networking
549                        && (javascript_resource || network_resource || document_resource)
550                    {
551                        self.intercept_manager.intercept_detection(
552                            &current_url,
553                            self.ignore_visuals,
554                            network_resource,
555                        )
556                    } else {
557                        skip_networking
558                    };
559
560                    let skip_networking =
561                        if !skip_networking && (javascript_resource || network_resource) {
562                            block_website(&current_url)
563                        } else {
564                            skip_networking
565                        };
566
567                    if skip_networking {
568                        tracing::debug!("Blocked: {:?} - {}", event.resource_type, current_url);
569                        let fullfill_params =
570                            crate::handler::network::fetch::FulfillRequestParams::new(
571                                event.request_id.clone(),
572                                200,
573                            );
574                        self.push_cdp_request(fullfill_params);
575                    } else {
576                        tracing::debug!("Allowed: {:?} - {}", event.resource_type, current_url);
577                        let mut continue_params =
578                            ContinueRequestParams::new(event.request_id.clone());
579
580                        if replacer.is_some() {
581                            continue_params.url = Some(current_url.into());
582                            continue_params.intercept_response = Some(false);
583                        }
584
585                        self.push_cdp_request(continue_params)
586                    }
587                }
588            } else {
589                self.push_cdp_request(ContinueRequestParams::new(event.request_id.clone()))
590            }
591        }
592    }
593
594    #[cfg(feature = "adblock")]
595    pub fn on_fetch_request_paused(&mut self, event: &EventRequestPaused) {
596        if !self.user_request_interception_enabled && self.protocol_request_interception_enabled {
597            self.push_cdp_request(ContinueRequestParams::new(event.request_id.clone()))
598        } else {
599            if let Some(network_id) = event.network_id.as_ref() {
600                if let Some(request_will_be_sent) =
601                    self.requests_will_be_sent.remove(network_id.as_ref())
602                {
603                    self.on_request(&request_will_be_sent, Some(event.request_id.clone().into()));
604                } else {
605                    let current_url = event.request.url.as_str();
606                    let javascript_resource = event.resource_type == ResourceType::Script;
607                    let document_resource = event.resource_type == ResourceType::Document;
608                    let network_resource = !document_resource
609                        && (event.resource_type == ResourceType::Xhr
610                            || event.resource_type == ResourceType::Fetch
611                            || event.resource_type == ResourceType::WebSocket);
612
613                    // block all of these events.
614                    let skip_networking =
615                        IGNORE_NETWORKING_RESOURCE_MAP.contains(event.resource_type.as_ref());
616
617                    let skip_networking = skip_networking || self.document_reload_tracker >= 3;
618
619                    if document_resource {
620                        if self.document_target_domain == current_url {
621                            // this will prevent the domain from looping (3 times is enough).
622                            self.document_reload_tracker += 1;
623                        } else if !self.document_target_domain.is_empty()
624                            && event.redirected_request_id.is_some()
625                        {
626                            let (http_document_replacement, mut https_document_replacement) =
627                                if self.document_target_domain.starts_with("http://") {
628                                    (
629                                        self.document_target_domain.replace("http://", "http//"),
630                                        self.document_target_domain.replace("http://", "https://"),
631                                    )
632                                } else {
633                                    (
634                                        self.document_target_domain.replace("https://", "https//"),
635                                        self.document_target_domain.replace("https://", "http://"),
636                                    )
637                                };
638
639                            let trailing = https_document_replacement.ends_with('/');
640
641                            if trailing {
642                                https_document_replacement.pop();
643                            }
644
645                            if https_document_replacement.ends_with('/') {
646                                https_document_replacement.pop();
647                            }
648
649                            let redirect_mask = format!(
650                                "{}{}",
651                                https_document_replacement, http_document_replacement
652                            );
653
654                            // handle redirect masking
655                            if current_url == redirect_mask {
656                                replacer = Some(if trailing {
657                                    format!("{}/", https_document_replacement)
658                                } else {
659                                    https_document_replacement
660                                });
661                            }
662                        }
663                        self.document_target_domain = event.request.url.clone();
664                    }
665
666                    let current_url = match &replacer {
667                        Some(r) => r,
668                        _ => &event.request.url,
669                    }
670                    .as_str();
671
672                    // main initial check
673                    let skip_networking = if !skip_networking {
674                        self.ignore_visuals
675                            && (IGNORE_VISUAL_RESOURCE_MAP.contains(event.resource_type.as_ref()))
676                            || self.block_stylesheets
677                                && ResourceType::Stylesheet == event.resource_type
678                            || self.block_javascript
679                                && javascript_resource
680                                && self.intercept_manager == NetworkInterceptManager::Unknown
681                                && !ALLOWED_MATCHER.is_match(current_url)
682                    } else {
683                        skip_networking
684                    };
685
686                    let skip_networking = if !skip_networking {
687                        self.detect_ad(event)
688                    } else {
689                        skip_networking
690                    };
691
692                    let skip_networking = if !skip_networking
693                        && (self.only_html || self.ignore_visuals)
694                        && (javascript_resource || document_resource)
695                    {
696                        ignore_script_embedded(current_url)
697                    } else {
698                        skip_networking
699                    };
700
701                    // analytics check
702                    let skip_networking = if !skip_networking && javascript_resource {
703                        self.ignore_script(
704                            current_url,
705                            self.block_analytics,
706                            self.intercept_manager,
707                        )
708                    } else {
709                        skip_networking
710                    };
711
712                    // XHR check
713                    let skip_networking = self.skip_xhr(skip_networking, &event, network_resource);
714
715                    // custom interception layer.
716                    let skip_networking = if !skip_networking
717                        && (javascript_resource || network_resource || document_resource)
718                    {
719                        self.intercept_manager.intercept_detection(
720                            &event.request.url,
721                            self.ignore_visuals,
722                            network_resource,
723                        )
724                    } else {
725                        skip_networking
726                    };
727
728                    let skip_networking =
729                        if !skip_networking && (javascript_resource || network_resource) {
730                            block_website(&event.request.url)
731                        } else {
732                            skip_networking
733                        };
734
735                    if skip_networking {
736                        tracing::debug!("Blocked: {:?} - {}", event.resource_type, current_url);
737
738                        let fullfill_params =
739                            crate::handler::network::fetch::FulfillRequestParams::new(
740                                event.request_id.clone(),
741                                200,
742                            );
743                        self.push_cdp_request(fullfill_params);
744                    } else {
745                        tracing::debug!("Allowed: {:?} - {}", event.resource_type, current_url);
746
747                        let mut continue_params =
748                            ContinueRequestParams::new(event.request_id.clone());
749
750                        if replacer.is_some() {
751                            continue_params.url = Some(current_url.into());
752                            continue_params.intercept_response = Some(false);
753                        }
754                    }
755                }
756            } else {
757                self.push_cdp_request(ContinueRequestParams::new(event.request_id.clone()))
758            }
759        }
760
761        // if self.only_html {
762        //     self.made_request = true;
763        // }
764    }
765
766    /// Perform a page intercept for chrome
767    #[cfg(feature = "adblock")]
768    pub fn detect_ad(&self, event: &EventRequestPaused) -> bool {
769        use adblock::{
770            lists::{FilterSet, ParseOptions, RuleTypes},
771            Engine,
772        };
773
774        lazy_static::lazy_static! {
775            static ref AD_ENGINE: Engine = {
776                let mut filter_set = FilterSet::new(false);
777                let mut rules = ParseOptions::default();
778                rules.rule_types = RuleTypes::All;
779
780                filter_set.add_filters(
781                    &*crate::handler::blockers::adblock_patterns::ADBLOCK_PATTERNS,
782                    rules,
783                );
784
785                Engine::from_filter_set(filter_set, true)
786            };
787        };
788
789        let blockable = ResourceType::Image == event.resource_type
790            || event.resource_type == ResourceType::Media
791            || event.resource_type == ResourceType::Stylesheet
792            || event.resource_type == ResourceType::Document
793            || event.resource_type == ResourceType::Fetch
794            || event.resource_type == ResourceType::Xhr;
795
796        let u = &event.request.url;
797
798        let block_request = blockable
799            // set it to example.com for 3rd party handling is_same_site
800        && {
801            let request = adblock::request::Request::preparsed(
802                 &u,
803                 "example.com",
804                 "example.com",
805                 &event.resource_type.as_ref().to_lowercase(),
806                 !event.request.is_same_site.unwrap_or_default());
807
808            AD_ENGINE.check_network_request(&request).matched
809        };
810
811        block_request
812    }
813
814    pub fn on_fetch_auth_required(&mut self, event: &EventAuthRequired) {
815        let response = if self
816            .attempted_authentications
817            .contains(event.request_id.as_ref())
818        {
819            AuthChallengeResponseResponse::CancelAuth
820        } else if self.credentials.is_some() {
821            self.attempted_authentications
822                .insert(event.request_id.clone().into());
823            AuthChallengeResponseResponse::ProvideCredentials
824        } else {
825            AuthChallengeResponseResponse::Default
826        };
827
828        let mut auth = AuthChallengeResponse::new(response);
829        if let Some(creds) = self.credentials.clone() {
830            auth.username = Some(creds.username);
831            auth.password = Some(creds.password);
832        }
833        self.push_cdp_request(ContinueWithAuthParams::new(event.request_id.clone(), auth));
834    }
835
836    pub fn set_offline_mode(&mut self, value: bool) {
837        if self.offline == value {
838            return;
839        }
840        self.offline = value;
841        if let Ok(network) = EmulateNetworkConditionsParams::builder()
842            .offline(self.offline)
843            .latency(0)
844            .download_throughput(-1.)
845            .upload_throughput(-1.)
846            .build()
847        {
848            self.push_cdp_request(network);
849        }
850    }
851
852    /// Request interception doesn't happen for data URLs with Network Service.
853    pub fn on_request_will_be_sent(&mut self, event: &EventRequestWillBeSent) {
854        if self.protocol_request_interception_enabled && !event.request.url.starts_with("data:") {
855            if let Some(interception_id) = self
856                .request_id_to_interception_id
857                .remove(event.request_id.as_ref())
858            {
859                self.on_request(event, Some(interception_id));
860            } else {
861                // TODO remove the clone for event
862                self.requests_will_be_sent
863                    .insert(event.request_id.clone(), event.clone());
864            }
865        } else {
866            self.on_request(event, None);
867        }
868    }
869
870    pub fn on_request_served_from_cache(&mut self, event: &EventRequestServedFromCache) {
871        if let Some(request) = self.requests.get_mut(event.request_id.as_ref()) {
872            request.from_memory_cache = true;
873        }
874    }
875
876    pub fn on_response_received(&mut self, event: &EventResponseReceived) {
877        if let Some(mut request) = self.requests.remove(event.request_id.as_ref()) {
878            request.set_response(event.response.clone());
879            self.queued_events
880                .push_back(NetworkEvent::RequestFinished(request))
881        }
882    }
883
884    pub fn on_network_loading_finished(&mut self, event: &EventLoadingFinished) {
885        if let Some(request) = self.requests.remove(event.request_id.as_ref()) {
886            if let Some(interception_id) = request.interception_id.as_ref() {
887                self.attempted_authentications
888                    .remove(interception_id.as_ref());
889            }
890            self.queued_events
891                .push_back(NetworkEvent::RequestFinished(request));
892        }
893    }
894
895    pub fn on_network_loading_failed(&mut self, event: &EventLoadingFailed) {
896        if let Some(mut request) = self.requests.remove(event.request_id.as_ref()) {
897            request.failure_text = Some(event.error_text.clone());
898            if let Some(interception_id) = request.interception_id.as_ref() {
899                self.attempted_authentications
900                    .remove(interception_id.as_ref());
901            }
902            self.queued_events
903                .push_back(NetworkEvent::RequestFailed(request));
904        }
905    }
906
907    fn on_request(
908        &mut self,
909        event: &EventRequestWillBeSent,
910        interception_id: Option<InterceptionId>,
911    ) {
912        let mut redirect_chain = Vec::new();
913        let mut redirect_location = None;
914
915        if let Some(redirect_resp) = &event.redirect_response {
916            if let Some(mut request) = self.requests.remove(event.request_id.as_ref()) {
917                if is_redirect_status(redirect_resp.status) {
918                    if let Some(location) = redirect_resp.headers.inner()["Location"].as_str() {
919                        if redirect_resp.url != location {
920                            let fixed_location = location.replace(&redirect_resp.url, "");
921                            request.response.as_mut().map(|resp| {
922                                resp.headers.0["Location"] =
923                                    serde_json::Value::String(fixed_location.clone());
924                            });
925                            redirect_location = Some(fixed_location);
926                        }
927                    }
928                }
929
930                self.handle_request_redirect(
931                    &mut request,
932                    if let Some(redirect_location) = redirect_location {
933                        let mut redirect_resp = redirect_resp.clone();
934                        redirect_resp.headers.0["Location"] =
935                            serde_json::Value::String(redirect_location);
936                        redirect_resp
937                    } else {
938                        redirect_resp.clone()
939                    },
940                );
941
942                redirect_chain = std::mem::take(&mut request.redirect_chain);
943                redirect_chain.push(request);
944            }
945        }
946
947        let request = HttpRequest::new(
948            event.request_id.clone(),
949            event.frame_id.clone(),
950            interception_id,
951            self.user_request_interception_enabled,
952            redirect_chain,
953        );
954
955        self.requests.insert(event.request_id.clone(), request);
956        self.queued_events
957            .push_back(NetworkEvent::Request(event.request_id.clone()));
958    }
959
960    fn handle_request_redirect(&mut self, request: &mut HttpRequest, response: Response) {
961        request.set_response(response);
962        if let Some(interception_id) = request.interception_id.as_ref() {
963            self.attempted_authentications
964                .remove(interception_id.as_ref());
965        }
966    }
967}
968
969#[derive(Debug)]
970pub enum NetworkEvent {
971    SendCdpRequest((MethodId, serde_json::Value)),
972    Request(RequestId),
973    Response(RequestId),
974    RequestFailed(HttpRequest),
975    RequestFinished(HttpRequest),
976}