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        self.user_cache_disabled = !enabled;
283        self.update_protocol_cache_disabled();
284    }
285
286    pub fn update_protocol_cache_disabled(&mut self) {
287        self.push_cdp_request(SetCacheDisabledParams::new(
288            self.user_cache_disabled || self.protocol_request_interception_enabled,
289        ));
290    }
291
292    pub fn authenticate(&mut self, credentials: Credentials) {
293        self.credentials = Some(credentials);
294        self.update_protocol_request_interception()
295    }
296
297    fn update_protocol_request_interception(&mut self) {
298        let enabled = self.user_request_interception_enabled || self.credentials.is_some();
299
300        if enabled == self.protocol_request_interception_enabled {
301            return;
302        }
303
304        self.update_protocol_cache_disabled();
305
306        if enabled {
307            self.push_cdp_request(ENABLE_FETCH.clone())
308        } else {
309            self.push_cdp_request(DisableParams::default())
310        }
311    }
312
313    /// Url matches analytics that we want to ignore or trackers.
314    pub(crate) fn ignore_script(
315        &self,
316        url: &str,
317        block_analytics: bool,
318        intercept_manager: NetworkInterceptManager,
319    ) -> bool {
320        let mut ignore_script = block_analytics && URL_IGNORE_TRIE.contains_prefix(url);
321
322        if !ignore_script {
323            if let Some(index) = url.find("//") {
324                let pos = index + 2;
325
326                // Ensure there is something after `//`
327                if pos < url.len() {
328                    // Find the first slash after the `//`
329                    if let Some(slash_index) = url[pos..].find('/') {
330                        let base_path_index = pos + slash_index + 1;
331
332                        if url.len() > base_path_index {
333                            let new_url: &str = &url[base_path_index..];
334
335                            // ignore assets we do not need for frameworks
336                            if !ignore_script
337                                && intercept_manager == NetworkInterceptManager::Unknown
338                            {
339                                let hydration_file =
340                                    JS_FRAMEWORK_PATH.iter().any(|p| new_url.starts_with(p));
341
342                                // ignore astro paths
343                                if hydration_file && new_url.ends_with(".js") {
344                                    ignore_script = true;
345                                }
346                            }
347
348                            if !ignore_script
349                                && URL_IGNORE_SCRIPT_BASE_PATHS.contains_prefix(new_url)
350                            {
351                                ignore_script = true;
352                            }
353
354                            if !ignore_script
355                                && self.ignore_visuals
356                                && URL_IGNORE_SCRIPT_STYLES_PATHS.contains_prefix(new_url)
357                            {
358                                ignore_script = true;
359                            }
360                        }
361                    }
362                }
363            }
364        }
365
366        // fallback for file ending in analytics.js
367        if !ignore_script && block_analytics {
368            ignore_script = URL_IGNORE_TRIE_PATHS.contains_prefix(url);
369        }
370
371        ignore_script
372    }
373
374    /// Determine if the request should be skipped.
375    fn skip_xhr(
376        &self,
377        skip_networking: bool,
378        event: &EventRequestPaused,
379        network_event: bool,
380    ) -> bool {
381        // XHR check
382        if !skip_networking && network_event {
383            let request_url = event.request.url.as_str();
384
385            // check if part of ignore scripts.
386            let skip_analytics =
387                self.block_analytics && (ignore_script_xhr(request_url) || block_xhr(request_url));
388
389            if skip_analytics {
390                true
391            } else if self.block_stylesheets || self.ignore_visuals {
392                let block_css = self.block_stylesheets;
393                let block_media = self.ignore_visuals;
394
395                let mut block_request = false;
396
397                if let Some(position) = request_url.rfind('.') {
398                    let hlen = request_url.len();
399                    let has_asset = hlen - position;
400
401                    if has_asset >= 3 {
402                        let next_position = position + 1;
403
404                        if block_media
405                            && IGNORE_XHR_ASSETS.contains::<CaseInsensitiveString>(
406                                &request_url[next_position..].into(),
407                            )
408                        {
409                            block_request = true;
410                        } else if block_css {
411                            block_request =
412                                CaseInsensitiveString::from(request_url[next_position..].as_bytes())
413                                    .contains(&**CSS_EXTENSION)
414                        }
415                    }
416                }
417
418                if !block_request {
419                    block_request = ignore_script_xhr_media(request_url);
420                }
421
422                block_request
423            } else {
424                skip_networking
425            }
426        } else {
427            skip_networking
428        }
429    }
430
431    #[cfg(not(feature = "adblock"))]
432    pub fn on_fetch_request_paused(&mut self, event: &EventRequestPaused) {
433        use super::blockers::block_websites::block_website;
434
435        if !self.user_request_interception_enabled && self.protocol_request_interception_enabled {
436            self.push_cdp_request(ContinueRequestParams::new(event.request_id.clone()))
437        } else {
438            if let Some(network_id) = event.network_id.as_ref() {
439                if let Some(request_will_be_sent) =
440                    self.requests_will_be_sent.remove(network_id.as_ref())
441                {
442                    self.on_request(&request_will_be_sent, Some(event.request_id.clone().into()));
443                } else {
444                    let current_url = event.request.url.as_str();
445                    let javascript_resource = event.resource_type == ResourceType::Script;
446                    let document_resource = event.resource_type == ResourceType::Document;
447                    let network_resource = !document_resource
448                        && (event.resource_type == ResourceType::Xhr
449                            || event.resource_type == ResourceType::Fetch
450                            || event.resource_type == ResourceType::WebSocket);
451
452                    let skip_networking =
453                        IGNORE_NETWORKING_RESOURCE_MAP.contains(event.resource_type.as_ref());
454
455                    let skip_networking = skip_networking || self.document_reload_tracker >= 3;
456                    let mut replacer = None;
457
458                    if document_resource {
459                        if self.document_target_domain == current_url {
460                            // this will prevent the domain from looping (3 times is enough).
461                            self.document_reload_tracker += 1;
462                        } else if !self.document_target_domain.is_empty()
463                            && event.redirected_request_id.is_some()
464                        {
465                            let (http_document_replacement, mut https_document_replacement) =
466                                if self.document_target_domain.starts_with("http://") {
467                                    (
468                                        self.document_target_domain.replace("http://", "http//"),
469                                        self.document_target_domain.replace("http://", "https://"),
470                                    )
471                                } else {
472                                    (
473                                        self.document_target_domain.replace("https://", "https//"),
474                                        self.document_target_domain.replace("https://", "http://"),
475                                    )
476                                };
477
478                            let trailing = https_document_replacement.ends_with('/');
479
480                            if trailing {
481                                https_document_replacement.pop();
482                            }
483
484                            if https_document_replacement.ends_with('/') {
485                                https_document_replacement.pop();
486                            }
487
488                            let redirect_mask = format!(
489                                "{}{}",
490                                https_document_replacement, http_document_replacement
491                            );
492
493                            // handle redirect masking
494                            if current_url == redirect_mask {
495                                replacer = Some(if trailing {
496                                    format!("{}/", https_document_replacement)
497                                } else {
498                                    https_document_replacement
499                                });
500                            }
501                        }
502                        self.document_target_domain = event.request.url.clone();
503                    }
504
505                    let current_url = match &replacer {
506                        Some(r) => r,
507                        _ => &event.request.url,
508                    }
509                    .as_str();
510
511                    // main initial check
512                    let skip_networking = if !skip_networking {
513                        self.ignore_visuals
514                            && (IGNORE_VISUAL_RESOURCE_MAP.contains(event.resource_type.as_ref()))
515                            || self.block_stylesheets
516                                && ResourceType::Stylesheet == event.resource_type
517                            || self.block_javascript
518                                && javascript_resource
519                                && self.intercept_manager == NetworkInterceptManager::Unknown
520                                && !ALLOWED_MATCHER.is_match(current_url)
521                    } else {
522                        skip_networking
523                    };
524
525                    let skip_networking = if !skip_networking
526                        && (self.only_html || self.ignore_visuals)
527                        && (javascript_resource || document_resource)
528                    {
529                        ignore_script_embedded(current_url)
530                    } else {
531                        skip_networking
532                    };
533
534                    // analytics check
535                    let skip_networking = if !skip_networking && javascript_resource {
536                        self.ignore_script(
537                            current_url,
538                            self.block_analytics,
539                            self.intercept_manager,
540                        )
541                    } else {
542                        skip_networking
543                    };
544
545                    // XHR check
546                    let skip_networking = self.skip_xhr(skip_networking, &event, network_resource);
547
548                    // custom interception layer.
549                    let skip_networking = if !skip_networking
550                        && (javascript_resource || network_resource || document_resource)
551                    {
552                        self.intercept_manager.intercept_detection(
553                            &current_url,
554                            self.ignore_visuals,
555                            network_resource,
556                        )
557                    } else {
558                        skip_networking
559                    };
560
561                    let skip_networking =
562                        if !skip_networking && (javascript_resource || network_resource) {
563                            block_website(&current_url)
564                        } else {
565                            skip_networking
566                        };
567
568                    if skip_networking {
569                        tracing::debug!("Blocked: {:?} - {}", event.resource_type, current_url);
570                        let fullfill_params =
571                            crate::handler::network::fetch::FulfillRequestParams::new(
572                                event.request_id.clone(),
573                                200,
574                            );
575                        self.push_cdp_request(fullfill_params);
576                    } else {
577                        tracing::debug!("Allowed: {:?} - {}", event.resource_type, current_url);
578                        let mut continue_params =
579                            ContinueRequestParams::new(event.request_id.clone());
580
581                        if replacer.is_some() {
582                            continue_params.url = Some(current_url.into());
583                            continue_params.intercept_response = Some(false);
584                        }
585
586                        self.push_cdp_request(continue_params)
587                    }
588                }
589            } else {
590                self.push_cdp_request(ContinueRequestParams::new(event.request_id.clone()))
591            }
592        }
593    }
594
595    #[cfg(feature = "adblock")]
596    pub fn on_fetch_request_paused(&mut self, event: &EventRequestPaused) {
597        if !self.user_request_interception_enabled && self.protocol_request_interception_enabled {
598            self.push_cdp_request(ContinueRequestParams::new(event.request_id.clone()))
599        } else {
600            if let Some(network_id) = event.network_id.as_ref() {
601                if let Some(request_will_be_sent) =
602                    self.requests_will_be_sent.remove(network_id.as_ref())
603                {
604                    self.on_request(&request_will_be_sent, Some(event.request_id.clone().into()));
605                } else {
606                    let current_url = event.request.url.as_str();
607                    let javascript_resource = event.resource_type == ResourceType::Script;
608                    let document_resource = event.resource_type == ResourceType::Document;
609                    let network_resource = !document_resource
610                        && (event.resource_type == ResourceType::Xhr
611                            || event.resource_type == ResourceType::Fetch
612                            || event.resource_type == ResourceType::WebSocket);
613
614                    // block all of these events.
615                    let skip_networking =
616                        IGNORE_NETWORKING_RESOURCE_MAP.contains(event.resource_type.as_ref());
617
618                    let skip_networking = skip_networking || self.document_reload_tracker >= 3;
619
620                    if document_resource {
621                        if self.document_target_domain == current_url {
622                            // this will prevent the domain from looping (3 times is enough).
623                            self.document_reload_tracker += 1;
624                        } else if !self.document_target_domain.is_empty()
625                            && event.redirected_request_id.is_some()
626                        {
627                            let (http_document_replacement, mut https_document_replacement) =
628                                if self.document_target_domain.starts_with("http://") {
629                                    (
630                                        self.document_target_domain.replace("http://", "http//"),
631                                        self.document_target_domain.replace("http://", "https://"),
632                                    )
633                                } else {
634                                    (
635                                        self.document_target_domain.replace("https://", "https//"),
636                                        self.document_target_domain.replace("https://", "http://"),
637                                    )
638                                };
639
640                            let trailing = https_document_replacement.ends_with('/');
641
642                            if trailing {
643                                https_document_replacement.pop();
644                            }
645
646                            if https_document_replacement.ends_with('/') {
647                                https_document_replacement.pop();
648                            }
649
650                            let redirect_mask = format!(
651                                "{}{}",
652                                https_document_replacement, http_document_replacement
653                            );
654
655                            // handle redirect masking
656                            if current_url == redirect_mask {
657                                replacer = Some(if trailing {
658                                    format!("{}/", https_document_replacement)
659                                } else {
660                                    https_document_replacement
661                                });
662                            }
663                        }
664                        self.document_target_domain = event.request.url.clone();
665                    }
666
667                    let current_url = match &replacer {
668                        Some(r) => r,
669                        _ => &event.request.url,
670                    }
671                    .as_str();
672
673                    // main initial check
674                    let skip_networking = if !skip_networking {
675                        self.ignore_visuals
676                            && (IGNORE_VISUAL_RESOURCE_MAP.contains(event.resource_type.as_ref()))
677                            || self.block_stylesheets
678                                && ResourceType::Stylesheet == event.resource_type
679                            || self.block_javascript
680                                && javascript_resource
681                                && self.intercept_manager == NetworkInterceptManager::Unknown
682                                && !ALLOWED_MATCHER.is_match(current_url)
683                    } else {
684                        skip_networking
685                    };
686
687                    let skip_networking = if !skip_networking {
688                        self.detect_ad(event)
689                    } else {
690                        skip_networking
691                    };
692
693                    let skip_networking = if !skip_networking
694                        && (self.only_html || self.ignore_visuals)
695                        && (javascript_resource || document_resource)
696                    {
697                        ignore_script_embedded(current_url)
698                    } else {
699                        skip_networking
700                    };
701
702                    // analytics check
703                    let skip_networking = if !skip_networking && javascript_resource {
704                        self.ignore_script(
705                            current_url,
706                            self.block_analytics,
707                            self.intercept_manager,
708                        )
709                    } else {
710                        skip_networking
711                    };
712
713                    // XHR check
714                    let skip_networking = self.skip_xhr(skip_networking, &event, network_resource);
715
716                    // custom interception layer.
717                    let skip_networking = if !skip_networking
718                        && (javascript_resource || network_resource || document_resource)
719                    {
720                        self.intercept_manager.intercept_detection(
721                            &event.request.url,
722                            self.ignore_visuals,
723                            network_resource,
724                        )
725                    } else {
726                        skip_networking
727                    };
728
729                    let skip_networking =
730                        if !skip_networking && (javascript_resource || network_resource) {
731                            block_website(&event.request.url)
732                        } else {
733                            skip_networking
734                        };
735
736                    if skip_networking {
737                        tracing::debug!("Blocked: {:?} - {}", event.resource_type, current_url);
738
739                        let fullfill_params =
740                            crate::handler::network::fetch::FulfillRequestParams::new(
741                                event.request_id.clone(),
742                                200,
743                            );
744                        self.push_cdp_request(fullfill_params);
745                    } else {
746                        tracing::debug!("Allowed: {:?} - {}", event.resource_type, current_url);
747
748                        let mut continue_params =
749                            ContinueRequestParams::new(event.request_id.clone());
750
751                        if replacer.is_some() {
752                            continue_params.url = Some(current_url.into());
753                            continue_params.intercept_response = Some(false);
754                        }
755                    }
756                }
757            } else {
758                self.push_cdp_request(ContinueRequestParams::new(event.request_id.clone()))
759            }
760        }
761
762        // if self.only_html {
763        //     self.made_request = true;
764        // }
765    }
766
767    /// Perform a page intercept for chrome
768    #[cfg(feature = "adblock")]
769    pub fn detect_ad(&self, event: &EventRequestPaused) -> bool {
770        use adblock::{
771            lists::{FilterSet, ParseOptions, RuleTypes},
772            Engine,
773        };
774
775        lazy_static::lazy_static! {
776            static ref AD_ENGINE: Engine = {
777                let mut filter_set = FilterSet::new(false);
778                let mut rules = ParseOptions::default();
779                rules.rule_types = RuleTypes::All;
780
781                filter_set.add_filters(
782                    &*crate::handler::blockers::adblock_patterns::ADBLOCK_PATTERNS,
783                    rules,
784                );
785
786                Engine::from_filter_set(filter_set, true)
787            };
788        };
789
790        let blockable = ResourceType::Image == event.resource_type
791            || event.resource_type == ResourceType::Media
792            || event.resource_type == ResourceType::Stylesheet
793            || event.resource_type == ResourceType::Document
794            || event.resource_type == ResourceType::Fetch
795            || event.resource_type == ResourceType::Xhr;
796
797        let u = &event.request.url;
798
799        let block_request = blockable
800            // set it to example.com for 3rd party handling is_same_site
801        && {
802            let request = adblock::request::Request::preparsed(
803                 &u,
804                 "example.com",
805                 "example.com",
806                 &event.resource_type.as_ref().to_lowercase(),
807                 !event.request.is_same_site.unwrap_or_default());
808
809            AD_ENGINE.check_network_request(&request).matched
810        };
811
812        block_request
813    }
814
815    pub fn on_fetch_auth_required(&mut self, event: &EventAuthRequired) {
816        let response = if self
817            .attempted_authentications
818            .contains(event.request_id.as_ref())
819        {
820            AuthChallengeResponseResponse::CancelAuth
821        } else if self.credentials.is_some() {
822            self.attempted_authentications
823                .insert(event.request_id.clone().into());
824            AuthChallengeResponseResponse::ProvideCredentials
825        } else {
826            AuthChallengeResponseResponse::Default
827        };
828
829        let mut auth = AuthChallengeResponse::new(response);
830        if let Some(creds) = self.credentials.clone() {
831            auth.username = Some(creds.username);
832            auth.password = Some(creds.password);
833        }
834        self.push_cdp_request(ContinueWithAuthParams::new(event.request_id.clone(), auth));
835    }
836
837    pub fn set_offline_mode(&mut self, value: bool) {
838        if self.offline == value {
839            return;
840        }
841        self.offline = value;
842        if let Ok(network) = EmulateNetworkConditionsParams::builder()
843            .offline(self.offline)
844            .latency(0)
845            .download_throughput(-1.)
846            .upload_throughput(-1.)
847            .build()
848        {
849            self.push_cdp_request(network);
850        }
851    }
852
853    /// Request interception doesn't happen for data URLs with Network Service.
854    pub fn on_request_will_be_sent(&mut self, event: &EventRequestWillBeSent) {
855        if self.protocol_request_interception_enabled && !event.request.url.starts_with("data:") {
856            if let Some(interception_id) = self
857                .request_id_to_interception_id
858                .remove(event.request_id.as_ref())
859            {
860                self.on_request(event, Some(interception_id));
861            } else {
862                // TODO remove the clone for event
863                self.requests_will_be_sent
864                    .insert(event.request_id.clone(), event.clone());
865            }
866        } else {
867            self.on_request(event, None);
868        }
869    }
870
871    pub fn on_request_served_from_cache(&mut self, event: &EventRequestServedFromCache) {
872        if let Some(request) = self.requests.get_mut(event.request_id.as_ref()) {
873            request.from_memory_cache = true;
874        }
875    }
876
877    pub fn on_response_received(&mut self, event: &EventResponseReceived) {
878        if let Some(mut request) = self.requests.remove(event.request_id.as_ref()) {
879            request.set_response(event.response.clone());
880            self.queued_events
881                .push_back(NetworkEvent::RequestFinished(request))
882        }
883    }
884
885    pub fn on_network_loading_finished(&mut self, event: &EventLoadingFinished) {
886        if let Some(request) = self.requests.remove(event.request_id.as_ref()) {
887            if let Some(interception_id) = request.interception_id.as_ref() {
888                self.attempted_authentications
889                    .remove(interception_id.as_ref());
890            }
891            self.queued_events
892                .push_back(NetworkEvent::RequestFinished(request));
893        }
894    }
895
896    pub fn on_network_loading_failed(&mut self, event: &EventLoadingFailed) {
897        if let Some(mut request) = self.requests.remove(event.request_id.as_ref()) {
898            request.failure_text = Some(event.error_text.clone());
899            if let Some(interception_id) = request.interception_id.as_ref() {
900                self.attempted_authentications
901                    .remove(interception_id.as_ref());
902            }
903            self.queued_events
904                .push_back(NetworkEvent::RequestFailed(request));
905        }
906    }
907
908    fn on_request(
909        &mut self,
910        event: &EventRequestWillBeSent,
911        interception_id: Option<InterceptionId>,
912    ) {
913        let mut redirect_chain = Vec::new();
914        let mut redirect_location = None;
915
916        if let Some(redirect_resp) = &event.redirect_response {
917            if let Some(mut request) = self.requests.remove(event.request_id.as_ref()) {
918                if is_redirect_status(redirect_resp.status) {
919                    if let Some(location) = redirect_resp.headers.inner()["Location"].as_str() {
920                        if redirect_resp.url != location {
921                            let fixed_location = location.replace(&redirect_resp.url, "");
922                            request.response.as_mut().map(|resp| {
923                                resp.headers.0["Location"] =
924                                    serde_json::Value::String(fixed_location.clone());
925                            });
926                            redirect_location = Some(fixed_location);
927                        }
928                    }
929                }
930
931                self.handle_request_redirect(
932                    &mut request,
933                    if let Some(redirect_location) = redirect_location {
934                        let mut redirect_resp = redirect_resp.clone();
935                        redirect_resp.headers.0["Location"] =
936                            serde_json::Value::String(redirect_location);
937                        redirect_resp
938                    } else {
939                        redirect_resp.clone()
940                    },
941                );
942
943                redirect_chain = std::mem::take(&mut request.redirect_chain);
944                redirect_chain.push(request);
945            }
946        }
947
948        let request = HttpRequest::new(
949            event.request_id.clone(),
950            event.frame_id.clone(),
951            interception_id,
952            self.user_request_interception_enabled,
953            redirect_chain,
954        );
955
956        self.requests.insert(event.request_id.clone(), request);
957        self.queued_events
958            .push_back(NetworkEvent::Request(event.request_id.clone()));
959    }
960
961    fn handle_request_redirect(&mut self, request: &mut HttpRequest, response: Response) {
962        request.set_response(response);
963        if let Some(interception_id) = request.interception_id.as_ref() {
964            self.attempted_authentications
965                .remove(interception_id.as_ref());
966        }
967    }
968}
969
970#[derive(Debug)]
971pub enum NetworkEvent {
972    SendCdpRequest((MethodId, serde_json::Value)),
973    Request(RequestId),
974    Response(RequestId),
975    RequestFailed(HttpRequest),
976    RequestFinished(HttpRequest),
977}