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
refactor(engine): consolidate API-key resolver, silence cargo-clippy cfg warnings
Louis Beaumontd7767a5d8490
diff --git a/crates/screenpipe-core/Cargo.toml b/crates/screenpipe-core/Cargo.tomlindex b24553743..800060c08 100644--- a/crates/screenpipe-core/Cargo.toml+++ b/crates/screenpipe-core/Cargo.toml@@ -58,6 +58,10 @@ tempfile = "3"[features]default = ["security"]+# objc's msg_send! emits #[cfg(feature = "cargo-clippy")] gates internally;+# declaring the feature silences "unexpected cfg" warnings in macOS builds+# without changing behavior (it's never enabled at compile time).+cargo-clippy = []security = ["dep:regex", "dep:lazy_static"]secrets = ["dep:screenpipe-secrets", "dep:sqlx"]cloud-sync = [diff --git a/crates/screenpipe-engine/src/auth_key.rs b/crates/screenpipe-engine/src/auth_key.rsindex 88254fd12..2d1a28ac8 100644--- a/crates/screenpipe-engine/src/auth_key.rs+++ b/crates/screenpipe-engine/src/auth_key.rs@@ -118,3 +118,44 @@ fn read_legacy_auth_json() -> Option<String> {.filter(|s| !s.is_empty()).map(|s| s.to_string())}++/// Read-only counterpart to `resolve_api_auth_key`. Same priority chain+/// (env → encrypted SecretStore → legacy file) but does NOT auto-generate+/// or persist anything when no key is found — returns `None` instead.+///+/// Use this from CLI callers that need to *find* the running server's key,+/// not mint a fresh one. The full resolver auto-generates on miss, which is+/// correct for the server's startup path but would silently produce a key+/// that doesn't match the running server's in-memory value when called from+/// a sibling process.+pub async fn find_api_auth_key() -> Option<String> {+ if let Ok(k) = std::env::var("SCREENPIPE_API_KEY") {+ if !k.is_empty() {+ return Some(k);+ }+ }+ // Tauri sidecar processes (pi-agent shelling into bash) inherit the+ // app's env under different names. Honor those too — without this the+ // agent's `connection list` couldn't authenticate even though the key+ // was right there.+ for var in ["SCREENPIPE_LOCAL_API_KEY", "SCREENPIPE_API_AUTH_KEY"] {+ if let Ok(k) = std::env::var(var) {+ if !k.is_empty() {+ return Some(k);+ }+ }+ }++ let data_dir = screenpipe_core::paths::default_screenpipe_data_dir();+ if let Ok(store) = open_secret_store(&data_dir).await {+ if let Ok(Some(bytes)) = store.get("api_auth_key").await {+ if let Ok(s) = String::from_utf8(bytes) {+ if !s.is_empty() {+ return Some(s);+ }+ }+ }+ }++ read_legacy_auth_json()+}diff --git a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs b/crates/screenpipe-engine/src/bin/screenpipe-engine.rsindex 078323b3f..e6276a67a 100644--- a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs+++ b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs@@ -41,8 +41,7 @@ use screenpipe_screen::monitor::list_monitors;use serde_json::json;use std::{env, fs,- net::SocketAddr,- net::{IpAddr, Ipv4Addr},+ net::{IpAddr, SocketAddr},ops::Deref,path::PathBuf,sync::Arc,diff --git a/crates/screenpipe-engine/src/cli/auth.rs b/crates/screenpipe-engine/src/cli/auth.rsindex 9ec3bd9de..f0202ab89 100644--- a/crates/screenpipe-engine/src/cli/auth.rs+++ b/crates/screenpipe-engine/src/cli/auth.rs@@ -5,17 +5,6 @@use super::AuthCommand;use anyhow::Result;-/// Open a lightweight SecretStore connection to db.sqlite.-/// Shared by auth, pipe, and other CLI commands that need credentials.-pub async fn open_secret_store() -> Result<screenpipe_secrets::SecretStore> {- let data_dir = screenpipe_core::paths::default_screenpipe_data_dir();- let db_path = data_dir.join("db.sqlite");- let db_url = format!("sqlite:{}?mode=rwc", db_path.display());- let pool = sqlx::SqlitePool::connect(&db_url).await?;- let store = screenpipe_secrets::SecretStore::new(pool, None).await?;- Ok(store)-}-pub async fn handle_auth_command(command: &AuthCommand) -> Result<()> {match command {AuthCommand::Token => print_token().await,@@ -23,37 +12,13 @@ pub async fn handle_auth_command(command: &AuthCommand) -> Result<()> {}async fn print_token() -> Result<()> {- // Priority 1: SCREENPIPE_API_KEY env var- if let Ok(key) = std::env::var("SCREENPIPE_API_KEY") {- if !key.is_empty() {- println!("{}", key);- return Ok(());- }- }-- // Priority 2: SecretStore in db.sqlite (encrypted, keychain key)- if let Ok(store) = open_secret_store().await {- if let Ok(Some(bytes)) = store.get("api_auth_key").await {- if let Ok(key) = String::from_utf8(bytes) {- if !key.is_empty() {- println!("{}", key);- return Ok(());- }- }- }- }-- // Priority 3: legacy auth.json (for users upgrading)- if let Some(home) = dirs::home_dir() {- let auth_path = home.join(".screenpipe/auth.json");- if let Ok(content) = std::fs::read_to_string(auth_path) {- if let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) {- if let Some(key) = json["token"].as_str().filter(|s| !s.is_empty()) {- println!("{}", key);- return Ok(());- }- }- }+ // All sources (env vars, encrypted SecretStore in db.sqlite, legacy+ // ~/.screenpipe/auth.json) live behind one resolver in `auth_key.rs`.+ // Don't reimplement the priority chain here — divergent copies are+ // exactly what caused agent-driven `connection list` to silently 403.+ if let Some(key) = crate::auth_key::find_api_auth_key().await {+ println!("{}", key);+ return Ok(());}eprintln!("no API token found. start screenpipe first, or set SCREENPIPE_API_KEY env var.");diff --git a/crates/screenpipe-engine/src/cli/connection.rs b/crates/screenpipe-engine/src/cli/connection.rsindex 267fbcfe7..3aeb81e6c 100644--- a/crates/screenpipe-engine/src/cli/connection.rs+++ b/crates/screenpipe-engine/src/cli/connection.rs@@ -305,17 +305,13 @@ struct BrowsersResponse {}async fn fetch_running_browsers() -> Vec<BrowserSummaryWire> {- // Honor the same auth knobs as the rest of the CLI plus the names the- // pi-agent's bash sandbox exports. The agent injects- // `SCREENPIPE_LOCAL_API_KEY` (and `SCREENPIPE_API_AUTH_KEY` historically),- // not `SCREENPIPE_API_KEY` — checking only the latter silently dropped- // the auth header for agent-driven `connection list` calls, so the- // engine returned 403 and we appended zero browser rows.- let auth_token = std::env::var("SCREENPIPE_API_KEY")- .ok()- .or_else(|| std::env::var("SCREENPIPE_LOCAL_API_KEY").ok())- .or_else(|| std::env::var("SCREENPIPE_API_AUTH_KEY").ok())- .or_else(read_auth_key_file);+ // Auth lookup goes through `crate::auth_key::find_api_auth_key` —+ // the single read-only resolver that knows about the encrypted+ // SecretStore in db.sqlite, the env-var aliases pi-agent injects,+ // and the legacy auth.json. Don't open-code another priority chain+ // here; that's how this query started silently 403'ing in the first+ // place.+ let auth_token = crate::auth_key::find_api_auth_key().await;let client = reqwest::Client::new();let mut req = client@@ -333,12 +329,3 @@ async fn fetch_running_browsers() -> Vec<BrowserSummaryWire> {_ => Vec::new(),}}--fn read_auth_key_file() -> Option<String> {- let path = screenpipe_core::paths::default_screenpipe_data_dir().join("auth.json");- let body = std::fs::read_to_string(path).ok()?;- let v: serde_json::Value = serde_json::from_str(&body).ok()?;- v.get("api_key")- .and_then(|s| s.as_str())- .map(|s| s.to_string())-}