darkwing/server/services/browser_profile_services/
args.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
use either::Either;
use std::vec;

use crate::{
  database::browser_profile::Platform,
  server::dtos::{
    browser_profile_dto::{self, BrowserProfileFullData, Mode},
    settings_dto::{DISABLE_GPU, DISABLE_IMAGES},
    start_dto::{LoggingLevel, Os, StartRequest},
  },
};
use darkwing_derive::DarkwingArgs;

use super::config::BrowserProfileConfig;

struct List(Vec<String>);

impl std::fmt::Display for List {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    self.0.iter().enumerate().try_for_each(|(i, s)| {
      if i > 0 {
        write!(f, ",")?;
      }
      write!(f, "{}", s)
    })
  }
}

impl From<Vec<String>> for List {
  fn from(value: Vec<String>) -> Self {
    Self(value)
  }
}

impl List {
  pub fn new(value: Vec<String>) -> Self {
    Self(value)
  }

  #[cfg(test)]
  pub fn empty() -> Self {
    Self(Vec::new())
  }

  pub fn has(&self, value: &str) -> bool {
    self.0.contains(&value.to_string())
  }
}

trait IsEmpty {
  fn is_empty(&self) -> bool;
}

impl IsEmpty for List {
  fn is_empty(&self) -> bool {
    self.0.is_empty()
  }
}

impl IsEmpty for String {
  fn is_empty(&self) -> bool {
    self.is_empty()
  }
}

impl IsEmpty for Option<String> {
  fn is_empty(&self) -> bool {
    match self {
      Some(value) => value.is_empty(),
      None => true,
    }
  }
}

impl IsEmpty for Option<usize> {
  fn is_empty(&self) -> bool {
    self.is_none()
  }
}

impl IsEmpty for usize {
  fn is_empty(&self) -> bool {
    false
  }
}

trait DisplayAnything {
  fn to_string(&self) -> String;
}

impl DisplayAnything for Option<usize> {
  fn to_string(&self) -> String {
    match self {
      Some(v) => v.to_string(),
      None => "".to_string(),
    }
  }
}

impl DisplayAnything for Option<String> {
  fn to_string(&self) -> String {
    match self {
      Some(v) => v.to_string(),
      None => "".to_string(),
    }
  }
}

#[derive(PartialEq, Eq)]
enum Switch {
  On,
  Off,
}

impl Default for Switch {
  fn default() -> Self {
    Self::Off
  }
}

impl IsEmpty for Switch {
  fn is_empty(&self) -> bool {
    self == &Switch::Off
  }
}

impl DisplayAnything for Switch {
  fn to_string(&self) -> String {
    match self {
      Switch::On => "".to_string(),
      Switch::Off => "".to_string(),
    }
  }
}

impl Switch {
  fn from_bool(value: bool) -> Self {
    if value {
      Switch::On
    } else {
      Switch::Off
    }
  }
}

