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: authentication + pipe store stripe integration

Louis Beaumont7d776b4dc966
diff --git a/Cargo.toml b/Cargo.toml
index 59b8c84e7..bb9230888 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -14,7 +14,7 @@ resolver = "2"
[workspace.package]
-version = "0.2.7"
+version = "0.2.8"
authors = ["louis030195 <[email protected]>"]
description = ""
repository = "https://github.com/mediar-ai/screenpipe"
diff --git a/screenpipe-app-tauri/app/layout.tsx b/screenpipe-app-tauri/app/layout.tsx
index 1b5b566bd..1927054b0 100644
--- a/screenpipe-app-tauri/app/layout.tsx
+++ b/screenpipe-app-tauri/app/layout.tsx
@@ -3,7 +3,6 @@ import { Inter } from "next/font/google";
import "./globals.css";
import { Providers } from "./providers";
import { Toaster } from "@/components/ui/toaster";
-import { ClerkProvider } from "@clerk/clerk-react";
const inter = Inter({ subsets: ["latin"] });
@@ -14,17 +13,12 @@ export default function RootLayout({
}) {
return (
<html lang="en" suppressHydrationWarning>
- <ClerkProvider
- publishableKey="pk_test_ZGVjZW50LXRyb3V0LTEuY2xlcmsuYWNjb3VudHMuZGV2JA"
- allowedRedirectOrigins={["http://localhost:3000", "tauri://localhost"]}
- >
- <Providers>
- <body className={inter.className}>
- {children}
- <Toaster />
- </body>
- </Providers>
- </ClerkProvider>
+ <Providers>
+ <body className={inter.className}>
+ {children}
+ <Toaster />
+ </body>
+ </Providers>
</html>
);
}
diff --git a/screenpipe-app-tauri/bun.lockb b/screenpipe-app-tauri/bun.lockb
index 732c6e972..257a0cb4d 100755
Binary files a/screenpipe-app-tauri/bun.lockb and b/screenpipe-app-tauri/bun.lockb differ
diff --git a/screenpipe-app-tauri/components/auth.tsx b/screenpipe-app-tauri/components/auth.tsx
index 6d1ff87ce..9f487934a 100644
--- a/screenpipe-app-tauri/components/auth.tsx
+++ b/screenpipe-app-tauri/components/auth.tsx
@@ -1,38 +1,43 @@
"use client";
-import { SignInButton, SignOutButton, useUser } from "@clerk/clerk-react";
+
+import { invoke } from "@tauri-apps/api/core";
import { Button } from "./ui/button";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
+import { useUser } from "@/lib/hooks/use-user";
+import { Avatar, AvatarFallback } from "./ui/avatar";
import posthog from "posthog-js";
-import { useSettings } from "@/lib/hooks/use-settings";
+
export function AuthButton() {
const { isSignedIn, user } = useUser();
- const { settings } = useSettings();
useEffect(() => {
- posthog.identify(settings.userId, {
- email: user?.primaryEmailAddress?.emailAddress,
- clerkId: user?.id,
+ posthog.identify(user?.user_id, {
+ email: user?.email,
});
posthog.setPersonProperties({
- email: user?.primaryEmailAddress?.emailAddress,
- clerkId: user?.id,
+ email: user?.email,
});
- }, [isSignedIn, user, settings.userId]);
+ }, [isSignedIn, user]);
+
+ const handleSignIn = async () => {
+ // This would typically open your auth window
+ await invoke("open_auth_window");
+ };
return (
- <div >
+ <div>
{isSignedIn ? (
- <SignOutButton>
- <Button variant="outline">
- sign out
- </Button>
- </SignOutButton>
+ <Button variant="ghost" onClick={handleSignIn}>
+ <Avatar>
+ <AvatarFallback>
+ {user?.email.charAt(0).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ </Button>
) : (
- <SignInButton mode="redirect">
- <Button variant="outline">
- sign in
- </Button>
- </SignInButton>
+ <Button variant="outline" onClick={handleSignIn}>
+ sign in
+ </Button>
)}
</div>
);
diff --git a/screenpipe-app-tauri/components/pipe-store.tsx b/screenpipe-app-tauri/components/pipe-store.tsx
index ff2cf09ef..acde89da5 100644
--- a/screenpipe-app-tauri/components/pipe-store.tsx
+++ b/screenpipe-app-tauri/components/pipe-store.tsx
@@ -51,8 +51,8 @@ import {
} from "@/components/ui/collapsible";
import { LogFileButton } from "./log-file-button";
import { useSettings } from "@/lib/hooks/use-settings";
-import { useUser } from "@clerk/clerk-react";
import { StripeSubscriptionButton } from "./stripe-subscription-button";
+import { useUser } from "@/lib/hooks/use-user";
export interface Pipe {
enabled: boolean;
@@ -105,7 +105,14 @@ const PipeDialog: React.FC = () => {
const [pipes, setPipes] = useState<Pipe[]>([]);
const { health } = useHealthCheck();
const { getDataDir } = useSettings();
- const { isSignedIn } = useUser();
+ const { user, checkLoomSubscription } = useUser();
+ const [hasLoomSubscription, setHasLoomSubscription] = useState(false);
+
+ useEffect(() => {
+ if (user) {
+ checkLoomSubscription().then(setHasLoomSubscription);
+ }
+ }, []);
useEffect(() => {
fetchInstalledPipes();
@@ -217,12 +224,11 @@ const PipeDialog: React.FC = () => {
const handleToggleEnabled = async (pipe: Pipe) => {
if (pipe.id === "pipe-for-loom" && !pipe.enabled) {
- const isSubscribed =
- localStorage.getItem("loom_pipe_subscribed") === "true";
- if (!isSubscribed) {
+ const hasLoomSubscription = await checkLoomSubscription();
+ if (!hasLoomSubscription) {
toast({
- title: "Subscription required",
- description: "Please subscribe to use the Loom pipe",
+ title: "subscription required",
+ description: "please subscribe to use the loom pipe",
});
return;
}
@@ -438,7 +444,7 @@ const PipeDialog: React.FC = () => {
<div className="flex space-x-2 mb-4">
{selectedPipe.id === "pipe-for-loom" &&
!selectedPipe.enabled &&
- !localStorage.getItem("loom_pipe_subscribed") ? (
+ !hasLoomSubscription ? (
<StripeSubscriptionButton
onSubscriptionComplete={() => handleToggleEnabled(selectedPipe)}
/>
diff --git a/screenpipe-app-tauri/components/settings.tsx b/screenpipe-app-tauri/components/settings.tsx
index 0f7d47b17..e7abcb6e1 100644
--- a/screenpipe-app-tauri/components/settings.tsx
+++ b/screenpipe-app-tauri/components/settings.tsx
@@ -60,6 +60,7 @@ import {
} from "@/components/ui/select";
import { useInterval } from "@/lib/hooks/use-interval";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
+import { AuthButton } from "./auth";
export function Settings({ className }: { className?: string }) {
const { settings, updateSettings, resetSetting } = useSettings();
@@ -484,7 +485,6 @@ export function Settings({ className }: { className?: string }) {
// Use the useInterval hook to periodically check the status
useInterval(checkEmbeddedAIStatus, 10000); // Check every 10 seconds
-
const handleShortcutToggle = (checked: boolean) => {
console.log("handleShortcutToggle", checked);
let newDisabledShortcuts = [...localSettings.disabledShortcuts];
@@ -515,22 +515,21 @@ export function Settings({ className }: { className?: string }) {
debouncedFetchHealth();
};
- window.addEventListener('settings-updated', handleSettingsUpdate);
-
+ window.addEventListener("settings-updated", handleSettingsUpdate);
+
return () => {
- window.removeEventListener('settings-updated', handleSettingsUpdate);
+ window.removeEventListener("settings-updated", handleSettingsUpdate);
};
}, [debouncedFetchHealth]);
-
return (
<Dialog
onOpenChange={(open) => {
if (!open) {
// Use a more reliable state update mechanism
- const event = new CustomEvent('settings-updated');
+ const event = new CustomEvent("settings-updated");
window.dispatchEvent(event);
-
+
// Add a small delay before refetching health
setTimeout(() => {
debouncedFetchHealth();
@@ -546,7 +545,12 @@ export function Settings({ className }: { className?: string }) {
</DialogTrigger>
<DialogContent className="max-w-[80vw] w-full max-h-[80vh] h-full overflow-y-auto">
<DialogHeader>
- <DialogTitle>settings</DialogTitle>
+ <DialogTitle>
+ <div className="flex items-center gap-4">
+ settings
+ <AuthButton />
+ </div>
+ </DialogTitle>
<DialogDescription>
choose your AI provider, enter necessary credentials, and more.
</DialogDescription>
diff --git a/screenpipe-app-tauri/components/stripe-subscription-button.tsx b/screenpipe-app-tauri/components/stripe-subscription-button.tsx
index 2b40f35db..edf7ea7d3 100644
--- a/screenpipe-app-tauri/components/stripe-subscription-button.tsx
+++ b/screenpipe-app-tauri/components/stripe-subscription-button.tsx
@@ -1,11 +1,11 @@
"use client";
import { Button } from "@/components/ui/button";
-import { useUser } from "@clerk/clerk-react";
import { open } from "@tauri-apps/plugin-shell";
import { toast } from "./ui/use-toast";
import posthog from "posthog-js";
import { useEffect, useState } from "react";
+import { useUser } from "@/lib/hooks/use-user";
interface StripeSubscriptionButtonProps {
onSubscriptionComplete?: () => void;
@@ -14,7 +14,7 @@ interface StripeSubscriptionButtonProps {
export function StripeSubscriptionButton({
onSubscriptionComplete,
}: StripeSubscriptionButtonProps) {
- const { user, isSignedIn } = useUser();
+ const { isSignedIn, user } = useUser();
const [isSubscribed, setIsSubscribed] = useState(false);
useEffect(() => {
@@ -24,7 +24,7 @@ export function StripeSubscriptionButton({
const handleSubscribe = async () => {
posthog.capture("subscribe_button_clicked", {
- email: user?.primaryEmailAddress?.emailAddress,
+ email: user?.email,
});
if (!isSignedIn) {
toast({
@@ -37,7 +37,7 @@ export function StripeSubscriptionButton({
try {
// Direct Stripe Checkout URL with price_id
- const checkoutUrl = `https://buy.stripe.com/28o00JcCq2JsgAE9AX?prefilled_email=${user.primaryEmailAddress?.emailAddress}&client_reference_id=${user.id}`;
+ const checkoutUrl = `https://buy.stripe.com/28o00JcCq2JsgAE9AX?prefilled_email=${user?.email}&client_reference_id=${user?.user_id}`;
// Open Stripe checkout in default browser
await open(checkoutUrl);
diff --git a/screenpipe-app-tauri/lib/hooks/use-health-check.tsx b/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
index 5fe13a37a..337de5053 100644
--- a/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
@@ -98,7 +98,7 @@ export function useHealthCheck() {
console.error("Health check error:", error);
if (!isServerDown) {
setIsServerDown(true);
- await invoke("set_tray_unhealth_icon");
+ // await invoke("set_tray_unhealth_icon");
const errorHealth: HealthCheckResponse = {
last_frame_timestamp: null,
last_audio_timestamp: null,
diff --git a/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 3672a5902..da2a43844 100644
--- a/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -156,6 +156,7 @@ export function useSettings() {
? "windows-native"
: "tesseract";
+
// no need to call load() as it's done automatically
const savedKey = (await store!.get<string>("openaiApiKey")) || "";
const savedDeepgramKey =
diff --git a/screenpipe-app-tauri/lib/hooks/use-user.ts b/screenpipe-app-tauri/lib/hooks/use-user.ts
new file mode 100644
index 000000000..6d5669436
--- /dev/null
+++ b/screenpipe-app-tauri/lib/hooks/use-user.ts
@@ -0,0 +1,92 @@
+import { useState, useEffect, useCallback } from "react";
+import { createStore } from "@tauri-apps/plugin-store";
+import { localDataDir, join } from "@tauri-apps/api/path";
+
+interface UserData {
+ token: string;
+ email: string;
+ user_id: string;
+}
+
+interface UserState {
+ isSignedIn: boolean;
+ isLoading: boolean;
+ error: string | null;
+ user: UserData | null;
+ checkLoomSubscription: () => Promise<boolean>;
+}
+
+let store: Awaited<ReturnType<typeof createStore>> | null = null;
+
+async function initStore() {
+ const dataDir = await localDataDir();
+ const storePath = await join(dataDir, "screenpipe", "store.bin");
+ store = await createStore(storePath);
+ const entries = await store.entries();
+ console.log("store", entries);
+}
+
+async function checkSubscription(email: string): Promise<boolean> {
+ try {
+ const isDev = window.location.href.includes("localhost");
+ const baseUrl = isDev ? "http://localhost:3001" : "https://screenpi.pe";
+
+ const response = await fetch(`${baseUrl}/api/stripe-loom`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ ...(isDev ? {} : { credentials: "include" }),
+ body: JSON.stringify({ email }),
+ });
+
+ if (!response.ok) {
+ console.error("subscription check failed with status:", response.status);
+ return false;
+ }
+
+ const data = await response.json();
+ console.log("subscription data:", data);
+ return data.hasActiveSubscription;
+ } catch (error) {
+ console.error("failed to check subscription:", error);
+ return false;
+ }
+}
+
+export function useUser() {
+ const [user, setUser] = useState<UserData | null>(null);
+ const [isLoading, setIsLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ const loadUser = async () => {
+ if (!store) await initStore();
+
+ try {
+ const savedUser = await store!.get<UserData>("auth_data");
+ setUser(savedUser || null);
+ } catch (err) {
+ console.error("failed to load user:", err);
+ setError(err instanceof Error ? err.message : "failed to load user");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ loadUser();
+ }, []);
+
+ const checkLoomSubscription = useCallback(async () => {
+ if (!user?.email) return false;
+ return checkSubscription(user.email);
+ }, [user?.email]);
+
+ return {
+ user,
+ isSignedIn: !!user,
+ isLoading,
+ error,
+ checkLoomSubscription,
+ };
+}
diff --git a/screenpipe-app-tauri/package.json b/screenpipe-app-tauri/package.json
index 1577f195a..e2f899bad 100644
--- a/screenpipe-app-tauri/package.json
+++ b/screenpipe-app-tauri/package.json
@@ -11,7 +11,6 @@
},
"dependencies": {
"@ai-sdk/openai": "^0.0.39",
- "@clerk/clerk-react": "^5.17.1",
"@dnd-kit/core": "^6.1.0",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-zone": "^1.22.0",
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lock
index 2cddc4346..e37a5ef53 100755
--- a/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -4170,7 +4170,7 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "screenpipe-app"
-version = "0.14.15"
+version = "0.14.18"
dependencies = [
"anyhow",
"axum",
@@ -4185,6 +4185,7 @@ dependencies = [
"libc",
"log",
"objc",
+ "once_cell",
"reqwest",
"serde",
"serde_derive",
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index 0f6b19801..4c36998b1 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.14.18"
+version = "0.14.21"
description = ""
authors = ["you"]
license = ""
@@ -77,7 +77,6 @@ axum = "0.6.0" # or your current version
dirs = "5.0.1"
-once_cell = "1.19.0"
[target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dependencies]
diff --git a/screenpipe-app-tauri/src-tauri/src/commands.rs b/screenpipe-app-tauri/src-tauri/src/commands.rs
index 1ef71a7be..b16b7ced3 100644
--- a/screenpipe-app-tauri/src-tauri/src/commands.rs
+++ b/screenpipe-app-tauri/src-tauri/src/commands.rs
@@ -1,7 +1,8 @@
+use crate::get_data_dir;
+use serde::{Serialize};
use serde_json::Value;
use tauri::Manager;
use tracing::info;
-use crate::get_data_dir;
#[tauri::command]
pub fn set_tray_unhealth_icon(app_handle: tauri::AppHandle<tauri::Wry>) {
@@ -44,13 +45,15 @@ pub fn open_mic_preferences() {
}
#[tauri::command]
-pub async fn load_pipe_config(app_handle: tauri::AppHandle<tauri::Wry>, pipe_name: String) -> Result<Value, String> {
+pub async fn load_pipe_config(
+ app_handle: tauri::AppHandle<tauri::Wry>,
+ pipe_name: String,
+) -> Result<Value, String> {
info!("Loading pipe config for {}", pipe_name);
let default_path = get_data_dir(&app_handle)
.map(|path| path.join("pipes"))
.unwrap_or_else(|_| dirs::home_dir().unwrap().join(".screenpipe").join("pipes"));
-
let config_path = default_path.join(pipe_name).join("pipe.json");
info!("Config path: {}", config_path.to_string_lossy());
let config_content = tokio::fs::read_to_string(config_path)
@@ -62,7 +65,11 @@ pub async fn load_pipe_config(app_handle: tauri::AppHandle<tauri::Wry>, pipe_nam
}
#[tauri::command]
-pub async fn save_pipe_config(app_handle: tauri::AppHandle<tauri::Wry>, pipe_name: String, config: Value) -> Result<(), String> {
+pub async fn save_pipe_config(
+ app_handle: tauri::AppHandle<tauri::Wry>,
+ pipe_name: String,
+ config: Value,
+) -> Result<(), String> {
info!("Saving pipe config for {}", pipe_name);
let default_path = get_data_dir(&app_handle)
.map(|path| path.join("pipes"))
@@ -188,7 +195,9 @@ pub fn update_show_screenpipe_shortcut(
};
if !enabled {
- let _ = app_handle.global_shortcut().unregister(show_window_shortcut);
+ let _ = app_handle
+ .global_shortcut()
+ .unregister(show_window_shortcut);
return Ok(());
}
@@ -256,3 +265,48 @@ pub fn check_accessibility_permissions() -> bool {
return true;
}
}
+
+// Add these new structs
+#[derive(Debug, Serialize)]
+pub struct AuthStatus {
+ authenticated: bool,
+ message: Option<String>,
+}
+
+// Command to open the auth window
+#[tauri::command]
+pub async fn open_auth_window(app_handle: tauri::AppHandle<tauri::Wry>) -> Result<(), String> {
+ #[cfg(debug_assertions)]
+ let auth_url = "http://localhost:3001/login";
+ #[cfg(not(debug_assertions))]
+ let auth_url = "https://screenpi.pe/login";
+
+ // If window exists, try to close it and wait a bit
+ if let Some(existing_window) = app_handle.get_webview_window("auth") {
+ let _ = existing_window.destroy();
+ // Give it a moment to properly close
+ tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
+ }
+
+ let window = tauri::WebviewWindowBuilder::new(
+ &app_handle,
+ "auth",
+ tauri::WebviewUrl::External(auth_url.parse().unwrap()),
+ )
+ .title("screenpipe auth")
+ .center()
+ .build()
+ .map_err(|e| format!("failed to open auth window: {}", e))?;
+
+ // Add close event listener to cleanup the window
+ let window_handle = window.clone();
+ window.on_window_event(move |event| {
+ if let tauri::WindowEvent::Destroyed = event {
+ if let Some(w) = window_handle.get_webview_window("auth") {
+ let _ = w.close();
+ }
+ }
+ });
+
+ Ok(())
+}
diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rs
index 61246daed..4bd9fec7e 100755
--- a/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -43,15 +43,15 @@ mod llm_sidecar;
mod server;
mod sidecar;
mod updates;
+pub use commands::check_accessibility_permissions;
+pub use commands::open_accessibility_preferences;
pub use commands::open_screen_capture_preferences;
pub use commands::reset_all_pipes;
-pub use commands::set_tray_unhealth_icon;
pub use commands::set_tray_health_icon;
+pub use commands::set_tray_unhealth_icon;
pub use server::spawn_server;
pub use sidecar::kill_all_sreenpipes;
pub use sidecar::spawn_screenpipe;
-pub use commands::open_accessibility_preferences;
-pub use commands::check_accessibility_permissions;
pub struct SidecarState(Arc<tokio::sync::Mutex<Option<SidecarManager>>>);
@@ -140,7 +140,8 @@ async fn main() {
commands::show_timeline,
commands::open_accessibility_preferences,
commands::check_accessibility_permissions,
- icons::get_app_icon
+ icons::get_app_icon,
+ commands::open_auth_window,
])
.setup(|app| {
// Logging setup
@@ -154,18 +155,21 @@ async fn main() {
.filename_prefix("screenpipe-app")
.filename_suffix("log")
.max_log_files(5)
- .build(&get_data_dir(&app.handle()).unwrap_or_else(|_| dirs::home_dir().unwrap().join(".screenpipe")))?;
+ .build(
+ &get_data_dir(&app.handle())
+ .unwrap_or_else(|_| dirs::home_dir().unwrap().join(".screenpipe")),
+ )?;
// Create a custom layer for file logging
let file_layer = tracing_subscriber::fmt::layer()
.with_writer(file_appender)
.with_ansi(false)
- .with_filter(EnvFilter::new("info"));
+ .with_filter(EnvFilter::new("info,hyper=error,tower_http=error"));
// Create a custom layer for console logging
let console_layer = tracing_subscriber::fmt::layer()
.with_writer(std::io::stdout)
- .with_filter(EnvFilter::new("debug"));
+ .with_filter(EnvFilter::new("info,hyper=error,tower_http=error"));
// Initialize the tracing subscriber with both layers
tracing_subscriber::registry()
@@ -282,10 +286,8 @@ async fn main() {
}
_ => {}
});
-
}
-
// Store setup and analytics initialization
let store = StoreBuilder::new(app.handle(), path.clone()).build();
@@ -434,7 +436,7 @@ async fn main() {
})
.build(tauri::generate_context!())
.expect("error while building tauri application");
-
+
// set_tray_unhealth_icon(app.app_handle().clone());
app.run(|app_handle, event| match event {
tauri::RunEvent::Ready { .. } => {
diff --git a/screenpipe-app-tauri/src-tauri/src/server.rs b/screenpipe-app-tauri/src-tauri/src/server.rs
index febaa6717..04ce8fec0 100644
--- a/screenpipe-app-tauri/src-tauri/src/server.rs
+++ b/screenpipe-app-tauri/src-tauri/src/server.rs
@@ -7,13 +7,14 @@ use http::header::HeaderValue;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use tauri::Emitter;
+use tauri::Manager;
#[allow(unused_imports)]
use tauri_plugin_notification::NotificationExt;
+use tauri_plugin_store::StoreBuilder;
use tokio::sync::mpsc;
use tower_http::cors::{Any, CorsLayer};
use tower_http::trace::{DefaultMakeSpan, TraceLayer};
use tracing::{error, info};
-
#[derive(Clone, serde::Serialize, serde::Deserialize)]
struct LogEntry {
pipe_id: String,
@@ -56,6 +57,20 @@ struct InboxMessageAction {
port: u16,
}
+#[derive(Deserialize, Debug)]
+struct AuthPayload {
+ token: Option<String>,
+ email: Option<String>,
+ user_id: Option<String>,
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+struct AuthData {
+ token: String,
+ email: String,
+ user_id: String,
+}
+
pub async fn run_server(app_handle: tauri::AppHandle, port: u16) {
let state = ServerState { app_handle };
@@ -69,9 +84,13 @@ pub async fn run_server(app_handle: tauri::AppHandle, port: u16) {
.route("/notify", axum::routing::post(send_notification))
.route("/inbox", axum::routing::post(send_inbox_message))
.route("/log", axum::routing::post(log_message))
+ .route("/auth", axum::routing::post(handle_auth))
.layer(cors)
.layer(
- TraceLayer::new_for_http().make_span_with(DefaultMakeSpan::new().include_headers(true)),
+ TraceLayer::new_for_http()
+ .make_span_with(DefaultMakeSpan::new().level(tracing::Level::INFO))
+ .on_request(())
+ .on_response(()),
)
.with_state(state);
@@ -152,6 +171,53 @@ async fn log_message(
}
}
+async fn handle_auth(
+ State(state): State<ServerState>,
+ Json(payload): Json<AuthPayload>,
+) -> Result<Json<ApiResponse>, (StatusCode, String)> {
+ info!("received auth data: {:?}", payload);
+
+ let path = state
+ .app_handle
+ .path()
+ .local_data_dir()
+ .unwrap()
+ .join("screenpipe")
+ .join("store.bin");
+ info!("store path: {:?}", path);
+ let store = StoreBuilder::new(&state.app_handle, path).build();
+
+ if payload.token.is_some() {
+ let auth_data = AuthData {
+ token: payload.token.unwrap(),
+ email: payload.email.unwrap_or_default(),
+ user_id: payload.user_id.unwrap_or_default(),
+ };
+
+ info!("saving auth data: {:?}", auth_data);
+
+ store.set("auth_data", serde_json::to_value(Some(auth_data)).unwrap());
+ } else {
+ store.set(
+ "auth_data",
+ serde_json::to_value::<Option<AuthData>>(None).unwrap(),
+ );
+ }
+
+ if let Err(e) = store.save() {
+ error!("failed to save store: {}", e);
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to save auth data".to_string(),
+ ));
+ }
+
+ Ok(Json(ApiResponse {
+ success: true,
+ message: "auth data stored successfully".to_string(),
+ }))
+}
+
pub fn spawn_server(app_handle: tauri::AppHandle, port: u16) -> mpsc::Sender<()> {
let (tx, mut rx) = mpsc::channel(1);