darkwing/server/services/browser_profile_services/config/
navigator.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
//! Navigator configuration module for browser profiles.
//!
//! This module handles browser navigator properties like user agent, platform
//! info, language settings, and other browser-specific details that are exposed
//! through the Navigator Web API.

use crate::{
  database::browser_profile::Platform,
  server::{
    dtos::{
      browser_profile_dto::{BrowserProfileFullData, Mode},
      start_dto::{self, ConnectionInfo, StartRequest},
    },
    error::Error,
  },
};
use serde::{Deserialize, Serialize};

use super::{
  consts::{
    COUNTRY_LOCALE_MAP, LATEST_CHROME_VERSION, LINUX_ACCEPTABLE_LOCALES,
    MACOS_ACCEPTABLE_LOCALES, WINDOWS_ACCEPTABLE_LOCALES,
  },
  FromStartRequest, Screen,
};

/// Represents network connection information exposed by the browser.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct Connection {
  /// Effective bandwidth estimate in Mbps
  pub downlink: f32,
  /// Connection type (e.g. "4g", "3g", etc)
  pub effective_type: String,
  /// Round trip time estimate in milliseconds
  pub rtt: i16,
  /// Whether the user has requested reduced data usage
  pub save_data: bool,
}

/// Represents browser navigator properties exposed through the Navigator Web
/// API.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct Navigator {
  /// Internal "Mozilla" code name for compatibility
  pub app_code_name: String,
  /// Application name ("Netscape" for compatibility)
  pub app_name: String,
  /// Network connection information
  pub connection: Connection,
  /// Amount of device memory in GB
  pub device_memory: i32,
  /// Whether Do Not Track is enabled
  pub do_not_track: bool,
  /// Number of logical processors
  pub hardware_concurrency: i32,
  /// Application locale setting
  pub app_locale: String,
  /// Browser UI locale
  pub locale: String,
  /// List of preferred languages
  pub languages: Vec<String>,
  /// Accept-Languages HTTP header value
  pub accept_languages: String,
  /// Platform/OS identifier
  pub platform: String,
  /// Product name ("Gecko")
  pub product: String,
  /// Product sub-identifier
  pub product_sub: String,
  /// Browser user agent string
  pub user_agent: String,
  /// Browser vendor name
  pub vendor: String,
  /// Browser vendor sub-identifier
  pub vendor_sub: String,
  /// User's timezone
  pub timezone: String,
}

impl Navigator {
  /// Creates the Accept-Languages header value from a locale string.
  ///
  /// # Arguments
  /// * `locale` - Locale string in format "language-REGION" (e.g. "en-US")
  ///
  /// # Returns
  /// Formatted Accept-Languages string with quality values
  pub fn make_accept_languages(locale: String) -> String {
    let mut split = locale.split('-');

    let language = split.next().unwrap_or("en").to_lowercase();
    let region = split.next().unwrap_or("US").to_uppercase();

    if language == *"en" {
      format!("en-{region},en;q=0.9")
    } else {
      format!("{language}-{region},{language};q=0.9;en-US,en;q=0.8")
    }
  }

  /// Creates the list of preferred languages from a locale string.
  ///
  /// # Arguments
  /// * `locale` - Locale string in format "language-REGION"
  ///
  /// # Returns
  /// Vector of language tags in descending order of preference
  pub fn make_languages(locale: String) -> Vec<String> {
    let mut split = locale.split('-');

    let language = split.next().unwrap_or("en").to_lowercase();
    let region = split.next().unwrap_or("US").to_uppercase();

    if language == *"en" {
      vec![format!("{language}-{region}"), "en".into()]
    } else {
      vec![
        format!("{language}-{region}"),
        language,
        "en-US".into(),
        "en".into(),
      ]
    }
  }

  /// Detects appropriate locale from a country code.
  ///
  /// # Arguments
  /// * `country_code` - Two-letter country code (e.g. "US")
  ///
  /// # Returns
  /// Locale string for the country, defaulting to "en-US" if not found
  pub fn detect_locale_from_country_code(country_code: String) -> String {
    for locale in COUNTRY_LOCALE_MAP {
      if locale.to_lowercase().contains(&country_code.to_lowercase()) {
        return locale.to_string();
      }
    }

    "en-US".into()
  }

