Skip to main content

rightkit_browser/
real_session.rs

1//! Consented real-session mode: detect the user's default browser, record what the user agreed
2//! to in a persistable, revocable receipt, copy a Chromium-family profile's sign-ins into a
3//! named RightKit profile, and scope every action of the resulting session to the consented
4//! domains.
5//!
6//! What this module does NOT do: it never reads, decrypts or transmits cookie values. Sign-ins
7//! travel as the browser's own files (cookie database, local storage, the `Local State` key
8//! material) copied into a private RightKit profile on the same machine. The browser's password
9//! store (`Login Data`), form data (`Web Data`) and history are never copied, and typing into a
10//! password field is refused, so passwords never pass through the agent: they stay in the
11//! browser's own password manager.
12
13use crate::error::{BrowserError, Result};
14use crate::policy::{ActionKind, AdmissionHook, AdmissionRequest, Decision};
15use futures::FutureExt;
16use serde::{Deserialize, Serialize};
17use std::collections::BTreeMap;
18use std::path::{Path, PathBuf};
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::Arc;
21use std::time::{SystemTime, UNIX_EPOCH};
22
23/// Schema version of [`UserConsentReceipt`].
24pub const CONSENT_SCHEMA: u32 = 1;
25
26/// Marker file written into an imported profile.
27pub(crate) const IMPORT_MARKER: &str = ".rightkit-import.json";
28
29pub(crate) fn now_ms() -> u64 {
30    SystemTime::now()
31        .duration_since(UNIX_EPOCH)
32        .map(|d| d.as_millis() as u64)
33        .unwrap_or(0)
34}
35
36// ---------------------------------------------------------------------------
37// Browser kinds and default-browser detection
38// ---------------------------------------------------------------------------
39
40/// A concrete browser product.
41#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum BrowserKind {
44    Chrome,
45    Edge,
46    Chromium,
47    Brave,
48    Safari,
49    Firefox,
50    Unknown,
51}
52
53impl BrowserKind {
54    /// Stable lower-case name (also used in profile names).
55    pub fn name(self) -> &'static str {
56        match self {
57            BrowserKind::Chrome => "chrome",
58            BrowserKind::Edge => "edge",
59            BrowserKind::Chromium => "chromium",
60            BrowserKind::Brave => "brave",
61            BrowserKind::Safari => "safari",
62            BrowserKind::Firefox => "firefox",
63            BrowserKind::Unknown => "unknown",
64        }
65    }
66
67    /// True for browsers that run on Chromium and keep a Chromium user-data directory.
68    pub fn is_chromium_family(self) -> bool {
69        matches!(
70            self,
71            BrowserKind::Chrome | BrowserKind::Edge | BrowserKind::Chromium | BrowserKind::Brave
72        )
73    }
74}
75
76/// Which browser an import reads from.
77#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
78#[serde(rename_all = "snake_case")]
79pub enum BrowserSource {
80    DefaultBrowser,
81    Chrome,
82    Edge,
83    Safari,
84    Firefox,
85}
86
87impl BrowserSource {
88    /// The concrete browser (`DefaultBrowser` is detected now).
89    pub fn resolve(self) -> BrowserKind {
90        match self {
91            BrowserSource::DefaultBrowser => default_browser(),
92            BrowserSource::Chrome => BrowserKind::Chrome,
93            BrowserSource::Edge => BrowserKind::Edge,
94            BrowserSource::Safari => BrowserKind::Safari,
95            BrowserSource::Firefox => BrowserKind::Firefox,
96        }
97    }
98}
99
100/// The user's default web browser on Windows, macOS and Linux, or [`BrowserKind::Unknown`]
101/// when it cannot be determined.
102pub fn default_browser() -> BrowserKind {
103    detect_default_browser().unwrap_or(BrowserKind::Unknown)
104}
105
106#[cfg(windows)]
107fn detect_default_browser() -> Option<BrowserKind> {
108    use std::os::windows::process::CommandExt;
109    const CREATE_NO_WINDOW: u32 = 0x0800_0000;
110    let output = std::process::Command::new("reg")
111        .args([
112            "query",
113            "HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice",
114            "/v",
115            "ProgId",
116        ])
117        .creation_flags(CREATE_NO_WINDOW)
118        .output()
119        .ok()?;
120    parse_windows_prog_id(&String::from_utf8_lossy(&output.stdout))
121}
122
123#[cfg(target_os = "macos")]
124fn detect_default_browser() -> Option<BrowserKind> {
125    let output = std::process::Command::new("defaults")
126        .args([
127            "read",
128            "com.apple.LaunchServices/com.apple.launchservices.secure",
129            "LSHandlers",
130        ])
131        .output()
132        .ok()?;
133    // No https handler recorded means the system default, Safari.
134    Some(
135        parse_macos_handlers(&String::from_utf8_lossy(&output.stdout))
136            .unwrap_or(BrowserKind::Safari),
137    )
138}
139
140#[cfg(not(any(windows, target_os = "macos")))]
141fn detect_default_browser() -> Option<BrowserKind> {
142    let output = std::process::Command::new("xdg-settings")
143        .args(["get", "default-web-browser"])
144        .output()
145        .ok()?;
146    parse_desktop_entry(&String::from_utf8_lossy(&output.stdout))
147}
148
149/// `reg query ... /v ProgId` output, for example `ProgId    REG_SZ    ChromeHTML`.
150#[allow(dead_code)]
151pub(crate) fn parse_windows_prog_id(output: &str) -> Option<BrowserKind> {
152    let line = output.lines().find(|l| l.contains("ProgId"))?;
153    let prog_id = line.split_whitespace().last()?.to_ascii_lowercase();
154    let kind = if prog_id.contains("chromehtml") {
155        BrowserKind::Chrome
156    } else if prog_id.contains("msedge") {
157        BrowserKind::Edge
158    } else if prog_id.contains("firefox") {
159        BrowserKind::Firefox
160    } else if prog_id.contains("bravehtml") {
161        BrowserKind::Brave
162    } else if prog_id.contains("safari") {
163        BrowserKind::Safari
164    } else {
165        BrowserKind::Unknown
166    };
167    Some(kind)
168}
169
170/// `defaults read ... LSHandlers` output: find the block that handles the `https` scheme.
171#[allow(dead_code)]
172pub(crate) fn parse_macos_handlers(output: &str) -> Option<BrowserKind> {
173    for block in output.split('}') {
174        let lower = block.to_ascii_lowercase();
175        let handles_https = lower
176            .lines()
177            .any(|l| l.contains("lshandlerurlscheme") && l.contains("https"));
178        if !handles_https {
179            continue;
180        }
181        for line in lower.lines() {
182            if line.contains("lshandlerroleall") {
183                let bundle = line
184                    .split('=')
185                    .nth(1)?
186                    .trim()
187                    .trim_end_matches(';')
188                    .trim_matches('"');
189                return Some(match bundle {
190                    "com.google.chrome" => BrowserKind::Chrome,
191                    "com.microsoft.edgemac" => BrowserKind::Edge,
192                    "org.chromium.chromium" => BrowserKind::Chromium,
193                    "com.brave.browser" => BrowserKind::Brave,
194                    "org.mozilla.firefox" => BrowserKind::Firefox,
195                    "com.apple.safari" => BrowserKind::Safari,
196                    _ => BrowserKind::Unknown,
197                });
198            }
199        }
200    }
201    None
202}
203
204/// `xdg-settings get default-web-browser` output, for example `google-chrome.desktop`.
205#[allow(dead_code)]
206pub(crate) fn parse_desktop_entry(output: &str) -> Option<BrowserKind> {
207    let entry = output.trim().to_ascii_lowercase();
208    if entry.is_empty() {
209        return None;
210    }
211    let kind = if entry.contains("google-chrome") {
212        BrowserKind::Chrome
213    } else if entry.contains("microsoft-edge") {
214        BrowserKind::Edge
215    } else if entry.contains("brave") {
216        BrowserKind::Brave
217    } else if entry.contains("chromium") {
218        BrowserKind::Chromium
219    } else if entry.contains("firefox") {
220        BrowserKind::Firefox
221    } else {
222        BrowserKind::Unknown
223    };
224    Some(kind)
225}
226
227// ---------------------------------------------------------------------------
228// Consent
229// ---------------------------------------------------------------------------
230
231/// Lower-case a domain and reject anything that is not a bare host name. A leading `*.` or `.`
232/// is accepted and dropped: a domain always covers its subdomains.
233pub(crate) fn normalize_domain(raw: &str) -> Result<String> {
234    let d = raw
235        .trim()
236        .trim_start_matches("*.")
237        .trim_start_matches('.')
238        .trim_end_matches('.')
239        .to_ascii_lowercase();
240    let ok = !d.is_empty()
241        && d.len() <= 253
242        && d.split('.').all(|label| {
243            !label.is_empty()
244                && label.len() <= 63
245                && !label.starts_with('-')
246                && !label.ends_with('-')
247                && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
248        });
249    if ok {
250        Ok(d)
251    } else {
252        Err(BrowserError::Invalid(format!(
253            "'{raw}' is not a bare domain name"
254        )))
255    }
256}
257
258fn normalize_domains(domains: Option<Vec<String>>) -> Result<Option<Vec<String>>> {
259    match domains {
260        None => Ok(None),
261        Some(list) => {
262            if list.is_empty() {
263                return Err(BrowserError::Invalid(
264                    "an empty domain list grants nothing; use None for all domains".into(),
265                ));
266            }
267            let mut out = Vec::with_capacity(list.len());
268            for d in &list {
269                let d = normalize_domain(d)?;
270                if !out.contains(&d) {
271                    out.push(d);
272                }
273            }
274            Ok(Some(out))
275        }
276    }
277}
278
279/// A plain profile directory name such as `Default` or `Profile 1`.
280pub(crate) fn validate_source_profile(name: &str) -> Result<()> {
281    let ok = !name.is_empty()
282        && name.len() <= 64
283        && !name.starts_with('.')
284        && name
285            .chars()
286            .all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_' | '.'));
287    if ok {
288        Ok(())
289    } else {
290        Err(BrowserError::Invalid(format!(
291            "invalid source profile name '{name}'"
292        )))
293    }
294}
295
296fn host_matches(domain: &str, host: &str) -> bool {
297    let host = host.trim_end_matches('.').to_ascii_lowercase();
298    host == domain || host.ends_with(&format!(".{domain}"))
299}
300
301fn domain_allowed(domains: &Option<Vec<String>>, host: &str) -> bool {
302    match domains {
303        None => true,
304        Some(list) => list.iter().any(|d| host_matches(d, host)),
305    }
306}
307
308/// What the user agreed to: which browser, which profile, which domains. The app persists it
309/// (it is `Serialize`/`Deserialize`), shows it, and revokes it. A revoked or expired receipt
310/// refuses every later import, attach and action.
311#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
312pub struct UserConsentReceipt {
313    pub schema: u32,
314    /// Caller-chosen unique id (for example a UUID).
315    pub id: String,
316    pub browser: BrowserKind,
317    /// Source profile directory name, for example `Default` or `Profile 1`.
318    pub profile: String,
319    /// Domains (each covers its subdomains) the agent may act on; `None` means every domain.
320    pub domains: Option<Vec<String>>,
321    pub granted_at_ms: u64,
322    pub expires_at_ms: Option<u64>,
323    pub revoked_at_ms: Option<u64>,
324}
325
326impl UserConsentReceipt {
327    pub fn new(
328        id: impl Into<String>,
329        browser: BrowserKind,
330        profile: impl Into<String>,
331        domains: Option<Vec<String>>,
332        granted_at_ms: u64,
333    ) -> Result<Self> {
334        let receipt = Self {
335            schema: CONSENT_SCHEMA,
336            id: id.into(),
337            browser,
338            profile: profile.into(),
339            domains,
340            granted_at_ms,
341            expires_at_ms: None,
342            revoked_at_ms: None,
343        };
344        receipt.validated()
345    }
346
347    /// Receipt that lapses at `expires_at_ms` (Unix milliseconds).
348    pub fn with_expiry(mut self, expires_at_ms: u64) -> Self {
349        self.expires_at_ms = Some(expires_at_ms);
350        self
351    }
352
353    fn validated(mut self) -> Result<Self> {
354        if self.schema != CONSENT_SCHEMA {
355            return Err(BrowserError::Consent(format!(
356                "unsupported receipt schema {}",
357                self.schema
358            )));
359        }
360        if self.id.is_empty() || self.id.len() > 128 {
361            return Err(BrowserError::Invalid(
362                "consent id must be 1-128 characters".into(),
363            ));
364        }
365        if self.browser == BrowserKind::Unknown {
366            return Err(BrowserError::Invalid(
367                "consent names an unknown browser".into(),
368            ));
369        }
370        validate_source_profile(&self.profile)?;
371        self.domains = normalize_domains(self.domains.take())?;
372        Ok(self)
373    }
374
375    /// Mark the receipt revoked at `now_ms`. The app persists the result.
376    pub fn revoke(&mut self, now_ms: u64) {
377        if self.revoked_at_ms.is_none() {
378            self.revoked_at_ms = Some(now_ms);
379        }
380    }
381
382    pub fn is_active_at(&self, now_ms: u64) -> bool {
383        self.revoked_at_ms.is_none() && self.expires_at_ms.is_none_or(|e| now_ms < e)
384    }
385
386    pub fn check_active(&self) -> Result<()> {
387        if self.is_active_at(now_ms()) {
388            Ok(())
389        } else {
390            Err(BrowserError::Consent(format!(
391                "consent {} is revoked or has expired",
392                self.id
393            )))
394        }
395    }
396
397    /// Whether `host` is inside the consented domains (a domain covers its subdomains).
398    pub fn permits_host(&self, host: &str) -> bool {
399        domain_allowed(&self.domains, host)
400    }
401
402    /// Whether an http(s) `url` is inside the consented domains.
403    pub fn permits_url(&self, url: &str) -> bool {
404        match url::Url::parse(url) {
405            Ok(u) if matches!(u.scheme(), "http" | "https") => {
406                u.host_str().is_some_and(|h| self.permits_host(h))
407            }
408            _ => false,
409        }
410    }
411
412    pub fn to_json(&self) -> Result<String> {
413        serde_json::to_string_pretty(self).map_err(|e| BrowserError::Consent(e.to_string()))
414    }
415
416    pub fn from_json(json: &str) -> Result<Self> {
417        let receipt: Self =
418            serde_json::from_str(json).map_err(|e| BrowserError::Consent(e.to_string()))?;
419        receipt.validated()
420    }
421}
422
423/// Live revocation switch shared with a running session. Calling [`Self::revoke`] makes the
424/// session's next action fail, without waiting for the app to persist the receipt.
425#[derive(Clone, Debug, Default)]
426pub struct ConsentRevocation(Arc<AtomicBool>);
427
428impl ConsentRevocation {
429    pub fn new() -> Self {
430        Self::default()
431    }
432    pub fn revoke(&self) {
433        self.0.store(true, Ordering::SeqCst);
434    }
435    pub fn is_revoked(&self) -> bool {
436        self.0.load(Ordering::SeqCst)
437    }
438}
439
440impl PartialEq for ConsentRevocation {
441    fn eq(&self, other: &Self) -> bool {
442        Arc::ptr_eq(&self.0, &other.0)
443    }
444}
445impl Eq for ConsentRevocation {}
446
447// ---------------------------------------------------------------------------
448// Import specification
449// ---------------------------------------------------------------------------
450
451/// Consent-gated copy of a browser profile's sign-ins into a named RightKit profile (see
452/// [`crate::ProfileSpec::ImportedFrom`]).
453#[derive(Clone, Debug, Eq, PartialEq)]
454pub struct ImportSpec {
455    pub browser: BrowserSource,
456    /// Source profile directory name; `None` means the consent's profile.
457    pub source_profile: Option<String>,
458    /// Narrow the consent further; `None` means the consent's domains. Every entry must be
459    /// inside the consent. Scopes the session's actions (the cookie database is copied whole).
460    pub domains: Option<Vec<String>>,
461    pub consent: UserConsentReceipt,
462    pub revocation: ConsentRevocation,
463    /// Copy again even when this consent already imported into the profile.
464    pub reimport: bool,
465}
466
467impl ImportSpec {
468    pub fn new(browser: BrowserSource, consent: UserConsentReceipt) -> Self {
469        Self {
470            browser,
471            source_profile: None,
472            domains: None,
473            consent,
474            revocation: ConsentRevocation::new(),
475            reimport: false,
476        }
477    }
478
479    pub fn source_profile(mut self, name: impl Into<String>) -> Self {
480        self.source_profile = Some(name.into());
481        self
482    }
483
484    pub fn domains(mut self, domains: Vec<String>) -> Self {
485        self.domains = Some(domains);
486        self
487    }
488
489    pub fn revocation(mut self, revocation: ConsentRevocation) -> Self {
490        self.revocation = revocation;
491        self
492    }
493
494    pub fn reimport(mut self) -> Self {
495        self.reimport = true;
496        self
497    }
498
499    pub(crate) fn effective_profile(&self) -> &str {
500        self.source_profile
501            .as_deref()
502            .unwrap_or(self.consent.profile.as_str())
503    }
504
505    /// Domains the session may act on: the narrowed list, else the consent's.
506    pub(crate) fn effective_domains(&self) -> Result<Option<Vec<String>>> {
507        match normalize_domains(self.domains.clone())? {
508            Some(list) => {
509                for d in &list {
510                    if !self.consent.permits_host(d) {
511                        return Err(BrowserError::Consent(format!(
512                            "domain {d} is outside the consent"
513                        )));
514                    }
515                }
516                Ok(Some(list))
517            }
518            None => Ok(self.consent.domains.clone()),
519        }
520    }
521
522    /// Everything that must hold before any browser data is touched.
523    pub(crate) fn validate(&self) -> Result<BrowserKind> {
524        self.consent.check_active()?;
525        if self.revocation.is_revoked() {
526            return Err(BrowserError::Consent("consent was revoked".into()));
527        }
528        let kind = self.browser.resolve();
529        if kind != self.consent.browser {
530            return Err(BrowserError::Consent(format!(
531                "consent was granted for {}, not {}",
532                self.consent.browser.name(),
533                kind.name()
534            )));
535        }
536        validate_source_profile(self.effective_profile())?;
537        if self.effective_profile() != self.consent.profile {
538            return Err(BrowserError::Consent(format!(
539                "consent was granted for profile '{}', not '{}'",
540                self.consent.profile,
541                self.effective_profile()
542            )));
543        }
544        self.effective_domains()?;
545        if !kind.is_chromium_family() {
546            return Err(BrowserError::Unsupported(format!(
547                "{} sessions cannot be imported into a CDP profile; drive {} through rightkit-automation",
548                kind.name(),
549                kind.name()
550            )));
551        }
552        Ok(kind)
553    }
554}
555
556// ---------------------------------------------------------------------------
557// Scoped admission
558// ---------------------------------------------------------------------------
559
560fn scope_verdict(
561    consent: &UserConsentReceipt,
562    domains: &Option<Vec<String>>,
563    revocation: &ConsentRevocation,
564    req: &AdmissionRequest,
565) -> Option<String> {
566    if revocation.is_revoked() || !consent.is_active_at(now_ms()) {
567        return Some("user consent was revoked or has expired".into());
568    }
569    if matches!(req.action, ActionKind::Fill | ActionKind::TypeText) {
570        let target = req.target.as_deref().unwrap_or("").to_ascii_lowercase();
571        if target.contains("password") || target.contains("passwd") {
572            return Some(
573                "passwords come from the browser's own password manager, never from the agent"
574                    .into(),
575            );
576        }
577    }
578    match req.url.as_deref() {
579        None => {
580            if matches!(req.action, ActionKind::Navigate) {
581                Some("navigation without a URL".into())
582            } else {
583                None
584            }
585        }
586        Some("about:blank") => None,
587        Some(raw) => match url::Url::parse(raw) {
588            Ok(u) if matches!(u.scheme(), "http" | "https") => match u.host_str() {
589                Some(host) if domain_allowed(domains, host) => None,
590                _ => Some(format!(
591                    "{raw} is outside the domains the user consented to"
592                )),
593            },
594            _ => Some(format!("{raw} is not an http(s) page inside the consent")),
595        },
596    }
597}
598
599/// Admission hook that refuses every action outside the consent, then defers to `inner`.
600pub(crate) fn scoped_admission(
601    spec: &ImportSpec,
602    inner: Option<AdmissionHook>,
603) -> Result<AdmissionHook> {
604    let consent = spec.consent.clone();
605    let domains = spec.effective_domains()?;
606    let revocation = spec.revocation.clone();
607    Ok(Arc::new(move |req: AdmissionRequest| {
608        let verdict = scope_verdict(&consent, &domains, &revocation, &req);
609        let inner = inner.clone();
610        async move {
611            if let Some(reason) = verdict {
612                return Decision::Deny(reason);
613            }
614            match inner {
615                Some(hook) => hook(req).await,
616                None => Decision::Allow,
617            }
618        }
619        .boxed()
620    }))
621}
622
623// ---------------------------------------------------------------------------
624// Chromium-family profile discovery and import
625// ---------------------------------------------------------------------------
626
627/// The browser's own user-data directory (read only by this module), when it exists.
628pub fn user_data_dir(kind: BrowserKind) -> Option<PathBuf> {
629    let rel: &[&str] = match kind {
630        BrowserKind::Chrome => &["Google", "Chrome"],
631        BrowserKind::Edge => &["Microsoft", "Edge"],
632        BrowserKind::Chromium => &["Chromium"],
633        BrowserKind::Brave => &["BraveSoftware", "Brave-Browser"],
634        _ => return None,
635    };
636    let base: PathBuf = if cfg!(windows) {
637        let mut p = PathBuf::from(std::env::var_os("LOCALAPPDATA")?);
638        for part in rel {
639            p.push(part);
640        }
641        p.push("User Data");
642        return p.is_dir().then_some(p);
643    } else if cfg!(target_os = "macos") {
644        let mut p = PathBuf::from(std::env::var_os("HOME")?);
645        p.push("Library");
646        p.push("Application Support");
647        p
648    } else {
649        let mut p = PathBuf::from(std::env::var_os("HOME")?);
650        p.push(".config");
651        p
652    };
653    let mut path = base;
654    if cfg!(target_os = "macos") {
655        for part in rel {
656            path.push(part);
657        }
658    } else {
659        // Linux directory names are lower-case and hyphenated.
660        let name = match kind {
661            BrowserKind::Chrome => "google-chrome",
662            BrowserKind::Edge => "microsoft-edge",
663            BrowserKind::Chromium => "chromium",
664            _ => "BraveSoftware/Brave-Browser",
665        };
666        path.push(name);
667    }
668    path.is_dir().then_some(path)
669}
670
671/// The installed browser executable for a Chromium-family kind.
672pub fn browser_executable(kind: BrowserKind) -> Option<PathBuf> {
673    let candidates: &[&str] = if cfg!(windows) {
674        match kind {
675            BrowserKind::Chrome => &[
676                "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
677                "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
678            ],
679            BrowserKind::Edge => &[
680                "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
681                "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
682            ],
683            BrowserKind::Brave => {
684                &["C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"]
685            }
686            _ => &[],
687        }
688    } else if cfg!(target_os = "macos") {
689        match kind {
690            BrowserKind::Chrome => {
691                &["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"]
692            }
693            BrowserKind::Edge => {
694                &["/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"]
695            }
696            BrowserKind::Chromium => &["/Applications/Chromium.app/Contents/MacOS/Chromium"],
697            BrowserKind::Brave => &["/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"],
698            _ => &[],
699        }
700    } else {
701        match kind {
702            BrowserKind::Chrome => &["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"],
703            BrowserKind::Edge => &["/usr/bin/microsoft-edge", "/usr/bin/microsoft-edge-stable"],
704            BrowserKind::Chromium => &["/usr/bin/chromium", "/usr/bin/chromium-browser"],
705            BrowserKind::Brave => &["/usr/bin/brave-browser"],
706            _ => &[],
707        }
708    };
709    candidates.iter().map(PathBuf::from).find(|p| p.exists())
710}
711
712/// One profile of a Chromium-family browser.
713#[derive(Clone, Debug, Eq, PartialEq)]
714pub struct SourceProfile {
715    /// Directory name inside the user-data directory (`Default`, `Profile 1`).
716    pub dir_name: String,
717    /// Name shown in the browser's profile picker.
718    pub display_name: String,
719}
720
721pub(crate) fn parse_profiles(local_state: &str) -> Result<Vec<SourceProfile>> {
722    let value: serde_json::Value = serde_json::from_str(local_state)
723        .map_err(|e| BrowserError::Profile(format!("unreadable Local State: {e}")))?;
724    let mut out = Vec::new();
725    if let Some(cache) = value
726        .get("profile")
727        .and_then(|p| p.get("info_cache"))
728        .and_then(|c| c.as_object())
729    {
730        for (dir, info) in cache {
731            let display = info
732                .get("name")
733                .and_then(|n| n.as_str())
734                .unwrap_or(dir.as_str())
735                .to_string();
736            out.push(SourceProfile {
737                dir_name: dir.clone(),
738                display_name: display,
739            });
740        }
741    }
742    out.sort_by(|a, b| a.dir_name.cmp(&b.dir_name));
743    Ok(out)
744}
745
746/// Profiles of an installed Chromium-family browser, for the consent screen.
747pub fn list_profiles(kind: BrowserKind) -> Result<Vec<SourceProfile>> {
748    if !kind.is_chromium_family() {
749        return Err(BrowserError::Unsupported(format!(
750            "profile listing covers Chromium-family browsers, not {}",
751            kind.name()
752        )));
753    }
754    let dir = user_data_dir(kind).ok_or_else(|| {
755        BrowserError::Profile(format!("{} has no user-data directory", kind.name()))
756    })?;
757    let text = std::fs::read_to_string(dir.join("Local State"))?;
758    parse_profiles(&text)
759}
760
761/// Result of one import. Per-domain cookie counts need the cookie database opened, which this
762/// module does not do, so `domain_counts` is `None`.
763#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
764pub struct ImportReport {
765    pub consent_id: String,
766    pub browser: BrowserKind,
767    pub source_profile: String,
768    /// Paths copied, relative to the source user-data directory.
769    pub files_copied: Vec<String>,
770    pub bytes_copied: u64,
771    pub domain_counts: Option<BTreeMap<String, u64>>,
772    pub imported_at_ms: u64,
773}
774
775fn copy_tree(src: &Path, dst: &Path, bytes: &mut u64) -> Result<()> {
776    std::fs::create_dir_all(dst)?;
777    for entry in std::fs::read_dir(src)? {
778        let entry = entry?;
779        let meta = std::fs::symlink_metadata(entry.path())?;
780        if meta.file_type().is_symlink() {
781            continue;
782        }
783        let target = dst.join(entry.file_name());
784        if meta.is_dir() {
785            copy_tree(&entry.path(), &target, bytes)?;
786        } else if entry.file_name() != "LOCK" {
787            *bytes += copy_file(&entry.path(), &target)?;
788        }
789    }
790    Ok(())
791}
792
793fn copy_file(src: &Path, dst: &Path) -> Result<u64> {
794    if let Some(parent) = dst.parent() {
795        std::fs::create_dir_all(parent)?;
796    }
797    std::fs::copy(src, dst).map_err(|e| {
798        BrowserError::Profile(format!(
799            "could not copy {} ({e}); close the browser or wait for it to release the file, then import again",
800            src.display()
801        ))
802    })
803}
804
805/// Copy the sign-in files of `source_profile` from `user_data` into `dest_root` (the RightKit
806/// profile directory, which Chrome later opens as its user-data directory). Copies the cookie
807/// database, local storage and `Local State`; never `Login Data`, `Web Data` or history.
808pub(crate) fn import_chromium_profile(
809    user_data: &Path,
810    source_profile: &str,
811    dest_root: &Path,
812    consent_id: &str,
813    browser: BrowserKind,
814) -> Result<ImportReport> {
815    validate_source_profile(source_profile)?;
816    let src = user_data.join(source_profile);
817    if !src.is_dir() {
818        return Err(BrowserError::Profile(format!(
819            "source profile not found: {}",
820            src.display()
821        )));
822    }
823    let dst = dest_root.join("Default");
824    let mut files: Vec<String> = Vec::new();
825    let mut bytes: u64 = 0;
826
827    for rel in [
828        "Network/Cookies",
829        "Network/Cookies-journal",
830        "Cookies",
831        "Cookies-journal",
832    ] {
833        let from = src.join(rel);
834        if from.is_file() {
835            bytes += copy_file(&from, &dst.join(rel))?;
836            files.push(format!("{source_profile}/{rel}"));
837        }
838    }
839    if !files.iter().any(|f| f.ends_with("Cookies")) {
840        return Err(BrowserError::Profile(format!(
841            "no cookie database in {}",
842            src.display()
843        )));
844    }
845    let local_storage = src.join("Local Storage");
846    if local_storage.is_dir() {
847        let target = dst.join("Local Storage");
848        if target.exists() {
849            std::fs::remove_dir_all(&target)?;
850        }
851        copy_tree(&local_storage, &target, &mut bytes)?;
852        files.push(format!("{source_profile}/Local Storage"));
853    }
854    let local_state = user_data.join("Local State");
855    if local_state.is_file() {
856        bytes += copy_file(&local_state, &dest_root.join("Local State"))?;
857        files.push("Local State".into());
858    }
859    Ok(ImportReport {
860        consent_id: consent_id.to_string(),
861        browser,
862        source_profile: source_profile.to_string(),
863        files_copied: files,
864        bytes_copied: bytes,
865        domain_counts: None,
866        imported_at_ms: now_ms(),
867    })
868}
869
870fn marker_consent_id(dest_root: &Path) -> Option<String> {
871    let text = std::fs::read_to_string(dest_root.join(IMPORT_MARKER)).ok()?;
872    let value: serde_json::Value = serde_json::from_str(&text).ok()?;
873    value.get("consent_id")?.as_str().map(|s| s.to_string())
874}
875
876/// Validate the spec and import into `dest_root` when this consent has not imported there yet
877/// (or `reimport` is set). Returns the report when a copy happened.
878pub(crate) fn import_if_needed(
879    spec: &ImportSpec,
880    dest_root: &Path,
881) -> Result<Option<ImportReport>> {
882    let kind = spec.validate()?;
883    if !spec.reimport && marker_consent_id(dest_root).as_deref() == Some(spec.consent.id.as_str()) {
884        return Ok(None);
885    }
886    let user_data = user_data_dir(kind).ok_or_else(|| {
887        BrowserError::Profile(format!(
888            "{} has no user-data directory on this machine",
889            kind.name()
890        ))
891    })?;
892    let report = import_chromium_profile(
893        &user_data,
894        spec.effective_profile(),
895        dest_root,
896        &spec.consent.id,
897        kind,
898    )?;
899    let json =
900        serde_json::to_string_pretty(&report).map_err(|e| BrowserError::Profile(e.to_string()))?;
901    std::fs::write(dest_root.join(IMPORT_MARKER), json)?;
902    Ok(Some(report))
903}
904
905/// Delete an imported RightKit profile (revoking consent should call this). Refuses a directory
906/// RightKit did not import into, and a profile a live session holds.
907pub fn purge_imported_profile(root: &Path, name: &str) -> Result<()> {
908    crate::config::validate_profile_name(name)?;
909    crate::config::reject_real_browser_profile(root)?;
910    let dir = root.join(name);
911    if !dir.join(IMPORT_MARKER).is_file() {
912        return Err(BrowserError::Profile(format!(
913            "'{name}' is not an imported profile; nothing deleted"
914        )));
915    }
916    {
917        let lock = std::fs::OpenOptions::new()
918            .create(true)
919            .write(true)
920            .truncate(false)
921            .open(dir.join(".rightkit-browser.lock"))?;
922        match lock.try_lock() {
923            Ok(()) => {}
924            Err(std::fs::TryLockError::WouldBlock) => {
925                return Err(BrowserError::ProfileInUse(name.to_string()));
926            }
927            Err(std::fs::TryLockError::Error(e)) => return Err(e.into()),
928        }
929    }
930    std::fs::remove_dir_all(&dir)?;
931    Ok(())
932}
933
934/// Profile name for [`crate::BrowserSession::attach_user_browser`].
935pub(crate) fn attach_profile_name(consent: &UserConsentReceipt) -> String {
936    let slug: String = consent
937        .profile
938        .chars()
939        .map(|c| {
940            if c.is_ascii_alphanumeric() {
941                c.to_ascii_lowercase()
942            } else {
943                '-'
944            }
945        })
946        .collect();
947    format!("user-{}-{}", consent.browser.name(), slug)
948}
949
950#[cfg(test)]
951mod tests {
952    use super::*;
953
954    fn receipt(domains: Option<Vec<&str>>) -> UserConsentReceipt {
955        UserConsentReceipt::new(
956            "c-1",
957            BrowserKind::Chrome,
958            "Default",
959            domains.map(|d| d.into_iter().map(String::from).collect()),
960            1_000,
961        )
962        .unwrap()
963    }
964
965    fn request(action: ActionKind, url: Option<&str>, target: Option<&str>) -> AdmissionRequest {
966        AdmissionRequest {
967            session_id: "bs-1".into(),
968            page_id: "p-1".into(),
969            action,
970            url: url.map(String::from),
971            target: target.map(String::from),
972            detail: None,
973        }
974    }
975
976    #[test]
977    fn detects_windows_prog_ids() {
978        let out =
979            "\r\nHKEY_CURRENT_USER\\...\\UserChoice\r\n    ProgId    REG_SZ    ChromeHTML\r\n";
980        assert_eq!(parse_windows_prog_id(out), Some(BrowserKind::Chrome));
981        let out = "    ProgId    REG_SZ    MSEdgeHTM";
982        assert_eq!(parse_windows_prog_id(out), Some(BrowserKind::Edge));
983        let out = "    ProgId    REG_SZ    FirefoxURL-308046B0AF4A39CB";
984        assert_eq!(parse_windows_prog_id(out), Some(BrowserKind::Firefox));
985        assert_eq!(parse_windows_prog_id("ERROR: not found"), None);
986    }
987
988    #[test]
989    fn detects_macos_https_handler() {
990        let out = "(\n    {\n        LSHandlerPreferredVersions = {\n            LSHandlerRoleAll = \"-\";\n        };\n        LSHandlerRoleAll = \"com.google.chrome\";\n        LSHandlerURLScheme = https;\n    },\n    {\n        LSHandlerRoleAll = \"com.apple.mail\";\n        LSHandlerURLScheme = mailto;\n    }\n)";
991        assert_eq!(parse_macos_handlers(out), Some(BrowserKind::Chrome));
992        assert_eq!(parse_macos_handlers("(\n)"), None);
993    }
994
995    #[test]
996    fn detects_linux_desktop_entries() {
997        assert_eq!(
998            parse_desktop_entry("google-chrome.desktop\n"),
999            Some(BrowserKind::Chrome)
1000        );
1001        assert_eq!(
1002            parse_desktop_entry("firefox.desktop"),
1003            Some(BrowserKind::Firefox)
1004        );
1005        assert_eq!(
1006            parse_desktop_entry("chromium-browser.desktop"),
1007            Some(BrowserKind::Chromium)
1008        );
1009        assert_eq!(parse_desktop_entry(""), None);
1010    }
1011
1012    #[test]
1013    fn domains_normalize_and_cover_subdomains() {
1014        let r = receipt(Some(vec!["*.Example.com", "example.com", "bank.test"]));
1015        assert_eq!(
1016            r.domains,
1017            Some(vec!["example.com".to_string(), "bank.test".to_string()])
1018        );
1019        assert!(r.permits_url("https://app.example.com/x"));
1020        assert!(r.permits_url("https://example.com"));
1021        assert!(!r.permits_url("https://notexample.com"));
1022        assert!(!r.permits_url("https://example.com.evil.test"));
1023        assert!(!r.permits_url("file:///etc/passwd"));
1024        assert!(
1025            UserConsentReceipt::new("c", BrowserKind::Chrome, "Default", Some(vec![]), 1).is_err()
1026        );
1027        assert!(UserConsentReceipt::new(
1028            "c",
1029            BrowserKind::Chrome,
1030            "Default",
1031            Some(vec!["a/b".into()]),
1032            1
1033        )
1034        .is_err());
1035        assert!(UserConsentReceipt::new("c", BrowserKind::Chrome, "..", None, 1).is_err());
1036        assert!(UserConsentReceipt::new("c", BrowserKind::Unknown, "Default", None, 1).is_err());
1037    }
1038
1039    #[test]
1040    fn receipt_round_trips_and_revokes() {
1041        let mut r = receipt(Some(vec!["example.com"])).with_expiry(5_000);
1042        assert!(r.is_active_at(4_999));
1043        assert!(!r.is_active_at(5_000));
1044        let back = UserConsentReceipt::from_json(&r.to_json().unwrap()).unwrap();
1045        assert_eq!(back, r);
1046        r.revoke(2_000);
1047        assert!(!r.is_active_at(2_001));
1048        assert_eq!(r.revoked_at_ms, Some(2_000));
1049        assert!(r.check_active().is_err());
1050    }
1051
1052    #[test]
1053    fn import_spec_rejects_scope_widening_and_mismatches() {
1054        let consent = receipt(Some(vec!["example.com"]));
1055        let ok = ImportSpec::new(BrowserSource::Chrome, consent.clone());
1056        assert!(ok.validate().is_ok());
1057        let wider = ImportSpec::new(BrowserSource::Chrome, consent.clone())
1058            .domains(vec!["other.test".into()]);
1059        assert!(matches!(wider.validate(), Err(BrowserError::Consent(_))));
1060        let narrower = ImportSpec::new(BrowserSource::Chrome, consent.clone())
1061            .domains(vec!["shop.example.com".into()]);
1062        assert_eq!(
1063            narrower.effective_domains().unwrap(),
1064            Some(vec!["shop.example.com".to_string()])
1065        );
1066        let wrong_browser = ImportSpec::new(BrowserSource::Edge, consent.clone());
1067        assert!(matches!(
1068            wrong_browser.validate(),
1069            Err(BrowserError::Consent(_))
1070        ));
1071        let wrong_profile =
1072            ImportSpec::new(BrowserSource::Chrome, consent.clone()).source_profile("Profile 1");
1073        assert!(matches!(
1074            wrong_profile.validate(),
1075            Err(BrowserError::Consent(_))
1076        ));
1077        let revocation = ConsentRevocation::new();
1078        let live = ImportSpec::new(BrowserSource::Chrome, consent).revocation(revocation.clone());
1079        revocation.revoke();
1080        assert!(matches!(live.validate(), Err(BrowserError::Consent(_))));
1081        let safari = UserConsentReceipt::new("s", BrowserKind::Safari, "Default", None, 1).unwrap();
1082        assert!(matches!(
1083            ImportSpec::new(BrowserSource::Safari, safari).validate(),
1084            Err(BrowserError::Unsupported(_))
1085        ));
1086    }
1087
1088    #[test]
1089    fn scope_refuses_other_domains_passwords_and_revocation() {
1090        let consent = receipt(Some(vec!["example.com"]));
1091        let spec = ImportSpec::new(BrowserSource::Chrome, consent);
1092        let hook = scoped_admission(&spec, None).unwrap();
1093        let run = |req| futures::executor::block_on(hook(req));
1094        assert_eq!(
1095            run(request(
1096                ActionKind::Navigate,
1097                Some("https://app.example.com/"),
1098                None
1099            )),
1100            Decision::Allow
1101        );
1102        assert_eq!(
1103            run(request(ActionKind::Click, Some("about:blank"), None)),
1104            Decision::Allow
1105        );
1106        assert!(matches!(
1107            run(request(
1108                ActionKind::Navigate,
1109                Some("https://evil.test/"),
1110                None
1111            )),
1112            Decision::Deny(_)
1113        ));
1114        assert!(matches!(
1115            run(request(
1116                ActionKind::Click,
1117                Some("https://evil.test/"),
1118                Some("#go")
1119            )),
1120            Decision::Deny(_)
1121        ));
1122        assert!(matches!(
1123            run(request(
1124                ActionKind::Fill,
1125                Some("https://example.com/login"),
1126                Some("input[type=password]")
1127            )),
1128            Decision::Deny(_)
1129        ));
1130        assert_eq!(
1131            run(request(
1132                ActionKind::Fill,
1133                Some("https://example.com/login"),
1134                Some("#user")
1135            )),
1136            Decision::Allow
1137        );
1138        spec.revocation.revoke();
1139        assert!(matches!(
1140            run(request(
1141                ActionKind::Click,
1142                Some("https://example.com/"),
1143                None
1144            )),
1145            Decision::Deny(_)
1146        ));
1147    }
1148
1149    #[test]
1150    fn scope_defers_to_the_inner_hook() {
1151        let consent = receipt(None);
1152        let spec = ImportSpec::new(BrowserSource::Chrome, consent);
1153        let inner: AdmissionHook = Arc::new(|_req: AdmissionRequest| {
1154            async { Decision::Deny("inner says no".into()) }.boxed()
1155        });
1156        let hook = scoped_admission(&spec, Some(inner)).unwrap();
1157        let verdict = futures::executor::block_on(hook(request(
1158            ActionKind::Click,
1159            Some("https://example.com/"),
1160            None,
1161        )));
1162        assert_eq!(verdict, Decision::Deny("inner says no".into()));
1163    }
1164
1165    #[test]
1166    fn parses_profile_picker_names() {
1167        let json = "{\"profile\":{\"info_cache\":{\"Profile 1\":{\"name\":\"Work\"},\"Default\":{\"name\":\"Adrian\"}}}}";
1168        let got = parse_profiles(json).unwrap();
1169        assert_eq!(
1170            got,
1171            vec![
1172                SourceProfile {
1173                    dir_name: "Default".into(),
1174                    display_name: "Adrian".into()
1175                },
1176                SourceProfile {
1177                    dir_name: "Profile 1".into(),
1178                    display_name: "Work".into()
1179                },
1180            ]
1181        );
1182    }
1183
1184    #[test]
1185    fn import_copies_sign_in_files_and_never_the_password_store() {
1186        let temp = tempfile::tempdir().unwrap();
1187        let user = temp.path().join("user data");
1188        let profile = user.join("Default");
1189        std::fs::create_dir_all(profile.join("Network")).unwrap();
1190        std::fs::create_dir_all(profile.join("Local Storage").join("leveldb")).unwrap();
1191        std::fs::write(profile.join("Network").join("Cookies"), "cookies").unwrap();
1192        std::fs::write(
1193            profile
1194                .join("Local Storage")
1195                .join("leveldb")
1196                .join("000003.log"),
1197            "ls",
1198        )
1199        .unwrap();
1200        std::fs::write(
1201            profile.join("Local Storage").join("leveldb").join("LOCK"),
1202            "",
1203        )
1204        .unwrap();
1205        std::fs::write(profile.join("Login Data"), "passwords").unwrap();
1206        std::fs::write(profile.join("Web Data"), "forms").unwrap();
1207        std::fs::write(profile.join("History"), "history").unwrap();
1208        std::fs::write(user.join("Local State"), "{}").unwrap();
1209        let dest = temp.path().join("dest");
1210        let report =
1211            import_chromium_profile(&user, "Default", &dest, "c-1", BrowserKind::Chrome).unwrap();
1212        assert!(dest
1213            .join("Default")
1214            .join("Network")
1215            .join("Cookies")
1216            .is_file());
1217        assert!(dest
1218            .join("Default")
1219            .join("Local Storage")
1220            .join("leveldb")
1221            .join("000003.log")
1222            .is_file());
1223        assert!(!dest
1224            .join("Default")
1225            .join("Local Storage")
1226            .join("leveldb")
1227            .join("LOCK")
1228            .exists());
1229        assert!(dest.join("Local State").is_file());
1230        for never in ["Login Data", "Web Data", "History"] {
1231            assert!(
1232                !dest.join("Default").join(never).exists(),
1233                "{never} was copied"
1234            );
1235        }
1236        assert_eq!(report.domain_counts, None);
1237        assert!(report
1238            .files_copied
1239            .iter()
1240            .any(|f| f == "Default/Network/Cookies"));
1241        let missing =
1242            import_chromium_profile(&user, "Profile 9", &dest, "c-1", BrowserKind::Chrome);
1243        assert!(matches!(missing, Err(BrowserError::Profile(_))));
1244        assert!(import_chromium_profile(&user, "../x", &dest, "c-1", BrowserKind::Chrome).is_err());
1245    }
1246
1247    #[test]
1248    fn purge_only_touches_imported_profiles() {
1249        let temp = tempfile::tempdir().unwrap();
1250        let plain = temp.path().join("plain");
1251        std::fs::create_dir_all(&plain).unwrap();
1252        assert!(purge_imported_profile(temp.path(), "plain").is_err());
1253        assert!(plain.is_dir());
1254        let imported = temp.path().join("imp");
1255        std::fs::create_dir_all(&imported).unwrap();
1256        std::fs::write(imported.join(IMPORT_MARKER), "{}").unwrap();
1257        purge_imported_profile(temp.path(), "imp").unwrap();
1258        assert!(!imported.exists());
1259    }
1260
1261    #[test]
1262    fn attach_profile_name_is_a_valid_profile_name() {
1263        let r = UserConsentReceipt::new("c", BrowserKind::Edge, "Profile 1", None, 1).unwrap();
1264        let name = attach_profile_name(&r);
1265        assert_eq!(name, "user-edge-profile-1");
1266        assert!(crate::config::validate_profile_name(&name).is_ok());
1267    }
1268}