guise 0.1.2

Canonical browser fingerprint bundles, human-behavior timing, and TLS profile re-exports for the Santh fleet
Documentation
//! Runtime stealth-surface probe + drift detector.
//!
//! [`crate::browser::apply_stealth`] injects JS overrides (the source is
//! [`crate::fingerprint::profile_js`]). That injection is a STATIC contract - it
//! asserts the override is present in the source. It does NOT verify that the
//! override WORKS at runtime: another script may have re-defined the property;
//! the browser build may not expose it at all; or the patched value may drift
//! from "looks like real Firefox."
//!
//! `StealthProbe` answers "does the page actually pass the
//! fingerprint tests" by probing 100+ live surfaces and comparing
//! against expected real-browser values. The output is a structured
//! drift report - for each probed surface, the report carries
//! `(expected, actual, severity)`. Operators run this in dev to
//! verify a stealth-profile change still passes; CI runs it
//! against a synthetic-page fixture to catch regressions where a
//! profile update accidentally drops a surface.
//!
//! No public captcha-solver crate ships a comparable runtime
//! drift detector. The closest prior art is the OSS
//! `creep-js` browser-side fingerprint disclosure tool - but
//! creep-js is a JS library a human runs in a browser, not a
//! Rust-side automated probe.

use anyhow::{anyhow, Result};
use runtime_foxdriver::Page;
use serde::{Deserialize, Serialize};

/// One surface probe: a name, JS expression, and a predicate that
/// classifies the returned `serde_json::Value` as `Pass` / `Drift` /
/// `Critical`.
pub struct Probe {
    /// Human-readable name of the surface this probe checks.
    pub name: &'static str,
    /// JS expression evaluated on the page; its return value is classified.
    pub js: &'static str,
    /// How badly a failure of this probe betrays automation.
    pub severity: Severity,
    /// Maps the probe's returned `serde_json::Value` to a [`ProbeOutcome`].
    pub classifier: fn(&serde_json::Value) -> ProbeOutcome,
}

/// Outcome of a single probe.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProbeOutcome {
    /// Surface looks like a real browser.
    Pass,
    /// Surface differs from a real browser but the difference is
    /// minor (e.g., uaFullVersion delta within the same major).
    /// Stored with a one-line explanation.
    Drift(String),
    /// Surface has a critical leak (navigator.webdriver === true,
    /// chrome === undefined, plugins.length === 0).
    Critical(String),
    /// The probe failed to execute (BiDi error, page navigated
    /// before probe finished). Stored with the error.
    ProbeError(String),
}

impl ProbeOutcome {
    /// `true` if the surface looked like a real browser.
    pub fn is_pass(&self) -> bool {
        matches!(self, ProbeOutcome::Pass)
    }

    /// `true` if the surface had a critical (automation-revealing) leak.
    pub fn is_critical(&self) -> bool {
        matches!(self, ProbeOutcome::Critical(_))
    }
}

/// Severity of a drift. `Low` won't fail CI; `High` should.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Severity {
    /// Cosmetic — does not by itself reveal automation.
    Low,
    /// Notable — contributes to a detection score.
    Medium,
    /// Strong — a fingerprinter weights this heavily.
    High,
}

/// Result of running every probe.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DriftReport {
    /// Total probes run.
    pub probed: usize,
    /// Probes that matched a real browser.
    pub passed: usize,
    /// Probes with a minor (non-critical) difference.
    pub drift: usize,
    /// Probes with an automation-revealing leak.
    pub critical: usize,
    /// Probes that failed to execute (BiDi error, navigation race).
    pub probe_errors: usize,
    /// Per-probe detail.
    pub per_probe: Vec<ProbeReport>,
}

/// Per-probe entry in the drift report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProbeReport {
    /// The probe's name.
    pub name: String,
    /// The probe's severity, rendered as a string for serialization.
    pub severity: String,
    /// The classified outcome.
    pub outcome: ProbeOutcome,
}

impl DriftReport {
    /// `true` when there are no criticals and ≥90% of probes pass.
    pub fn is_green(&self) -> bool {
        self.critical == 0 && self.probed > 0 && self.passed >= self.probed * 90 / 100
    }

    /// One-line human summary of the report.
    pub fn summary(&self) -> String {
        format!(
            "{}/{} probes pass ({} drift, {} critical, {} errors)",
            self.passed, self.probed, self.drift, self.critical, self.probe_errors
        )
    }
}