#[derive(DarkwingArgs)]
pub struct Args {
  /// Operation system of user's device. NOT the operation system that browser
  /// will emulate.
  ///
  /// Will be used to stringify args according to OS requirements, i.e. path
  /// separators (C:__\\__ Program Files on Windows, but **/** on *nix)
  ///
  /// This argument will NOT be serialized and is for internal use only.
  #[darkwing_args(internal)]
  user_os: Os,
  /// List of arguments that user passed to the browser.
  ///
  /// This argument will be joined at later stages of args serialization.
  #[darkwing_args(internal)]
  user_args: browser_profile_dto::Args,
  /// Directory of browser profile data.
  ///
  /// Most important subdirectory is "Default", which contains browser's
  /// cookies, cache, local storage, etc.
  #[darkwing_args(name = "user-data-dir")]
  browser_profile_datadir: String,
  /// Directory of our shared components.
  ///
  /// Contains browser's shared components, such as Widevine CDM libraries.
  /// They are pointless to copy into each browser profile, so we're putting
  /// them in one shared directory.
  #[darkwing_args(name = "dolphin-shared-dir")]
  dolphin_components_dir: String,
  /// List of so-called Chromium `features` to be enabled.
  ///
  /// See <https://chromium.googlesource.com/chromium/src/+/HEAD/docs/configuration.md>
  #[darkwing_args(name = "enable-features")]
  enable_features: List,
  /// List of so-called Chromium `features` to be disabled.
  #[darkwing_args(name = "disable-features")]
  disable_features: List,
  /// Logging target to be set for browser.
  ///
  /// If not set, logging will be disabled.
  ///
  /// If set to "stderr", logging will be enabled and logs will be printed to
  /// stderr.
  #[darkwing_args(name = "enable-logging")]
  enable_logging: Option<String>,
  /// Logging verbosity to be set for browser.
  /// Only works when enable_logging is set to "stderr".
  /// 0 - low amount of _debug_ logs (~5 lines per sec), 1 - fairly high amount
  /// of _debug_ logs (~100 per sec), 2 - very high amount of logs. 3 - very
  /// very high amount.
  #[darkwing_args(name = "v")]
  logging_verbosity: Option<usize>,
  /// Whether to disable backgrounding occluded windows.
  ///
  /// If set to `On`, browser will not be able to run in background.
  #[darkwing_args(name = "disable-backgrounding-occluded-windows")]
  disable_backgrounding_occluded_windows: Switch,
  /// Whether to disable web security.
  ///
  /// If set to `On`, some security features will be disabled, like CORS.
  #[darkwing_args(name = "disable-web-security")]
  disable_web_security: Switch,
  /// This switch is used to mark the beginning of a series of flag switches.
  ///
  /// It is used to mark the beginning of a series of flag switches.
  /// ** The switch MUST be set in correct order: flag_switches_begin must be
  /// set before flag_switches_end, and there must be ONLY flag switches
  /// between them **
  ///
  /// See <https://chromium.googlesource.com/chromium/src/+/HEAD/docs/configuration.md>
  #[darkwing_args(name = "flag-switches-begin")]
  flag_switches_begin: Switch,
  /// Whether to disable site isolation trials.
  ///
  /// _Trials_ are experiments that are launched by Google to test new
  /// features. If set to `On`, site isolation trial will be disabled. This
  /// affects web security.
  #[darkwing_args(name = "disable-site-isolation-trials")]
  disable_site_isolation_trials: Switch,
  /// This switch is used to mark the end of a series of flag switches.
  ///
  /// It is used to mark the end of a series of flag switches.
  /// ** The switch MUST be set in correct order: flag_switches_begin must be
  /// set before flag_switches_end, and there must be ONLY flag switches
  /// between them **
  ///
  /// See <https://chromium.googlesource.com/chromium/src/+/HEAD/docs/configuration.md>
  #[darkwing_args(name = "flag-switches-end")]
  flag_switches_end: Switch,
  /// Port to be used for our TCP server in browser.
  ///
  /// Currently this server is only used for browser shutdown: when someone
  /// initiates connection to this server, browser shuts down. In future this
  /// server will be used for more things, like window resizing, and this arg
  /// will be renamed.
  #[darkwing_args(name = "down-port")]
  down_port: usize,
  /// Port to be used for remote debugging.
  ///
  /// If not set, remote debugging will be disabled. If set to 0, remote
  /// debugging will be enabled on any free port.
  ///
  /// See <https://chromedevtools.github.io/devtools-protocol/>
  #[darkwing_args(name = "remote-debugging-port")]
  remote_debugging_port: Option<usize>,
  /// Origins to be allowed for remote debugging.
  ///
  /// If not set, no origins will be allowed for remote debugging.
  /// If set to "*", all origins will be allowed for remote debugging.
  #[darkwing_args(name = "remote-allow-origins")]
  remote_allow_origins: Option<String>,
  /// List of Blink (Chrome's rendering engine) features to be enabled.
  ///
  /// See <https://www.chromium.org/blink>
  #[darkwing_args(name = "enable-blink-features")]
  enable_blink_features: List,
  /// Whether to disable field trial config.
  ///
  /// Field trials are experiments that are launched by Google to test new
  /// features. If set to `On`, field trials will be disabled.
  #[darkwing_args(name = "disable-field-trial-config")]
  disable_field_trial_config: Switch,
  /// Locale to be used for browser.
  ///
  /// If not set, browser will use system locale. Most likely we want to set it
  /// to fingerprint locale.
  #[darkwing_args(name = "locale")]
  locale: String,
  /// User agent to be used for browser.
  ///
  /// If not set, browser will use default user agent.
  #[darkwing_args(name = "user-agent")]
  user_agent: Option<String>,
  /// Whether to run browser in headless mode.
  ///
  /// Chrome has two headless modes: old and new.
  /// We want to use new, because it offers more consistent behaviour across
  /// headless and headful mode. To set to new mode, just set this arg to
  /// `new`.
  #[darkwing_args(name = "headless")]
  headless: Option<String>,
  /// Whether to enable unsafe WebGPU.
  ///
  /// WebGPU is a technology that allows to accelerate GPU rendering.
  /// We DO NOT KNOW why this flag is used and this is subject to further
  /// research.
  #[darkwing_args(name = "enable-unsafe-webgpu")]
  enable_unsafe_webgpu: Switch,
  /// This flags changes browser extension id calculation method.
  /// It was used to slowly transfer all browser profiles to new id calculation
  /// method.
  #[darkwing_args(name = "new-extensions")]
  new_extensions: Switch,
  /// Disables WebRTC IP updater.
  ///
  /// WebRTC is a technology that allows to establish peer-to-peer connections
  /// between browsers. IP updater is a service that updates browser's IP
  /// address in WebRTC spoofing according to user's current IP.
  #[darkwing_args(name = "off-updater")]
  off_updater: Switch,
  /// Blink settings to be used for browser.
  ///
  /// Blink is Chrome's rendering engine.
  #[darkwing_args(name = "blink-settings")]
  blink_settings: Option<String>,
  /*

     @tltsutltsu: Я закомментировал эти аргументы, так как сейчас они добавляются в local-api.
     В будущем это может измениться.

  */
  // /// List of browser extensions to be loaded.
  // ///
  // /// This is standard Chromium flag. It will only _load_ extensions, like
  // if installed from Dev Mode. Not install them. #[darkwing_args(name =
  // "load-extension")] load_extension: List,
  // /// List of browser extensions to be installed.
  // ///
  // /// This is our custom Chromium flag. It will emulate installation of
  // browser extensions. /// Comment from browser code: `Comma-separated list
  // of paths to add extensions like from Chrome-settings`.
  // #[darkwing_args(name = "install-extension")]
  // install_extension: List,
  /// Disables WebGL completely.
  ///
  /// WebGL is a JavaScript API for rendering interactive 2D and 3D graphics.
  /// We want to disable it if WebGL spoof is set to disabled.
  #[darkwing_args(name = "disable-webgl")]
  disable_webgl: Switch,
  /// Disables GPU acceleration completely.
  ///
  /// GPU acceleration is a technology that allows to accelerate GPU rendering.
  /// We want to disable it if WebGL is disabled.
  #[darkwing_args(name = "disable-gpu")]
  disable_gpu: Switch,
  /// Proxy server to be used for browser.
  ///
  /// If not set, browser will use system proxy settings.
  /// Proxy here must be passed in `base64` encoding, where the username and
  /// password are base64-encoded, and sent in "password" field.
  #[darkwing_args(name = "proxy-server")]
  proxy_server: Option<String>,
  /// List of domains to bypass proxy.
  ///
  /// Currently we're using it to bypass `anty-api.com` domain from proxy.
  /// This domain is used by our extension to connect to our server, and some
  /// proxies forbid access to our domain.
  #[darkwing_args(name = "proxy-bypass-list")]
  proxy_bypass_list: Option<String>,
  /// Component updater toggle.
  ///
  /// Used for Widevine CDM updater. Must be enabled to enable Widevine.
  #[darkwing_args(name = "component-updater")]
  component_updater: String,
}

