Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ NEXTAUTH_SECRET=

# Audio transcription
# DEEPGRAM_API_KEY=
# Cap AI
# OPENAI_API_KEY=

# Only needed by cap.so cloud
# NEXT_LOOPS_KEY=
Expand Down
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions apps/desktop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"@tauri-apps/plugin-deep-link": "^2.2.0",
"@tauri-apps/plugin-dialog": "2.0.1",
"@tauri-apps/plugin-fs": "2.2.0",
"@tauri-apps/plugin-http": "^2.0.1",
"@tauri-apps/plugin-http": "^2.4.4",
"@tauri-apps/plugin-notification": "2.0.0",
"@tauri-apps/plugin-opener": "^2.2.6",
"@tauri-apps/plugin-os": "2.0.0",
Expand All @@ -64,7 +64,8 @@
"unplugin-icons": "^0.19.2",
"uuid": "^9.0.1",
"vinxi": "^0.5.6",
"webcodecs": "^0.1.0"
"webcodecs": "^0.1.0",
"zod": "^3.24.2"
},
"devDependencies": {
"@fontsource/geist-sans": "^5.0.3",
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "cap-desktop"
version = "0.3.46"
version = "0.3.48"
description = "Beautiful screen recordings, owned by you."
authors = ["you"]
edition = "2021"
Expand Down
16 changes: 8 additions & 8 deletions apps/desktop/src-tauri/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,19 @@ use crate::web_api;

#[derive(Serialize, Deserialize, Type, Debug)]
pub struct AuthStore {
pub token: String,
pub secret: AuthSecret,
pub user_id: Option<String>,
pub expires: i32,
pub plan: Option<Plan>,
pub intercom_hash: Option<String>,
}

#[derive(Serialize, Deserialize, Type, Debug)]
#[serde(untagged)]
pub enum AuthSecret {
ApiKey { api_key: String },
Session { token: String, expires: i32 },
}

#[derive(Serialize, Deserialize, Type, Debug)]
pub struct Plan {
pub upgraded: bool,
Expand Down Expand Up @@ -108,12 +114,6 @@ impl AuthStore {
return Err("Store not found".to_string());
};

let value = value.map(|mut auth| {
// Set expiration to 100 years in the future
auth.expires = (chrono::Utc::now() + chrono::Duration::days(36500)).timestamp() as i32;
auth
});

store.set("auth", json!(value));
store.save().map_err(|e| e.to_string())
}
Expand Down
6 changes: 2 additions & 4 deletions apps/desktop/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1715,7 +1715,7 @@ async fn check_upgraded_and_update(app: AppHandle) -> Result<bool, String> {
}
}