  /// Prepares the locale based on profile settings and request info.
  ///
  /// # Arguments
  /// * `bp` - Browser profile data
  /// * `request` - Start request containing connection info
  ///
  /// # Returns
  /// Result containing the determined locale string
  pub fn prepare_locale(
    bp: &BrowserProfileFullData,
    request: &StartRequest,
  ) -> Result<String, Error> {
    match (bp.locale.mode, bp.locale.value.clone()) {
      (Mode::Manual, Some(value)) => Ok(value),
      _ => {
        if !request.connection_info.country.is_empty() {
          return Ok(Self::detect_locale_from_country_code(
            request.connection_info.country.clone(),
          ));
        }
        Ok("en-US".to_string())
      }
    }
  }

  /// Creates an OS-appropriate application locale string.
  ///
  /// # Arguments
  /// * `locale` - Input locale string
  /// * `os` - Target operating system
  ///
  /// # Returns
  /// Locale string compatible with the specified OS
  pub fn make_app_locale(locale: String, os: start_dto::Os) -> String {
    use start_dto::Os::*;

    let acceptable_list = match os {
      MacOS => MACOS_ACCEPTABLE_LOCALES,
      Windows => WINDOWS_ACCEPTABLE_LOCALES,
      Linux => LINUX_ACCEPTABLE_LOCALES,
    };

    if acceptable_list.contains(&locale.as_str()) {
      locale
    } else if acceptable_list
      .contains(&locale.chars().take(2).collect::<String>().as_str())
    {
      locale.chars().take(2).collect()
    } else {
      match os {
        MacOS => "en".to_string(),
        _ => "en-US".to_string(),
      }
    }
  }

  /// Determines timezone based on profile settings and connection info.
  ///
  /// # Arguments
  /// * `bp` - Browser profile data
  /// * `connection_info` - Connection information including timezone
  ///
  /// # Returns
  /// Determined timezone string
  pub fn make_timezone(
    bp: &BrowserProfileFullData,
    connection_info: ConnectionInfo,
  ) -> String {
    match (bp.timezone.mode, bp.timezone.value.clone()) {
      (Mode::Manual, Some(value)) => value,
      _ => connection_info.timezone.clone(),
    }
  }
}

impl FromStartRequest<Navigator> for Navigator {
  /// Creates a Navigator instance from a start request and profile data.
  ///
  /// # Arguments
  /// * `bp` - Browser profile data
  /// * `request` - Start request containing configuration
  /// * `navigator` - Base navigator settings
  /// * `screen` - Screen configuration
  /// * `token` - Authentication token
  ///
  /// # Returns
  /// Result containing the configured Navigator instance
  fn from_start_request(
    bp: &BrowserProfileFullData,
    request: &StartRequest,
    _navigator: &Navigator,
    _screen: &Screen,
    _token: &str,
  ) -> Result<Self, Error> {
    let device_memory = match bp.memory.mode {
      Mode::Manual => {
        if bp.memory.value > 8 {
          8
        } else {
          bp.memory.value as i32
        }
      }
      _ => 0,
    };

    let hardware_concurrency = match bp.cpu.mode {
      Mode::Manual => {
        if bp.cpu.value > 16 {
          16
        } else {
          bp.cpu.value as i32
        }
      }
      _ => 0,
    };

    let locale = Self::prepare_locale(bp, request)?;
    let languages = Self::make_languages(locale.clone());
    let accept_languages = Self::make_accept_languages(locale.clone());
    let app_locale = Self::make_app_locale(locale.clone(), request.os.clone());
    let locale = locale.chars().take(2).collect();

    let platform = match bp.platform {
      Platform::Macos => "MacIntel".to_string(),
      Platform::Windows => "Win32".to_string(),
      Platform::Linux => "Linux".to_string(),
    };

    let user_agent = match bp.useragent.mode {
      Mode::Manual => bp
        .useragent
        .value
        .clone()
        .unwrap_or(get_latest_user_agent(bp.platform.clone())),
      _ => get_latest_user_agent(bp.platform.clone()),
    };

    let timezone = Self::make_timezone(bp, request.connection_info.clone());

    Ok(Self {
      app_code_name: "Mozilla".to_string(),
      app_name: "Netscape".to_string(),
      connection: Connection {
        downlink: 10.2,
        effective_type: "4g".to_string(),
        rtt: 50,
        save_data: false,
      },
      device_memory,
      do_not_track: bp.do_not_track,
      hardware_concurrency,
      app_locale,
      locale,
      languages,
      accept_languages,
      platform,
      product: "Gecko".to_string(),
      product_sub: "20030107".to_string(),
      user_agent: user_agent.clone(),
      vendor: "Google Inc.".to_string(),
      vendor_sub: "".to_string(),
      timezone,
    })
  }
}