impl Args {
  fn make_enable_features(bp: &BrowserProfileFullData) -> List {
    let mut enable_features_vec = vec!["enable-tls13-early-data".into()];

    if bp.platform == Platform::Windows {
      enable_features_vec.push("SharedStorageAPI".into());
    }

    List::new(enable_features_vec)
  }

  fn make_disable_features(
    bp: &BrowserProfileFullData,
    request: &StartRequest,
    config: &BrowserProfileConfig,
  ) -> List {
    let mut disable_features =
      vec!["UseOsCryptAsyncForCookieEncryption".into()];

    if request.for_scenario {
      disable_features.push("IsolateOrigins".into());
      disable_features.push("site-per-process".into());
      disable_features.push("SitePerProcess".into());
    }

    if bp.platform == Platform::Windows {
      disable_features.push("kJavaScriptIteratorHelpers".into());
      disable_features.push("PrintCompositorLPAC".into());
    }

    if bp.webgl.mode == Mode::Off
      || bp.webgpu.mode == Mode::Off
      || (bp.webgpu.mode != Mode::Real && config.webgpu.is_none())
      || (bp.webgpu.mode == Mode::Empty && bp.webgl_info.mode != Mode::Real)
    {
      disable_features.push("WebGPU".into());
      disable_features.push("WebGPUService".into());
    }

    List::new(disable_features)
  }

