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: optional API auth for remote access (--api-auth)
Louis Beaumont09f18141a77c
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-device-monitor.ts b/apps/screenpipe-app-tauri/lib/hooks/use-device-monitor.tsindex 14a6ac5fd..bf017f725 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-device-monitor.ts+++ b/apps/screenpipe-app-tauri/lib/hooks/use-device-monitor.ts@@ -89,10 +89,12 @@ async function fetchWithTimeout(}}-async function remotePost(address: string, path: string, body?: object) {+async function remotePost(address: string, path: string, body?: object, authToken?: string) {+ const headers: Record<string, string> = { "Content-Type": "application/json" };+ if (authToken) headers["Authorization"] = `Bearer ${authToken}`;const res = await fetchWithTimeout(`http://${address}${path}`, FETCH_TIMEOUT_MS, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers,body: body ? JSON.stringify(body) : undefined,});if (!res.ok) {@@ -102,6 +104,10 @@ async function remotePost(address: string, path: string, body?: object) {return res.json().catch(() => ({}));}+function authHeaders(token?: string): Record<string, string> {+ return token ? { "Authorization": `Bearer ${token}` } : {};+}+export function useDeviceMonitor() {const { settings, updateSettings } = useSettings();const [devices, setDevices] = useState<DeviceMonitorData[]>([]);@@ -118,14 +124,18 @@ export function useDeviceMonitor() {// Stable key for effect dependencyconst deviceKey = registeredDevices.map((d) => d.address).sort().join(",");+ const apiKey = settings.user?.api_key || settings.user?.token;+const pollDevice = useCallback(async (address: string, label?: string): Promise<DeviceMonitorData> => {try {+ const headers = authHeaders(apiKey ?? undefined);const [healthRes, pipesRes] = await Promise.all([- fetchWithTimeout(`http://${address}/health`, FETCH_TIMEOUT_MS),+ fetchWithTimeout(`http://${address}/health`, FETCH_TIMEOUT_MS, { headers }),fetchWithTimeout(`http://${address}/pipes?include_executions=true`,- FETCH_TIMEOUT_MS+ FETCH_TIMEOUT_MS,+ { headers }),]);@@ -306,20 +316,20 @@ export function useDeviceMonitor() {// Remote control actionsconst runPipe = useCallback(async (address: string, pipeName: string) => {- await remotePost(address, `/pipes/${encodeURIComponent(pipeName)}/run`);- }, []);+ await remotePost(address, `/pipes/${encodeURIComponent(pipeName)}/run`, undefined, apiKey ?? undefined);+ }, [apiKey]);const stopPipe = useCallback(async (address: string, pipeName: string) => {- await remotePost(address, `/pipes/${encodeURIComponent(pipeName)}/stop`);- }, []);+ await remotePost(address, `/pipes/${encodeURIComponent(pipeName)}/stop`, undefined, apiKey ?? undefined);+ }, [apiKey]);const enablePipe = useCallback(async (address: string, pipeName: string, enabled: boolean) => {await remotePost(address, `/pipes/${encodeURIComponent(pipeName)}/enable`, {enabled,- });+ }, apiKey ?? undefined);},- []+ [apiKey]);// Fetch full execution history for a specific pipediff --git a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rsindex 677885252..083514a24 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs@@ -459,6 +459,8 @@ pub async fn start_embedded_server(server.hot_frame_cache = Some(hot_frame_cache);server.power_manager = Some(power_manager);server.manual_meeting = Some(manual_meeting);+ server.api_auth = config.api_auth;+ server.api_auth_key = config.api_auth_key.clone();// Initialize pipe managerlet pipes_dir = config.data_dir.join("pipes");diff --git a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs b/crates/screenpipe-engine/src/bin/screenpipe-engine.rsindex 070a558da..7ef4e5ebd 100644--- a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs+++ b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs@@ -856,6 +856,8 @@ async fn main() -> anyhow::Result<()> {server.hot_frame_cache = Some(hot_frame_cache);server.power_manager = Some(power_manager);server.manual_meeting = Some(manual_meeting.clone());+ server.api_auth = config.api_auth;+ server.api_auth_key = config.api_auth_key.clone();// Attach sync handle if sync is enabledlet server = if let Some(ref handle) = sync_service_handle {diff --git a/crates/screenpipe-engine/src/cli/mod.rs b/crates/screenpipe-engine/src/cli/mod.rsindex 31c75bc5a..c73022e73 100644--- a/crates/screenpipe-engine/src/cli/mod.rs+++ b/crates/screenpipe-engine/src/cli/mod.rs@@ -343,6 +343,12 @@ pub struct RecordArgs {/// Pause screen and audio capture when DRM content (Netflix, Disney+, etc.) is detected#[arg(long, default_value_t = false)]pub pause_on_drm_content: bool,++ /// Require authentication for remote API access. When enabled, non-localhost+ /// requests must include Authorization: Bearer <SCREENPIPE_API_KEY>.+ /// Localhost requests are always allowed.+ #[arg(long, default_value_t = false)]+ pub api_auth: bool,}impl RecordArgs {@@ -480,7 +486,19 @@ impl RecordArgs {settings.audio_transcription_engine = safe.to_string();}- crate::recording_config::RecordingConfig::from_settings(&settings, data_dir, None)+ let mut config =+ crate::recording_config::RecordingConfig::from_settings(&settings, data_dir, None);+ config.api_auth = self.api_auth;+ if config.api_auth {+ // Load API key from env or auth.json+ config.api_auth_key = std::env::var("SCREENPIPE_API_KEY").ok().or_else(|| {+ let auth_path = dirs::home_dir()?.join(".screenpipe/auth.json");+ let content = std::fs::read_to_string(auth_path).ok()?;+ let json: serde_json::Value = serde_json::from_str(&content).ok()?;+ json["token"].as_str().map(|s| s.to_string())+ });+ }+ config}}diff --git a/crates/screenpipe-engine/src/recording_config.rs b/crates/screenpipe-engine/src/recording_config.rsindex 30b678cb4..9e7dc365d 100644--- a/crates/screenpipe-engine/src/recording_config.rs+++ b/crates/screenpipe-engine/src/recording_config.rs@@ -109,6 +109,15 @@ pub struct RecordingConfig {/// Maximum width for stored snapshots (0 = no limit). Default: 1920.pub max_snapshot_width: u32,++ /// Require authentication for remote (non-localhost) API access.+ /// When true, requests from other devices must include+ /// `Authorization: Bearer <SCREENPIPE_API_KEY>`.+ pub api_auth: bool,++ /// The API key for this instance (from SCREENPIPE_API_KEY env or auth.json).+ /// Used to validate incoming remote requests when api_auth is enabled.+ pub api_auth_key: Option<String>,}impl RecordingConfig {@@ -196,6 +205,8 @@ impl RecordingConfig {schedule_enabled: settings.schedule_enabled,schedule_rules: settings.schedule_rules.clone(),max_snapshot_width: settings.max_snapshot_width,+ api_auth: false,+ api_auth_key: None,}}diff --git a/crates/screenpipe-engine/src/server.rs b/crates/screenpipe-engine/src/server.rsindex 72dfe8015..f50d79da2 100644--- a/crates/screenpipe-engine/src/server.rs+++ b/crates/screenpipe-engine/src/server.rs@@ -166,6 +166,10 @@ pub struct AppState {pub manual_meeting: Arc<tokio::sync::RwLock<Option<i64>>>,/// Browser extension bridge — relays JS eval requests to the connected extensionpub browser_bridge: Arc<crate::routes::browser::BrowserBridge>,+ /// When true, non-localhost requests require Authorization: Bearer <api_key>+ pub api_auth: bool,+ /// The API key to validate against (from SCREENPIPE_API_KEY or auth.json)+ pub api_auth_key: Option<String>,}pub struct SCServer {@@ -190,6 +194,10 @@ pub struct SCServer {Arc<DashMap<String, Arc<screenpipe_core::pipes::permissions::PipePermissions>>>,/// Shared manual meeting lock — pass in from binary so persister and server share the same state.pub manual_meeting: Option<Arc<tokio::sync::RwLock<Option<i64>>>>,+ /// Require auth for remote API access+ pub api_auth: bool,+ /// API key for remote auth validation+ pub api_auth_key: Option<String>,}impl SCServer {@@ -222,6 +230,8 @@ impl SCServer {power_manager: None,pipe_permissions: Arc::new(DashMap::new()),manual_meeting: None,+ api_auth: false,+ api_auth_key: None,}}@@ -463,6 +473,8 @@ impl SCServer {.clone().unwrap_or_else(|| Arc::new(tokio::sync::RwLock::new(None))),browser_bridge: crate::routes::browser::BrowserBridge::new(),+ api_auth: self.api_auth,+ api_auth_key: self.api_auth_key.clone(),});let cors = CorsLayer::new()@@ -772,6 +784,57 @@ impl SCServer {.layer(axum::middleware::from_fn(crate::routes::timezone::timestamp_middleware,))+ .layer({+ // Remote API auth middleware — when api_auth is enabled,+ // non-localhost requests must include a valid bearer token.+ let auth_enabled = self.api_auth;+ let auth_key = self.api_auth_key.clone();+ axum::middleware::from_fn(+ move |req: axum::extract::Request, next: axum::middleware::Next| {+ let auth_enabled = auth_enabled;+ let auth_key = auth_key.clone();+ async move {+ if !auth_enabled {+ return next.run(req).await;+ }++ // Always allow localhost+ let is_localhost = req+ .extensions()+ .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()+ .map(|ci| ci.0.ip().is_loopback())+ .unwrap_or(true); // default to allow if no connect info++ if is_localhost {+ return next.run(req).await;+ }++ // Check bearer token+ let authorized = req+ .headers()+ .get(axum::http::header::AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.strip_prefix("Bearer "))+ .map(|token| {+ auth_key.as_deref() == Some(token)+ })+ .unwrap_or(false);++ if authorized {+ next.run(req).await+ } else {+ axum::response::Response::builder()+ .status(403)+ .header("Content-Type", "application/json")+ .body(axum::body::Body::from(+ r#"{"error":"unauthorized: remote API access requires authentication. Pass Authorization: Bearer <SCREENPIPE_API_KEY>"}"#,+ ))+ .unwrap()+ }+ }+ },+ )+ }).layer(cors).layer(TraceLayer::new_for_http().make_span_with(DefaultMakeSpan::default()))}