Open source CapCut alternative.
TypeScript
Use Better Auth cookies for Mac sessions
David Le98bf476ab738
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift b/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swiftindex c9e1a8ff..520500c2 100644--- a/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyAuthCoordinator.swift@@ -5,12 +5,16 @@ struct DonkeyAuthSession: Codable, Equatable {var id: Stringvar provider: Stringvar authenticatedAt: Date+ var remoteSessionID: String? = nil+ var userEmail: String? = nil+ var userName: String? = nil}enum DonkeyAuthPhase: Equatable {case signedOutcase openingBrowsercase waitingForCallback+ case exchangingSessioncase signedIn(DonkeyAuthSession)case failed(String)@@ -91,13 +95,16 @@ final class DonkeyAuthCoordinator: ObservableObject {private let configuration: DonkeyAuthConfigurationprivate let stateStore: DonkeyAuthStateStoring+ private let nativeSessionExchanger: any DonkeyNativeSessionExchanginginit(configuration: DonkeyAuthConfiguration = .current(),- stateStore: DonkeyAuthStateStoring = DonkeyAuthStateStore()+ stateStore: DonkeyAuthStateStoring = DonkeyAuthStateStore(),+ nativeSessionExchanger: any DonkeyNativeSessionExchanging = DonkeyNativeSessionCookieExchanger()) {self.configuration = configurationself.stateStore = stateStore+ self.nativeSessionExchanger = nativeSessionExchangerif let session = stateStore.loadSession() {phase = .signedIn(session)@@ -113,8 +120,7 @@ final class DonkeyAuthCoordinator: ObservableObject {func beginGoogleSignIn() {let state = Self.makeStateToken()- guard let callbackURL = callbackURL(state: state),- let signInURL = signInURL(callbackURL: callbackURL) else {+ guard let signInURL = signInURL(state: state) else {phase = .failed("Sign-in could not be configured.")return}@@ -152,15 +158,49 @@ final class DonkeyAuthCoordinator: ObservableObject {return true}+ guard let code = Self.queryValue(named: "code", in: queryItems),+ !code.isEmpty else {+ phase = .failed("Google sign-in did not return a Mac session code.")+ return true+ }++ phase = .exchangingSession+ exchangeNativeSession(code: code)+ return true+ }++ private func exchangeNativeSession(code: String) {+ let webBaseURL = configuration.webBaseURL+ let nativeSessionExchanger = nativeSessionExchanger+ Task { [weak self] in+ do {+ let nativeSession = try await nativeSessionExchanger.exchange(+ code: code,+ webBaseURL: webBaseURL+ )+ await MainActor.run {+ self?.completeNativeSessionExchange(nativeSession)+ }+ } catch {+ await MainActor.run {+ self?.phase = .failed("Mac session could not be created. Please try again.")+ }+ }+ }+ }++ private func completeNativeSessionExchange(_ nativeSession: DonkeyNativeCookieSession) {let session = DonkeyAuthSession(- id: UUID().uuidString,+ id: nativeSession.sessionID,provider: "google",- authenticatedAt: Date()+ authenticatedAt: Date(),+ remoteSessionID: nativeSession.sessionID,+ userEmail: nativeSession.userEmail,+ userName: nativeSession.userName)stateStore.saveSession(session)phase = .signedIn(session)authenticationCompleted?(session)- return true}func clearFailedState() {@@ -168,18 +208,7 @@ final class DonkeyAuthCoordinator: ObservableObject {phase = stateStore.loadSession().map(DonkeyAuthPhase.signedIn) ?? .signedOut}- private func callbackURL(state: String) -> URL? {- var components = URLComponents()- components.scheme = configuration.callbackScheme- components.host = "auth"- components.path = "/callback"- components.queryItems = [- URLQueryItem(name: "state", value: state)- ]- return components.url- }-- private func signInURL(callbackURL: URL) -> URL? {+ private func signInURL(state: String) -> URL? {var components = URLComponents(url: configuration.webBaseURL,resolvingAgainstBaseURL: false@@ -189,8 +218,7 @@ final class DonkeyAuthCoordinator: ObservableObject {.filter { !$0.isEmpty }.joined(separator: "/")components?.queryItems = [- URLQueryItem(name: "callbackURL", value: callbackURL.absoluteString),- URLQueryItem(name: "errorCallbackURL", value: callbackURL.absoluteString)+ URLQueryItem(name: "state", value: state)]return components?.url}diff --git a/apps/Donkey/Sources/Donkey/DonkeyLoginWindowController.swift b/apps/Donkey/Sources/Donkey/DonkeyLoginWindowController.swiftindex 64801848..53b6f42e 100644--- a/apps/Donkey/Sources/Donkey/DonkeyLoginWindowController.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyLoginWindowController.swift@@ -103,6 +103,8 @@ private struct DonkeyLoginView: View {return "Opening Google..."case .waitingForCallback:return "Waiting for Google..."+ case .exchangingSession:+ return "Signing in..."default:return "Continue with Google"}@@ -110,7 +112,7 @@ private struct DonkeyLoginView: View {private var buttonIsDisabled: Bool {switch authCoordinator.phase {- case .openingBrowser, .waitingForCallback:+ case .openingBrowser, .waitingForCallback, .exchangingSession:return truedefault:return false@@ -122,6 +124,8 @@ private struct DonkeyLoginView: View {switch authCoordinator.phase {case .waitingForCallback:Text("Finish sign-in in your browser to continue.")+ case .exchangingSession:+ Text("Creating a secure Mac session...")case .failed(let message):Text(message)default:diff --git a/apps/Donkey/Sources/Donkey/DonkeyNativeSessionCookieExchanger.swift b/apps/Donkey/Sources/Donkey/DonkeyNativeSessionCookieExchanger.swiftnew file mode 100644index 00000000..81b24d72--- /dev/null+++ b/apps/Donkey/Sources/Donkey/DonkeyNativeSessionCookieExchanger.swift@@ -0,0 +1,128 @@+import Foundation++struct DonkeyNativeCookieSession: Equatable, Sendable {+ var sessionID: String+ var userEmail: String?+ var userName: String?+}++enum DonkeyNativeSessionCookieExchangeError: Error, Equatable {+ case invalidURL+ case invalidResponse+ case httpStatus(Int, String)+ case missingSessionCookie+}++protocol DonkeyNativeSessionExchanging: Sendable {+ func exchange(+ code: String,+ webBaseURL: URL+ ) async throws -> DonkeyNativeCookieSession+}++struct DonkeyNativeSessionCookieExchanger: DonkeyNativeSessionExchanging {+ var urlSession: URLSession+ var cookieStorage: HTTPCookieStorage++ init(+ urlSession: URLSession = .shared,+ cookieStorage: HTTPCookieStorage = .shared+ ) {+ self.urlSession = urlSession+ self.cookieStorage = cookieStorage+ }++ func exchange(+ code: String,+ webBaseURL: URL+ ) async throws -> DonkeyNativeCookieSession {+ guard let url = exchangeURL(webBaseURL: webBaseURL) else {+ throw DonkeyNativeSessionCookieExchangeError.invalidURL+ }++ var request = URLRequest(url: url)+ request.httpMethod = "POST"+ request.httpShouldHandleCookies = true+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ request.httpBody = try JSONEncoder().encode(VerifyOneTimeTokenRequest(token: code))++ let (data, response) = try await urlSession.data(for: request)+ guard let httpResponse = response as? HTTPURLResponse else {+ throw DonkeyNativeSessionCookieExchangeError.invalidResponse+ }++ guard (200..<300).contains(httpResponse.statusCode) else {+ throw DonkeyNativeSessionCookieExchangeError.httpStatus(+ httpResponse.statusCode,+ String(data: data, encoding: .utf8) ?? HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode)+ )+ }++ storeCookies(from: httpResponse, for: url)+ guard hasStoredSessionCookie(for: webBaseURL) else {+ throw DonkeyNativeSessionCookieExchangeError.missingSessionCookie+ }++ return try JSONDecoder().decode(VerifyOneTimeTokenResponse.self, from: data).nativeSession+ }++ private func exchangeURL(webBaseURL: URL) -> URL? {+ var components = URLComponents(+ url: webBaseURL,+ resolvingAgainstBaseURL: false+ )+ let basePath = components?.path.trimmingCharacters(in: CharacterSet(charactersIn: "/")) ?? ""+ components?.path = "/" + [basePath, "api/auth/one-time-token/verify"]+ .filter { !$0.isEmpty }+ .joined(separator: "/")+ components?.query = nil+ components?.fragment = nil+ return components?.url+ }++ private func storeCookies(+ from response: HTTPURLResponse,+ for url: URL+ ) {+ let headerFields = response.allHeaderFields.reduce(into: [String: String]()) { result, pair in+ guard let key = pair.key as? String else { return }+ result[key] = String(describing: pair.value)+ }+ let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url)+ for cookie in cookies {+ cookieStorage.setCookie(cookie)+ }+ }++ private func hasStoredSessionCookie(for webBaseURL: URL) -> Bool {+ cookieStorage.cookies(for: webBaseURL)?.contains { cookie in+ cookie.name.contains("session_token")+ } ?? false+ }+}++private struct VerifyOneTimeTokenRequest: Encodable {+ var token: String+}++private struct VerifyOneTimeTokenResponse: Decodable {+ var session: Session+ var user: User++ var nativeSession: DonkeyNativeCookieSession {+ DonkeyNativeCookieSession(+ sessionID: session.id,+ userEmail: user.email,+ userName: user.name+ )+ }++ struct Session: Decodable {+ var id: String+ }++ struct User: Decodable {+ var email: String?+ var name: String?+ }+}diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.mdindex f8d4c452..81066380 100644--- a/docs/guides/backend-apis.md+++ b/docs/guides/backend-apis.md@@ -13,6 +13,10 @@ Backend APIs live in `site/src/app/api/**/route.ts`.- Keep the Mac app callback origin (`donkey://` by default) in Better Authtrusted origins so `/mac-auth` can return successful Google sign-in to theapp.+- Mac app sign-in uses Better Auth's one-time-token plugin. `/mac-auth/callback`+ mints a short-lived code from the browser session, then the app exchanges it+ at `/api/auth/one-time-token/verify` so `URLSession` stores the resulting+ Better Auth cookie in the app-owned cookie jar.- In Vercel, configure `BETTER_AUTH_URL`, `BETTER_AUTH_SECRET`,`GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, and`DONKEY_MAC_AUTH_REDIRECT_ORIGINS`. Do not commit real OAuth credentials.diff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.mdindex 9d0f08ef..5881b90d 100644--- a/docs/guides/pointer-prompt-overlay.md+++ b/docs/guides/pointer-prompt-overlay.md@@ -7,8 +7,8 @@ quick local-app actions:- On first launch, Donkey shows a Google-only Mac sign-in window before startingthe overlay. Until the browser returns through the `donkey://auth/callback`- handoff, the notch surface is not shown and double-Command activation is not- registered.+ handoff and the app exchanges the returned code for a Better Auth cookie, the+ notch surface is not shown and double-Command activation is not registered.- Double-tap Command and release to open a centered prompt with keyboard focus.- Double-tap Command and hold the second press to open the prompt in voice mode.- Show a top-center notch status surface for task progress, recent tasks, follow-up input, file drops, updates, and per-task pause/resume.@@ -30,7 +30,8 @@ quick local-app actions:- `PointerPromptOverlayController` owns AppKit surfaces, placement, hover tracking, focus, keyboard shortcut recognition, dismissal, file-drop routing, and microphone level capture.- `DonkeyAuthCoordinator` and `DonkeyLoginWindowController` own the Mac sign-ingate. App startup should create the overlay controller only after a stored- Google session exists or a pending sign-in callback validates its state token.+ Google session exists or a pending sign-in callback validates its state token+ and stores a Better Auth cookie in the app cookie jar.- SwiftUI rendering lives in `DonkeyUI` and consumes state/contracts from `DonkeyContracts`. It should not perform command parsing, model calls, input execution, screen capture, or microphone capture.- `PointerPromptOverlayModel` owns product state. Durable task data is persisted through Core Data in Application Support.- Spawn display state is typed state. The model emits progress, target hints, and current selection; the overlay controller resolves hints against safe visible windows and keeps voice capture on the centered prompt; SwiftUI renders the notch cue, cursors, labels, label-to-editor transition, and selection state.diff --git a/site/.env.example b/site/.env.exampleindex 3a94007d..6c4a39d1 100644--- a/site/.env.example+++ b/site/.env.example@@ -1,8 +1,8 @@DATABASE_URL="postgresql://postgres:[PASSWORD]@[PROJECT-REF].pooler.supabase.com:6543/postgres?pgbouncer=true&connection_limit=1"DIRECT_URL="postgresql://postgres:[PASSWORD]@db.[PROJECT-REF].supabase.co:5432/postgres"-DONKEY_API_TOKEN="replace-with-a-long-random-token"BETTER_AUTH_URL="http://localhost:3000"BETTER_AUTH_SECRET="replace-with-a-long-random-secret"GOOGLE_CLIENT_ID="replace-with-google-web-client-id"GOOGLE_CLIENT_SECRET="replace-with-google-web-client-secret"DONKEY_MAC_AUTH_REDIRECT_ORIGINS="donkey://"+DONKEY_MAC_AUTH_CALLBACK_SCHEME="donkey"diff --git a/site/src/app/mac-auth/MacAuthRedirector.tsx b/site/src/app/mac-auth/MacAuthRedirector.tsxindex 2560b0c0..d5ceea1b 100644--- a/site/src/app/mac-auth/MacAuthRedirector.tsx+++ b/site/src/app/mac-auth/MacAuthRedirector.tsx@@ -6,34 +6,35 @@ import { useCallback, useEffect, useRef, useState } from "react";import { authClient } from "@/lib/auth-client";type Props = {- callbackURL: string | null;- errorCallbackURL: string | null;+ state: string | null;};-type RedirectStatus = "opening" | "failed" | "missing-callback";+type RedirectStatus = "opening" | "failed" | "missing-state";-export function MacAuthRedirector({ callbackURL, errorCallbackURL }: Props) {+export function MacAuthRedirector({ state }: Props) {const [status, setStatus] = useState<RedirectStatus>("opening");const hasStartedRef = useRef(false);const startGoogleAuth = useCallback(async () => {- if (!callbackURL) {- setStatus("missing-callback");+ if (!state) {+ setStatus("missing-state");return;}setStatus("opening");+ const encodedState = encodeURIComponent(state);+ const callbackURL = `/mac-auth/callback?state=${encodedState}`;try {await authClient.signIn.social({callbackURL,- errorCallbackURL: errorCallbackURL ?? callbackURL,+ errorCallbackURL: `${callbackURL}&error=oauth`,provider: "google",});} catch {setStatus("failed");}- }, [callbackURL, errorCallbackURL]);+ }, [state]);useEffect(() => {if (hasStartedRef.current) {@@ -160,8 +161,8 @@ function messageForStatus(status: RedirectStatus) {switch (status) {case "failed":return "Google sign-in could not start in this browser.";- case "missing-callback":- return "The Mac app callback was missing from this sign-in request.";+ case "missing-state":+ return "The Mac app state token was missing from this sign-in request.";case "opening":return "Use your Google account, then Donkey will bring you back to the Mac app.";}diff --git a/site/src/app/mac-auth/callback/route.ts b/site/src/app/mac-auth/callback/route.tsnew file mode 100644index 00000000..e0b7c838--- /dev/null+++ b/site/src/app/mac-auth/callback/route.ts@@ -0,0 +1,79 @@+import { NextRequest, NextResponse } from "next/server";+import { z } from "zod";++import { auth } from "@/lib/auth";++export const dynamic = "force-dynamic";++const callbackSearchParamsSchema = z.object({+ error: z.string().optional(),+ state: z.string().min(1),+});++/**+ * GET /mac-auth/callback+ *+ * Browser landing point after Better Auth completes Google OAuth for the Mac app.+ * It mints a short-lived one-time token from the browser session, then deep-links+ * that code back to the native app for cookie-jar exchange.+ */+export async function GET(request: NextRequest) {+ const parsedParams = callbackSearchParamsSchema.safeParse(+ Object.fromEntries(request.nextUrl.searchParams),+ );+ if (!parsedParams.success) {+ return NextResponse.json(+ {+ error: "Invalid callback",+ message: "Missing Mac app state token.",+ },+ { status: 400 },+ );+ }++ const { error, state } = parsedParams.data;+ if (error) {+ return redirectToMac(macCallbackURL(state, { error }));+ }++ try {+ const token = await auth.api.generateOneTimeToken({+ headers: request.headers,+ });++ return redirectToMac(macCallbackURL(state, { code: token.token }));+ } catch {+ return redirectToMac(macCallbackURL(state, { error: "session" }));+ }+}++function redirectToMac(url: URL) {+ return new NextResponse(null, {+ status: 302,+ headers: {+ Location: url.toString(),+ },+ });+}++function macCallbackURL(+ state: string,+ query: {+ code?: string;+ error?: string;+ },+) {+ const callbackScheme = process.env.DONKEY_MAC_AUTH_CALLBACK_SCHEME ?? "donkey";+ const url = new URL(`${callbackScheme}://auth/callback`);+ url.searchParams.set("state", state);++ if (query.code) {+ url.searchParams.set("code", query.code);+ }++ if (query.error) {+ url.searchParams.set("error", query.error);+ }++ return url;+}diff --git a/site/src/app/mac-auth/page.tsx b/site/src/app/mac-auth/page.tsxindex dfeb5897..459cb643 100644--- a/site/src/app/mac-auth/page.tsx+++ b/site/src/app/mac-auth/page.tsx@@ -18,8 +18,7 @@ export default async function Page({ searchParams }: Props) {return (<MacAuthRedirector- callbackURL={firstParam(params.callbackURL)}- errorCallbackURL={firstParam(params.errorCallbackURL)}+ state={firstParam(params.state)}/>);}diff --git a/site/src/lib/auth.ts b/site/src/lib/auth.tsindex 06fbf694..40da795f 100644--- a/site/src/lib/auth.ts+++ b/site/src/lib/auth.ts@@ -1,5 +1,6 @@import { betterAuth } from "better-auth";import { prismaAdapter } from "better-auth/adapters/prisma";+import { oneTimeToken } from "better-auth/plugins";import { prisma } from "@/lib/prisma";@@ -30,4 +31,10 @@ export const auth = betterAuth({clientSecret: process.env.GOOGLE_CLIENT_SECRET ?? "",},},+ plugins: [+ oneTimeToken({+ expiresIn: 3,+ storeToken: "hashed",+ }),+ ],});diff --git a/site/src/lib/donkey-api-auth.ts b/site/src/lib/donkey-api-auth.tsindex bb6984b5..99f8249e 100644--- a/site/src/lib/donkey-api-auth.ts+++ b/site/src/lib/donkey-api-auth.ts@@ -1,9 +1,13 @@import { type NextRequest, NextResponse } from "next/server";+import { auth } from "@/lib/auth";+export type DonkeyAuthContext = {platform: "api";app: "donkey";+ method: "session-cookie";clientId: string | null;+ userId: string;};export type DonkeyAuthenticatedRequest = NextRequest & {@@ -13,39 +17,17 @@ export type DonkeyAuthenticatedRequest = NextRequest & {export type DonkeyAuthHandler<TReq extends DonkeyAuthenticatedRequest = DonkeyAuthenticatedRequest,TArgs extends unknown[] = [],-> = (request: TReq, ...args: TArgs) => Promise<NextResponse> | NextResponse;+> = (request: TReq, ...args: TArgs) => Promise<Response> | Response;-const apiTokenEnvName = "DONKEY_API_TOKEN";-const apiKeyHeader = "x-donkey-api-key";const clientIdHeader = "x-donkey-client-id";-function getConfiguredApiToken() {- const token = process.env[apiTokenEnvName]?.trim();-- return token ? token : null;-}--function getRequestApiToken(headers: Headers) {- const authorizationHeader = headers.get("authorization")?.trim();-- if (authorizationHeader) {- const bearerMatch = authorizationHeader.match(/^Bearer\s+(.+)$/i);-- if (bearerMatch?.[1]) {- return bearerMatch[1].trim();- }- }-- const apiKey = headers.get(apiKeyHeader)?.trim();-- return apiKey ? apiKey : null;-}--export function getDonkeyAuthContext(headers: Headers): DonkeyAuthContext | null {- const configuredToken = getConfiguredApiToken();- const requestToken = getRequestApiToken(headers);-- if (!configuredToken || requestToken !== configuredToken) {+export async function getDonkeyAuthContext(+ headers: Headers,+): Promise<DonkeyAuthContext | null> {+ const session = await auth.api.getSession({+ headers,+ });+ if (!session) {return null;}@@ -54,7 +36,9 @@ export function getDonkeyAuthContext(headers: Headers): DonkeyAuthContext | nullreturn {platform: "api",app: "donkey",+ method: "session-cookie",clientId: clientId ? clientId : null,+ userId: session.user.id,};}@@ -62,8 +46,8 @@ export function withDonkeyAuth<TReq extends DonkeyAuthenticatedRequest = DonkeyAuthenticatedRequest,TArgs extends unknown[] = [],>(handler: DonkeyAuthHandler<TReq, TArgs>) {- return (request: NextRequest, ...args: TArgs) => {- const authContext = getDonkeyAuthContext(request.headers);+ return async (request: NextRequest, ...args: TArgs) => {+ const authContext = await getDonkeyAuthContext(request.headers);if (!authContext) {return NextResponse.json(@@ -73,9 +57,6 @@ export function withDonkeyAuth<},{status: 401,- headers: {- "WWW-Authenticate": "Bearer",- },},);}