  fn make_proxy_server(
    request: &StartRequest,
    bp: &BrowserProfileFullData,
  ) -> Option<String> {
    if let Some(override_proxy_url) =
      &request.connection_info.override_proxy_url
    {
      Some(override_proxy_url.clone())
    } else {
      bp.proxy.as_ref().map(|proxy| proxy.as_base64_url())
    }
  }

  fn make_user_proxy_bypass_list(
    bp: &BrowserProfileFullData,
  ) -> Option<Vec<String>> {
    let user_proxy_bypass_list = bp.args.0.clone().unwrap_or_default();
    let user_proxy_bypass_list = user_proxy_bypass_list
      .iter()
      .filter(|arg| arg.starts_with("proxy-bypass-list"));

    let proxy_bypass_list = user_proxy_bypass_list
      .filter_map(|arg| {
        arg
          .split('=')
          .nth(1)
          .map(|value| value.trim_matches('\"').to_string())
      })
      .collect::<Vec<String>>();

    let domains_list = proxy_bypass_list
      .iter()
      .flat_map(|arg| arg.split(';').map(|arg| arg.to_string()))
      .collect();

    Some(domains_list)
  }

  fn make_proxy_bypass_list(
    bp: &BrowserProfileFullData,
    request: &StartRequest,
    proxy_bypass_domains_list: Option<Vec<String>>,
  ) -> Option<String> {
    let mut full_list = vec![
      "*anty-api.com".to_string(),
      request.remote_api_base_url.clone(),
    ];
    full_list.extend(
      proxy_bypass_domains_list
        .unwrap_or_default()
        .iter()
        .cloned(),
    );

    if bp.proxy.is_none() {
      None
    } else {
      Some(full_list.join("; "))
    }
  }

  pub fn new(
    config: BrowserProfileConfig,
    bp: BrowserProfileFullData,
    request: StartRequest,
  ) -> Self {
    let enable_features = Self::make_enable_features(&bp);
    let disable_features = Self::make_disable_features(&bp, &request, &config);

    let (enable_logging, logging_verbosity) =
      if request.logging_level.clone() == LoggingLevel::Trace {
        (Some("stderr".into()), Some(1))
      } else {
        (None, None)
      };

    let disable_backgrounding_occluded_windows = Switch::from_bool(
      request.automation || request.for_scenario || request.scenum_custom_mode,
    );

    let (
      disable_web_security,
      flag_switches_begin,
      disable_site_isolation_trials,
      flag_switches_end,
    ) = if request.for_scenario {
      (Switch::On, Switch::On, Switch::On, Switch::On)
    } else {
      (Switch::Off, Switch::Off, Switch::Off, Switch::Off)
    };

    let (remote_debugging_port, remote_allow_origins) = if request.automation {
      (Some(0), Some("*".into()))
    } else {
      (None, None)
    };

    let enable_blink_features = List::new(vec![
      "SharedStorageAPI".into(),
      "FencedFrames".into(),
      "EnforceAnonymityExposure".into(),
      "Fledge".into(),
    ]);

    let headless = if request.headless {
      Some("new".into())
    } else {
      None
    };

    let enable_unsafe_webgpu = Switch::from_bool(
      request.os == Os::Windows
        && bp.webgl_info.mode != Mode::Real
        && !disable_features.has("WebGPU"),
    );

    let off_updater = Switch::from_bool(bp.webrtc.mode == Mode::Manual);

    let blink_settings = if request.imageless || bp.settings.any(DISABLE_IMAGES)
    {
      Some("imagesEnabled=false".into())
    } else {
      None
    };

    let disable_webgl = Switch::from_bool(
      bp.webgl_info.mode == Mode::Off || bp.webgl.mode == Mode::Off,
    );

    let disable_gpu = Switch::from_bool(
      bp.webgl_info.mode == Mode::Software || bp.settings.any(DISABLE_GPU),
    );

    let proxy_server = Self::make_proxy_server(&request, &bp);

    let proxy_bypass_domains_list = Self::make_user_proxy_bypass_list(&bp);
    let proxy_bypass_list =
      Self::make_proxy_bypass_list(&bp, &request, proxy_bypass_domains_list);

    Self {
      user_os: request.os,
      user_args: bp.args,
      browser_profile_datadir: request.paths.user_data_dir,
      dolphin_components_dir: request.paths.user_chromium_components_dir,
      enable_features,
      disable_features,
      enable_logging,
      logging_verbosity,
      disable_backgrounding_occluded_windows,
      disable_web_security,
      flag_switches_begin,
      disable_site_isolation_trials,
      flag_switches_end,
      down_port: request.browser_down_port as usize,
      remote_debugging_port,
      remote_allow_origins,
      enable_blink_features,
      disable_field_trial_config: Switch::On,
      locale: config.navigator.app_locale,
      user_agent: bp.useragent.value,
      headless,
      enable_unsafe_webgpu,
      new_extensions: Switch::On,
      off_updater,
      blink_settings,
      disable_webgl,
      disable_gpu,
      proxy_server,
      proxy_bypass_list,
      component_updater: "fast-update".into(),
    }
  }

