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

feat: enforce localhost auth via Tauri IPC — no async race

Louis Beaumont8cea07154f1c
diff --git a/apps/screenpipe-app-tauri/lib/api.ts b/apps/screenpipe-app-tauri/lib/api.ts
index b9aa1ee93..3b174ca65 100644
--- a/apps/screenpipe-app-tauri/lib/api.ts
+++ b/apps/screenpipe-app-tauri/lib/api.ts
@@ -19,43 +19,36 @@
*/
// ---------------------------------------------------------------------------
-// Configuration — set once at app startup, read everywhere
+// Configuration — loaded from Tauri IPC (fast, synchronous on Rust side)
// ---------------------------------------------------------------------------
let _port = 3030;
let _apiKey: string | null = null;
let _authEnabled = false;
let _initialized = false;
-
-// Eager initialization promise — reads from Tauri store immediately on import.
-// This ensures auth is available before any React component mounts.
let _initPromise: Promise<void> | null = null;
+/**
+ * Load API config from the Tauri backend via IPC command.
+ * This is fast (microseconds — reads from memory, no disk I/O).
+ * Falls back to defaults in non-Tauri contexts (tests, SSR).
+ */
function ensureInitialized(): Promise<void> {
if (_initialized) return Promise.resolve();
if (_initPromise) return _initPromise;
_initPromise = (async () => {
try {
- const { Store } = await import("@tauri-apps/plugin-store");
- const store = await Store.load("store.bin");
- const settings = await store.get<Record<string, unknown>>("settings");
- if (settings) {
- const port = (settings as any)?.port;
- const apiKey = (settings as any)?.apiKey;
- const apiAuth = (settings as any)?.apiAuth;
- if (port) _port = port;
- if (apiAuth) {
- _authEnabled = true;
- if (apiKey) _apiKey = apiKey;
- }
- }
- // Also check user token as fallback key
- if (_authEnabled && !_apiKey) {
- const user = await store.get<Record<string, unknown>>("user");
- const token = (user as any)?.token || (user as any)?.api_key;
- if (token) _apiKey = token;
- }
+ const { invoke } = await import("@tauri-apps/api/core");
+ const config = await invoke<{
+ key: string | null;
+ port: number;
+ auth_enabled: boolean;
+ }>("get_local_api_config");
+
+ _port = config.port;
+ _apiKey = config.key;
+ _authEnabled = config.auth_enabled;
} catch {
// Not in Tauri context (tests, SSR) — defaults are fine
}
@@ -65,12 +58,12 @@ function ensureInitialized(): Promise<void> {
return _initPromise;
}
-// Start loading immediately on import — don't wait for React mount
+// Start loading immediately on import
ensureInitialized();
/**
- * Configure the API module. Call from SettingsProvider after loading settings.
- * Overrides the eager initialization with authoritative values.
+ * Configure the API module explicitly. Called by SettingsProvider when
+ * settings change (port, auth key). Overrides the IPC-loaded values.
*/
export function configureApi(opts: {
port?: number;
@@ -85,7 +78,6 @@ export function configureApi(opts: {
/**
* Get the base URL for the local screenpipe API.
- * Use this instead of hardcoding "http://localhost:3030".
*/
export function getApiBaseUrl(): string {
return `http://localhost:${_port}`;
@@ -100,7 +92,6 @@ export function getApiPort(): number {
/**
* Build auth headers for the current config.
- * Returns empty object if auth is disabled.
*/
export function getAuthHeaders(): Record<string, string> {
if (_authEnabled && _apiKey) {
@@ -119,16 +110,12 @@ export function getAuthHeaders(): Record<string, string> {
* - Resolves paths relative to the configured base URL
* - Auto-injects auth header when API auth is enabled
* - Passes through full URLs unchanged (for remote device access)
- * - Waits for initialization on first call if needed
- *
- * @param path - API path (e.g. "/search?q=hello") or full URL
- * @param init - Standard fetch RequestInit
+ * - Waits for IPC config on first call (typically already resolved)
*/
export async function localFetch(
path: string,
init?: RequestInit
): Promise<Response> {
- // Ensure config is loaded before first request
await ensureInitialized();
const url = path.startsWith("http")
diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
index fec9f4cc7..fd7894dd4 100644
--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -170,6 +170,10 @@ async updateGlobalShortcuts(showShortcut: string, startShortcut: string, stopSho
else return { status: "error", error: e as any };
}
},
+/**
+ * Start the server (if not running) and capture.
+ * This is the main entry point called by the frontend.
+ */
async spawnScreenpipe(overrideArgs: string[] | null) : Promise<Result<null, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("spawn_screenpipe", { overrideArgs }) };
@@ -178,6 +182,10 @@ async spawnScreenpipe(overrideArgs: string[] | null) : Promise<Result<null, stri
else return { status: "error", error: e as any };
}
},
+/**
+ * Stop everything — capture only. Server stays alive.
+ * This is the command called by the tray toggle and keyboard shortcut.
+ */
async stopScreenpipe() : Promise<Result<null, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("stop_screenpipe") };
@@ -186,22 +194,6 @@ async stopScreenpipe() : Promise<Result<null, string>> {
else return { status: "error", error: e as any };
}
},
-async startCapture() : Promise<Result<null, string>> {
- try {
- return { status: "ok", data: await TAURI_INVOKE("start_capture") };
-} catch (e) {
- if(e instanceof Error) throw e;
- else return { status: "error", error: e as any };
-}
-},
-async stopCapture() : Promise<Result<null, string>> {
- try {
- return { status: "ok", data: await TAURI_INVOKE("stop_capture") };
-} catch (e) {
- if(e instanceof Error) throw e;
- else return { status: "error", error: e as any };
-}
-},
async getMonitors() : Promise<Result<MonitorDevice[], string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("get_monitors") };
@@ -1264,12 +1256,12 @@ ignoreIncognitoWindows: boolean;
* Experimental: pause screen capture when a DRM streaming app or site is focused.
* Off by default; engine-only pause (no full app shutdown).
*/
-pauseOnDrmContent?: boolean;
+pauseOnDrmContent?: boolean;
/**
* Continue recording audio when the screen is locked.
* Default: false (audio pauses when screen is locked to save resources).
*/
-recordWhileLocked?: boolean;
+recordWhileLocked?: boolean;
/**
* Automatically append text typed during a meeting to the meeting's note
* when the meeting ends. Groups typed text by app/window context.
@@ -1373,7 +1365,11 @@ scheduleRules?: ScheduleRule[];
/**
* Require authentication for remote (non-localhost) API access.
*/
-apiAuth?: boolean }) &
+apiAuth?: boolean;
+/**
+ * Custom API key for remote authentication. If empty, a key is auto-generated.
+ */
+apiKey?: string }) &
/**
* Catch-all for fields added by the frontend (e.g. chatHistory)
* that the Rust struct doesn't know about. Without this, `save()` would
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
index deb353112..864b3c8b8 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
@@ -132,6 +132,33 @@ pub fn is_enterprise_build_cmd(app_handle: tauri::AppHandle) -> bool {
is_enterprise_build(&app_handle)
}
+/// Get the local API auth key and port for the frontend to use.
+/// Returns immediately (no async, no disk I/O) — the key is already in memory.
+/// Returns { key: string | null, port: number, auth_enabled: bool }.
+#[tauri::command]
+#[specta::specta]
+pub fn get_local_api_config(
+ app_handle: tauri::AppHandle,
+) -> serde_json::Value {
+ use crate::recording::RecordingState;
+ if let Some(state) = app_handle.try_state::<RecordingState>() {
+ if let Ok(guard) = state.server.try_lock() {
+ if let Some(ref core) = *guard {
+ return serde_json::json!({
+ "key": core.local_api_key,
+ "port": core.port,
+ "auth_enabled": core.local_api_key.is_some(),
+ });
+ }
+ }
+ }
+ serde_json::json!({
+ "key": null,
+ "port": 3030,
+ "auth_enabled": false,
+ })
+}
+
/// Read the enterprise license key from `enterprise.json`.
/// Checks in order:
/// 1. Next to executable (pushed via Intune/MDM to Program Files / .app bundle)
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index b65c29966..68f92b367 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -836,6 +836,7 @@ async fn main() {
.manage(sync_scheduler)
.invoke_handler(tauri::generate_handler![
commands::is_enterprise_build_cmd,
+ commands::get_local_api_config,
commands::get_enterprise_license_key,
enterprise_policy::set_enterprise_policy,
commands::save_enterprise_license_key,
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
index 3908f471b..5a7902dad 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
@@ -45,6 +45,9 @@ pub struct ServerCore {
pub data_dir: PathBuf,
pub data_path: PathBuf,
pub port: u16,
+ /// Local API auth key — exposed to the frontend via Tauri command so
+ /// localFetch can inject it synchronously (no async store race).
+ pub local_api_key: Option<String>,
}
impl ServerCore {
@@ -369,6 +372,7 @@ impl ServerCore {
data_dir: local_data_dir,
data_path,
port: config.port,
+ local_api_key: config.api_auth_key.clone(),
})
}
diff --git a/crates/screenpipe-engine/src/server.rs b/crates/screenpipe-engine/src/server.rs
index 621fc0b3d..c2a95105d 100644
--- a/crates/screenpipe-engine/src/server.rs
+++ b/crates/screenpipe-engine/src/server.rs
@@ -794,12 +794,11 @@ impl SCServer {
crate::routes::timezone::timestamp_middleware,
))
.layer({
- // API auth middleware — when api_auth is enabled,
- // non-localhost requests must include a valid bearer token.
- // Localhost is always allowed because the Tauri frontend runs
- // in-process and can't reliably inject auth before first render.
- // Local security is handled by the credential proxy (connections
- // never expose raw keys to callers) rather than transport auth.
+ // API auth middleware — when api_auth is enabled, ALL requests
+ // (including localhost) must include a valid bearer token.
+ // This prevents other apps on the same machine from accessing
+ // screen data. The Tauri frontend gets the key via IPC command
+ // (get_local_api_config), pipes get it via SCREENPIPE_LOCAL_API_KEY env var.
let auth_enabled = self.api_auth;
let auth_key = self.api_auth_key.clone();
axum::middleware::from_fn(
@@ -811,19 +810,13 @@ impl SCServer {
return next.run(req).await;
}
- // Always allow localhost — the Tauri app and pipes
- // run locally and can't pass auth synchronously
- let is_localhost = req
- .extensions()
- .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
- .map(|ci| ci.0.ip().is_loopback())
- .unwrap_or(true);
-
- if is_localhost {
+ // Always allow health check — needed for startup detection
+ // and monitoring before the frontend has the token
+ if req.uri().path() == "/health" {
return next.run(req).await;
}
- // Check bearer token for remote requests
+ // Check bearer token
let authorized = req
.headers()
.get(axum::http::header::AUTHORIZATION)
@@ -841,7 +834,7 @@ impl SCServer {
.status(403)
.header("Content-Type", "application/json")
.body(axum::body::Body::from(
- r#"{"error":"unauthorized: remote API access requires authentication. Pass Authorization: Bearer <your-api-key> (find your key in Settings > Privacy)"}"#,
+ r#"{"error":"unauthorized: API authentication is enabled. Pass Authorization: Bearer <your-api-key> (find your key in Settings > Privacy)"}"#,
))
.unwrap()
}