/// Generates the latest Chrome user agent string for a given platform.
///
/// # Arguments
/// * `platform` - Target platform (Windows, MacOS, or Linux)
///
/// # Returns
/// User agent string for the latest Chrome version on the platform
fn get_latest_user_agent(platform: Platform) -> String {
  match platform {
    Platform::Linux => format!("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{}.0.0.0 Safari/537.36", LATEST_CHROME_VERSION),
    Platform::Macos => format!("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{}.0.0.0 Safari/537.36", LATEST_CHROME_VERSION),
    Platform::Windows => format!("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{}.0.0.0 Safari/537.36", LATEST_CHROME_VERSION)
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::server::dtos::browser_profile_dto::{Locale, Timezone};
  use crate::server::dtos::start_dto::Os;
  use crate::server::services::browser_profile_services::config::consts::LINUX_MOCK_PROFILE;

  fn create_base_profile() -> BrowserProfileFullData {
    BrowserProfileFullData {
      locale: Locale {
        mode: Mode::Auto,
        value: None,
      },
      timezone: Timezone {
        mode: Mode::Auto,
        value: None,
      },
      ..LINUX_MOCK_PROFILE.clone()
    }
  }

  #[test]
  fn test_make_accept_languages_english() {
    let result = Navigator::make_accept_languages("en-US".to_string());
    assert_eq!(result, "en-US,en;q=0.9");

    let result = Navigator::make_accept_languages("en-GB".to_string());
    assert_eq!(result, "en-GB,en;q=0.9");
  }

  #[test]
  fn test_make_accept_languages_other() {
    let result = Navigator::make_accept_languages("fr-FR".to_string());
    assert_eq!(result, "fr-FR,fr;q=0.9;en-US,en;q=0.8");

    let result = Navigator::make_accept_languages("de-DE".to_string());
    assert_eq!(result, "de-DE,de;q=0.9;en-US,en;q=0.8");
  }

  #[test]
  fn test_make_languages_english() {
    let result = Navigator::make_languages("en-US".to_string());
    assert_eq!(result, vec!["en-US", "en"]);

    let result = Navigator::make_languages("en-GB".to_string());
    assert_eq!(result, vec!["en-GB", "en"]);
  }

  #[test]
  fn test_make_languages_other() {
    let result = Navigator::make_languages("fr-FR".to_string());
    assert_eq!(result, vec!["fr-FR", "fr", "en-US", "en"]);

    let result = Navigator::make_languages("de-DE".to_string());
    assert_eq!(result, vec!["de-DE", "de", "en-US", "en"]);
  }

  #[test]
  #[ignore = "Current implementation is not reliable and returns fr-BE for country code FR, so the second assert fails"]
  fn test_detect_locale_from_country_code() {
    let result = Navigator::detect_locale_from_country_code("US".to_string());
    assert_eq!(result, "en-US");

    let result = Navigator::detect_locale_from_country_code("FR".to_string());
    assert_eq!(result, "fr-FR");

    // Test fallback for unknown country code
    let result = Navigator::detect_locale_from_country_code("XX".to_string());
    assert_eq!(result, "en-US");
  }

  #[test]
  fn test_prepare_locale_manual() -> Result<(), Error> {
    let mut profile = create_base_profile();
    profile.locale.mode = Mode::Manual;
    profile.locale.value = Some("fr-FR".to_string());

    let request = StartRequest::get_mock();
    let result = Navigator::prepare_locale(&profile, &request)?;
    assert_eq!(result, "fr-FR");
    Ok(())
  }

  #[test]
  #[ignore = "Current implementation is not reliable and returns fr-BE for country code FR, so the assert fails"]
  fn test_prepare_locale_auto() -> Result<(), Error> {
    let profile = create_base_profile();
    let mut request = StartRequest::get_mock();
    request.connection_info = ConnectionInfo {
      country: "FR".to_string(),
      ..ConnectionInfo::get_mock()
    };

    let result = Navigator::prepare_locale(&profile, &request)?;
    assert_eq!(result, "fr-FR");
    Ok(())
  }

  #[test]
  fn test_make_app_locale_macos() {
    let result = Navigator::make_app_locale("en-US".to_string(), Os::MacOS);
    assert_eq!(result, "en");

    let result = Navigator::make_app_locale("fr-FR".to_string(), Os::MacOS);
    assert_eq!(result, "fr");
  }

  #[test]
  fn test_make_app_locale_other_os() {
    let result = Navigator::make_app_locale("en-US".to_string(), Os::Windows);
    assert_eq!(result, "en");

    let result = Navigator::make_app_locale("fr-FR".to_string(), Os::Linux);
    assert_eq!(result, "fr");
  }

  #[test]
  fn test_make_timezone_manual() {
    let mut profile = create_base_profile();
    profile.timezone.mode = Mode::Manual;
    profile.timezone.value = Some("Europe/Paris".to_string());

    let result = Navigator::make_timezone(&profile, ConnectionInfo::get_mock());
    assert_eq!(result, "Europe/Paris");
  }

  #[test]
  fn test_make_timezone_auto() {
    let profile = create_base_profile();
    let connection_info = ConnectionInfo {
      timezone: "America/New_York".to_string(),
      ..ConnectionInfo::get_mock()
    };

    let result = Navigator::make_timezone(&profile, connection_info);
    assert_eq!(result, "America/New_York");
  }

  #[test]
  fn test_make_timezone_empty() {
    let profile = create_base_profile();
    let result = Navigator::make_timezone(&profile, ConnectionInfo::get_mock());
    assert_eq!(result, "");
  }

  #[test]
  fn test_from_start_request() -> Result<(), Error> {
    let mut profile = create_base_profile();
    profile.memory.mode = Mode::Manual;
    profile.memory.value = 8;
    profile.cpu.mode = Mode::Manual;
    profile.cpu.value = 8;
    profile.platform = Platform::Windows;
    profile.useragent.mode = Mode::Manual;
    profile.useragent.value = Some("Custom UA".to_string());
    profile.do_not_track = true;

    let request = StartRequest::get_mock();
    let navigator = Navigator::default();
    let screen = Screen::default();
    let token = String::new();

    let result = Navigator::from_start_request(
      &profile, &request, &navigator, &screen, &token,
    )?;

    assert_eq!(result.device_memory, 8);
    assert_eq!(result.hardware_concurrency, 8);
    assert_eq!(result.platform, "Win32");
    assert_eq!(result.user_agent, "Custom UA");
    assert!(result.do_not_track);
    assert_eq!(result.app_code_name, "Mozilla");
    assert_eq!(result.app_name, "Netscape");
    assert_eq!(result.product, "Gecko");
    assert_eq!(result.product_sub, "20030107");
    assert_eq!(result.vendor, "Google Inc.");
    assert_eq!(result.vendor_sub, "");

    Ok(())
  }

  #[test]
  fn test_memory_and_cpu_limits() -> Result<(), Error> {
    let mut profile = create_base_profile();
    profile.memory.mode = Mode::Manual;
    profile.memory.value = 16; // Should be capped at 8
    profile.cpu.mode = Mode::Manual;
    profile.cpu.value = 32; // Should be capped at 16

    let request = StartRequest::get_mock();
    let navigator = Navigator::default();
    let screen = Screen::default();
    let token = String::new();

    let result = Navigator::from_start_request(
      &profile, &request, &navigator, &screen, &token,
    )?;

    assert_eq!(result.device_memory, 8);
    assert_eq!(result.hardware_concurrency, 16);
    Ok(())
  }
}