Skip to main content

stealth_oxide/
config.rs

1use crate::error::ValidationIssue;
2use crate::profiles::chrome_linux::chrome_linux;
3use crate::profiles::chrome_macos::chrome_macos;
4use crate::profiles::chrome_windows::chrome_windows;
5use crate::profiles::{
6    BrowserProfile, ColorGamut, ColorScheme, ForcedColors, MediaFeaturesConfig, NavigatorProfile,
7    ReducedMotion, ScreenConfig, TouchConfig, UserAgentClientHintsProfile,
8};
9
10/// Built-in desktop profile selection.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum PlatformProfile {
13    /// Chrome running on Linux.
14    Linux,
15    /// Chrome running on macOS.
16    MacOS,
17    /// Chrome running on Windows.
18    Windows,
19}
20
21/// An independently selectable CDP patch.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23#[non_exhaustive]
24pub enum Patch {
25    /// User agent, navigator platform, languages, and UA Client Hints.
26    Identity,
27    /// Intl locale override.
28    Locale,
29    /// IANA timezone override.
30    Timezone,
31    /// Screen and viewport metrics.
32    Screen,
33    /// CSS media feature overrides.
34    MediaFeatures,
35    /// Touch capability emulation.
36    Touch,
37}
38
39/// Controls how one patch obtains its value.
40#[derive(Debug, Clone, PartialEq)]
41#[non_exhaustive]
42pub enum PatchMode<T> {
43    /// Preserve the value already supplied by Chromium or the host environment.
44    Native,
45    /// Apply the supplied override through CDP.
46    Override(T),
47    /// Exclude the patch from the application plan.
48    Disabled,
49}
50
51/// Non-generic state of a configured patch.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum PatchState {
54    /// Chromium's existing value is preserved.
55    Native,
56    /// A configured value will be applied.
57    Override,
58    /// The patch is excluded from the plan.
59    Disabled,
60}
61
62/// Controls how cross-surface contradictions are handled.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub enum ConsistencyPolicy {
65    /// Reject known contradictions before executing any CDP command.
66    #[default]
67    Strict,
68    /// Apply valid CDP values and include consistency issues in the report.
69    Warn,
70    /// Apply exactly what the caller requested, subject only to CDP requirements.
71    Permissive,
72}
73
74impl PlatformProfile {
75    /// Builds the selected profile.
76    pub fn profile(self) -> BrowserProfile {
77        match self {
78            Self::Linux => chrome_linux(),
79            Self::MacOS => chrome_macos(),
80            Self::Windows => chrome_windows(),
81        }
82    }
83}
84
85/// Fully configurable patch selection and override values.
86#[derive(Debug, Clone, PartialEq)]
87pub struct StealthConfig {
88    identity: PatchMode<NavigatorProfile>,
89    locale: PatchMode<String>,
90    timezone: PatchMode<String>,
91    screen: PatchMode<ScreenConfig>,
92    media_features: PatchMode<MediaFeaturesConfig>,
93    touch: PatchMode<TouchConfig>,
94    policy: ConsistencyPolicy,
95    defaults: BrowserProfile,
96}
97
98impl StealthConfig {
99    /// Creates a configuration with every patch disabled.
100    pub fn none() -> Self {
101        let defaults = PlatformProfile::Linux.profile();
102        Self {
103            identity: PatchMode::Disabled,
104            locale: PatchMode::Disabled,
105            timezone: PatchMode::Disabled,
106            screen: PatchMode::Disabled,
107            media_features: PatchMode::Disabled,
108            touch: PatchMode::Disabled,
109            policy: ConsistencyPolicy::Strict,
110            defaults,
111        }
112    }
113
114    /// Creates a complete override configuration from a built-in platform preset.
115    pub fn for_platform(platform: PlatformProfile) -> Self {
116        Self::from_profile(platform.profile())
117    }
118
119    /// Creates a complete override configuration from an editable profile.
120    pub fn from_profile(profile: BrowserProfile) -> Self {
121        Self {
122            identity: PatchMode::Override(profile.navigator.clone()),
123            locale: PatchMode::Override(profile.locale.locale.clone()),
124            timezone: PatchMode::Override(profile.locale.timezone.clone()),
125            screen: PatchMode::Override((&profile.screen).into()),
126            media_features: PatchMode::Override((&profile.device_environment).into()),
127            touch: PatchMode::Override((&profile.device_environment).into()),
128            policy: ConsistencyPolicy::Strict,
129            defaults: profile,
130        }
131    }
132
133    /// Selects strict, warning, or permissive consistency handling.
134    pub const fn consistency_policy(mut self, policy: ConsistencyPolicy) -> Self {
135        self.policy = policy;
136        self
137    }
138
139    /// Enables a patch using the selected platform's default value.
140    pub fn enable(mut self, patch: Patch) -> Self {
141        match patch {
142            Patch::Identity => self.identity = PatchMode::Override(self.defaults.navigator.clone()),
143            Patch::Locale => self.locale = PatchMode::Override(self.defaults.locale.locale.clone()),
144            Patch::Timezone => {
145                self.timezone = PatchMode::Override(self.defaults.locale.timezone.clone());
146            }
147            Patch::Screen => self.screen = PatchMode::Override((&self.defaults.screen).into()),
148            Patch::MediaFeatures => {
149                self.media_features =
150                    PatchMode::Override((&self.defaults.device_environment).into());
151            }
152            Patch::Touch => {
153                self.touch = PatchMode::Override((&self.defaults.device_environment).into());
154            }
155        }
156        self
157    }
158
159    /// Disables a patch completely.
160    pub fn disable(mut self, patch: Patch) -> Self {
161        match patch {
162            Patch::Identity => self.identity = PatchMode::Disabled,
163            Patch::Locale => self.locale = PatchMode::Disabled,
164            Patch::Timezone => self.timezone = PatchMode::Disabled,
165            Patch::Screen => self.screen = PatchMode::Disabled,
166            Patch::MediaFeatures => self.media_features = PatchMode::Disabled,
167            Patch::Touch => self.touch = PatchMode::Disabled,
168        }
169        self
170    }
171
172    /// Preserves Chromium's native value for a patch.
173    pub fn use_native(mut self, patch: Patch) -> Self {
174        match patch {
175            Patch::Identity => self.identity = PatchMode::Native,
176            Patch::Locale => self.locale = PatchMode::Native,
177            Patch::Timezone => self.timezone = PatchMode::Native,
178            Patch::Screen => self.screen = PatchMode::Native,
179            Patch::MediaFeatures => self.media_features = PatchMode::Native,
180            Patch::Touch => self.touch = PatchMode::Native,
181        }
182        self
183    }
184
185    /// Replaces the complete identity override.
186    pub fn identity(mut self, identity: NavigatorProfile) -> Self {
187        self.identity = PatchMode::Override(identity);
188        self
189    }
190
191    /// Sets the complete identity patch mode.
192    pub fn identity_patch(mut self, mode: PatchMode<NavigatorProfile>) -> Self {
193        self.identity = mode;
194        self
195    }
196
197    /// Replaces UA Client Hints and enables identity patching.
198    pub fn client_hints(mut self, hints: Option<UserAgentClientHintsProfile>) -> Self {
199        self.identity_value_mut().client_hints = hints;
200        self
201    }
202
203    /// Overrides the user-agent string and enables identity patching.
204    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
205        self.identity_value_mut().user_agent = user_agent.into();
206        self
207    }
208
209    /// Overrides navigator platform and enables identity patching.
210    pub fn navigator_platform(mut self, platform: impl Into<String>) -> Self {
211        self.identity_value_mut().platform = platform.into();
212        self
213    }
214
215    /// Overrides navigator languages and enables identity patching.
216    pub fn languages<I, S>(mut self, languages: I) -> Self
217    where
218        I: IntoIterator<Item = S>,
219        S: Into<String>,
220    {
221        self.identity_value_mut().languages = languages.into_iter().map(Into::into).collect();
222        self
223    }
224
225    /// Overrides the Intl locale and enables locale patching.
226    pub fn locale(mut self, locale: impl Into<String>) -> Self {
227        self.locale = PatchMode::Override(locale.into());
228        self
229    }
230
231    /// Sets the complete locale patch mode.
232    pub fn locale_patch(mut self, mode: PatchMode<String>) -> Self {
233        self.locale = mode;
234        self
235    }
236
237    /// Overrides the IANA timezone and enables timezone patching.
238    pub fn timezone(mut self, timezone: impl Into<String>) -> Self {
239        self.timezone = PatchMode::Override(timezone.into());
240        self
241    }
242
243    /// Sets the complete timezone patch mode.
244    pub fn timezone_patch(mut self, mode: PatchMode<String>) -> Self {
245        self.timezone = mode;
246        self
247    }
248
249    /// Replaces the complete screen override.
250    pub fn screen(mut self, screen: ScreenConfig) -> Self {
251        self.screen = PatchMode::Override(screen);
252        self
253    }
254
255    /// Sets the complete screen patch mode.
256    pub fn screen_patch(mut self, mode: PatchMode<ScreenConfig>) -> Self {
257        self.screen = mode;
258        self
259    }
260
261    /// Overrides total screen dimensions and enables screen patching.
262    pub fn screen_size(mut self, width: u32, height: u32) -> Self {
263        let screen = self.screen_value_mut();
264        screen.width = width;
265        screen.height = height;
266        self
267    }
268
269    /// Overrides the device scale factor and enables screen patching.
270    pub fn device_scale_factor(mut self, factor: f64) -> Self {
271        self.screen_value_mut().device_scale_factor = factor;
272        self
273    }
274
275    /// Replaces all media-feature overrides.
276    pub fn media_features(mut self, media: MediaFeaturesConfig) -> Self {
277        self.media_features = PatchMode::Override(media);
278        self
279    }
280
281    /// Sets the complete media-feature patch mode.
282    pub fn media_features_patch(mut self, mode: PatchMode<MediaFeaturesConfig>) -> Self {
283        self.media_features = mode;
284        self
285    }
286
287    /// Overrides `prefers-color-scheme` and enables media-feature patching.
288    pub fn color_scheme(mut self, value: ColorScheme) -> Self {
289        self.media_features_value_mut().color_scheme = value;
290        self
291    }
292
293    /// Overrides `prefers-reduced-motion` and enables media-feature patching.
294    pub fn reduced_motion(mut self, value: ReducedMotion) -> Self {
295        self.media_features_value_mut().reduced_motion = value;
296        self
297    }
298
299    /// Overrides `forced-colors` and enables media-feature patching.
300    pub fn forced_colors(mut self, value: ForcedColors) -> Self {
301        self.media_features_value_mut().forced_colors = value;
302        self
303    }
304
305    /// Overrides `color-gamut` and enables media-feature patching.
306    pub fn color_gamut(mut self, value: ColorGamut) -> Self {
307        self.media_features_value_mut().color_gamut = value;
308        self
309    }
310
311    /// Replaces the touch override.
312    pub fn touch(mut self, enabled: bool, max_touch_points: u32) -> Self {
313        self.touch = PatchMode::Override(TouchConfig {
314            enabled,
315            max_touch_points,
316        });
317        self
318    }
319
320    /// Sets the complete touch patch mode.
321    pub fn touch_patch(mut self, mode: PatchMode<TouchConfig>) -> Self {
322        self.touch = mode;
323        self
324    }
325
326    /// Returns the selected consistency policy.
327    pub const fn policy(&self) -> ConsistencyPolicy {
328        self.policy
329    }
330
331    /// Returns the current state of an individual patch.
332    pub fn patch_state(&self, patch: Patch) -> PatchState {
333        match patch {
334            Patch::Identity => state(&self.identity),
335            Patch::Locale => state(&self.locale),
336            Patch::Timezone => state(&self.timezone),
337            Patch::Screen => state(&self.screen),
338            Patch::MediaFeatures => state(&self.media_features),
339            Patch::Touch => state(&self.touch),
340        }
341    }
342
343    /// Builds the deterministic patch order and validates it without a browser.
344    pub fn plan(&self) -> PatchPlan {
345        let operations = [
346            Patch::Locale,
347            Patch::Timezone,
348            Patch::Identity,
349            Patch::Screen,
350            Patch::MediaFeatures,
351            Patch::Touch,
352        ]
353        .into_iter()
354        .map(|patch| (patch, self.patch_state(patch)))
355        .collect();
356        PatchPlan {
357            operations,
358            issues: crate::validation::validate_config(self),
359        }
360    }
361
362    /// Returns every known consistency issue without applying any patch.
363    pub fn validation_issues(&self) -> Vec<ValidationIssue> {
364        self.plan().issues
365    }
366
367    /// Returns the configured identity override, if identity is in override mode.
368    pub fn identity_override(&self) -> Option<&NavigatorProfile> {
369        override_value(&self.identity)
370    }
371
372    /// Returns the configured locale override, if locale is in override mode.
373    pub fn locale_override(&self) -> Option<&str> {
374        override_value(&self.locale).map(String::as_str)
375    }
376
377    /// Returns the configured timezone override, if timezone is in override mode.
378    pub fn timezone_override(&self) -> Option<&str> {
379        override_value(&self.timezone).map(String::as_str)
380    }
381
382    /// Returns the configured screen override, if screen is in override mode.
383    pub fn screen_override(&self) -> Option<&ScreenConfig> {
384        override_value(&self.screen)
385    }
386
387    /// Returns the configured media-feature override, if enabled.
388    pub fn media_features_override(&self) -> Option<&MediaFeaturesConfig> {
389        override_value(&self.media_features)
390    }
391
392    /// Returns the configured touch override, if enabled.
393    pub fn touch_override(&self) -> Option<&TouchConfig> {
394        override_value(&self.touch)
395    }
396
397    pub(crate) fn identity_mode(&self) -> &PatchMode<NavigatorProfile> {
398        &self.identity
399    }
400
401    pub(crate) fn locale_mode(&self) -> &PatchMode<String> {
402        &self.locale
403    }
404
405    pub(crate) fn timezone_mode(&self) -> &PatchMode<String> {
406        &self.timezone
407    }
408
409    pub(crate) fn screen_mode(&self) -> &PatchMode<ScreenConfig> {
410        &self.screen
411    }
412
413    pub(crate) fn media_features_mode(&self) -> &PatchMode<MediaFeaturesConfig> {
414        &self.media_features
415    }
416
417    pub(crate) fn touch_mode(&self) -> &PatchMode<TouchConfig> {
418        &self.touch
419    }
420
421    fn identity_value_mut(&mut self) -> &mut NavigatorProfile {
422        if !matches!(self.identity, PatchMode::Override(_)) {
423            self.identity = PatchMode::Override(self.defaults.navigator.clone());
424        }
425        let PatchMode::Override(value) = &mut self.identity else {
426            unreachable!("identity was replaced with an override")
427        };
428        value
429    }
430
431    fn screen_value_mut(&mut self) -> &mut ScreenConfig {
432        if !matches!(self.screen, PatchMode::Override(_)) {
433            self.screen = PatchMode::Override((&self.defaults.screen).into());
434        }
435        let PatchMode::Override(value) = &mut self.screen else {
436            unreachable!("screen was replaced with an override")
437        };
438        value
439    }
440
441    fn media_features_value_mut(&mut self) -> &mut MediaFeaturesConfig {
442        if !matches!(self.media_features, PatchMode::Override(_)) {
443            self.media_features = PatchMode::Override((&self.defaults.device_environment).into());
444        }
445        let PatchMode::Override(value) = &mut self.media_features else {
446            unreachable!("media features were replaced with an override")
447        };
448        value
449    }
450}
451
452fn state<T>(mode: &PatchMode<T>) -> PatchState {
453    match mode {
454        PatchMode::Native => PatchState::Native,
455        PatchMode::Override(_) => PatchState::Override,
456        PatchMode::Disabled => PatchState::Disabled,
457    }
458}
459
460fn override_value<T>(mode: &PatchMode<T>) -> Option<&T> {
461    match mode {
462        PatchMode::Override(value) => Some(value),
463        PatchMode::Native | PatchMode::Disabled => None,
464    }
465}
466
467/// Result of applying a stealth configuration.
468#[derive(Debug, Clone, PartialEq, Eq, Default)]
469pub struct ApplyReport {
470    pub(crate) applied: Vec<Patch>,
471    pub(crate) skipped: Vec<Patch>,
472    pub(crate) native: Vec<Patch>,
473    pub(crate) warnings: Vec<ValidationIssue>,
474}
475
476/// Deterministic patch order and validation result prepared without a browser.
477#[derive(Debug, Clone, PartialEq, Eq)]
478pub struct PatchPlan {
479    operations: Vec<(Patch, PatchState)>,
480    issues: Vec<ValidationIssue>,
481}
482
483impl PatchPlan {
484    /// Ordered patch states that will be processed by [`StealthConfig::apply`].
485    pub fn operations(&self) -> &[(Patch, PatchState)] {
486        &self.operations
487    }
488
489    /// Known consistency issues in this plan.
490    pub fn issues(&self) -> &[ValidationIssue] {
491        &self.issues
492    }
493}
494
495impl ApplyReport {
496    /// Patches whose CDP commands completed successfully.
497    pub fn applied(&self) -> &[Patch] {
498        &self.applied
499    }
500
501    /// Patches explicitly disabled by the caller.
502    pub fn skipped(&self) -> &[Patch] {
503        &self.skipped
504    }
505
506    /// Patches configured to preserve Chromium's native values.
507    pub fn native(&self) -> &[Patch] {
508        &self.native
509    }
510
511    /// Non-fatal consistency issues produced in warning mode.
512    pub fn warnings(&self) -> &[ValidationIssue] {
513        &self.warnings
514    }
515}