Open source CapCut alternative.
TypeScript
feat(site): make donkeycut.com own auth, retire cross-domain handoff
David Le31255cd1655b
diff --git a/site/src/app/api/auth/[...all]/route.ts b/site/src/app/api/auth/[...all]/route.tsindex 46c1ab06..4657cf25 100644--- a/site/src/app/api/auth/[...all]/route.ts+++ b/site/src/app/api/auth/[...all]/route.ts@@ -1,17 +1,8 @@import { toNextJsHandler } from "better-auth/next-js";import { auth } from "@/lib/auth";-import { withHostScopedAuthCookies } from "@/lib/cut-auth";-// Auth responses served to donkeycut.com re-scope their cookies to host-only-// (see src/lib/cut-auth.ts); session refresh and sign-out set cookies through-// this handler, so without it the browser would silently reject them there.-const handler = toNextJsHandler(auth);--export async function GET(request: Request) {- return withHostScopedAuthCookies(await handler.GET(request), request.headers.get("host"));-}--export async function POST(request: Request) {- return withHostScopedAuthCookies(await handler.POST(request), request.headers.get("host"));-}+// donkeycut.com owns auth directly, so its cookies are already host-valid — no+// per-host cookie re-scoping is needed. better-auth's handler serves GET/POST+// for the whole /api/auth/* surface (sign-in, callback, session, sign-out).+export const { GET, POST } = toNextJsHandler(auth);diff --git a/site/src/app/cut-auth/route.ts b/site/src/app/cut-auth/route.tsdeleted file mode 100644index acba59df..00000000--- a/site/src/app/cut-auth/route.ts+++ /dev/null@@ -1,39 +0,0 @@-import { NextRequest, NextResponse } from "next/server";--import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";-import { auth } from "@/lib/auth";--export const dynamic = "force-dynamic";--/**- * GET /cut-auth?next=/app/…- *- * Apex half of the donkeycut.com sign-in handoff. The session cookie is scoped- * to donkeyuse.com and Google's redirect_uri is pinned to the apex, so- * donkeycut.com cannot sign in on its own. It sends the browser here instead:- * with an apex session (established through the normal /sign-in flow when- * needed) this mints a short-lived one-time token — the same machinery the Mac- * app uses — and bounces to donkeycut.com/auth/callback, which exchanges the- * token for a host-only session cookie there.- *- * On donkeycut.com this path rewrites into /cut and 404s, keeping the handoff- * start apex-only.- */-export async function GET(request: NextRequest) {- const rawNext = request.nextUrl.searchParams.get("next") ?? "";- const next = rawNext.startsWith("/") && !rawNext.startsWith("//") ? rawNext : "/app";-- const session = await auth.api.getSession({ headers: request.headers });- if (!session) {- const retry = `/cut-auth?next=${encodeURIComponent(next)}`;- return NextResponse.redirect(- new URL(`/sign-in?callbackURL=${encodeURIComponent(retry)}`, request.nextUrl.origin),- );- }-- const token = await auth.api.generateOneTimeToken({ headers: request.headers });- const url = new URL(`${DONKEYCUT_CANONICAL}/auth/callback`);- url.searchParams.set("token", token.token);- url.searchParams.set("next", next);- return NextResponse.redirect(url, 307);-}diff --git a/site/src/app/cut/auth/callback/route.ts b/site/src/app/cut/auth/callback/route.tsdeleted file mode 100644index 9f6cd8fe..00000000--- a/site/src/app/cut/auth/callback/route.ts+++ /dev/null@@ -1,40 +0,0 @@-import { NextRequest, NextResponse } from "next/server";--import { auth } from "@/lib/auth";-import { stripCookieDomain } from "@/lib/cut-auth";--export const dynamic = "force-dynamic";--/**- * GET donkeycut.com/auth/callback?token=…&next=… (route path /cut/auth/callback)- *- * donkeycut.com half of the sign-in handoff (see /cut-auth). Verifies the- * one-time token minted on the apex; the verify response carries the session- * Set-Cookie (the Mac app's cookie exchanger rides the same endpoint), which is- * re-scoped to a host-only donkeycut.com cookie. A missing or expired token- * just lands the user on `next` signed out.- */-export async function GET(request: NextRequest) {- const params = request.nextUrl.searchParams;- const rawNext = params.get("next") ?? "";- const next = rawNext.startsWith("/") && !rawNext.startsWith("//") ? rawNext : "/app";- const token = params.get("token");-- const origin = `${request.nextUrl.protocol}//${request.headers.get("host") ?? "donkeycut.com"}`;- const res = NextResponse.redirect(new URL(next, origin), 303);- if (!token) return res;-- try {- const verified = await auth.api.verifyOneTimeToken({- body: { token },- asResponse: true,- });- for (const cookie of verified.headers.getSetCookie()) {- res.headers.append("set-cookie", stripCookieDomain(cookie));- }- } catch {- // Expired or replayed token: arrive signed out and let the page's own- // sign-in entry points restart the handoff.- }- return res;-}diff --git a/site/src/cut/components/SettingsGuard.tsx b/site/src/cut/components/SettingsGuard.tsxindex b026674f..8a4d8149 100644--- a/site/src/cut/components/SettingsGuard.tsx+++ b/site/src/cut/components/SettingsGuard.tsx@@ -8,10 +8,9 @@ import { authClient } from "@/lib/auth-client";// Session guard for Cut's billing and usage pages. Signed-out visitors go// through the same host-aware sign-in flow as the editor's generation-// surfaces (signInUrl): the apex sign-in page on donkeyuse.com hosts (Google's-// redirect_uri is pinned there), the /cut-auth one-time-token handoff on-// donkeycut.com. Reading window.location is safe from hydration mismatch: the-// redirect runs only after the client session resolves.+// surfaces (signInUrl): the same-host sign-in page (Google's redirect_uri is+// pinned to the auth-owning host). Reading window.location is safe from+// hydration mismatch: the redirect runs only after the client session resolves.export function SettingsGuard({ children }: { children: ReactNode }) {const { data: session, isPending } = authClient.useSession();diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.tsindex 2fe0290a..ff158b63 100644--- a/site/src/cut/lib/generate.ts+++ b/site/src/cut/lib/generate.ts@@ -7,7 +7,7 @@ import type { AssetRef } from "./assetRef";import { bytesFromBase64 } from "./bytes";import { composeGenPrompt, foldTextRefs } from "./composeGen";import { stockAssetInDoc } from "./genvideo/docWriter";-import { DONKEY_APEX_ORIGIN, cutAppBase, isDonkeycutHost } from "./hosts";+import { cutAppBase } from "./hosts";import { hostedPost } from "./hosted";import { enrichAsset, importFileToProject } from "./media";import { refsToInlineImages, videoSafeInline, visualRefs, type InlineImage } from "./refMedia";@@ -181,14 +181,10 @@ const promptSlug = (prompt: string) =>* surface links here when signed out. */export function signInUrl(): string {if (typeof window === "undefined") return "/sign-in";- const { protocol, host, href, pathname, search } = window.location;- // Sign-in runs on the apex (Google's redirect_uri is pinned there), but bring- // the user back to the Cut page they started from once it completes.- // donkeycut.com is a different registrable domain the apex cookie can't- // reach, so it goes through the /cut-auth one-time-token handoff instead.- if (isDonkeycutHost(host)) {- return `${DONKEY_APEX_ORIGIN}/cut-auth?next=${encodeURIComponent(pathname + search)}`;- }+ const { protocol, host, href } = window.location;+ // Sign-in runs on the auth-owning host (Google's redirect_uri is pinned+ // there) and returns to the Cut page the user started from. donkeycut.com owns+ // auth directly; the legacy cut.* host strips to its apex.const apex = `${protocol}//${host.replace(/^cut\./, "")}`;return `${apex}/sign-in?callbackURL=${encodeURIComponent(href)}`;}diff --git a/site/src/cut/lib/hosts.ts b/site/src/cut/lib/hosts.tsindex 1670186e..c28f967a 100644--- a/site/src/cut/lib/hosts.ts+++ b/site/src/cut/lib/hosts.ts@@ -15,10 +15,6 @@ export const DONKEYCUT_HOSTS = new Set(["donkeycut.com", "www.donkeycut.com"]);export const DONKEYCUT_CANONICAL = "https://donkeycut.com";-// The apex origin that owns auth (Google OAuth redirect_uri, session minting).-// donkeycut.com signs in by bouncing through it — see /cut-auth.-export const DONKEY_APEX_ORIGIN = "https://donkeyuse.com";-function hostname(host: string | null | undefined): string {return host ? host.split(":")[0] : "";}diff --git a/site/src/lib/auth.ts b/site/src/lib/auth.tsindex 6c5fcafa..ea82bfb2 100644--- a/site/src/lib/auth.ts+++ b/site/src/lib/auth.ts@@ -12,16 +12,15 @@ import { prisma } from "@/lib/prisma";// once at creation; only a hash is stored (handled by the apiKey plugin).export const visionApiKeyPrefix = "dk_live_";-// Both donkeyuse.com and www.donkeyuse.com serve the app, but the Google OAuth+// Both donkeycut.com and www.donkeycut.com serve the site, but the Google OAuth// redirect_uri is pinned to BETTER_AUTH_URL's host. A sign-in started on one// host would set a host-only state cookie there while the callback lands on the// other, so better-auth can't find the cookie and rejects it as state_mismatch.-// Scoping the auth cookies to the registrable host lets them ride across both,-// and across the cut.donkeyuse.com subdomain that serves the editor.+// Scoping the auth cookies to the registrable host lets them ride across both.//-// Local dev needs none of this: Cut is served from the apex under /cut, so its-// session cookie is already same-origin. (A Domain=localhost cookie doesn't-// reach a cut.localhost subdomain in Chrome anyway.)+// Local dev needs none of this: everything is served from the one localhost+// origin, so the session cookie is already same-origin. (A Domain=localhost+// cookie doesn't reach a subdomain in Chrome anyway.)function crossSubDomainCookieDomain() {const baseURL = process.env.BETTER_AUTH_URL;if (!baseURL) return undefined;@@ -39,33 +38,15 @@ function crossSubDomainCookieDomain() {return host;}-// In production the editor is served from cut.donkeyuse.com, a different origin-// from the apex where Google's redirect_uri is pinned, so a sign-in that starts-// on Cut redirects back to that origin — it has to be trusted for the redirect-// to be honored. Local dev serves Cut under /cut on the apex (same origin), so-// nothing extra is needed there.-function cutRedirectOrigins(): string[] {- const baseURL = process.env.BETTER_AUTH_URL;- if (!baseURL) return [];- try {- const url = new URL(baseURL);- if (url.hostname === "localhost" || url.hostname.endsWith(".localhost")) return [];- if (!url.hostname.startsWith("cut.")) url.hostname = `cut.${url.hostname}`;- return [url.origin];- } catch {- return [];- }-}-const cookieDomain = crossSubDomainCookieDomain();export const auth = betterAuth({baseURL: process.env.BETTER_AUTH_URL,secret: process.env.BETTER_AUTH_SECRET,- // donkeycut.com POSTs to the auth API cross-origin (sign-out, session- // refresh), so better-auth's Origin check must trust it alongside the- // cut.donkeyuse.com sign-in redirects.- trustedOrigins: [...macAuthRedirectOrigins(), ...cutRedirectOrigins(), DONKEYCUT_CANONICAL],+ // donkeycut.com is the canonical host and its www. mirror POSTs to the auth+ // API cross-origin (sign-out, session refresh), so better-auth's Origin check+ // trusts it alongside the Mac-app handoff scheme.+ trustedOrigins: [...macAuthRedirectOrigins(), DONKEYCUT_CANONICAL],// Sessions last a year, and the rolling expiry is refreshed daily on use, so an active user effectively// never has to sign in again. The Mac app's native session cookie rides this same lifetime, keeping the// desktop signed in long after the handoff.diff --git a/site/src/lib/cut-auth.ts b/site/src/lib/cut-auth.tsdeleted file mode 100644index c4cc16a8..00000000--- a/site/src/lib/cut-auth.ts+++ /dev/null@@ -1,31 +0,0 @@-import { isDonkeycutHost } from "@/cut/lib/hosts";--// better-auth stamps Domain=donkeyuse.com on every auth cookie-// (crossSubDomainCookies in src/lib/auth.ts) so sessions ride the apex and its-// subdomains. donkeycut.com is a different registrable domain: browsers reject-// a Set-Cookie whose Domain does not cover the responding host, so cookies for-// donkeycut.com responses must drop the attribute and become host-only. The-// signed cookie value is domain-independent — the server accepts it either way.-export function stripCookieDomain(setCookie: string): string {- return setCookie.replace(/;\s*Domain=[^;]*/i, "");-}--/** Re-scope every Set-Cookie on a response to host-only when it is being served- * to donkeycut.com; responses for other hosts pass through untouched. */-export function withHostScopedAuthCookies(- res: Response,- host: string | null | undefined,-): Response {- if (!isDonkeycutHost(host)) return res;- const cookies = res.headers.getSetCookie();- if (cookies.length === 0) return res;-- const headers = new Headers(res.headers);- headers.delete("set-cookie");- for (const cookie of cookies) headers.append("set-cookie", stripCookieDomain(cookie));- return new Response(res.body, {- status: res.status,- statusText: res.statusText,- headers,- });-}diff --git a/site/src/proxy.ts b/site/src/proxy.tsindex 429a048a..cb0d9468 100644--- a/site/src/proxy.ts+++ b/site/src/proxy.ts@@ -14,9 +14,10 @@ import {// serving Donkey://// donkeycut.com "/" → landing, "/app/…" → editor app (generic-// "/…" → "/cut/…" rewrite). "/install" and the legal-// pages pass through so the shared apex routes serve-// them same-host. www. 308s to the apex.+// "/…" → "/cut/…" rewrite). The auth pages (/sign-in,+// /sign-up, /mac-auth), "/install", and the legal pages+// pass through so the shared apex routes serve them+// same-host. www. 308s to the apex.// cut.donkeyuse.com legacy host, unchanged URLs: "/…" → "/cut/app/…" so// "/", "/library", "/p/[id]" keep working.//@@ -62,25 +63,27 @@ function cutApi(req: NextRequest): NextResponse {}// Paths served by shared apex routes that must not be captured by the generic-// "/…" → "/cut/…" rewrite on donkeycut.com. "/install" carries the Mac-// download, and the legal pages are shared verbatim. "/app/settings" is not-// among them: Cut ships its own billing and usage pages under /cut/app/settings,-// which the generic rewrite serves at /app/settings on this host.-const DONKEYCUT_PASSTHROUGH = ["/install", "/privacy", "/terms"];--// Local dev mirrors donkeycut.com (Cut at "/", the editor at "/app/…"), so it-// additionally passes through the auth flows and the notch prototype, which-// only exist on the apex and are exercised from localhost during development.-const LOCAL_PASSTHROUGH = [- ...DONKEYCUT_PASSTHROUGH,+// "/…" → "/cut/…" rewrite on donkeycut.com. donkeycut.com owns auth directly,+// so the sign-in/sign-up pages and the Mac-app handoff serve same-host here;+// "/install" carries the Mac download and the legal pages are shared verbatim.+// "/app/settings" is not among them: Cut ships its own billing and usage pages+// under /cut/app/settings, which the generic rewrite serves at /app/settings on+// this host.+const DONKEYCUT_PASSTHROUGH = [+ "/install",+ "/privacy",+ "/terms","/sign-in","/sign-up","/mac-auth",- "/cut-auth",- "/prototype",];-// Whole-segment prefix match, so "/cut" covers "/cut/…" but not "/cut-auth".+// Local dev mirrors donkeycut.com (Cut at "/", the editor at "/app/…"). It adds+// the notch prototype, which only exists on the apex and is exercised from+// localhost during development.+const LOCAL_PASSTHROUGH = [...DONKEYCUT_PASSTHROUGH, "/prototype"];++// Whole-segment prefix match, so "/cut" covers "/cut/…" but not "/cut-app".const underPath = (pathname: string, prefix: string) =>pathname === prefix || pathname.startsWith(`${prefix}/`);