  pub fn output(&self) -> Either<String, Vec<String>> {
    let args = self.stringify();

    if self.user_os == Os::Windows {
      let mut result = args
        .into_iter()
        .map(|(arg, value)| match value.is_empty() {
          true => arg,
          false => format!("{arg}={value}"),
        })
        .collect::<Vec<String>>();

      for arg in self.user_args.splitted() {
        result.push(arg);
      }

      Either::Right(result)
    } else {
      let our_args = args
        .into_iter()
        .map(|(arg, value)| match value.is_empty() {
          true => arg,
          false => format!(r#"{arg}="{value}""#),
        })
        .collect::<Vec<String>>()
        .join(" ");

      let user_args = self.user_args.join();

      Either::Left(format!("{} {}", our_args, user_args).trim().to_string())
    }
  }
}

#[cfg(test)]
mod tests {
  use crate::server::{
    dtos::proxy_dto::ProxyFullData,
    services::browser_profile_services::{
      BrowserProfileService, BrowserProfileServiceTrait,
    },
  };

  use super::*;

  #[test]
  fn test_list_display() {
    let list = List::new(vec!["a".into(), "b".into(), "c".into()]);
    assert_eq!(format!("{}", list), "a,b,c");
  }

  #[test]
  fn test_args_serialize() {
    let mut args = Args {
      user_os: Os::MacOS,
      user_args: browser_profile_dto::Args(None),
      browser_profile_datadir: "~/Library/Application Support/Google/Chrome"
        .into(),
      dolphin_components_dir: "~/Library/Application Support/Google/Chrome"
        .into(),
      enable_features: List::empty(),
      disable_features: List::empty(),
      enable_logging: Some("stderr".into()),
      logging_verbosity: Some(1),
      disable_backgrounding_occluded_windows: Switch::Off,
      disable_web_security: Switch::Off,
      flag_switches_begin: Switch::Off,
      disable_site_isolation_trials: Switch::Off,
      flag_switches_end: Switch::Off,
      down_port: 0,
      remote_debugging_port: None,
      remote_allow_origins: None,
      enable_blink_features: List::empty(),
      disable_field_trial_config: Switch::Off,
      locale: "en-US".into(),
      user_agent: None,
      headless: None,
      enable_unsafe_webgpu: Switch::Off,
      new_extensions: Switch::Off,
      off_updater: Switch::Off,
      blink_settings: None,
      disable_webgl: Switch::Off,
      disable_gpu: Switch::Off,
      proxy_server: None,
      proxy_bypass_list: None,
      component_updater: "fast-update".into(),
    };

    let expected = vec![
      (
        "--user-data-dir".into(),
        "~/Library/Application Support/Google/Chrome".into(),
      ),
      (
        "--dolphin-shared-dir".into(),
        "~/Library/Application Support/Google/Chrome".into(),
      ),
      ("--enable-logging".into(), "stderr".into()),
      ("--v".into(), "1".into()),
      ("--down-port".into(), "0".into()),
      ("--locale".into(), "en-US".into()),
      ("--component-updater".into(), "fast-update".into()),
    ];
    let serialized = args.stringify();

    assert_eq!(serialized, expected);

    args.enable_logging = None;
    args.logging_verbosity = None;
    let expected = vec![
      (
        "--user-data-dir".into(),
        "~/Library/Application Support/Google/Chrome".into(),
      ),
      (
        "--dolphin-shared-dir".into(),
        "~/Library/Application Support/Google/Chrome".into(),
      ),
      ("--down-port".into(), "0".into()),
      ("--locale".into(), "en-US".into()),
      ("--component-updater".into(), "fast-update".into()),
    ];
    let serialized = args.stringify();
    assert_eq!(serialized, expected);

    args.disable_backgrounding_occluded_windows = Switch::On;
    let expected = vec![
      (
        "--user-data-dir".into(),
        "~/Library/Application Support/Google/Chrome".into(),
      ),
      (
        "--dolphin-shared-dir".into(),
        "~/Library/Application Support/Google/Chrome".into(),
      ),
      ("--disable-backgrounding-occluded-windows".into(), "".into()),
      ("--down-port".into(), "0".into()),
      ("--locale".into(), "en-US".into()),
      ("--component-updater".into(), "fast-update".into()),
    ];
    let serialized = args.stringify();
    assert_eq!(serialized, expected);
  }

