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: store ChatGPT OAuth tokens in encrypted store, not plain file

Louis Beaumontdcb2c925f6d7
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/chatgpt_oauth.rs b/apps/screenpipe-app-tauri/src-tauri/src/chatgpt_oauth.rs
index 75bf99ac4..d559a7af3 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/chatgpt_oauth.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/chatgpt_oauth.rs
@@ -11,11 +11,14 @@
//! 1. PKCE authorize → auth code
//! 2. Exchange auth code → access_token + refresh_token
//! 3. Use access_token directly as Bearer token for OpenAI API
+//!
+//! Tokens are stored in the encrypted Tauri store (store.bin), not as a
+//! separate file, so they persist across restarts and benefit from keychain
+//! encryption.
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
-use std::path::PathBuf;
use tauri::AppHandle;
use tauri_plugin_opener::OpenerExt;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -26,15 +29,14 @@ const ISSUER: &str = "https://auth.openai.com";
const TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
const CALLBACK_PORT: u16 = 1455;
+const STORE_KEY: &str = "chatgpt_oauth";
+
// ── Token storage ──────────────────────────────────────────────────────
#[derive(Serialize, Deserialize, Clone)]
struct OAuthTokens {
- /// The OAuth access_token used as Bearer token for OpenAI API calls
access_token: String,
- /// OAuth refresh token for obtaining new credentials
refresh_token: String,
- /// Unix-epoch seconds when the access token expires
expires_at: Option<u64>,
}
@@ -43,32 +45,35 @@ pub struct ChatGptOAuthStatus {
pub logged_in: bool,
}
-fn get_token_path() -> Result<PathBuf, String> {
- let dir = screenpipe_core::paths::default_screenpipe_data_dir();
- std::fs::create_dir_all(&dir)
- .map_err(|e| format!("failed to create .screenpipe dir: {}", e))?;
- Ok(dir.join("chatgpt-oauth.json"))
+fn read_tokens(app: &AppHandle) -> Option<OAuthTokens> {
+ let store = crate::store::get_store(app, None).ok()?;
+ let val = store.get(STORE_KEY)?;
+ serde_json::from_value(val).ok()
}
-fn read_tokens() -> Option<OAuthTokens> {
- let path = get_token_path().ok()?;
- let content = std::fs::read_to_string(path).ok()?;
- serde_json::from_str(&content).ok()
+fn write_tokens(app: &AppHandle, tokens: &OAuthTokens) -> Result<(), String> {
+ let store =
+ crate::store::get_store(app, None).map_err(|e| format!("failed to get store: {}", e))?;
+ let val =
+ serde_json::to_value(tokens).map_err(|e| format!("failed to serialize tokens: {}", e))?;
+ store.set(STORE_KEY, val);
+ store.save().map_err(|e| format!("failed to save store: {}", e))?;
+ crate::store::reencrypt_store_file(app);
+ Ok(())
}
-fn write_tokens(tokens: &OAuthTokens) -> Result<(), String> {
- let path = get_token_path()?;
- let content = serde_json::to_string_pretty(tokens)
- .map_err(|e| format!("failed to serialize tokens: {}", e))?;
- std::fs::write(path, content).map_err(|e| format!("failed to write tokens: {}", e))
+fn delete_tokens(app: &AppHandle) -> Result<(), String> {
+ let store =
+ crate::store::get_store(app, None).map_err(|e| format!("failed to get store: {}", e))?;
+ store.delete(STORE_KEY);
+ store.save().map_err(|e| format!("failed to save store: {}", e))?;
+ crate::store::reencrypt_store_file(app);
+ Ok(())
}
fn is_token_expired(tokens: &OAuthTokens) -> bool {
match tokens.expires_at {
- Some(expires_at) => {
- let now = unix_now();
- now >= expires_at.saturating_sub(60)
- }
+ Some(expires_at) => unix_now() >= expires_at.saturating_sub(60),
None => false,
}
}
@@ -80,6 +85,43 @@ fn unix_now() -> u64 {
.as_secs()
}
+/// Migrate tokens from the old `chatgpt-oauth.json` file to the encrypted store.
+/// Called once on startup. Deletes the file after successful migration.
+pub fn migrate_from_file(app: &AppHandle) {
+ let path = screenpipe_core::paths::default_screenpipe_data_dir().join("chatgpt-oauth.json");
+ if !path.exists() {
+ return;
+ }
+
+ let content = match std::fs::read_to_string(&path) {
+ Ok(c) => c,
+ Err(e) => {
+ error!("chatgpt oauth: failed to read old token file: {}", e);
+ return;
+ }
+ };
+
+ let tokens: OAuthTokens = match serde_json::from_str(&content) {
+ Ok(t) => t,
+ Err(e) => {
+ error!("chatgpt oauth: failed to parse old token file: {}", e);
+ // Remove corrupt file
+ let _ = std::fs::remove_file(&path);
+ return;
+ }
+ };
+
+ match write_tokens(app, &tokens) {
+ Ok(()) => {
+ let _ = std::fs::remove_file(&path);
+ info!("chatgpt oauth: migrated tokens from file to encrypted store");
+ }
+ Err(e) => {
+ error!("chatgpt oauth: migration failed: {}", e);
+ }
+ }
+}
+
// ── PKCE helpers ───────────────────────────────────────────────────────
fn generate_pkce() -> (String, String) {
@@ -98,7 +140,10 @@ fn generate_pkce() -> (String, String) {
// ── Token refresh ──────────────────────────────────────────────────────
-async fn do_refresh_token(refresh_token: &str) -> Result<OAuthTokens, String> {
+async fn do_refresh_token(
+ app: &AppHandle,
+ refresh_token: &str,
+) -> Result<OAuthTokens, String> {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
@@ -111,7 +156,7 @@ async fn do_refresh_token(refresh_token: &str) -> Result<OAuthTokens, String> {
"grant_type": "refresh_token",
"client_id": CLIENT_ID,
"refresh_token": refresh_token,
- "scope": "openid profile email offline_access",
+ "scope": "openai offline_access",
}))
.send()
.await
@@ -146,17 +191,17 @@ async fn do_refresh_token(refresh_token: &str) -> Result<OAuthTokens, String> {
expires_at: Some(unix_now() + expires_in),
};
- write_tokens(&tokens)?;
+ write_tokens(app, &tokens)?;
info!("ChatGPT token refreshed successfully");
Ok(tokens)
}
/// Get a valid access token, refreshing automatically if expired.
-pub async fn get_valid_token() -> Result<String, String> {
- let tokens = read_tokens().ok_or("not logged in to ChatGPT")?;
+pub async fn get_valid_token(app: &AppHandle) -> Result<String, String> {
+ let tokens = read_tokens(app).ok_or("not logged in to ChatGPT")?;
if is_token_expired(&tokens) {
- let refreshed = do_refresh_token(&tokens.refresh_token).await?;
+ let refreshed = do_refresh_token(app, &tokens.refresh_token).await?;
return Ok(refreshed.access_token);
}
@@ -166,8 +211,6 @@ pub async fn get_valid_token() -> Result<String, String> {
// ── Local callback server ──────────────────────────────────────────────
async fn wait_for_callback(listener: tokio::net::TcpListener) -> Result<String, String> {
- // Loop to handle preflight/favicon requests that browsers (especially on
- // Windows) send before the actual OAuth redirect arrives.
loop {
let (mut stream, _) = listener
.accept()
@@ -177,12 +220,11 @@ async fn wait_for_callback(listener: tokio::net::TcpListener) -> Result<String,
let mut buf = vec![0u8; 4096];
let n = match stream.read(&mut buf).await {
Ok(n) => n,
- Err(_) => continue, // broken connection, try next
+ Err(_) => continue,
};
let request = String::from_utf8_lossy(&buf[..n]);
- // Parse: GET /auth/callback?code=xxx HTTP/1.1
let code = request
.lines()
.next()
@@ -208,7 +250,6 @@ async fn wait_for_callback(listener: tokio::net::TcpListener) -> Result<String,
return Ok(code);
}
None => {
- // Not the callback — respond with 404 and keep listening
let _ = stream
.write_all(b"HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n")
.await;
@@ -224,9 +265,6 @@ async fn wait_for_callback(listener: tokio::net::TcpListener) -> Result<String,
pub async fn chatgpt_oauth_login(app_handle: AppHandle) -> Result<bool, String> {
let (code_verifier, code_challenge) = generate_pkce();
- // Bind the local callback server.
- // Try IPv4 first, then IPv6 (Windows often resolves "localhost" to [::1]),
- // then any available port as last resort.
let listener = match tokio::net::TcpListener::bind(format!("127.0.0.1:{}", CALLBACK_PORT)).await
{
Ok(l) => l,
@@ -247,14 +285,13 @@ pub async fn chatgpt_oauth_login(app_handle: AppHandle) -> Result<bool, String>
let state = uuid::Uuid::new_v4().simple().to_string();
- // Build the authorization URL (matches Codex CLI params)
let mut auth_url = reqwest::Url::parse(&format!("{ISSUER}/oauth/authorize")).unwrap();
auth_url
.query_pairs_mut()
.append_pair("response_type", "code")
.append_pair("client_id", CLIENT_ID)
.append_pair("redirect_uri", &redirect_uri)
- .append_pair("scope", "openid profile email offline_access")
+ .append_pair("scope", "openai offline_access")
.append_pair("code_challenge", &code_challenge)
.append_pair("code_challenge_method", "S256")
.append_pair("id_token_add_organizations", "true")
@@ -262,7 +299,6 @@ pub async fn chatgpt_oauth_login(app_handle: AppHandle) -> Result<bool, String>
.append_pair("state", &state)
.append_pair("originator", "codex_cli_rs");
- // Open system browser
app_handle
.opener()
.open_url(auth_url.as_str(), None::<&str>)
@@ -270,7 +306,6 @@ pub async fn chatgpt_oauth_login(app_handle: AppHandle) -> Result<bool, String>
info!("waiting for ChatGPT OAuth callback on port {}", port);
- // Wait for the redirect with a 120-second timeout
let auth_code = tokio::time::timeout(
std::time::Duration::from_secs(120),
wait_for_callback(listener),
@@ -279,7 +314,6 @@ pub async fn chatgpt_oauth_login(app_handle: AppHandle) -> Result<bool, String>
.map_err(|_| "OAuth login timed out (120s)".to_string())?
.map_err(|e| format!("OAuth callback error: {}", e))?;
- // Exchange authorization code for access_token + refresh_token
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
@@ -329,19 +363,19 @@ pub async fn chatgpt_oauth_login(app_handle: AppHandle) -> Result<bool, String>
expires_at: Some(unix_now() + expires_in),
};
- write_tokens(&tokens)?;
- info!("ChatGPT OAuth login successful — token saved");
+ write_tokens(&app_handle, &tokens)?;
+ info!("ChatGPT OAuth login successful — token saved to encrypted store");
Ok(true)
}
#[tauri::command]
#[specta::specta]
-pub async fn chatgpt_oauth_status() -> Result<ChatGptOAuthStatus, String> {
- match read_tokens() {
+pub async fn chatgpt_oauth_status(app_handle: AppHandle) -> Result<ChatGptOAuthStatus, String> {
+ match read_tokens(&app_handle) {
Some(tokens) => {
if is_token_expired(&tokens) {
- match do_refresh_token(&tokens.refresh_token).await {
+ match do_refresh_token(&app_handle, &tokens.refresh_token).await {
Ok(_) => Ok(ChatGptOAuthStatus { logged_in: true }),
Err(e) => {
error!("ChatGPT token refresh failed: {}", e);
@@ -356,19 +390,16 @@ pub async fn chatgpt_oauth_status() -> Result<ChatGptOAuthStatus, String> {
}
}
-/// Return the current valid access token (auto-refreshing if needed).
-/// Used by the frontend to call OpenAI APIs directly (e.g. /v1/models).
#[tauri::command]
#[specta::specta]
-pub async fn chatgpt_oauth_get_token() -> Result<String, String> {
- get_valid_token().await
+pub async fn chatgpt_oauth_get_token(app_handle: AppHandle) -> Result<String, String> {
+ get_valid_token(&app_handle).await
}
-/// Fetch available models from OpenAI using the stored OAuth token.
#[tauri::command]
#[specta::specta]
-pub async fn chatgpt_oauth_models() -> Result<Vec<String>, String> {
- let token = get_valid_token().await?;
+pub async fn chatgpt_oauth_models(app_handle: AppHandle) -> Result<Vec<String>, String> {
+ let token = get_valid_token(&app_handle).await?;
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(15))
@@ -407,11 +438,8 @@ pub async fn chatgpt_oauth_models() -> Result<Vec<String>, String> {
#[tauri::command]
#[specta::specta]
-pub async fn chatgpt_oauth_logout() -> Result<bool, String> {
- let path = get_token_path()?;
- if path.exists() {
- std::fs::remove_file(&path).map_err(|e| format!("failed to remove token file: {}", e))?;
- }
+pub async fn chatgpt_oauth_logout(app_handle: AppHandle) -> Result<bool, String> {
+ delete_tokens(&app_handle)?;
info!("ChatGPT OAuth logged out");
Ok(true)
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 68f92b367..a993a1ebb 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -1245,6 +1245,9 @@ async fn main() {
}
}
+ // Migrate ChatGPT OAuth tokens from old file to encrypted store
+ chatgpt_oauth::migrate_from_file(&app.handle());
+
// Pre-download AI models in background immediately.
// These downloads don't need any permissions — they just fetch files to cache.
// On macOS, granting screen recording permission restarts the app, killing
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index 818851f57..e7adb93b0 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -1261,9 +1261,9 @@ pub async fn pi_start_inner(
// Pass the user's API key as env var for non-screenpipe providers
if let Some(ref config) = provider_config {
- // ChatGPT OAuth: inject token from stored OAuth file (no api_key in config)
+ // ChatGPT OAuth: inject token from encrypted store (no api_key in config)
if config.provider == "openai-chatgpt" {
- match crate::chatgpt_oauth::get_valid_token().await {
+ match crate::chatgpt_oauth::get_valid_token(&app).await {
Ok(token) => {
cmd.env("OPENAI_CHATGPT_TOKEN", token);
}