Open source CapCut alternative.
TypeScript
Fix Mac auth handoff dev flow
David Lec9b91bc2f723
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.mdindex 2a1c669c..a6c22cc4 100644--- a/docs/guides/backend-apis.md+++ b/docs/guides/backend-apis.md@@ -14,9 +14,11 @@ Backend APIs live in `site/src/app/api/**/route.ts`.trusted 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.+ mints a short-lived code from the browser session, renders a browser handoff+ page that opens `donkey://auth/callback`, then the app exchanges the code at+ `/api/auth/one-time-token/verify` so `URLSession` stores the resulting Better+ Auth cookie in the app-owned cookie jar. The code should remain short-lived+ while still allowing a manual "Open Donkey" fallback click.- 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/install-donkey.md b/docs/guides/install-donkey.mdindex 3a275924..2bc97eaf 100644--- a/docs/guides/install-donkey.md+++ b/docs/guides/install-donkey.md@@ -112,12 +112,19 @@ hosted-model install path.## Local Development-For local development, `scripts/run-donkey-dev.sh` builds and launches the debug app:+For local development, `scripts/run-donkey-dev.sh` starts the local site when+`DONKEY_WEB_BASE_URL` points at localhost, builds Donkey, wraps the debug+executable in `apps/Donkey/.build/debug/Donkey.app`, registers that app bundle+for `donkey://auth/callback`, and launches it:```bash./scripts/run-donkey-dev.sh```+Use `DONKEY_START_SITE=0` to skip starting the site, `DONKEY_LAUNCH_APP=0` to+build and register the debug app without opening it, or `DONKEY_WEB_BASE_URL` /+`DONKEY_AUTH_CALLBACK_SCHEME` to test a different auth handoff.+Development builds use the same hosted-model boundary as packaged builds. If adeveloper needs to test provider behavior, configure the site/backendenvironment and keep provider credentials out of the Mac app.diff --git a/scripts/run-donkey-dev.sh b/scripts/run-donkey-dev.shindex f2cdc4e1..7dae0f9f 100755--- a/scripts/run-donkey-dev.sh+++ b/scripts/run-donkey-dev.sh@@ -4,7 +4,24 @@ set -euo pipefailROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"APP_DIR="$ROOT_DIR/apps/Donkey"LOG_SCRIPT="$ROOT_DIR/scripts/tail-donkey-logs.sh"-DONKEY_BIN="$APP_DIR/.build/debug/Donkey"+BUILD_PRODUCTS_DIR="$APP_DIR/.build/debug"+DONKEY_BIN="$BUILD_PRODUCTS_DIR/Donkey"+DEV_APP_DIR="$BUILD_PRODUCTS_DIR/Donkey.app"+CACHE_DIR="$APP_DIR/.build/dev-script-cache"+CACHE_CLANG_DIR="$CACHE_DIR/clang"+CACHE_SWIFTPM_DIR="$CACHE_DIR/swiftpm"+CACHE_HOME_DIR="$CACHE_DIR/home"+CONTENTS_DIR="$DEV_APP_DIR/Contents"+MACOS_DIR="$CONTENTS_DIR/MacOS"+RESOURCES_DIR="$CONTENTS_DIR/Resources"+FRAMEWORKS_DIR="$CONTENTS_DIR/Frameworks"+APP_ICON_SOURCE="$APP_DIR/Sources/Donkey/Resources/Donkey.icns"+APP_ICONSET_SOURCE="$APP_DIR/Sources/Donkey/Resources/Donkey.iconset"+AUTH_CALLBACK_SCHEME="${DONKEY_AUTH_CALLBACK_SCHEME:-donkey}"+LAUNCH_APP="${DONKEY_LAUNCH_APP:-1}"+LSREGISTER="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"+SITE_PID=""+SITE_LOG="${DONKEY_SITE_LOG:-${TMPDIR:-/tmp}/donkey-site-dev.log}"LOG_PID=""export DONKEY_WEB_BASE_URL="${DONKEY_WEB_BASE_URL:-http://localhost:3000}"@@ -14,6 +31,10 @@ cleanup() {kill "$LOG_PID" >/dev/null 2>&1 || truewait "$LOG_PID" >/dev/null 2>&1 || truefi+ if [ -n "$SITE_PID" ] && kill -0 "$SITE_PID" >/dev/null 2>&1; then+ kill "$SITE_PID" >/dev/null 2>&1 || true+ wait "$SITE_PID" >/dev/null 2>&1 || true+ fi}start_logger() {@@ -52,21 +73,245 @@ start_logger() {LOG_PID="$!"}+is_local_web_base_url() {+ case "$DONKEY_WEB_BASE_URL" in+ http://localhost|http://localhost:*|http://127.0.0.1|http://127.0.0.1:*|http://[::1]|http://[::1]:*)+ return 0+ ;;+ *)+ return 1+ ;;+ esac+}++site_health_url() {+ printf '%s/api/health' "${DONKEY_WEB_BASE_URL%/}"+}++site_is_running() {+ command -v curl >/dev/null 2>&1 &&+ curl --silent --fail --max-time 1 "$(site_health_url)" >/dev/null 2>&1+}++ensure_site_server() {+ if [ "${DONKEY_START_SITE:-1}" = "0" ]; then+ echo "Skipping site dev server because DONKEY_START_SITE=0."+ return+ fi++ if ! is_local_web_base_url; then+ echo "Skipping site dev server because DONKEY_WEB_BASE_URL is not local: $DONKEY_WEB_BASE_URL"+ return+ fi++ if site_is_running; then+ echo "Site dev server is already running at $DONKEY_WEB_BASE_URL."+ return+ fi++ if [ ! -d "$ROOT_DIR/site" ]; then+ echo "Missing site directory at $ROOT_DIR/site." >&2+ exit 1+ fi++ if ! command -v npm >/dev/null 2>&1; then+ echo "npm is required to start the local site dev server." >&2+ exit 1+ fi++ echo "Starting site dev server at $DONKEY_WEB_BASE_URL ..."+ (+ cd "$ROOT_DIR/site"+ npm run dev+ ) >"$SITE_LOG" 2>&1 &+ SITE_PID="$!"++ local wait_seconds="${DONKEY_SITE_WAIT_SECONDS:-30}"+ local elapsed=0+ while [ "$elapsed" -lt "$wait_seconds" ]; do+ if site_is_running; then+ echo "Site dev server is ready."+ return+ fi++ if ! kill -0 "$SITE_PID" >/dev/null 2>&1; then+ echo "Site dev server exited before becoming ready. Log: $SITE_LOG" >&2+ tail -n 60 "$SITE_LOG" >&2 || true+ exit 1+ fi++ sleep 1+ elapsed=$((elapsed + 1))+ done++ echo "Timed out waiting for the site dev server. Log: $SITE_LOG" >&2+ tail -n 60 "$SITE_LOG" >&2 || true+ exit 1+}++xml_escape() {+ printf '%s' "$1" |+ sed \+ -e 's/&/\&/g' \+ -e 's/</\</g' \+ -e 's/>/\>/g' \+ -e 's/"/\"/g' \+ -e "s/'/\'/g"+}++prepare_app_icon() {+ local destination="$RESOURCES_DIR/Donkey.icns"++ if [ -f "$APP_ICON_SOURCE" ]; then+ cp "$APP_ICON_SOURCE" "$destination"+ return+ fi++ if [ -d "$APP_ICONSET_SOURCE" ]; then+ if ! command -v iconutil >/dev/null 2>&1; then+ echo "iconutil is required to package Donkey.app from $APP_ICONSET_SOURCE." >&2+ exit 1+ fi+ iconutil --convert icns --output "$destination" "$APP_ICONSET_SOURCE"+ return+ fi++ echo "Missing app icon sources: $APP_ICON_SOURCE or $APP_ICONSET_SOURCE" >&2+ exit 1+}++write_info_plist() {+ local escaped_web_base_url+ local escaped_callback_scheme+ escaped_web_base_url="$(xml_escape "$DONKEY_WEB_BASE_URL")"+ escaped_callback_scheme="$(xml_escape "$AUTH_CALLBACK_SCHEME")"++ cat > "$CONTENTS_DIR/Info.plist" <<PLIST+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleExecutable</key>+ <string>Donkey</string>+ <key>CFBundleIdentifier</key>+ <string>ai.donkey.Donkey</string>+ <key>CFBundleName</key>+ <string>Donkey</string>+ <key>CFBundleDisplayName</key>+ <string>Donkey</string>+ <key>CFBundleIconFile</key>+ <string>Donkey.icns</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>0.1.0-dev</string>+ <key>CFBundleVersion</key>+ <string>1</string>+ <key>LSMinimumSystemVersion</key>+ <string>14.0</string>+ <key>DonkeyWebBaseURL</key>+ <string>$escaped_web_base_url</string>+ <key>DonkeyAuthCallbackScheme</key>+ <string>$escaped_callback_scheme</string>+ <key>CFBundleURLTypes</key>+ <array>+ <dict>+ <key>CFBundleURLName</key>+ <string>ai.donkey.Donkey.auth</string>+ <key>CFBundleURLSchemes</key>+ <array>+ <string>$escaped_callback_scheme</string>+ </array>+ </dict>+ </array>+ <key>NSMicrophoneUsageDescription</key>+ <string>Donkey uses the microphone for user-requested voice input.</string>+ <key>NSScreenCaptureUsageDescription</key>+ <string>Donkey captures bounded screenshots for user-requested app context.</string>+ <key>NSAppleEventsUsageDescription</key>+ <string>Donkey uses local app automation only for user-requested actions.</string>+</dict>+</plist>+PLIST+}++create_debug_app_bundle() {+ local resource_bundle+ local sparkle_framework++ rm -rf "$DEV_APP_DIR"+ mkdir -p "$MACOS_DIR" "$RESOURCES_DIR" "$FRAMEWORKS_DIR"++ cp "$DONKEY_BIN" "$MACOS_DIR/Donkey"+ if ! otool -l "$MACOS_DIR/Donkey" | grep -q "@executable_path/../Frameworks"; then+ if ! command -v install_name_tool >/dev/null 2>&1; then+ echo "install_name_tool is required to package the Donkey debug app." >&2+ exit 1+ fi+ install_name_tool -add_rpath "@executable_path/../Frameworks" "$MACOS_DIR/Donkey"+ fi++ resource_bundle="$(find "$APP_DIR/.build" -path "*/debug/Donkey_Donkey.bundle" -type d | head -n 1 || true)"+ if [ -n "$resource_bundle" ]; then+ cp -R "$resource_bundle" "$RESOURCES_DIR/"+ else+ echo "Missing SwiftPM resource bundle for Donkey." >&2+ exit 1+ fi++ sparkle_framework="$(find "$APP_DIR/.build" -path "*/debug/Sparkle.framework" -type d | head -n 1 || true)"+ if [ -n "$sparkle_framework" ]; then+ cp -R "$sparkle_framework" "$FRAMEWORKS_DIR/"+ fi++ prepare_app_icon+ write_info_plist++ if command -v codesign >/dev/null 2>&1; then+ codesign --force --deep --sign - "$DEV_APP_DIR" >/dev/null+ fi++ if [ -x "$LSREGISTER" ]; then+ "$LSREGISTER" -f "$DEV_APP_DIR" >/dev/null 2>&1 || true+ fi+}++swift_build() {+ mkdir -p "$CACHE_CLANG_DIR" "$CACHE_SWIFTPM_DIR" "$CACHE_HOME_DIR"+ CLANG_MODULE_CACHE_PATH="$CACHE_CLANG_DIR" \+ SWIFTPM_CACHE_PATH="$CACHE_SWIFTPM_DIR" \+ HOME="$CACHE_HOME_DIR" \+ swift build --quiet+}+trap cleanup EXIT-echo "Stopping any running Donkey app..."-killall Donkey >/dev/null 2>&1 || true+ensure_site_server++if [ "$LAUNCH_APP" != "0" ]; then+ echo "Stopping any running Donkey app..."+ killall Donkey >/dev/null 2>&1 || true+ficd "$APP_DIR"echo "Building Donkey..."-swift build --quiet+swift_buildif [ ! -x "$DONKEY_BIN" ]; thenecho "Built Donkey executable was not found at $DONKEY_BIN." >&2exit 1fi+echo "Creating debug app bundle..."+create_debug_app_bundle++echo "Prepared $DEV_APP_DIR"+if [ "$LAUNCH_APP" = "0" ]; then+ echo "Skipping Donkey launch because DONKEY_LAUNCH_APP=0."+ exit 0+fi+echo "Starting Donkey..."start_logger-"$DONKEY_BIN"+open -W -n "$DEV_APP_DIR"diff --git a/site/src/app/mac-auth/MacAuthRedirector.tsx b/site/src/app/mac-auth/MacAuthRedirector.tsxindex d5ceea1b..6166dd06 100644--- a/site/src/app/mac-auth/MacAuthRedirector.tsx+++ b/site/src/app/mac-auth/MacAuthRedirector.tsx@@ -1,6 +1,7 @@"use client";-import { ArrowRight, LoaderCircle } from "lucide-react";+import { ArrowRight } from "lucide-react";+import Image from "next/image";import { useCallback, useEffect, useRef, useState } from "react";import { authClient } from "@/lib/auth-client";@@ -51,93 +52,28 @@ export function MacAuthRedirector({ state }: Props) {}, [startGoogleAuth]);return (- <main- style={{- alignItems: "center",- background: "#1f201e",- boxSizing: "border-box",- color: "#f7f4ee",- display: "flex",- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',- justifyContent: "center",- minHeight: "100vh",- padding: 24,- }}- >- <section- style={{- alignItems: "center",- display: "grid",- gap: 18,- justifyItems: "center",- maxWidth: 460,- textAlign: "center",- width: "100%",- }}- >- <div- style={{- alignItems: "center",- background: "#df704a",- borderRadius: 18,- display: "flex",- height: 68,- justifyContent: "center",- width: 68,- }}- >- <LoaderCircle- aria-hidden="true"- size={34}- strokeWidth={2.5}- style={{- animation: status === "opening" ? "donkey-spin 1s linear infinite" : undefined,- }}- />- </div>-- <h1- style={{- fontSize: 42,- fontWeight: 800,- letterSpacing: 0,- lineHeight: 1.05,- margin: "22px 0 0",- }}- >- {status === "opening" ? "Opening Google" : "Google sign-in paused"}+ <main className="box-border flex min-h-screen items-center justify-center bg-[#1f201e] px-6 py-6 text-[#f7f4ee]">+ <section className="grid w-full max-w-[460px] justify-items-center gap-[18px] text-center">+ <Image+ alt=""+ className="size-[72px] rounded-[18px] shadow-[0_18px_44px_rgba(0,0,0,0.32)]"+ height={72}+ src="/donkey-app-icon.png"+ width={72}+ />++ <h1 className="mt-[22px] text-[42px] leading-[1.05] font-extrabold tracking-normal">+ {headingForStatus(status)}</h1>- <p- style={{- color: "rgba(247, 244, 238, 0.68)",- fontSize: 17,- lineHeight: 1.5,- margin: 0,- }}- >+ <p className="m-0 max-w-[420px] text-[17px] leading-6 text-[#f7f4ee]/68">{messageForStatus(status)}</p>{status === "failed" ? (<button+ className="mt-[14px] inline-flex h-12 cursor-pointer items-center justify-center gap-2.5 rounded-xl border-0 bg-[#f7f4ee] px-[22px] text-base font-extrabold text-[#222]"onClick={retry}- style={{- alignItems: "center",- background: "#f7f4ee",- border: 0,- borderRadius: 12,- color: "#222",- cursor: "pointer",- display: "inline-flex",- fontSize: 16,- fontWeight: 800,- gap: 10,- height: 48,- justifyContent: "center",- marginTop: 14,- padding: "0 22px",- }}type="button">Try again@@ -146,17 +82,20 @@ export function MacAuthRedirector({ state }: Props) {) : null}</section>- <style jsx>{`- @keyframes donkey-spin {- to {- transform: rotate(360deg);- }- }- `}</style></main>);}+function headingForStatus(status: RedirectStatus) {+ switch (status) {+ case "failed":+ case "missing-state":+ return "Google sign-in paused";+ case "opening":+ return "Continuing with Google";+ }+}+function messageForStatus(status: RedirectStatus) {switch (status) {case "failed":diff --git a/site/src/app/mac-auth/callback/route.ts b/site/src/app/mac-auth/callback/route.tsindex e0b7c838..4aa6c6c9 100644--- a/site/src/app/mac-auth/callback/route.ts+++ b/site/src/app/mac-auth/callback/route.ts@@ -14,8 +14,9 @@ const callbackSearchParamsSchema = z.object({* 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.+ * It mints a short-lived one-time token from the browser session, then renders+ * a small handoff page that deep-links that code back to the native app for+ * cookie-jar exchange.*/export async function GET(request: NextRequest) {const parsedParams = callbackSearchParamsSchema.safeParse(@@ -33,7 +34,10 @@ export async function GET(request: NextRequest) {const { error, state } = parsedParams.data;if (error) {- return redirectToMac(macCallbackURL(state, { error }));+ return macHandoffPage(macCallbackURL(state, { error }), {+ heading: "Returning to Donkey",+ message: "Google sign-in did not finish. Donkey will ask you to try again.",+ });}try {@@ -41,21 +45,149 @@ export async function GET(request: NextRequest) {headers: request.headers,});- return redirectToMac(macCallbackURL(state, { code: token.token }));+ return macHandoffPage(macCallbackURL(state, { code: token.token }), {+ heading: "You're signed in",+ message: "Donkey is opening on your Mac. You can close this tab after the app appears.",+ });} catch {- return redirectToMac(macCallbackURL(state, { error: "session" }));+ return macHandoffPage(macCallbackURL(state, { error: "session" }), {+ heading: "Returning to Donkey",+ message: "Donkey could not create a Mac session yet. The app will ask you to try again.",+ });}}-function redirectToMac(url: URL) {- return new NextResponse(null, {- status: 302,+function macHandoffPage(+ url: URL,+ copy: {+ heading: string;+ message: string;+ },+) {+ const callbackURL = url.toString();+ const scriptURL = JSON.stringify(callbackURL)+ .replace(/</g, "\\u003c")+ .replace(/\u2028/g, "\\u2028")+ .replace(/\u2029/g, "\\u2029");++ return new NextResponse(`<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>${escapeHTML(copy.heading)} - Donkey</title>+ <style>+ :root {+ color-scheme: dark;+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ }++ * {+ box-sizing: border-box;+ }++ body {+ align-items: center;+ background: #1f201e;+ color: #f7f4ee;+ display: flex;+ justify-content: center;+ margin: 0;+ min-height: 100vh;+ padding: 24px;+ }++ main {+ align-items: center;+ display: grid;+ gap: 18px;+ justify-items: center;+ max-width: 460px;+ text-align: center;+ width: 100%;+ }++ img {+ border-radius: 18px;+ box-shadow: 0 18px 44px rgba(0, 0, 0, 0.32);+ height: 72px;+ width: 72px;+ }++ h1 {+ font-size: clamp(36px, 7vw, 48px);+ font-weight: 800;+ letter-spacing: 0;+ line-height: 1.04;+ margin: 18px 0 0;+ }++ p {+ color: rgba(247, 244, 238, 0.68);+ font-size: 17px;+ line-height: 1.5;+ margin: 0;+ max-width: 390px;+ }++ a {+ align-items: center;+ border: 1px solid rgba(247, 244, 238, 0.26);+ border-radius: 999px;+ color: #f7f4ee;+ display: inline-flex;+ font-size: 15px;+ font-weight: 750;+ height: 44px;+ justify-content: center;+ margin-top: 12px;+ padding: 0 20px;+ text-decoration: none;+ }++ a:focus-visible {+ outline: 3px solid rgba(115, 162, 255, 0.72);+ outline-offset: 3px;+ }+ </style>+</head>+<body>+ <main>+ <img alt="" src="/donkey-app-icon.png" />+ <h1>${escapeHTML(copy.heading)}</h1>+ <p>${escapeHTML(copy.message)}</p>+ <a href="${escapeHTMLAttribute(callbackURL)}">Open Donkey</a>+ </main>+ <script>+ const callbackURL = ${scriptURL};+ window.setTimeout(() => {+ window.location.href = callbackURL;+ }, 250);+ </script>+</body>+</html>`, {+ status: 200,headers: {- Location: url.toString(),+ "Cache-Control": "no-store",+ "Content-Type": "text/html; charset=utf-8",+ "Referrer-Policy": "no-referrer",},});}+function escapeHTML(value: string) {+ return value+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">");+}++function escapeHTMLAttribute(value: string) {+ return escapeHTML(value)+ .replace(/"/g, """)+ .replace(/'/g, "'");+}+function macCallbackURL(state: string,query: {diff --git a/site/src/lib/auth.ts b/site/src/lib/auth.tsindex 40da795f..1e6d8b01 100644--- a/site/src/lib/auth.ts+++ b/site/src/lib/auth.ts@@ -33,7 +33,7 @@ export const auth = betterAuth({},plugins: [oneTimeToken({- expiresIn: 3,+ expiresIn: 60,storeToken: "hashed",}),],