  #[test]
  fn test_args_output() {
    let mut args = Args {
      user_os: Os::MacOS,
      user_args: browser_profile_dto::Args(None),
      browser_profile_datadir: "~/Library/Application Support/Google/Chrome"
        .into(),
      dolphin_components_dir: "~/Library/Application Support/Google/Chrome"
        .into(),
      enable_features: List::empty(),
      disable_features: List::empty(),
      enable_logging: Some("stderr".into()),
      logging_verbosity: Some(1),
      disable_backgrounding_occluded_windows: Switch::Off,
      disable_web_security: Switch::Off,
      flag_switches_begin: Switch::Off,
      disable_site_isolation_trials: Switch::Off,
      flag_switches_end: Switch::Off,
      down_port: 0,
      remote_debugging_port: None,
      remote_allow_origins: None,
      enable_blink_features: List::empty(),
      disable_field_trial_config: Switch::Off,
      locale: "en-US".into(),
      user_agent: None,
      headless: None,
      enable_unsafe_webgpu: Switch::Off,
      new_extensions: Switch::Off,
      off_updater: Switch::Off,
      blink_settings: None,
      disable_webgl: Switch::Off,
      disable_gpu: Switch::Off,
      proxy_server: None,
      proxy_bypass_list: None,
      component_updater: "fast-update".into(),
    };

    let expected =
      r#"--user-data-dir="~/Library/Application Support/Google/Chrome"
--dolphin-shared-dir="~/Library/Application Support/Google/Chrome"
--enable-logging="stderr"
--v="1"
--down-port="0"
--locale="en-US"
--component-updater="fast-update""#
        .replace('\n', " ");

    assert_eq!(args.output(), Either::Left(expected));

    args.disable_backgrounding_occluded_windows = Switch::On;
    let expected =
      r#"--user-data-dir="~/Library/Application Support/Google/Chrome"
--dolphin-shared-dir="~/Library/Application Support/Google/Chrome"
--enable-logging="stderr"
--v="1"
--disable-backgrounding-occluded-windows
--down-port="0"
--locale="en-US"
--component-updater="fast-update""#
        .replace('\n', " ");

    assert_eq!(args.output(), Either::Left(expected));
  }