let Ok(Some(mut auth)) = AuthStore::get(&app) else {
let Ok(Some(auth)) = AuthStore::get(&app) else {
println!("No auth found, clearing auth store");
AuthStore::set(&app, None).map_err(|e| e.to_string())?;
return Ok(false);
Expand All @@ -1732,7 +1732,6 @@ async fn check_upgraded_and_update(app: AppHandle) -> Result<bool, String> {
"Fetching plan for user {}",
auth.user_id.as_deref().unwrap_or("unknown")
);
let plan_url = app.make_app_url("/api/desktop/plan");
let response = app
.authed_api_request("/api/desktop/plan", |client, url| client.get(url))
.await
Expand All @@ -1759,9 +1758,8 @@ async fn check_upgraded_and_update(app: AppHandle) -> Result<bool, String> {
.unwrap_or(false);
println!("Pro status: {}", is_pro);
let updated_auth = AuthStore {
token: auth.token,
secret: auth.secret,
user_id: auth.user_id,
expires: auth.expires,
intercom_hash: auth.intercom_hash,
plan: Some(Plan {
upgraded: is_pro,
Expand Down
6 changes: 5 additions & 1 deletion apps/desktop/src-tauri/src/presets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use serde_json::json;
use specta::Type;
use tauri::{AppHandle, Wry};
use tauri_plugin_store::StoreExt;
use tracing::error;

#[derive(Serialize, Deserialize, Type, Debug, Default)]
#[serde(rename_all = "camelCase")]
Expand All @@ -26,7 +27,10 @@ impl PresetsStore {
// Handle potential deserialization errors gracefully
match serde_json::from_value(store) {
Ok(settings) => Ok(Some(settings)),
Err(_) => Err("Failed to deserialize presets store".to_string()),
Err(_) => {
error!("Failed to deserialize presets store");
Ok(None)
}
}
}
_ => Ok(None),
Expand Down
15 changes: 12 additions & 3 deletions apps/desktop/src-tauri/src/web_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use tauri::{Emitter, Manager, Runtime};
use tauri_specta::Event;

use crate::{
auth::{AuthStore, AuthenticationInvalid},
ArcLock, MutableState,
auth::{AuthSecret, AuthStore, AuthenticationInvalid},
ArcLock,
};

async fn do_authed_request(
Expand All @@ -14,7 +14,16 @@ async fn do_authed_request(
) -> Result<reqwest::Response, reqwest::Error> {
let client = reqwest::Client::new();

let mut req = build(client, url).header("Authorization", format!("Bearer {}", auth.token));
let mut req = build(client, url).header(
"Authorization",
format!(
"Bearer {}",
match &auth.secret {
AuthSecret::ApiKey { api_key } => api_key,
AuthSecret::Session { token, .. } => token,
}
),
);

if let Some(s) = std::option_env!("VITE_VERCEL_AUTOMATION_BYPASS_SECRET") {
req = req.header("x-vercel-protection-bypass", s);
Expand Down
140 changes: 3 additions & 137 deletions apps/desktop/src/components/SignInButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { onOpenUrl } from "@tauri-apps/plugin-deep-link";
import * as shell from "@tauri-apps/plugin-shell";
import { z } from "zod";

import { getCurrentWindow } from "@tauri-apps/api/window";
import { ComponentProps } from "solid-js";
Expand All @@ -12,27 +13,12 @@ import { identifyUser, trackEvent } from "~/utils/analytics";
import { clientEnv } from "~/utils/env";
import { commands } from "~/utils/tauri";
import callbackTemplate from "./callback.template";
import { createSignInMutation } from "~/utils/auth";

export function SignInButton(
props: Omit<ComponentProps<typeof Button>, "onClick">
) {
const signIn = createMutation(() => ({
mutationFn: async (abort: AbortController) => {
const platform = import.meta.env.DEV ? "web" : "desktop";

let session;

if (platform === "web")
session = await createLocalServerSession(abort.signal);
else session = await createDeepLinkSession(abort.signal);

await shell.open(session.url.toString());

await processAuthData(await session.complete());

getCurrentWindow().setFocus();
},
}));
const signIn = createSignInMutation();

return (
<Button
Expand All @@ -53,123 +39,3 @@ export function SignInButton(
</Button>
);
}

async function createSessionRequestUrl(
port: string | null,
platform: "web" | "desktop"
) {
const serverUrl =
(await generalSettingsStore.get())?.serverUrl ?? "https://cap.so";
const callbackUrl = new URL(`/api/desktop/session/request`, serverUrl);

if (port !== null) callbackUrl.searchParams.set("port", port);
callbackUrl.searchParams.set("platform", platform);

return callbackUrl;
}

type AuthData = { token: string; user_id: string; expires: number };

async function createLocalServerSession(signal: AbortSignal) {
await invoke("plugin:oauth|stop").catch(() => {});

const port: string = await invoke("plugin:oauth|start", {
config: {
response: callbackTemplate,
headers: {
"Content-Type": "text/html; charset=utf-8",
"Cache-Control": "no-store, no-cache, must-revalidate",
Pragma: "no-cache",
},
// Add a cleanup function to stop the server after handling the request
cleanup: true,
},
});

signal.onabort = () => {
invoke("plugin:oauth|stop").catch(() => {});
};

let res: (url: URL) => void;
const stopListening = await listen(
"oauth://url",
(data: { payload: string }) => {
if (!data.payload.includes("token")) {
return;
}

const urlObject = new URL(data.payload);
res(urlObject);
}
);

return {
url: await createSessionRequestUrl(port, "web"),
complete: async () => {
const url = await new Promise<URL>((r) => {
res = r;
});

stopListening();

if (signal.aborted) throw new Error("Sign in aborted");

const token = url.searchParams.get("token");
const user_id = url.searchParams.get("user_id");
const expires = Number(url.searchParams.get("expires"));
if (!token || !expires || !user_id)
throw new Error("Invalid token or expires");

return { token, user_id, expires };
},
};
}

async function createDeepLinkSession(signal: AbortSignal) {
let res: (data: AuthData) => void;
const p = new Promise<AuthData>((r) => {
res = r;
});
const stopListening = await onOpenUrl(async (urls) => {
for (const url of urls) {
if (!url.includes("token=")) return;
if (signal.aborted) return;

const urlObject = new URL(url);
const token = urlObject.searchParams.get("token");
const user_id = urlObject.searchParams.get("user_id");
const expires = Number(urlObject.searchParams.get("expires"));

if (!token || !expires || !user_id) {
throw new Error("Invalid signin params");
}

res({ token, user_id, expires });
}
});

signal.onabort = () => {
stopListening();
};

return {
url: await createSessionRequestUrl(null, "desktop"),
complete: () => p,
};
}

async function processAuthData({ token, user_id, expires }: AuthData) {
identifyUser(user_id);
trackEvent("user_signed_in", { platform: "desktop" });

const existingAuth = await authStore.get();
await authStore.set({
token,
user_id,
intercom_hash: existingAuth?.intercom_hash ?? "",
expires,
plan: null,
});

await commands.updateAuthPlan();
}
26 changes: 14 additions & 12 deletions apps/desktop/src/components/Toggle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,34 +9,36 @@ const toggleControlStyles = cva(
size: {
sm: "w-9 h-[1.25rem] p-[0.125rem]",
md: "w-11 h-[1.5rem] p-[0.125rem]",
lg: "w-14 h-[1.75rem] p-[0.1875rem]"
}
lg: "w-14 h-[1.75rem] p-[0.1875rem]",
},
},
defaultVariants: {
size: "md"
}
size: "md",
},
}
);

const toggleThumbStyles = cva(
"ui-checked:bg-solid-white bg-gray-10 rounded-full transition-transform ui-checked:translate-x-[calc(100%)]",
"bg-white rounded-full transition-transform ui-checked:translate-x-[calc(100%)]",
{
variants: {
size: {
sm: "size-[1rem]",
md: "size-[1.25rem]",
lg: "size-[1.5rem]"
}
lg: "size-[1.5rem]",
},
},
defaultVariants: {
size: "md"
}
size: "md",
},
}
);

export function Toggle(props: ComponentProps<typeof KSwitch> & { size?: 'sm' | 'md' | 'lg' }) {
const [local, others] = splitProps(props, ['size']);

export function Toggle(
props: ComponentProps<typeof KSwitch> & { size?: "sm" | "md" | "lg" }
) {
const [local, others] = splitProps(props, ["size"]);

return (
<KSwitch {...others}>
<KSwitch.Input class="peer" />
Expand Down
Loading