Skip to content

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

gate owned browser session access

Louis Beaumont35c50a6b298c
diff --git a/apps/screenpipe-app-tauri/components/browser-sidebar.tsx b/apps/screenpipe-app-tauri/components/browser-sidebar.tsx
index 7655d5125..c9da294c2 100644
--- a/apps/screenpipe-app-tauri/components/browser-sidebar.tsx
+++ b/apps/screenpipe-app-tauri/components/browser-sidebar.tsx
@@ -29,13 +29,15 @@ import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { motion, AnimatePresence } from "framer-motion";
-import { RotateCw, PanelRightClose, PanelRightOpen } from "lucide-react";
+import { KeyRound, PanelRightClose, PanelRightOpen, RotateCw } from "lucide-react";
import {
loadConversationFile,
updateConversationFlags,
} from "@/lib/chat-storage";
+import { Button } from "@/components/ui/button";
const NAVIGATE_EVENT = "owned-browser:navigate";
+const SESSION_ACCESS_REQUEST_EVENT = "owned-browser:session-access-request";
const DEFAULT_WIDTH = 480;
const MIN_WIDTH = 320;
const MIN_CHAT_WIDTH = 360;
@@ -44,6 +46,19 @@ interface BrowserSidebarProps {
conversationId: string | null;
}
+interface SessionAccessEvent {
+ request_id?: string;
+ requestId?: string;
+ url: string;
+ host: string;
+}
+
+interface ActiveSessionAccessRequest {
+ requestId: string;
+ url: string;
+ host: string;
+}
+
/** Clamp the panel width so it can never push the chat below MIN_CHAT_WIDTH
* in the *available* horizontal area (the chat layout's split host, not
* the whole window — AppSidebar / history sidebar can eat into it).
@@ -59,6 +74,11 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
const [visible, setVisible] = useState(false);
const [collapsed, setCollapsed] = useState(false);
const [currentUrl, setCurrentUrl] = useState<string | null>(null);
+ const [sessionAccessRequest, setSessionAccessRequest] =
+ useState<ActiveSessionAccessRequest | null>(null);
+ const [sessionAccessAnswer, setSessionAccessAnswer] = useState<
+ "allow" | "deny" | null
+ >(null);
const [requestedWidth, setRequestedWidth] = useState(DEFAULT_WIDTH);
// `availableW` = the width of the panel's flex parent (the host marked
// with data-browser-panel-host in standalone-chat.tsx). That's the real
@@ -181,6 +201,8 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
const unlistenPromise = listen<string>(NAVIGATE_EVENT, (e) => {
const url = typeof e.payload === "string" ? e.payload : null;
if (!url) return;
+ setSessionAccessRequest(null);
+ setSessionAccessAnswer(null);
setVisible(true);
setCollapsed(false);
setCurrentUrl(url);
@@ -191,6 +213,32 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
};
}, [persistState]);
+ useEffect(() => {
+ const unlistenPromise = listen<SessionAccessEvent>(
+ SESSION_ACCESS_REQUEST_EVENT,
+ (e) => {
+ const payload = e.payload;
+ const requestId = payload?.requestId ?? payload?.request_id;
+ if (!requestId || !payload?.url || !payload?.host) return;
+ const request = {
+ requestId,
+ url: payload.url,
+ host: payload.host,
+ };
+ setSessionAccessRequest(request);
+ setSessionAccessAnswer(null);
+ setVisible(true);
+ setCollapsed(false);
+ setCurrentUrl(request.url);
+ persistState({ url: request.url, collapsed: false });
+ invoke("owned_browser_hide").catch(() => {});
+ },
+ );
+ return () => {
+ unlistenPromise.then((fn) => fn()).catch(() => {});
+ };
+ }, [persistState]);
+
// ---------------------------------------------------------------------------
// Per-conversation restore
// ---------------------------------------------------------------------------
@@ -201,6 +249,8 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
setVisible(false);
setCollapsed(false);
setCurrentUrl(null);
+ setSessionAccessRequest(null);
+ setSessionAccessAnswer(null);
setRequestedWidth(DEFAULT_WIDTH);
invoke("owned_browser_hide").catch(() => {});
return () => {
@@ -401,6 +451,34 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
persistState({ collapsed: false });
}, [persistState]);
+ const answerSessionAccess = useCallback(
+ async (allow: boolean) => {
+ const request = sessionAccessRequest;
+ if (!request || sessionAccessAnswer) return;
+ setSessionAccessAnswer(allow ? "allow" : "deny");
+ try {
+ await invoke("owned_browser_resolve_session_access", {
+ requestId: request.requestId,
+ allow,
+ });
+ if (!allow) {
+ setSessionAccessRequest((current) =>
+ current?.requestId === request.requestId ? null : current,
+ );
+ }
+ } catch (e) {
+ console.error("owned_browser_resolve_session_access failed", e);
+ setSessionAccessRequest((current) =>
+ current?.requestId === request.requestId ? null : current,
+ );
+ setSessionAccessAnswer(null);
+ } finally {
+ if (!allow) setSessionAccessAnswer(null);
+ }
+ },
+ [sessionAccessRequest, sessionAccessAnswer],
+ );
+
// ---------------------------------------------------------------------------
// Render
// ---------------------------------------------------------------------------
@@ -460,7 +538,57 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
ref={placeholderRef}
className="flex-1 bg-background relative flex items-center justify-center text-xs text-muted-foreground"
>
- loading…
+ {sessionAccessRequest ? (
+ <div className="absolute inset-0 z-20 flex items-center justify-center bg-background p-4">
+ <div className="w-full max-w-sm border border-border bg-card p-4 shadow-sm">
+ <div className="mb-3 flex items-start gap-3">
+ <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center border border-border bg-muted text-foreground">
+ <KeyRound className="h-4 w-4" />
+ </div>
+ <div className="min-w-0">
+ <div className="text-sm font-medium text-foreground">
+ Use your browser login?
+ </div>
+ <div className="mt-1 break-all text-xs text-muted-foreground">
+ {sessionAccessRequest.host}
+ </div>
+ </div>
+ </div>
+ <p className="text-xs leading-5 text-muted-foreground">
+ ScreenPipe Browser can copy matching session cookies from
+ your browser so the agent opens this site already signed
+ in. It does not read saved passwords.
+ </p>
+ <p className="mt-2 text-xs leading-5 text-muted-foreground">
+ If you allow it, macOS may ask for access to browser safe
+ storage next.
+ </p>
+ <div className="mt-4 flex flex-col gap-2">
+ <Button
+ size="sm"
+ disabled={sessionAccessAnswer !== null}
+ onClick={() => answerSessionAccess(true)}
+ className="w-full"
+ >
+ {sessionAccessAnswer === "allow"
+ ? "Waiting for macOS"
+ : "Use browser session"}
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={sessionAccessAnswer !== null}
+ onClick={() => answerSessionAccess(false)}
+ className="w-full"
+ >
+ Continue logged out
+ </Button>
+ </div>
+ </div>
+ </div>
+ ) : (
+ "loading…"
+ )}
</div>
</motion.div>
)}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index a88b1e4ff..00441e530 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -1015,6 +1015,7 @@ async fn main() {
owned_browser::owned_browser_set_bounds,
owned_browser::owned_browser_navigate,
owned_browser::owned_browser_hide,
+ owned_browser::owned_browser_resolve_session_access,
permissions::reset_and_request_permission,
permissions::get_missing_permissions,
permissions::check_arc_installed,
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs
index 7d5210430..f4e63edf6 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs
@@ -43,16 +43,15 @@
use async_trait::async_trait;
use screenpipe_connect::connections::browser::{EvalResult, OwnedWebviewHandle};
+use std::collections::HashMap;
use std::path::PathBuf;
-use std::sync::Arc;
-#[cfg(target_os = "macos")]
-use std::sync::OnceLock;
+use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
use tauri::{
AppHandle, Emitter, LogicalPosition, LogicalSize, Manager, WebviewUrl, WebviewWindow,
WebviewWindowBuilder,
};
-use tokio::sync::Mutex;
+use tokio::sync::{oneshot, Mutex};
use tracing::{debug, info, warn};
use uuid::Uuid;
@@ -70,6 +69,12 @@ const NAVIGATE_EVENT: &str = "owned-browser:navigate";
/// `owned_browser_navigate` that lost the install race on cold start.
const READY_EVENT: &str = "owned-browser:ready";
+/// Emitted when the owned browser is about to copy cookies from the
+/// user's real browser. The sidebar answers through the
+/// `owned_browser_resolve_session_access` command.
+const SESSION_ACCESS_REQUEST_EVENT: &str = "owned-browser:session-access-request";
+const SESSION_ACCESS_TIMEOUT: Duration = Duration::from_secs(60);
+
/// Marker prefix for `document.title`-based result delivery. The bridge JS
/// sets `document.title = "<MARKER>:<json>"`; the Rust eval polls
/// `WebviewWindow::title()` until it sees this prefix and parses the
@@ -101,6 +106,60 @@ const BRIDGE_INIT_SCRIPT: &str = r#"
})();
"#;
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum BrowserSessionDecision {
+ UseBrowserSession,
+ ContinueLoggedOut,
+}
+
+#[derive(serde::Serialize, Clone)]
+struct BrowserSessionAccessRequestPayload {
+ request_id: String,
+ url: String,
+ host: String,
+}
+
+static SESSION_ACCESS_PENDING: OnceLock<
+ Mutex<HashMap<String, oneshot::Sender<BrowserSessionDecision>>>,
+> = OnceLock::new();
+static SESSION_ACCESS_DECISIONS: OnceLock<Mutex<HashMap<String, BrowserSessionDecision>>> =
+ OnceLock::new();
+
+fn pending_session_access(
+) -> &'static Mutex<HashMap<String, oneshot::Sender<BrowserSessionDecision>>> {
+ SESSION_ACCESS_PENDING.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+fn remembered_session_access() -> &'static Mutex<HashMap<String, BrowserSessionDecision>> {
+ SESSION_ACCESS_DECISIONS.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+async fn remember_session_access_decision(host: &str, decision: BrowserSessionDecision) {
+ remembered_session_access()
+ .lock()
+ .await
+ .insert(host.to_ascii_lowercase(), decision);
+}
+
+#[tauri::command]
+pub async fn owned_browser_resolve_session_access(
+ request_id: String,
+ allow: bool,
+) -> Result<(), String> {
+ let decision = if allow {
+ BrowserSessionDecision::UseBrowserSession
+ } else {
+ BrowserSessionDecision::ContinueLoggedOut
+ };
+ let tx = pending_session_access()
+ .lock()
+ .await
+ .remove(&request_id)
+ .ok_or_else(|| "session access request expired".to_string())?;
+ tx.send(decision)
+ .map_err(|_| "session access request was already closed".to_string())
+}
+
// ---------------------------------------------------------------------------
// Handle implementation
// ---------------------------------------------------------------------------
@@ -132,12 +191,11 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
// A hidden WebView2 window can accept `eval()` without actually
// executing the script. Make sure the native webview is live before
- // we use JS either for navigation or result delivery. If this was a
- // code-only background eval, restore the hidden state at the end; URL
- // navigations are expected to remain visible because the frontend
- // sidebar will receive NAVIGATE_EVENT and position the window.
+ // code-only evals. URL navigations defer showing until after the
+ // optional session-access prompt, so the sidebar can explain the
+ // request before any native webview covers it.
let was_visible = webview_window.is_visible().unwrap_or(false);
- if !was_visible {
+ if !was_visible && url.is_none() {
let _ = webview_window.show();
tokio::time::sleep(Duration::from_millis(100)).await;
}
@@ -152,6 +210,10 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
.parse()
.map_err(|e: url::ParseError| format!("invalid url: {e}"))?;
inject_cookies_for_url(&self.app, &parsed).await;
+ if !webview_window.is_visible().unwrap_or(false) {
+ let _ = webview_window.show();
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
let _ = self.app.emit(NAVIGATE_EVENT, parsed.as_str());
webview_window
.navigate(parsed)
@@ -279,14 +341,6 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
.parse()
.map_err(|e: url::ParseError| format!("invalid url: {e}"))?;
- // Make the webview live before navigating — a hidden WebView2
- // window can silently drop the navigate call. We do NOT hold the
- // eval_lock here; navigate is independent of in-flight evals so
- // a long-running snapshot can't queue behind it.
- if !webview_window.is_visible().unwrap_or(false) {
- let _ = webview_window.show();
- }
-
// Push the user's real-browser cookies for this host into
// WKHTTPCookieStore before issuing the navigate, so the request
// ships logged-in. This is the agent's primary path
@@ -297,6 +351,14 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
// path was injecting correctly.
inject_cookies_for_url(&self.app, &parsed).await;
+ // Make the webview live before navigating — a hidden WebView2
+ // window can silently drop the navigate call. We do NOT hold the
+ // eval_lock here; navigate is independent of in-flight evals so
+ // a long-running snapshot can't queue behind it.
+ if !webview_window.is_visible().unwrap_or(false) {
+ let _ = webview_window.show();
+ }
+
let _ = self.app.emit(NAVIGATE_EVENT, parsed.as_str());
webview_window
.navigate(parsed)
@@ -554,10 +616,7 @@ fn bound_parent() -> &'static Mutex<Option<String>> {
/// globally over other apps. Cocoa enforces single-parent semantics, so
/// re-binding to a different parent automatically removes the old one.
#[cfg(target_os = "macos")]
-async fn bind_owned_browser_to_parent(
- app: &AppHandle,
- parent_label: &str,
-) -> Result<(), String> {
+async fn bind_owned_browser_to_parent(app: &AppHandle, parent_label: &str) -> Result<(), String> {
use objc::runtime::Object;
use objc::{msg_send, sel, sel_impl};
@@ -602,8 +661,7 @@ async fn bind_owned_browser_to_parent(
// NSWindowOrderingMode::NSWindowAbove == 1
unsafe {
- let _: () =
- msg_send![parent_ptr, addChildWindow: child_ptr ordered: 1i64];
+ let _: () = msg_send![parent_ptr, addChildWindow: child_ptr ordered: 1i64];
}
Ok(())
})();
@@ -660,9 +718,20 @@ async fn inject_cookies_for_url(app: &AppHandle, url: &url::Url) {
info!("owned-browser cookies: skipping inject — url has no host");
return;
};
+
+ if browser_session_decision_for_url(app, url).await != BrowserSessionDecision::UseBrowserSession
+ {
+ info!(
+ host,
+ "owned-browser cookies: navigating without real-browser session"
+ );
+ return;
+ }
+
info!(host, "owned-browser cookies: pre-navigate inject starting");
let cookies = crate::owned_browser_cookies::cookies_for_host(host).await;
if cookies.is_empty() {
+ remember_session_access_decision(host, BrowserSessionDecision::ContinueLoggedOut).await;
info!(
host,
"owned-browser cookies: 0 cookies available — navigating without inject \
@@ -690,6 +759,68 @@ async fn inject_cookies_for_url(app: &AppHandle, url: &url::Url) {
let _ = (app, &cookies); // until Windows/Linux injectors land
}
+async fn browser_session_decision_for_url(
+ app: &AppHandle,
+ url: &url::Url,
+) -> BrowserSessionDecision {
+ let Some(host) = url.host_str() else {
+ return BrowserSessionDecision::ContinueLoggedOut;
+ };
+ let host_key = host.to_ascii_lowercase();
+
+ if !crate::owned_browser_cookies::has_cookies_for_host(&host_key).await {
+ return BrowserSessionDecision::ContinueLoggedOut;
+ }
+
+ if let Some(decision) = remembered_session_access()
+ .lock()
+ .await
+ .get(&host_key)
+ .copied()
+ {
+ return decision;
+ }
+
+ if let Some(webview_window) = app.get_webview_window(WEBVIEW_LABEL) {
+ let _ = webview_window.hide();
+ }
+
+ let request_id = Uuid::new_v4().to_string();
+ let (tx, rx) = oneshot::channel();
+ pending_session_access()
+ .lock()
+ .await
+ .insert(request_id.clone(), tx);
+
+ let payload = BrowserSessionAccessRequestPayload {
+ request_id: request_id.clone(),
+ url: url.as_str().to_string(),
+ host: host_key.clone(),
+ };
+
+ if let Err(e) = app.emit(SESSION_ACCESS_REQUEST_EVENT, payload) {
+ pending_session_access().lock().await.remove(&request_id);
+ warn!("owned-browser session access: failed to emit request: {e}");
+ return BrowserSessionDecision::ContinueLoggedOut;
+ }
+
+ let decision = match tokio::time::timeout(SESSION_ACCESS_TIMEOUT, rx).await {
+ Ok(Ok(decision)) => decision,
+ Ok(Err(_)) => BrowserSessionDecision::ContinueLoggedOut,
+ Err(_) => {
+ pending_session_access().lock().await.remove(&request_id);
+ warn!(
+ host = host_key.as_str(),
+ "owned-browser session access: user prompt timed out"
+ );
+ BrowserSessionDecision::ContinueLoggedOut
+ }
+ };
+
+ remember_session_access_decision(&host_key, decision).await;
+ decision
+}
+
/// macOS only: push a batch of cookies (read from the user's real
/// browser by [`crate::owned_browser_cookies::cookies_for_host`]) into
/// the shared `WKHTTPCookieStore` so the next `webview.navigate(url)`
@@ -751,9 +882,8 @@ async fn inject_cookies_macos(
// as Chromium stored it — that's what controls scope.
let domain_v: id = NSString::alloc(nil).init_str(&c.domain);
push("Domain", domain_v, &mut keys, &mut vals);
- let path_v: id = NSString::alloc(nil).init_str(
- if c.path.is_empty() { "/" } else { &c.path },
- );
+ let path_v: id =
+ NSString::alloc(nil).init_str(if c.path.is_empty() { "/" } else { &c.path });
push("Path", path_v, &mut keys, &mut vals);
if c.secure {
let s: id = NSString::alloc(nil).init_str("TRUE");
@@ -769,7 +899,8 @@ async fn inject_cookies_macos(
}
if let Some(secs) = c.expires_at {
let date_class = class!(NSDate);
- let date: id = msg_send![date_class, dateWithTimeIntervalSince1970: secs as f64];
+ let date: id =
+ msg_send![date_class, dateWithTimeIntervalSince1970: secs as f64];
push("Expires", date, &mut keys, &mut vals);
} else {
let s: id = NSString::alloc(nil).init_str("TRUE");
@@ -792,13 +923,11 @@ async fn inject_cookies_macos(
let keys_arr = NSArray::arrayWithObjects(nil, &keys);
let vals_arr = NSArray::arrayWithObjects(nil, &vals);
- let dict: id = NSDictionary::dictionaryWithObjects_forKeys_(
- nil, vals_arr, keys_arr,
- );
+ let dict: id =
+ NSDictionary::dictionaryWithObjects_forKeys_(nil, vals_arr, keys_arr);
let cookie_class = class!(NSHTTPCookie);
- let ns_cookie: id =
- msg_send![cookie_class, cookieWithProperties: dict];
+ let ns_cookie: id = msg_send![cookie_class, cookieWithProperties: dict];
if ns_cookie.is_null() {
continue;
}
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.rs
index 294724fa6..40824d138 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
@@ -21,10 +21,7 @@
//! ## Currently supports
//!
//! - macOS only.
-//! - Arc browser (Keychain service `Arc Safe Storage`, account `Arc`).
-//! Chrome / Brave use the same cookie format and same SQLite layout —
-//! adding them is a one-line change to [`KeychainEntry`] + the data
-//! dir path. Deferred until someone actually asks.
+//! - Chrome / Brave / Edge / Arc default profiles.
//! - Default profile only. Arc's Spaces / Chrome's profiles are picked
//! up the day a user reports they need a non-default one.
//!
@@ -123,6 +120,16 @@ pub async fn cookies_for_host(host: &str) -> Vec<Cookie> {
cookies_for_host_impl(host).await
}
+/// Cheap preflight used before showing the session-access prompt. This checks
+/// for matching cookie rows without touching Keychain, so public sites do not
+/// trigger a scary permission flow.
+pub async fn has_cookies_for_host(host: &str) -> bool {
+ if host.is_empty() {
+ return false;
+ }
+ has_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
@@ -150,6 +157,11 @@ async fn cookies_for_host_impl(_host: &str) -> Vec<Cookie> {
Vec::new()
}
+#[cfg(not(target_os = "macos"))]
+async fn has_cookies_for_host_impl(_host: &str) -> bool {
+ false
+}
+
#[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
@@ -159,7 +171,11 @@ async fn cookies_for_host_impl(host: &str) -> Vec<Cookie> {
let cache = cache().lock().await;
if let Some((fetched_at, cookies)) = cache.get(host) {
if fetched_at.elapsed() < CACHE_TTL {
- debug!(host, count = cookies.len(), "owned-browser cookies: cache hit");
+ debug!(
+ host,
+ count = cookies.len(),
+ "owned-browser cookies: cache hit"
+ );
return cookies.clone();
}
}
@@ -203,10 +219,34 @@ async fn cookies_for_host_impl(host: &str) -> Vec<Cookie> {
cache.insert(host.to_string(), (Instant::now(), cookies.clone()));
}
- debug!(host, count = cookies.len(), "owned-browser cookies: cache miss → read");
+ debug!(
+ host,
+ count = cookies.len(),
+ "owned-browser cookies: cache miss → read"
+ );
cookies
}
+#[cfg(target_os = "macos")]
+async fn has_cookies_for_host_impl(host: &str) -> bool {
+ let host_owned = host.to_string();
+ tokio::task::spawn_blocking(move || {
+ for source in SOURCES {
+ match has_cookie_rows(source, &host_owned) {
+ Ok(true) => return true,
+ Ok(false) => {}
+ Err(e) => debug!(
+ source = source.name,
+ "owned-browser cookies: row preflight skip — {e}"
+ ),
+ }
+ }
+ false
+ })
+ .await
+ .unwrap_or(false)
+}
+
// ---------------------------------------------------------------------------
// macOS — Chromium-derived browsers (Chrome / Brave / Edge / Arc)
// ---------------------------------------------------------------------------
@@ -242,8 +282,7 @@ const SOURCES: &[KeychainEntry] = &[
name: "Chrome",
keychain_service: "Chrome Safe Storage",
keychain_account: "Chrome",
- cookies_path_under_library:
- "Application Support/Google/Chrome/Default/Cookies",
+ cookies_path_under_library: "Application Support/Google/Chrome/Default/Cookies",
},
KeychainEntry {
name: "Brave",
@@ -256,15 +295,13 @@ const SOURCES: &[KeychainEntry] = &[
name: "Edge",
keychain_service: "Microsoft Edge Safe Storage",
keychain_account: "Microsoft Edge",
- cookies_path_under_library:
- "Application Support/Microsoft Edge/Default/Cookies",
+ 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",
+ cookies_path_under_library: "Application Support/Arc/User Data/Default/Cookies",
},
];
@@ -308,7 +345,6 @@ fn keychain_key(source: &KeychainEntry) -> Result<[u8; 16], String> {
Ok(key)
}
-
/// 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.
@@ -317,40 +353,59 @@ 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.
#[cfg(target_os = "macos")]
-fn read_cookies(source: &KeychainEntry, host: &str) -> Result<Vec<Cookie>, String> {
+fn open_cookie_db(source: &KeychainEntry) -> Result<rusqlite::Connection, String> {
let library = library_dir().ok_or_else(|| "no $HOME".to_string())?;
let cookies_path = library.join(source.cookies_path_under_library);
if !cookies_path.exists() {
return Err(format!("{} not installed (no Cookies file)", source.name));
}
- // Pull the AES key from Keychain. First call after app launch
- // surfaces a system "Allow" prompt unless the binary is already
- // trusted; subsequent navigates within the same process hit the
- // in-memory cache and skip the prompt. Each Chromium-derived
- // browser has its own Keychain entry — Chrome won't unlock Arc's
- // cookies and vice versa.
- let key = keychain_key(source)?;
-
// Open read-only — the SQLite file is also held open for write by
// Arc. Read-only + immutable URI prevents lock contention.
// `?immutable=1` tells SQLite "I promise no other process will
// mutate while I read", which lets it skip the WAL/journal dance
// and avoids "database is locked" against Arc's live writes.
- let uri = format!(
- "file:{}?mode=ro&immutable=1",
- cookies_path.display()
- );
- let conn = rusqlite::Connection::open_with_flags(
+ let uri = format!("file:{}?mode=ro&immutable=1", cookies_path.display());
+ rusqlite::Connection::open_with_flags(
&uri,
OpenFlags::SQLITE_OPEN_READ_ONLY
| OpenFlags::SQLITE_OPEN_URI
| OpenFlags::SQLITE_OPEN_NO_MUTEX,
)
- .map_err(|e| format!("sqlite open: {e}"))?;
+ .map_err(|e| format!("sqlite open: {e}"))
+}
+
+#[cfg(target_os = "macos")]
+fn host_where_clause(filters: &[String]) -> String {
+ filters
+ .iter()
+ .enumerate()
+ .map(|(i, _)| format!("host_key = ?{}", i + 1))
+ .collect::<Vec<_>>()
+ .join(" OR ")
+}
+
+#[cfg(target_os = "macos")]
+fn has_cookie_rows(source: &KeychainEntry, host: &str) -> Result<bool, String> {
+ let conn = open_cookie_db(source)?;
+ let host_filters = host_match_clauses(host);
+ let where_clause = host_where_clause(&host_filters);
+ let sql = format!("SELECT 1 FROM cookies WHERE {where_clause} LIMIT 1");
+ let mut stmt = conn.prepare(&sql).map_err(|e| format!("prepare: {e}"))?;
+ let mut rows = stmt
+ .query(rusqlite::params_from_iter(host_filters.iter()))
+ .map_err(|e| format!("query: {e}"))?;
+ rows.next()
+ .map(|row| row.is_some())
+ .map_err(|e| format!("row: {e}"))
+}
+
+/// Synchronous worker — runs inside spawn_blocking. Returns Vec on
+/// success, Err with a printable string for the debug log on failure.
+#[cfg(target_os = "macos")]
+fn read_cookies(source: &KeychainEntry, host: &str) -> Result<Vec<Cookie>, String> {
+ let conn = open_cookie_db(source)?;
// Match cookies whose host_key applies to `host`: exact, dot-prefix
// for parent domains, no-dot for raw host. eTLD+1 falls out for free
@@ -361,12 +416,7 @@ fn read_cookies(source: &KeychainEntry, host: &str) -> Result<Vec<Cookie>, Strin
// signed (-1..=2). expires_utc is microseconds since 1601 — convert
// to seconds-since-1970 in [`row_to_cookie`].
let host_filters = host_match_clauses(host);
- let where_clause = host_filters
- .iter()
- .enumerate()
- .map(|(i, _)| format!("host_key = ?{}", i + 1))
- .collect::<Vec<_>>()
- .join(" OR ");
+ let where_clause = host_where_clause(&host_filters);
let sql = format!(
"SELECT name, value, encrypted_value, host_key, path, \
is_secure, is_httponly, expires_utc, samesite \
@@ -391,51 +441,60 @@ fn read_cookies(source: &KeychainEntry, host: &str) -> Result<Vec<Cookie>, Strin
})
.map_err(|e| format!("query: {e}"))?;
+ let rows = rows
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|e| format!("row: {e}"))?;
+ if rows.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ // Pull the AES key from Keychain only after we know this source has
+ // cookies for the requested host. First call after app launch surfaces
+ // a system "Allow" prompt unless the binary is already trusted;
+ // subsequent navigates within the same process hit the in-memory cache.
+ // Each Chromium-derived browser has its own Keychain entry — Chrome
+ // won't unlock Arc's cookies and vice versa.
+ let key = keychain_key(source)?;
+
let mut cookies = Vec::new();
let mut row_count = 0usize;
let mut decrypt_failed = 0usize;
- let mut row_decode_failed = 0usize;
let mut sample_enc_prefix: Option<String> = None;
- for row in rows {
+ for (name, plain_val, enc_val, host_key, path, secure, http_only, expires_utc, ss) in rows {
row_count += 1;
- match row {
- Ok((name, plain_val, enc_val, host_key, path, secure, http_only, expires_utc, ss)) => {
- let value = if enc_val.is_empty() {
- plain_val
- } else {
- if sample_enc_prefix.is_none() {
- let n = enc_val.len().min(3);
- sample_enc_prefix = Some(
- enc_val[..n]
- .iter()
- .map(|b| format!("{:02x}", b))
- .collect::<String>(),
- );
- }
- match decrypt_v10(&enc_val, &key) {
- Some(v) => v,
- None => {
- // Skip individual decrypt failures rather
- // than abort the whole batch — one corrupt
- // row shouldn't deny the agent every cookie.
- decrypt_failed += 1;
- continue;
- }
- }
- };
- cookies.push(Cookie {
- name,
- value,
- domain: host_key,
- path,
- secure: secure != 0,
- http_only: http_only != 0,
- expires_at: chromium_micros_to_unix_secs(expires_utc),
- same_site: ss,
- });
+ let value = if enc_val.is_empty() {
+ plain_val
+ } else {
+ if sample_enc_prefix.is_none() {
+ let n = enc_val.len().min(3);
+ sample_enc_prefix = Some(
+ enc_val[..n]
+ .iter()
+ .map(|b| format!("{:02x}", b))
+ .collect::<String>(),
+ );
}
- Err(_) => row_decode_failed += 1,
- }
+ match decrypt_v10(&enc_val, &key) {
+ Some(v) => v,
+ None => {
+ // Skip individual decrypt failures rather than abort
+ // the whole batch — one corrupt row shouldn't deny the
+ // agent every cookie.
+ decrypt_failed += 1;
+ continue;
+ }
+ }
+ };
+ cookies.push(Cookie {
+ name,
+ value,
+ domain: host_key,
+ path,
+ secure: secure != 0,
+ http_only: http_only != 0,
+ expires_at: chromium_micros_to_unix_secs(expires_utc),
+ same_site: ss,
+ });
}
info!(
source = source.name,
@@ -443,7 +502,6 @@ fn read_cookies(source: &KeychainEntry, host: &str) -> Result<Vec<Cookie>, Strin
rows = row_count,
decrypted = cookies.len(),
decrypt_failed,
- row_decode_failed,
first_enc_prefix = sample_enc_prefix.as_deref().unwrap_or("none"),
"owned-browser cookies: source done"
);
@@ -524,7 +582,11 @@ fn decrypt_v10(encrypted: &[u8], key: &[u8; 16]) -> Option<String> {
let plain = Aes128CbcDec::new(key.into(), &iv.into())
.decrypt_padded_mut::<Pkcs7>(&mut buf)
.ok()?;
- let value_bytes = if plain.len() >= 32 { &plain[32..] } else { &plain[..] };
+ let value_bytes = if plain.len() >= 32 {
+ &plain[32..]
+ } else {
+ &plain[..]
+ };
String::from_utf8(value_bytes.to_vec()).ok()
}
@@ -551,10 +613,7 @@ mod tests {
// 2026-01-01T00:00:00Z = 1767225600 unix.
// (Date - 1601-01-01) = 13_411_699_200_000_000 micros.
let micros = (11_644_473_600 + 1_767_225_600) * 1_000_000;
- assert_eq!(
- chromium_micros_to_unix_secs(micros),
- Some(1_767_225_600)
- );
+ assert_eq!(chromium_micros_to_unix_secs(micros), Some(1_767_225_600));
}
#[test]
diff --git a/crates/screenpipe-connect/src/connections/browser/owned.rs b/crates/screenpipe-connect/src/connections/browser/owned.rs
index ab2d7a90c..939e729f5 100644
--- a/crates/screenpipe-connect/src/connections/browser/owned.rs
+++ b/crates/screenpipe-connect/src/connections/browser/owned.rs
@@ -90,8 +90,9 @@ impl OwnedBrowser {
"owned-default",
"Owned Browser",
"An isolated app-managed webview with its own persistent cookie \
- jar. Empty by default — does NOT have the user's logged-in \
- sessions. Use this for: scraping, signups under screenpipe's \
+ jar. Starts logged out; when a site has matching browser cookies, \
+ ScreenPipe asks the user before copying that browser session into \
+ this webview. Use this for: scraping, signups under screenpipe's \
own accounts, scheduled background tasks, navigating to a public \
URL the user asked you to open. \
Navigating auto-opens the embedded sidebar in the user's chat — \