  #[test]
  fn test_make_user_proxy_bypass_list() {
    // Test case 1: No proxy-bypass-list arguments
    let mut bp = BrowserProfileService::get_mock_profile(Os::MacOS);
    bp.args = browser_profile_dto::Args(Some(vec![
      "some-arg=value".to_string(),
      "another-arg".to_string(),
    ]));
    assert_eq!(Args::make_user_proxy_bypass_list(&bp), Some(vec![]));

    // Test case 2: Single proxy-bypass-list argument
    let mut bp = BrowserProfileService::get_mock_profile(Os::MacOS);
    bp.args = browser_profile_dto::Args(Some(vec![
      "proxy-bypass-list=example.com".to_string(),
    ]));
    assert_eq!(
      Args::make_user_proxy_bypass_list(&bp),
      Some(vec!["example.com".to_string()])
    );

    // Test case 3: Multiple proxy-bypass-list arguments
    let mut bp = BrowserProfileService::get_mock_profile(Os::MacOS);
    bp.args = browser_profile_dto::Args(Some(vec![
      "proxy-bypass-list=example.com".to_string(),
      "proxy-bypass-list=test.com;another.com".to_string(),
    ]));
    assert_eq!(
      Args::make_user_proxy_bypass_list(&bp),
      Some(vec![
        "example.com".to_string(),
        "test.com".to_string(),
        "another.com".to_string()
      ])
    );

    // Test case 4: Proxy-bypass-list with quoted values
    let mut bp = BrowserProfileService::get_mock_profile(Os::MacOS);
    bp.args = browser_profile_dto::Args(Some(vec![
      r#"proxy-bypass-list="example.com;test.com""#.to_string(),
    ]));
    assert_eq!(
      Args::make_user_proxy_bypass_list(&bp),
      Some(vec!["example.com".to_string(), "test.com".to_string()])
    );

    // Test case 5: Mixed arguments
    let mut bp = BrowserProfileService::get_mock_profile(Os::MacOS);
    bp.args = browser_profile_dto::Args(Some(vec![
      "some-arg=value".to_string(),
      "proxy-bypass-list=example.com".to_string(),
      "another-arg".to_string(),
      r#"proxy-bypass-list="test.com;another.com""#.to_string(),
    ]));
    assert_eq!(
      Args::make_user_proxy_bypass_list(&bp),
      Some(vec![
        "example.com".to_string(),
        "test.com".to_string(),
        "another.com".to_string()
      ])
    );
  }

  #[test]
  fn test_make_proxy_bypass_list() {
    let mut request = StartRequest::get_mock();
    request.remote_api_base_url = "https://api.example.com".to_string();

    // Test case 1: No proxy set
    let mut bp = BrowserProfileService::get_mock_profile(Os::MacOS);
    bp.proxy = None;
    let result = Args::make_proxy_bypass_list(&bp, &request, None);
    assert_eq!(result, None);

    // Test case 2: Proxy set, no additional domains
    bp.proxy = Some(ProxyFullData::get_mock());
    let result = Args::make_proxy_bypass_list(&bp, &request, None);
    assert_eq!(
      result,
      Some("*anty-api.com; https://api.example.com".to_string())
    );

    // Test case 3: Proxy set, with additional domains
    let additional_domains =
      Some(vec!["test.com".to_string(), "example.org".to_string()]);
    let result =
      Args::make_proxy_bypass_list(&bp, &request, additional_domains);
    assert_eq!(
      result,
      Some(
        "*anty-api.com; https://api.example.com; test.com; example.org"
          .to_string()
      )
    );

    // Test case 4: Proxy set, with empty additional domains
    let result = Args::make_proxy_bypass_list(&bp, &request, Some(vec![]));
    assert_eq!(
      result,
      Some("*anty-api.com; https://api.example.com".to_string())
    );

    // Test case 5: Proxy set, with duplicate domains
    let additional_domains =
      Some(vec!["*anty-api.com".to_string(), "test.com".to_string()]);
    let result =
      Args::make_proxy_bypass_list(&bp, &request, additional_domains);
    assert_eq!(
      result,
      Some(
        "*anty-api.com; https://api.example.com; *anty-api.com; test.com"
          .to_string()
      )
    );
  }

  #[test]
  fn test_user_custom_args() {
    let request = StartRequest::get_mock();

    let mut bp = BrowserProfileService::get_mock_profile(Os::MacOS);

    let config =
      BrowserProfileService::create_config(&bp, request.clone(), "".into())
        .unwrap();

    bp.args = browser_profile_dto::Args(Some(vec!["--test-arg".to_string()]));

    let args = Args::new(config, bp, request);
    assert_eq!(args.user_args.splitted(), ["--test-arg"]);
  }
}