YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat(owned-browser): cookie inheritance — add Chrome/Brave/Edge on macOS, stub Win/Linux
Louis Beaumont59b5fb45d3ca
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex 56d441abe..487d46845 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -55,7 +55,10 @@ mod livetext;mod livetext_ffi;mod oauth;mod owned_browser;-#[cfg(target_os = "macos")]+// Cross-platform shape: macOS reads Arc/Chrome/Brave/Edge cookies and+// injects via WKHTTPCookieStore; other platforms compile to a stub+// `cookies_for_host` that returns empty until Windows (DPAPI + AES-256-+// GCM + WebView2) and Linux (libsecret + webkit2gtk) readers land.mod owned_browser_cookies;mod permission_events;mod permissions;diff --git a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rsindex 2d6424173..b71afed1a 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs@@ -583,18 +583,21 @@ pub async fn owned_browser_navigate(app: AppHandle, url: String) -> Result<(), S.parse().map_err(|e: url::ParseError| format!("invalid url: {e}"))?;- // Inherit the user's logged-in sessions from their real browser- // (currently Arc only) before navigating. Reads cookies for the- // target host out of the user's Cookies SQLite, AES-CBC-decrypts- // them with the macOS Keychain key, and pushes them into the- // shared `WKHTTPCookieStore`. Fails open: if Arc isn't installed,- // the Keychain prompt is denied, or decryption errors out, we- // navigate without injection — same behavior as before.- #[cfg(target_os = "macos")]+ // Inherit the user's logged-in sessions from their real browser.+ // `cookies_for_host` is cross-platform but currently only returns+ // non-empty on macOS (Arc / Chrome / Brave / Edge). The injection+ // step is platform-gated because each webview engine has its own+ // cookie-store API: macOS WKHTTPCookieStore today; Windows WebView2+ // ICoreWebView2CookieManager and Linux webkit2gtk to come.+ // Fail-open everywhere — any error and we navigate without cookies,+ // same UX as before this hook existed.if let Some(host) = parsed.host_str() {let cookies = crate::owned_browser_cookies::cookies_for_host(host).await;if !cookies.is_empty() {+ #[cfg(target_os = "macos")]inject_cookies_macos(&app, &cookies).await;+ #[cfg(not(target_os = "macos"))]+ let _ = (&app, &cookies); // suppress unused warning until inject impls land}}let _ = app.emit(NAVIGATE_EVENT, parsed.as_str());diff --git a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser_cookies.rs b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser_cookies.rsindex 2a3932829..e1f75fb4f 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser_cookies.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser_cookies.rs@@ -58,24 +58,45 @@//! cookies, so we forward the flag. The cookie is unreadable from//! page JS, only sent on requests — same semantics as a real browser.-#![cfg(target_os = "macos")]+// Cross-platform module shape: the `Cookie` struct and the public+// `cookies_for_host` entry point compile on every OS. The actual+// readers + decryption are gated to macOS for now; Windows / Linux+// fall through to a stub that returns an empty Vec, so the rest of+// the codebase can call `cookies_for_host` unconditionally without+// per-cfg branching at the call site. Adding Windows or Linux is a+// matter of dropping in the platform-specific reader at the bottom+// of this file — see the TODO comments there.+use std::time::{Duration, Instant};++#[cfg(target_os = "macos")]use std::path::PathBuf;+#[cfg(target_os = "macos")]use std::sync::OnceLock;-use std::time::{Duration, Instant};+#[cfg(target_os = "macos")]use tokio::sync::Mutex;use tracing::{debug, warn};+#[cfg(target_os = "macos")]use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, KeyIvInit};+#[cfg(target_os = "macos")]use hmac::Hmac;+#[cfg(target_os = "macos")]use rusqlite::OpenFlags;+#[cfg(target_os = "macos")]use security_framework::passwords::get_generic_password;+#[cfg(target_os = "macos")]/// AES-128-CBC decrypt with PKCS7 padding (Chromium "v10" cookie scheme).type Aes128CbcDec = cbc::Decryptor<aes::Aes128>;-/// One cookie ready for `WKHTTPCookieStore.setCookie:`.+/// One cookie ready for the platform's webview cookie-store API+/// (macOS: `WKHTTPCookieStore.setCookie:`; Windows: `ICoreWebView2-+/// CookieManager.AddOrUpdateCookie`; Linux: `webkit_cookie_manager-+/// _add_cookie`). Shape is intentionally platform-agnostic so the+/// inject helper in `owned_browser.rs` can stay one impl per platform+/// while the reader and the agent see the same struct.#[derive(Debug, Clone)]pub struct Cookie {pub name: String,@@ -91,51 +112,46 @@ pub struct Cookie {pub same_site: i32,}-/// What we know about a real browser the user might have installed.-struct KeychainEntry {- /// Display name surfaced in errors / logs.- name: &'static str,- /// macOS Keychain *service* attribute. Chromium-based browsers store- /// the cookie-encryption AES key under "<Brand> Safe Storage".- keychain_service: &'static str,- /// macOS Keychain *account* attribute — usually the brand name.- keychain_account: &'static str,- /// Where the SQLite cookies file lives, relative to `~/Library`.- cookies_path_under_library: &'static str,-}--/// The single browser we currently support — the user's Arc install.-/// Chrome/Brave are deliberately commented out: same code path, but-/// we'd rather have one user explicitly ask before we pull cookies-/// from their primary work browser without consent.-const ARC: KeychainEntry = KeychainEntry {- name: "Arc",- keychain_service: "Arc Safe Storage",- keychain_account: "Arc",- cookies_path_under_library:- "Application Support/Arc/User Data/Default/Cookies",-};--/// Domain → (cookies, fetched_at). Per-process, in-memory, no eviction-/// (cookie sets per host are tiny — kilobytes — and the cache lives-/// only for the session). TTL is enforced at read time.-static CACHE: OnceLock<Mutex<std::collections::HashMap<String, (Instant, Vec<Cookie>)>>> =- OnceLock::new();-const CACHE_TTL: Duration = Duration::from_secs(30);--fn cache() -> &'static Mutex<std::collections::HashMap<String, (Instant, Vec<Cookie>)>> {- CACHE.get_or_init(|| Mutex::new(std::collections::HashMap::new()))-}--/// Public entry: fetch every cookie that would be sent to `host` from the-/// user's Arc browser. Never errors at the type level — every failure-/// (Keychain locked, SQLite missing, decrypt mismatch, …) returns an-/// empty vec so the caller can fall through to a normal navigate.+/// Public entry: fetch every cookie that would be sent to `host`,+/// merged across every browser source the platform supports. Returns+/// an empty Vec on platforms where the source readers haven't been+/// implemented yet — call sites can invoke this unconditionally.pub async fn cookies_for_host(host: &str) -> Vec<Cookie> {if host.is_empty() {return Vec::new();}+ cookies_for_host_impl(host).await+}+#[cfg(not(target_os = "macos"))]+async fn cookies_for_host_impl(_host: &str) -> Vec<Cookie> {+ // Windows TODO: Chromium-on-Windows stores cookies at+ // %LOCALAPPDATA%\<browser>\User Data\Default\Network\Cookies+ // The encrypted_value uses AES-256-GCM (NOT 128-CBC like macOS); the+ // 32-byte AES key is itself DPAPI-protected and lives base64'd in the+ // sibling `Local State` JSON's `os_crypt.encrypted_key` field.+ // Decrypt with `windows::Win32::Security::Cryptography::CryptUnprotectData`,+ // strip the "DPAPI" prefix, then `aes-gcm` over the 12-byte nonce ++ // ciphertext that follows the literal "v10"/"v11" prefix on each+ // cookie value. WebView2 cookie injection is via+ // `ICoreWebView2CookieManager.AddOrUpdateCookie` from the COM+ // controller — Tauri exposes the underlying `WebView2` via+ // `WebviewWindow::with_webview`.+ //+ // Linux TODO: Chromium-on-Linux stores cookies at+ // ~/.config/<browser>/Default/Cookies+ // Encrypted with the same AES-128-CBC scheme as macOS but the key+ // comes from libsecret/kwallet via D-Bus (`secret_password_lookup`)+ // under collection "Chromium Keys", schema "chrome_libsecret_os_crypt_-+ // password_v2". Falls back to a hardcoded "peanuts" password when+ // libsecret isn't reachable. Webview cookie injection via+ // `webkit_cookie_manager_add_cookie` from the gtk-rs webkit2gtk+ // bindings.+ Vec::new()+}++#[cfg(target_os = "macos")]+async fn cookies_for_host_impl(host: &str) -> Vec<Cookie> {// Lookup cache first — same host hit twice in 30s is the common// case during multi-step agent flows (open URL, snapshot, follow// link on same domain).@@ -149,22 +165,33 @@ pub async fn cookies_for_host(host: &str) -> Vec<Cookie> {}}- // Cache miss — go to disk + Keychain. Spawn-blocking so the SQLite- // open + AES decrypt loop doesn't wedge the tokio worker.let host_owned = host.to_string();- let cookies = match tokio::task::spawn_blocking(move || read_arc_cookies(&host_owned)).await {- Ok(Ok(c)) => c,- Ok(Err(e)) => {- // Don't log loud — Arc not installed is a normal state, not- // an error. Keychain prompts will surface to the user themselves.- debug!("owned-browser cookies: arc read failed: {e}");- Vec::new()- }- Err(e) => {- warn!("owned-browser cookies: spawn_blocking join failed: {e}");- Vec::new()+ let cookies = tokio::task::spawn_blocking(move || {+ let mut out: Vec<Cookie> = Vec::new();+ for source in SOURCES {+ match read_cookies(source, &host_owned) {+ Ok(mut c) => {+ if !c.is_empty() {+ debug!(+ source = source.name,+ count = c.len(),+ "owned-browser cookies: read"+ );+ }+ out.append(&mut c);+ }+ Err(e) => {+ debug!(source = source.name, "owned-browser cookies: skip — {e}");+ }+ }}- };+ out+ })+ .await+ .unwrap_or_else(|e| {+ warn!("owned-browser cookies: spawn_blocking join failed: {e}");+ Vec::new()+ });{let mut cache = cache().lock().await;@@ -175,27 +202,107 @@ pub async fn cookies_for_host(host: &str) -> Vec<Cookie> {cookies}+// ---------------------------------------------------------------------------+// macOS — Chromium-derived browsers (Chrome / Brave / Edge / Arc)+// ---------------------------------------------------------------------------++/// One Chromium-derived browser the user might have installed. All+/// fields are platform-specific (macOS for now). Adding Chrome / Brave /+/// Edge on macOS is one entry each in [`SOURCES`]; Windows / Linux+/// would need a different struct + reader pair (different decryption,+/// different file paths) — see the trait sketch in the doc comment at+/// the top of this file.+#[cfg(target_os = "macos")]+struct KeychainEntry {+ /// Display name surfaced in errors / logs.+ name: &'static str,+ /// macOS Keychain *service* attribute. Chromium-based browsers+ /// store the cookie-encryption AES key under "<Brand> Safe Storage".+ keychain_service: &'static str,+ /// macOS Keychain *account* attribute — usually the brand name.+ keychain_account: &'static str,+ /// Where the SQLite cookies file lives, relative to `~/Library`.+ cookies_path_under_library: &'static str,+}++/// Sources we iterate per navigate, in the order we want **earlier**+/// entries to be **overridden** by later ones. WKHTTPCookieStore's+/// `setCookie:` replaces by `(name, domain, path)`, so the final+/// browser in this list wins on conflicts. Arc is last because it's+/// Louis's daily driver and his fresh sessions should beat stale+/// Chrome cookies when both are logged in to the same site.+#[cfg(target_os = "macos")]+const SOURCES: &[KeychainEntry] = &[+ KeychainEntry {+ name: "Chrome",+ keychain_service: "Chrome Safe Storage",+ keychain_account: "Chrome",+ cookies_path_under_library:+ "Application Support/Google/Chrome/Default/Cookies",+ },+ KeychainEntry {+ name: "Brave",+ keychain_service: "Brave Safe Storage",+ keychain_account: "Brave",+ cookies_path_under_library:+ "Application Support/BraveSoftware/Brave-Browser/Default/Cookies",+ },+ KeychainEntry {+ name: "Edge",+ keychain_service: "Microsoft Edge Safe Storage",+ keychain_account: "Microsoft Edge",+ cookies_path_under_library:+ "Application Support/Microsoft Edge/Default/Cookies",+ },+ KeychainEntry {+ name: "Arc",+ keychain_service: "Arc Safe Storage",+ keychain_account: "Arc",+ cookies_path_under_library:+ "Application Support/Arc/User Data/Default/Cookies",+ },+];++/// Domain → (cookies, fetched_at). Per-process, in-memory, no eviction+/// (cookie sets per host are tiny — kilobytes — and the cache lives+/// only for the session). TTL is enforced at read time.+#[cfg(target_os = "macos")]+static CACHE: OnceLock<Mutex<std::collections::HashMap<String, (Instant, Vec<Cookie>)>>> =+ OnceLock::new();+#[cfg(target_os = "macos")]+const CACHE_TTL: Duration = Duration::from_secs(30);++#[cfg(target_os = "macos")]+fn cache() -> &'static Mutex<std::collections::HashMap<String, (Instant, Vec<Cookie>)>> {+ CACHE.get_or_init(|| Mutex::new(std::collections::HashMap::new()))+}++/// Resolve `~/Library` for the current user. We don't use $HOME because/// it's not always set when launched as a LaunchAgent. `dirs` would do/// it but pulling another crate for one path is overkill.+#[cfg(target_os = "macos")]fn library_dir() -> Option<PathBuf> {std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library"))}/// Synchronous worker — runs inside spawn_blocking. Returns Vec on/// success, Err with a printable string for the debug log on failure.-fn read_arc_cookies(host: &str) -> Result<Vec<Cookie>, String> {+#[cfg(target_os = "macos")]+fn read_cookies(source: &KeychainEntry, host: &str) -> Result<Vec<Cookie>, String> {let library = library_dir().ok_or_else(|| "no $HOME".to_string())?;- let cookies_path = library.join(ARC.cookies_path_under_library);+ let cookies_path = library.join(source.cookies_path_under_library);if !cookies_path.exists() {- return Err(format!("{} not installed (no Cookies file)", ARC.name));+ return Err(format!("{} not installed (no Cookies file)", source.name));}// Pull the AES key from Keychain. First call after app launch will// surface a system "Allow" prompt unless the binary is already- // trusted — cached after the user clicks Allow once.- let password = get_generic_password(ARC.keychain_service, ARC.keychain_account)- .map_err(|e| format!("keychain '{}': {e}", ARC.keychain_service))?;+ // trusted — cached after the user clicks Allow once. Each Chromium-+ // derived browser has its own Keychain entry — Chrome won't unlock+ // Arc's cookies and vice versa.+ let password = get_generic_password(source.keychain_service, source.keychain_account)+ .map_err(|e| format!("keychain '{}': {e}", source.keychain_service))?;let key = derive_aes_key(&password);// Open read-only — the SQLite file is also held open for write by@@ -296,6 +403,7 @@ fn read_arc_cookies(host: &str) -> Result<Vec<Cookie>, String> {/// `.com` is etld so cookies aren't actually allowed there, but Arc //// Chrome don't enforce that themselves; we return whatever's stored/// and let WKWebView's own cookie policy filter at request time).+#[cfg(target_os = "macos")]fn host_match_clauses(host: &str) -> Vec<String> {let mut out = vec![host.to_string(), format!(".{host}")];let mut rest = host;@@ -312,6 +420,7 @@ fn host_match_clauses(host: &str) -> Vec<String> {/// Chromium stores `expires_utc` in microseconds since 1601-01-01 UTC/// (the Windows FILETIME epoch — yes, even in macOS Chrome). `0` means/// "session cookie". Convert to seconds since 1970-01-01 for NSDate.+#[cfg(target_os = "macos")]fn chromium_micros_to_unix_secs(micros: i64) -> Option<i64> {if micros == 0 {return None;@@ -325,6 +434,7 @@ fn chromium_micros_to_unix_secs(micros: i64) -> Option<i64> {/// salt = "saltysalt", iterations = 1003, key length = 16 bytes./// (These are not secret — Chromium's open-source cookie code/// hard-codes them; the actual secret is the Keychain password.)+#[cfg(target_os = "macos")]fn derive_aes_key(password: &[u8]) -> [u8; 16] {const SALT: &[u8] = b"saltysalt";const ITER: u32 = 1003;@@ -339,6 +449,7 @@ fn derive_aes_key(password: &[u8]) -> [u8; 16] {/// Layout: `b"v10" || ciphertext`. AES-128-CBC, IV = 16 spaces (literal/// b' '), PKCS7 padding. v11 is the same scheme but with a Linux/// libsecret key — we don't see those on macOS.+#[cfg(target_os = "macos")]fn decrypt_v10(encrypted: &[u8], key: &[u8; 16]) -> Option<String> {if encrypted.len() < 3 || &encrypted[..3] != b"v10" {return None;@@ -351,7 +462,7 @@ fn decrypt_v10(encrypted: &[u8], key: &[u8; 16]) -> Option<String> {String::from_utf8(plain.to_vec()).ok()}-#[cfg(test)]+#[cfg(all(test, target_os = "macos"))]mod tests {use super::*;