mod catalogue;
mod catalogue_misc;
mod classify;
mod codec;
mod oracle;
mod redteam;
#[cfg(test)]
mod tests;

pub use catalogue::{probes, probes_for};
pub use oracle::{diff_pages, render_differential, DifferentialReport, Divergence};
pub use guise_profiles::UserAgentBrowser;
/// Probe count target - used in tests to catch regressions where a
/// probe is silently dropped.
pub const PROBE_COUNT_FLOOR: usize = 100;

/// Run every probe against the page; return a structured report.
///
/// Measures against Chrome truth (the back-compatible default). For a Firefox
/// disguise — what guise's live BiDi browser actually is — use [`run_for`] so
/// Chromium-only surfaces aren't falsely flagged.
///
/// Errors at the BiDi layer become `ProbeOutcome::ProbeError` rather
/// than failing the whole probe - operators see WHICH probe broke
/// rather than a single top-level error.
pub async fn run(page: &Page) -> Result<DriftReport> {
    run_for(page, UserAgentBrowser::Chrome).await
}

/// Run the family-aware probe catalogue for `browser` against the page.
///
/// See [`probes_for`]: a Firefox target drops the Chromium-only surfaces and
/// adds the Firefox truths, so the drift report reflects whether the disguise
/// is coherent with the *target* browser rather than always with Chrome.
pub async fn run_for(page: &Page, browser: UserAgentBrowser) -> Result<DriftReport> {
    let catalogue = probes_for(browser);
    let mut report = DriftReport {
        probed: catalogue.len(),
        passed: 0,
        drift: 0,
        critical: 0,
        probe_errors: 0,
        per_probe: Vec::with_capacity(catalogue.len()),
    };
    for probe in catalogue {
        let result = page.evaluate(probe.js).await;
        let outcome = match result {
            Ok(eval) => {
                let value = eval
                    .into_value::<serde_json::Value>()
                    .unwrap_or(serde_json::Value::Null);
                (probe.classifier)(&value)
            }
            Err(e) => ProbeOutcome::ProbeError(e.to_string()),
        };
        match &outcome {
            ProbeOutcome::Pass => report.passed += 1,
            ProbeOutcome::Drift(_) => report.drift += 1,
            ProbeOutcome::Critical(_) => report.critical += 1,
            ProbeOutcome::ProbeError(_) => report.probe_errors += 1,
        }
        report.per_probe.push(ProbeReport {
            name: probe.name.to_string(),
            severity: format!("{:?}", probe.severity),
            outcome,
        });
    }
    Ok(report)
}

/// Diagnostic helper: render the report as a human-readable table.
pub fn render_report(report: &DriftReport) -> String {
    use std::fmt::Write;
    let mut out = String::with_capacity(report.per_probe.len() * 120);
    let _ = writeln!(out, "STEALTH PROBE - {}", report.summary());
    let _ = writeln!(out, "{:-^100}", "");
    for r in &report.per_probe {
        let icon = match &r.outcome {
            ProbeOutcome::Pass => "✓",
            ProbeOutcome::Drift(_) => "~",
            ProbeOutcome::Critical(_) => "✘",
            ProbeOutcome::ProbeError(_) => "?",
        };
        let detail = match &r.outcome {
            ProbeOutcome::Pass => String::new(),
            ProbeOutcome::Drift(m) | ProbeOutcome::Critical(m) | ProbeOutcome::ProbeError(m) => {
                format!(" - {m}")
            }
        };
        let _ = writeln!(out, "  {icon} [{}] {}{}", r.severity, r.name, detail);
    }
    out
}

/// Apply every probe and return Result. Sugar over [`run`] for the
/// CLI subcommand wrapper. Uses the Chromium catalogue; for a Firefox disguise
/// use [`audit_page_for`].
pub async fn audit_page(page: &Page) -> Result<DriftReport> {
    audit_page_for(page, UserAgentBrowser::Chrome).await
}

/// Family-aware variant of [`audit_page`]: probe against `browser`'s real
/// fingerprint. Sugar over [`run_for`].
pub async fn audit_page_for(page: &Page, browser: UserAgentBrowser) -> Result<DriftReport> {
    let r = run_for(page, browser)
        .await
        .map_err(|e| anyhow!("probe run failed: {e}"))?;
    Ok(r)
}