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    };
112
113    /// Ignore the resources for visual content types.
114    pub static ref IGNORE_VISUAL_RESOURCE_MAP: phf::Set<&'static str> = phf::phf_set! {
115        "Image",
116        "Media",
117        "Font"
118    };
119
120    /// Ignore the resources for visual content types.
121    pub static ref IGNORE_NETWORKING_RESOURCE_MAP: phf::Set<&'static str> = phf::phf_set! {
122        "CspViolationReport",
123        "Manifest",
124        "Other",
125        "Prefetch",
126        "Ping",
127    };
128
129    /// Case insenstive css matching
130    pub static ref CSS_EXTENSION: CaseInsensitiveString = CaseInsensitiveString::from("css");
131
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#[derive(Debug)]
169pub struct NetworkManager {
170    queued_events: VecDeque<NetworkEvent>,
171    ignore_httpserrors: bool,
172    requests: HashMap<RequestId, HttpRequest>,
173    // TODO put event in an Arc?
174    requests_will_be_sent: HashMap<RequestId, EventRequestWillBeSent>,
175    extra_headers: std::collections::HashMap<String, String>,
176    request_id_to_interception_id: HashMap<RequestId, InterceptionId>,
177    user_cache_disabled: bool,
178    attempted_authentications: HashSet<RequestId>,
179    credentials: Option<Credentials>,
180    // unused atm for remote connections, needs to be used for self launches.
181    user_request_interception_enabled: bool,
182    protocol_request_interception_enabled: bool,
183    offline: bool,
184    request_timeout: Duration,
185    // made_request: bool,
186    /// Ignore visuals (no pings, prefetching, and etc).
187    pub ignore_visuals: bool,
188    /// Block CSS stylesheets.
189    pub block_stylesheets: bool,
190    /// Block javascript that is not critical to rendering.
191    pub block_javascript: bool,
192    /// Block analytics from rendering
193    pub block_analytics: bool,
194    /// Only html from loading.
195    pub only_html: bool,
196    /// The custom intercept handle logic to run on the website.
197    pub intercept_manager: NetworkInterceptManager,
198    /// Track the amount of times the document reloaded.
199    pub document_reload_tracker: u8,
200    /// The initial target domain.
201    pub document_target_domain: String,
202}
203
204impl NetworkManager {
205    pub fn new(ignore_httpserrors: bool, request_timeout: Duration) -> Self {
206        Self {
207            queued_events: Default::default(),
208            ignore_httpserrors,
209            requests: Default::default(),
210            requests_will_be_sent: Default::default(),
211            extra_headers: Default::default(),
212            request_id_to_interception_id: Default::default(),
213            user_cache_disabled: false,
214            attempted_authentications: Default::default(),
215            credentials: None,
216            user_request_interception_enabled: false,
217            protocol_request_interception_enabled: false,
218            offline: false,
219            request_timeout,
220            ignore_visuals: false,
221            block_javascript: false,
222            block_stylesheets: false,
223            block_analytics: true,
224            only_html: false,
225            intercept_manager: NetworkInterceptManager::Unknown,
226            document_reload_tracker: 0,
227            document_target_domain: String::new(),
228        }
229    }
230
231    pub fn init_commands(&self) -> CommandChain {
232        let cmds = if self.ignore_httpserrors {
233            INIT_CHAIN_IGNORE_HTTP_ERRORS.clone()
234        } else {
235            INIT_CHAIN.clone()
236        };
237
238        CommandChain::new(cmds, self.request_timeout)
239    }
240
241    fn push_cdp_request<T: Command>(&mut self, cmd: T) {
242        let method = cmd.identifier();
243        if let Ok(params) = serde_json::to_value(cmd) {
244            self.queued_events
245                .push_back(NetworkEvent::SendCdpRequest((method, params)));
246        }
247    }
248
249    /// The next event to handle
250    pub fn poll(&mut self) -> Option<NetworkEvent> {
251        self.queued_events.pop_front()
252    }
253
254    pub fn extra_headers(&self) -> &std::collections::HashMap<String, String> {
255        &self.extra_headers
256    }
257
258    pub fn set_extra_headers(&mut self, headers: std::collections::HashMap<String, String>) {
259        self.extra_headers = headers;
260        self.extra_headers.remove(PROXY_AUTHORIZATION.as_str());
261        if let Ok(headers) = serde_json::to_value(&self.extra_headers) {
262            self.push_cdp_request(SetExtraHttpHeadersParams::new(Headers::new(headers)));
263        }
264    }
265
266    pub fn set_service_worker_enabled(&mut self, bypass: bool) {
267        self.push_cdp_request(SetBypassServiceWorkerParams::new(bypass));
268    }
269
270    pub fn set_request_interception(&mut self, enabled: bool) {
271        self.user_request_interception_enabled = enabled;
272        self.update_protocol_request_interception();
273    }
274
275    pub fn set_cache_enabled(&mut self, enabled: bool) {
276        self.user_cache_disabled = !enabled;
277        self.update_protocol_cache_disabled();
278    }
279
280    pub fn update_protocol_cache_disabled(&mut self) {
281        self.push_cdp_request(SetCacheDisabledParams::new(
282            self.user_cache_disabled || self.protocol_request_interception_enabled,
283        ));
284    }
285
286    pub fn authenticate(&mut self, credentials: Credentials) {
287        self.credentials = Some(credentials);
288        self.update_protocol_request_interception()
289    }
290
291    fn update_protocol_request_interception(&mut self) {
292        let enabled = self.user_request_interception_enabled || self.credentials.is_some();
293
294        if enabled == self.protocol_request_interception_enabled {
295            return;
296        }
297
298        self.update_protocol_cache_disabled();
299
300        if enabled {
301            self.push_cdp_request(ENABLE_FETCH.clone())
302        } else {
303            self.push_cdp_request(DisableParams::default())
304        }
305    }
306
307    /// Url matches analytics that we want to ignore or trackers.
308    pub(crate) fn ignore_script(
309        &self,
310        url: &str,
311        block_analytics: bool,
312        intercept_manager: NetworkInterceptManager,
313    ) -> bool {
314        let mut ignore_script = block_analytics && URL_IGNORE_TRIE.contains_prefix(url);
315
316        if !ignore_script {
317            if let Some(index) = url.find("//") {
318                let pos = index + 2;
319
320                // Ensure there is something after `//`
321                if pos < url.len() {
322                    // Find the first slash after the `//`
323                    if let Some(slash_index) = url[pos..].find('/') {
324                        let base_path_index = pos + slash_index + 1;
325
326                        if url.len() > base_path_index {
327                            let new_url: &str = &url[base_path_index..];
328
329                            ignore_script = URL_IGNORE_TRIE_PATHS.contains_prefix(new_url);
330
331                            // ignore assets we do not need for frameworks
332                            if !ignore_script
333                                && intercept_manager == NetworkInterceptManager::Unknown
334                            {
335                                let hydration_file =
336                                    JS_FRAMEWORK_PATH.iter().any(|p| new_url.starts_with(p));
337
338                                // ignore astro paths
339                                if hydration_file && new_url.ends_with(".js") {
340                                    ignore_script = true;
341                                }
342                            }
343
344                            if !ignore_script
345                                && URL_IGNORE_SCRIPT_BASE_PATHS.contains_prefix(new_url)
346                            {
347                                ignore_script = true;
348                            }
349
350                            if !ignore_script
351                                && self.ignore_visuals
352                                && URL_IGNORE_SCRIPT_STYLES_PATHS.contains_prefix(new_url)
353                            {
354                                ignore_script = true;
355                            }
356                        }
357                    }
358                }
359            }
360        }
361
362        // fallback for file ending in analytics.js
363        if !ignore_script {
364            ignore_script = url.ends_with("analytics.js")
365                || url.ends_with("ads.js")
366                || url.ends_with("tracking.js")
367                || url.ends_with("track.js");
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
456                    if document_resource {
457                        if self.document_target_domain == current_url {
458                            // this will prevent the domain from looping (3 times is enough).
459                            self.document_reload_tracker += 1;
460                        }
461                        self.document_target_domain = event.request.url.clone();
462                    }
463
464                    // main initial check
465                    let skip_networking = if !skip_networking {
466                        self.ignore_visuals
467                            && (IGNORE_VISUAL_RESOURCE_MAP.contains(event.resource_type.as_ref()))
468                            || self.block_stylesheets
469                                && ResourceType::Stylesheet == event.resource_type
470                            || self.block_javascript
471                                && javascript_resource
472                                && self.intercept_manager == NetworkInterceptManager::Unknown
473                                && !ALLOWED_MATCHER.is_match(current_url)
474                    } else {
475                        skip_networking
476                    };
477
478                    let skip_networking = if !skip_networking
479                        && (self.only_html || self.ignore_visuals)
480                        && (javascript_resource || document_resource)
481                    {
482                        ignore_script_embedded(current_url)
483                    } else {
484                        skip_networking
485                    };
486
487                    // analytics check
488                    let skip_networking = if !skip_networking && javascript_resource {
489                        self.ignore_script(
490                            current_url,
491                            self.block_analytics,
492                            self.intercept_manager,
493                        )
494                    } else {
495                        skip_networking
496                    };
497
498                    // XHR check
499                    let skip_networking = self.skip_xhr(skip_networking, &event, network_resource);
500
501                    // custom interception layer.
502                    let skip_networking = if !skip_networking
503                        && (javascript_resource || network_resource || document_resource)
504                    {
505                        self.intercept_manager.intercept_detection(
506                            &event.request.url,
507                            self.ignore_visuals,
508                            network_resource,
509                        )
510                    } else {
511                        skip_networking
512                    };
513
514                    let skip_networking =
515                        if !skip_networking && (javascript_resource || network_resource) {
516                            block_website(&event.request.url)
517                        } else {
518                            skip_networking
519                        };
520
521                    if skip_networking {
522                        tracing::debug!(
523                            "Blocked: {:?} - {}",
524                            event.resource_type,
525                            event.request.url
526                        );
527                        let fullfill_params =
528                            crate::handler::network::fetch::FulfillRequestParams::new(
529                                event.request_id.clone(),
530                                200,
531                            );
532                        self.push_cdp_request(fullfill_params);
533                    } else {
534                        tracing::debug!(
535                            "Allowed: {:?} - {}",
536                            event.resource_type,
537                            event.request.url
538                        );
539
540                        self.push_cdp_request(ContinueRequestParams::new(event.request_id.clone()))
541                    }
542                }
543            } else {
544                self.push_cdp_request(ContinueRequestParams::new(event.request_id.clone()))
545            }
546        }
547    }
548
549    #[cfg(feature = "adblock")]
550    pub fn on_fetch_request_paused(&mut self, event: &EventRequestPaused) {
551        if !self.user_request_interception_enabled && self.protocol_request_interception_enabled {
552            self.push_cdp_request(ContinueRequestParams::new(event.request_id.clone()))
553        } else {
554            if let Some(network_id) = event.network_id.as_ref() {
555                if let Some(request_will_be_sent) =
556                    self.requests_will_be_sent.remove(network_id.as_ref())
557                {
558                    self.on_request(&request_will_be_sent, Some(event.request_id.clone().into()));
559                } else {
560                    let current_url = event.request.url.as_str();
561                    let javascript_resource = event.resource_type == ResourceType::Script;
562                    let document_resource = event.resource_type == ResourceType::Document;
563                    let network_resource = !document_resource
564                        && (event.resource_type == ResourceType::Xhr
565                            || event.resource_type == ResourceType::Fetch
566                            || event.resource_type == ResourceType::WebSocket);
567
568                    // block all of these events.
569                    let skip_networking =
570                        IGNORE_NETWORKING_RESOURCE_MAP.contains(event.resource_type.as_ref());
571
572                    let skip_networking = skip_networking || self.document_reload_tracker >= 3;
573
574                    if document_resource {
575                        if self.document_target_domain == current_url {
576                            // this will prevent the domain from looping (3 times is enough).
577                            self.document_reload_tracker += 1;
578                        }
579                        self.document_target_domain = event.request.url.clone();
580                    }
581
582                    // main initial check
583                    let skip_networking = if !skip_networking {
584                        self.ignore_visuals
585                            && (IGNORE_VISUAL_RESOURCE_MAP.contains(event.resource_type.as_ref()))
586                            || self.block_stylesheets
587                                && ResourceType::Stylesheet == event.resource_type
588                            || self.block_javascript
589                                && javascript_resource
590                                && self.intercept_manager == NetworkInterceptManager::Unknown
591                                && !ALLOWED_MATCHER.is_match(current_url)
592                    } else {
593                        skip_networking
594                    };
595
596                    let skip_networking = if !skip_networking {
597                        self.detect_ad(event)
598                    } else {
599                        skip_networking
600                    };
601
602                    let skip_networking = if !skip_networking
603                        && (self.only_html || self.ignore_visuals)
604                        && (javascript_resource || document_resource)
605                    {
606                        ignore_script_embedded(current_url)
607                    } else {
608                        skip_networking
609                    };
610
611                    // analytics check
612                    let skip_networking = if !skip_networking && javascript_resource {
613                        self.ignore_script(
614                            current_url,
615                            self.block_analytics,
616                            self.intercept_manager,
617                        )
618                    } else {
619                        skip_networking
620                    };
621
622                    // XHR check
623                    let skip_networking = self.skip_xhr(skip_networking, &event, network_resource);
624
625                    // custom interception layer.
626                    let skip_networking = if !skip_networking
627                        && (javascript_resource || network_resource || document_resource)
628                    {
629                        self.intercept_manager.intercept_detection(
630                            &event.request.url,
631                            self.ignore_visuals,
632                            network_resource,
633                        )
634                    } else {
635                        skip_networking
636                    };
637
638                    let skip_networking =
639                        if !skip_networking && (javascript_resource || network_resource) {
640                            block_website(&event.request.url)
641                        } else {
642                            skip_networking
643                        };
644
645                    if skip_networking {
646                        let fullfill_params =
647                            crate::handler::network::fetch::FulfillRequestParams::new(
648                                event.request_id.clone(),
649                                200,
650                            );
651                        self.push_cdp_request(fullfill_params);
652                    } else {
653                        self.push_cdp_request(ContinueRequestParams::new(event.request_id.clone()))
654                    }
655                }
656            }
657        }
658
659        // if self.only_html {
660        //     self.made_request = true;
661        // }
662    }
663
664    /// Perform a page intercept for chrome
665    #[cfg(feature = "adblock")]
666    pub fn detect_ad(&self, event: &EventRequestPaused) -> bool {
667        use adblock::{
668            lists::{FilterSet, ParseOptions, RuleTypes},
669            Engine,
670        };
671
672        lazy_static::lazy_static! {
673            static ref AD_ENGINE: Engine = {
674                let mut filter_set = FilterSet::new(false);
675                let mut rules = ParseOptions::default();
676                rules.rule_types = RuleTypes::All;
677
678                filter_set.add_filters(
679                    &*crate::handler::blockers::adblock_patterns::ADBLOCK_PATTERNS,
680                    rules,
681                );
682
683                Engine::from_filter_set(filter_set, true)
684            };
685        };
686
687        let blockable = ResourceType::Image == event.resource_type
688            || event.resource_type == ResourceType::Media
689            || event.resource_type == ResourceType::Stylesheet
690            || event.resource_type == ResourceType::Document
691            || event.resource_type == ResourceType::Fetch
692            || event.resource_type == ResourceType::Xhr;
693
694        let u = &event.request.url;
695
696        let block_request = blockable
697            // set it to example.com for 3rd party handling is_same_site
698        && {
699            let request = adblock::request::Request::preparsed(
700                 &u,
701                 "example.com",
702                 "example.com",
703                 &event.resource_type.as_ref().to_lowercase(),
704                 !event.request.is_same_site.unwrap_or_default());
705
706            AD_ENGINE.check_network_request(&request).matched
707        };
708
709        block_request
710    }
711
712    pub fn on_fetch_auth_required(&mut self, event: &EventAuthRequired) {
713        let response = if self
714            .attempted_authentications
715            .contains(event.request_id.as_ref())
716        {
717            AuthChallengeResponseResponse::CancelAuth
718        } else if self.credentials.is_some() {
719            self.attempted_authentications
720                .insert(event.request_id.clone().into());
721            AuthChallengeResponseResponse::ProvideCredentials
722        } else {
723            AuthChallengeResponseResponse::Default
724        };
725
726        let mut auth = AuthChallengeResponse::new(response);
727        if let Some(creds) = self.credentials.clone() {
728            auth.username = Some(creds.username);
729            auth.password = Some(creds.password);
730        }
731        self.push_cdp_request(ContinueWithAuthParams::new(event.request_id.clone(), auth));
732    }
733
734    pub fn set_offline_mode(&mut self, value: bool) {
735        if self.offline == value {
736            return;
737        }
738        self.offline = value;
739        if let Ok(network) = EmulateNetworkConditionsParams::builder()
740            .offline(self.offline)
741            .latency(0)
742            .download_throughput(-1.)
743            .upload_throughput(-1.)
744            .build()
745        {
746            self.push_cdp_request(network);
747        }
748    }
749
750    /// Request interception doesn't happen for data URLs with Network Service.
751    pub fn on_request_will_be_sent(&mut self, event: &EventRequestWillBeSent) {
752        if self.protocol_request_interception_enabled && !event.request.url.starts_with("data:") {
753            if let Some(interception_id) = self
754                .request_id_to_interception_id
755                .remove(event.request_id.as_ref())
756            {
757                self.on_request(event, Some(interception_id));
758            } else {
759                // TODO remove the clone for event
760                self.requests_will_be_sent
761                    .insert(event.request_id.clone(), event.clone());
762            }
763        } else {
764            self.on_request(event, None);
765        }
766    }
767
768    pub fn on_request_served_from_cache(&mut self, event: &EventRequestServedFromCache) {
769        if let Some(request) = self.requests.get_mut(event.request_id.as_ref()) {
770            request.from_memory_cache = true;
771        }
772    }
773
774    pub fn on_response_received(&mut self, event: &EventResponseReceived) {
775        if let Some(mut request) = self.requests.remove(event.request_id.as_ref()) {
776            request.set_response(event.response.clone());
777            self.queued_events
778                .push_back(NetworkEvent::RequestFinished(request))
779        }
780    }
781
782    pub fn on_network_loading_finished(&mut self, event: &EventLoadingFinished) {
783        if let Some(request) = self.requests.remove(event.request_id.as_ref()) {
784            if let Some(interception_id) = request.interception_id.as_ref() {
785                self.attempted_authentications
786                    .remove(interception_id.as_ref());
787            }
788            self.queued_events
789                .push_back(NetworkEvent::RequestFinished(request));
790        }
791    }
792
793    pub fn on_network_loading_failed(&mut self, event: &EventLoadingFailed) {
794        if let Some(mut request) = self.requests.remove(event.request_id.as_ref()) {
795            request.failure_text = Some(event.error_text.clone());
796            if let Some(interception_id) = request.interception_id.as_ref() {
797                self.attempted_authentications
798                    .remove(interception_id.as_ref());
799            }
800            self.queued_events
801                .push_back(NetworkEvent::RequestFailed(request));
802        }
803    }
804
805    fn on_request(
806        &mut self,
807        event: &EventRequestWillBeSent,
808        interception_id: Option<InterceptionId>,
809    ) {
810        let mut redirect_chain = Vec::new();
811        if let Some(redirect_resp) = event.redirect_response.as_ref() {
812            if let Some(mut request) = self.requests.remove(event.request_id.as_ref()) {
813                self.handle_request_redirect(&mut request, redirect_resp.clone());
814                redirect_chain = std::mem::take(&mut request.redirect_chain);
815                redirect_chain.push(request);
816            }
817        }
818        let request = HttpRequest::new(
819            event.request_id.clone(),
820            event.frame_id.clone(),
821            interception_id,
822            self.user_request_interception_enabled,
823            redirect_chain,
824        );
825
826        self.requests.insert(event.request_id.clone(), request);
827        self.queued_events
828            .push_back(NetworkEvent::Request(event.request_id.clone()));
829    }
830
831    fn handle_request_redirect(&mut self, request: &mut HttpRequest, response: Response) {
832        request.set_response(response);
833        if let Some(interception_id) = request.interception_id.as_ref() {
834            self.attempted_authentications
835                .remove(interception_id.as_ref());
836        }
837    }
838}
839
840#[derive(Debug)]
841pub enum NetworkEvent {
842    SendCdpRequest((MethodId, serde_json::Value)),
843    Request(RequestId),
844    Response(RequestId),
845    RequestFailed(HttpRequest),
846    RequestFinished(HttpRequest),
847}