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

fix: re-import OAuth tokens when file is newer than SecretStore entry

Louis Beaumont952693f48d2c
diff --git a/Cargo.lock b/Cargo.lock
index 7817e6c9c..453432d7a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7118,6 +7118,7 @@ dependencies = [
"anyhow",
"base64 0.22.1",
"chacha20poly1305",
+ "chrono",
"rand 0.8.5",
"serde",
"serde_json",
diff --git a/apps/screenpipe-app-tauri/components/settings/privacy-section.tsx b/apps/screenpipe-app-tauri/components/settings/privacy-section.tsx
index f4e7f7cb1..f0e68936a 100644
--- a/apps/screenpipe-app-tauri/components/settings/privacy-section.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/privacy-section.tsx
@@ -22,6 +22,7 @@ import {
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { HelpTooltip } from "@/components/ui/help-tooltip";
@@ -406,12 +407,25 @@ export function PrivacySection() {
</div>
</div>
<Switch
- checked={settings.apiAuth ?? false}
+ checked={settings.apiAuth ?? true}
onCheckedChange={(checked) => {
handleSettingsChange({ apiAuth: checked });
}}
/>
</div>
+ {(settings.apiAuth ?? true) && (
+ <div className="mt-2.5 flex items-center space-x-2.5 pl-6.5">
+ <Input
+ type="text"
+ placeholder="custom API key (leave empty to auto-generate)"
+ value={settings.apiKey ?? ""}
+ onChange={(e) => {
+ handleSettingsChange({ apiKey: e.target.value });
+ }}
+ className="h-8 text-xs font-mono"
+ />
+ </div>
+ )}
</CardContent>
</Card>
<Card className="border-border bg-card">
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 24d0c00f9..fd21a16bc 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -190,6 +190,7 @@ export type Settings = SettingsStore & {
recordMode: string;
}>;
apiAuth?: boolean;
+ apiKey?: string;
encryptStore?: boolean;
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/store.rs b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
index 9363ee521..70eadd50e 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/store.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
@@ -890,13 +890,31 @@ impl SettingsStore {
data_dir,
Some(&resolved_engine),
);
- // Set the API auth key from the user's token/api_key for remote auth
+ // Set the API auth key: settings apiKey > user api_key > user token > auto-generate
if config.api_auth {
- config.api_auth_key = self
- .user
- .api_key
- .clone()
- .or_else(|| self.user.token.clone());
+ let settings_key = settings.api_key.as_str();
+ config.api_auth_key = if !settings_key.is_empty() {
+ Some(settings_key.to_string())
+ } else {
+ None
+ }
+ .or_else(|| self.user.api_key.clone())
+ .or_else(|| self.user.token.clone());
+
+ // Auto-generate if no key found
+ if config.api_auth_key.is_none() {
+ let key = format!("sp-{}", uuid::Uuid::new_v4().simple());
+ if let Some(home) = dirs::home_dir() {
+ let auth_path = home.join(".screenpipe/auth.json");
+ let json = serde_json::json!({ "token": &key });
+ let _ = std::fs::write(
+ &auth_path,
+ serde_json::to_string_pretty(&json).unwrap_or_default(),
+ );
+ }
+ tracing::info!("api auth enabled — auto-generated key: {}", key);
+ config.api_auth_key = Some(key);
+ }
}
config
}
diff --git a/crates/screenpipe-config/src/recording.rs b/crates/screenpipe-config/src/recording.rs
index 180f0b9ba..04922cd9a 100644
--- a/crates/screenpipe-config/src/recording.rs
+++ b/crates/screenpipe-config/src/recording.rs
@@ -255,8 +255,12 @@ pub struct RecordingSettings {
pub schedule_rules: Vec<ScheduleRule>,
/// Require authentication for remote (non-localhost) API access.
- #[serde(rename = "apiAuth", default)]
+ #[serde(rename = "apiAuth", default = "default_true")]
pub api_auth: bool,
+
+ /// Custom API key for remote authentication. If empty, a key is auto-generated.
+ #[serde(rename = "apiKey", default)]
+ pub api_key: String,
}
impl RecordingSettings {
@@ -333,7 +337,8 @@ impl Default for RecordingSettings {
device_tier: None,
schedule_enabled: false,
schedule_rules: vec![],
- api_auth: false,
+ api_auth: true,
+ api_key: String::new(),
}
}
}
diff --git a/crates/screenpipe-engine/src/cli/mod.rs b/crates/screenpipe-engine/src/cli/mod.rs
index 17acfa47e..820aea661 100644
--- a/crates/screenpipe-engine/src/cli/mod.rs
+++ b/crates/screenpipe-engine/src/cli/mod.rs
@@ -347,7 +347,7 @@ pub struct RecordArgs {
/// 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)]
+ #[arg(long, default_value_t = true)]
pub api_auth: bool,
}
@@ -490,13 +490,46 @@ impl RecordArgs {
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())
- });
+ // Priority: env var > settings > auth.json > auto-generate
+ config.api_auth_key = std::env::var("SCREENPIPE_API_KEY")
+ .ok()
+ .or_else(|| {
+ let key = settings.api_key.as_str();
+ if key.is_empty() {
+ None
+ } else {
+ Some(key.to_string())
+ }
+ })
+ .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())
+ });
+
+ // Auto-generate a key if none found
+ if config.api_auth_key.is_none() {
+ let chars: &[u8] =
+ b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ let random_part: String = (0..32)
+ .map(|_| chars[fastrand::usize(..chars.len())] as char)
+ .collect();
+ let key = format!("sp-{}", random_part);
+ // Persist to auth.json so it survives restarts
+ if let Some(home) = dirs::home_dir() {
+ let auth_path = home.join(".screenpipe/auth.json");
+ let json = serde_json::json!({ "token": key });
+ let _ = std::fs::write(
+ &auth_path,
+ serde_json::to_string_pretty(&json).unwrap_or_default(),
+ );
+ }
+ tracing::info!("api auth enabled — auto-generated key: {}", key);
+ config.api_auth_key = Some(key);
+ } else {
+ tracing::info!("api auth enabled — key loaded");
+ }
}
config
diff --git a/crates/screenpipe-secrets/Cargo.toml b/crates/screenpipe-secrets/Cargo.toml
index bcd94f5f5..68ce64912 100644
--- a/crates/screenpipe-secrets/Cargo.toml
+++ b/crates/screenpipe-secrets/Cargo.toml
@@ -13,6 +13,7 @@ anyhow = "1"
tokio = { version = "1", features = ["full"] }
chacha20poly1305 = "0.10"
rand = "0.8"
+chrono = { version = "0.4", features = ["serde"] }
[dev-dependencies]
tokio = { version = "1", features = ["full", "test-util"] }
diff --git a/crates/screenpipe-secrets/src/migration.rs b/crates/screenpipe-secrets/src/migration.rs
index e0b877fc7..854e659da 100644
--- a/crates/screenpipe-secrets/src/migration.rs
+++ b/crates/screenpipe-secrets/src/migration.rs
@@ -49,23 +49,46 @@ pub async fn migrate_legacy_secrets(
match std::fs::read(&path) {
Ok(contents) => {
- // Check if already migrated and readable
- match store.get(&store_key).await {
+ // Check if already migrated — but re-import if file is newer
+ // (handles re-auth writing to file after migration)
+ let should_import = match store.get(&store_key).await {
Ok(Some(_)) => {
- report
- .skipped
- .push(format!("{} (already migrated)", filename));
- continue;
+ // Check if file is newer than store entry
+ let file_mtime = std::fs::metadata(&path)
+ .ok()
+ .and_then(|m| m.modified().ok());
+ let store_time = store
+ .get_updated_at(&store_key)
+ .await
+ .ok()
+ .flatten()
+ .and_then(|t| chrono::DateTime::parse_from_rfc3339(&t).ok())
+ .map(|dt| std::time::SystemTime::from(dt));
+
+ match (file_mtime, store_time) {
+ (Some(fm), Some(st)) if fm > st => {
+ info!("re-importing {} (file newer than store)", filename);
+ true
+ }
+ _ => {
+ report
+ .skipped
+ .push(format!("{} (already migrated)", filename));
+ false
+ }
+ }
}
- Ok(None) => {}
+ Ok(None) => true,
Err(_) => {
- // Decryption failed — likely a key change (new computer).
- // Re-migrate from the file to overwrite with the new key.
info!(
"re-migrating {} (old encrypted value unreadable, likely key change)",
filename
);
+ true
}
+ };
+ if !should_import {
+ continue;
}
if let Err(e) = store.set(&store_key, &contents).await {
diff --git a/crates/screenpipe-secrets/src/store.rs b/crates/screenpipe-secrets/src/store.rs
index 35d672b2b..311820bbd 100644
--- a/crates/screenpipe-secrets/src/store.rs
+++ b/crates/screenpipe-secrets/src/store.rs
@@ -104,6 +104,16 @@ impl SecretStore {
}
}
+ /// Get the updated_at timestamp for a secret. Returns None if key doesn't exist.
+ pub async fn get_updated_at(&self, key: &str) -> Result<Option<String>> {
+ let row: Option<(String,)> = sqlx::query_as("SELECT updated_at FROM secrets WHERE key = ?")
+ .bind(key)
+ .fetch_optional(&self.pool)
+ .await
+ .context("failed to get secret timestamp")?;
+ Ok(row.map(|(t,)| t))
+ }
+
/// Delete a secret by key.
pub async fn delete(&self, key: &str) -> Result<()> {
sqlx::query("DELETE FROM secrets WHERE key = ?")