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    let per_user: &[&str] = if cfg!(windows) {
710        match kind {
711            BrowserKind::Chrome => &[r"Google\Chrome\Application\chrome.exe"],
712            BrowserKind::Edge => &[r"Microsoft\Edge\Application\msedge.exe"],
713            BrowserKind::Brave => &[r"BraveSoftware\Brave-Browser\Application\brave.exe"],
714            _ => &[],
715        }
716    } else {
717        &[]
718    };
719    candidates
720        .iter()
721        .map(PathBuf::from)
722        .chain(crate::config::windows_local_app_candidates(per_user))
723        .find(|p| p.exists())
724}
725
726/// One profile of a Chromium-family browser.
727#[derive(Clone, Debug, Eq, PartialEq)]
728pub struct SourceProfile {
729    /// Directory name inside the user-data directory (`Default`, `Profile 1`).
730    pub dir_name: String,
731    /// Name shown in the browser's profile picker.
732    pub display_name: String,
733}
734
735pub(crate) fn parse_profiles(local_state: &str) -> Result<Vec<SourceProfile>> {
736    let value: serde_json::Value = serde_json::from_str(local_state)
737        .map_err(|e| BrowserError::Profile(format!("unreadable Local State: {e}")))?;
738    let mut out = Vec::new();
739    if let Some(cache) = value
740        .get("profile")
741        .and_then(|p| p.get("info_cache"))
742        .and_then(|c| c.as_object())
743    {
744        for (dir, info) in cache {
745            let display = info
746                .get("name")
747                .and_then(|n| n.as_str())
748                .unwrap_or(dir.as_str())
749                .to_string();
750            out.push(SourceProfile {
751                dir_name: dir.clone(),
752                display_name: display,
753            });
754        }
755    }
756    out.sort_by(|a, b| a.dir_name.cmp(&b.dir_name));
757    Ok(out)
758}
759
760/// Profiles of an installed Chromium-family browser, for the consent screen.
761pub fn list_profiles(kind: BrowserKind) -> Result<Vec<SourceProfile>> {
762    if !kind.is_chromium_family() {
763        return Err(BrowserError::Unsupported(format!(
764            "profile listing covers Chromium-family browsers, not {}",
765            kind.name()
766        )));
767    }
768    let dir = user_data_dir(kind).ok_or_else(|| {
769        BrowserError::Profile(format!("{} has no user-data directory", kind.name()))
770    })?;
771    let text = std::fs::read_to_string(dir.join("Local State"))?;
772    parse_profiles(&text)
773}
774
775/// Result of one import. Per-domain cookie counts need the cookie database opened, which this
776/// module does not do, so `domain_counts` is `None`.
777#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
778pub struct ImportReport {
779    pub consent_id: String,
780    pub browser: BrowserKind,
781    pub source_profile: String,
782    /// Paths copied, relative to the source user-data directory.
783    pub files_copied: Vec<String>,
784    pub bytes_copied: u64,
785    pub domain_counts: Option<BTreeMap<String, u64>>,
786    pub imported_at_ms: u64,
787}
788
789fn copy_tree(src: &Path, dst: &Path, bytes: &mut u64) -> Result<()> {
790    std::fs::create_dir_all(dst)?;
791    for entry in std::fs::read_dir(src)? {
792        let entry = entry?;
793        let meta = std::fs::symlink_metadata(entry.path())?;
794        if meta.file_type().is_symlink() {
795            continue;
796        }
797        let target = dst.join(entry.file_name());
798        if meta.is_dir() {
799            copy_tree(&entry.path(), &target, bytes)?;
800        } else if entry.file_name() != "LOCK" {
801            *bytes += copy_file(&entry.path(), &target)?;
802        }
803    }
804    Ok(())
805}
806
807fn copy_file(src: &Path, dst: &Path) -> Result<u64> {
808    if let Some(parent) = dst.parent() {
809        std::fs::create_dir_all(parent)?;
810    }
811    std::fs::copy(src, dst).map_err(|e| {
812        BrowserError::Profile(format!(
813            "could not copy {} ({e}); close the browser or wait for it to release the file, then import again",
814            src.display()
815        ))
816    })
817}
818
819/// Copy the sign-in files of `source_profile` from `user_data` into `dest_root` (the RightKit
820/// profile directory, which Chrome later opens as its user-data directory). Copies the cookie
821/// database, local storage and `Local State`; never `Login Data`, `Web Data` or history.
822pub(crate) fn import_chromium_profile(
823    user_data: &Path,
824    source_profile: &str,
825    dest_root: &Path,
826    consent_id: &str,
827    browser: BrowserKind,
828) -> Result<ImportReport> {
829    validate_source_profile(source_profile)?;
830    let src = user_data.join(source_profile);
831    if !src.is_dir() {
832        return Err(BrowserError::Profile(format!(
833            "source profile not found: {}",
834            src.display()
835        )));
836    }
837    let dst = dest_root.join("Default");
838    let mut files: Vec<String> = Vec::new();
839    let mut bytes: u64 = 0;
840
841    for rel in [
842        "Network/Cookies",
843        "Network/Cookies-journal",
844        "Cookies",
845        "Cookies-journal",
846    ] {
847        let from = src.join(rel);
848        if from.is_file() {
849            bytes += copy_file(&from, &dst.join(rel))?;
850            files.push(format!("{source_profile}/{rel}"));
851        }
852    }
853    if !files.iter().any(|f| f.ends_with("Cookies")) {
854        return Err(BrowserError::Profile(format!(
855            "no cookie database in {}",
856            src.display()
857        )));
858    }
859    let local_storage = src.join("Local Storage");
860    if local_storage.is_dir() {
861        let target = dst.join("Local Storage");
862        if target.exists() {
863            std::fs::remove_dir_all(&target)?;
864        }
865        copy_tree(&local_storage, &target, &mut bytes)?;
866        files.push(format!("{source_profile}/Local Storage"));
867    }
868    let local_state = user_data.join("Local State");
869    if local_state.is_file() {
870        bytes += copy_file(&local_state, &dest_root.join("Local State"))?;
871        files.push("Local State".into());
872    }
873    Ok(ImportReport {
874        consent_id: consent_id.to_string(),
875        browser,
876        source_profile: source_profile.to_string(),
877        files_copied: files,
878        bytes_copied: bytes,
879        domain_counts: None,
880        imported_at_ms: now_ms(),
881    })
882}
883
884fn marker_consent_id(dest_root: &Path) -> Option<String> {
885    let text = std::fs::read_to_string(dest_root.join(IMPORT_MARKER)).ok()?;
886    let value: serde_json::Value = serde_json::from_str(&text).ok()?;
887    value.get("consent_id")?.as_str().map(|s| s.to_string())
888}
889
890/// Validate the spec and import into `dest_root` when this consent has not imported there yet
891/// (or `reimport` is set). Returns the report when a copy happened.
892pub(crate) fn import_if_needed(
893    spec: &ImportSpec,
894    dest_root: &Path,
895) -> Result<Option<ImportReport>> {
896    let kind = spec.validate()?;
897    if !spec.reimport && marker_consent_id(dest_root).as_deref() == Some(spec.consent.id.as_str()) {
898        return Ok(None);
899    }
900    let user_data = user_data_dir(kind).ok_or_else(|| {
901        BrowserError::Profile(format!(
902            "{} has no user-data directory on this machine",
903            kind.name()
904        ))
905    })?;
906    let report = import_chromium_profile(
907        &user_data,
908        spec.effective_profile(),
909        dest_root,
910        &spec.consent.id,
911        kind,
912    )?;
913    let json =
914        serde_json::to_string_pretty(&report).map_err(|e| BrowserError::Profile(e.to_string()))?;
915    std::fs::write(dest_root.join(IMPORT_MARKER), json)?;
916    Ok(Some(report))
917}
918
919/// Delete an imported RightKit profile (revoking consent should call this). Refuses a directory
920/// RightKit did not import into, and a profile a live session holds.
921pub fn purge_imported_profile(root: &Path, name: &str) -> Result<()> {
922    crate::config::validate_profile_name(name)?;
923    crate::config::reject_real_browser_profile(root)?;
924    let dir = root.join(name);
925    if !dir.join(IMPORT_MARKER).is_file() {
926        return Err(BrowserError::Profile(format!(
927            "'{name}' is not an imported profile; nothing deleted"
928        )));
929    }
930    {
931        let lock = std::fs::OpenOptions::new()
932            .create(true)
933            .write(true)
934            .truncate(false)
935            .open(dir.join(".rightkit-browser.lock"))?;
936        match lock.try_lock() {
937            Ok(()) => {}
938            Err(std::fs::TryLockError::WouldBlock) => {
939                return Err(BrowserError::ProfileInUse(name.to_string()));
940            }
941            Err(std::fs::TryLockError::Error(e)) => return Err(e.into()),
942        }
943    }
944    std::fs::remove_dir_all(&dir)?;
945    Ok(())
946}
947
948/// Profile name for [`crate::BrowserSession::attach_user_browser`].
949pub(crate) fn attach_profile_name(consent: &UserConsentReceipt) -> String {
950    let slug: String = consent
951        .profile
952        .chars()
953        .map(|c| {
954            if c.is_ascii_alphanumeric() {
955                c.to_ascii_lowercase()
956            } else {
957                '-'
958            }
959        })
960        .collect();
961    format!("user-{}-{}", consent.browser.name(), slug)
962}