Skip to content

Open source CapCut alternative.

TypeScript

feat(site): sign donkeycut.com in through an apex one-time-token handoff

David Lecd19b7097abf
diff --git a/site/src/app/api/auth/[...all]/route.ts b/site/src/app/api/auth/[...all]/route.ts
index 076e5786..46c1ab06 100644
--- a/site/src/app/api/auth/[...all]/route.ts
+++ b/site/src/app/api/auth/[...all]/route.ts
@@ -1,5 +1,17 @@
import { toNextJsHandler } from "better-auth/next-js";
import { auth } from "@/lib/auth";
+import { withHostScopedAuthCookies } from "@/lib/cut-auth";
-export const { GET, POST } = toNextJsHandler(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"));
+}
diff --git a/site/src/app/cut-auth/route.ts b/site/src/app/cut-auth/route.ts
new file mode 100644
index 00000000..acba59df
--- /dev/null
+++ b/site/src/app/cut-auth/route.ts
@@ -0,0 +1,39 @@
+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.ts
new file mode 100644
index 00000000..9f6cd8fe
--- /dev/null
+++ b/site/src/app/cut/auth/callback/route.ts
@@ -0,0 +1,40 @@
+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/lib/generate.ts b/site/src/cut/lib/generate.ts
index b5c4d080..e48fac37 100644
--- a/site/src/cut/lib/generate.ts
+++ b/site/src/cut/lib/generate.ts
@@ -7,6 +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, isDonkeycutHost } from "./hosts";
import { hostedPost } from "./hosted";
import { enrichAsset, importFileToProject } from "./media";
import { refsToInlineImages, videoSafeInline, visualRefs, type InlineImage } from "./refMedia";
@@ -180,9 +181,14 @@ 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 } = window.location;
+ 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 apex = `${protocol}//${host.replace(/^cut\./, "")}`;
return `${apex}/sign-in?callbackURL=${encodeURIComponent(href)}`;
}
@@ -197,6 +203,8 @@ export const NO_CREDITS_MESSAGE = "No credits left";
export function creditsUrl(): string {
if (typeof window === "undefined") return "/app/settings";
const { protocol, host } = window.location;
+ // On donkeycut.com the settings routes are served same-host (see src/proxy.ts).
+ if (isDonkeycutHost(host)) return "/app/settings";
const apex = `${protocol}//${host.replace(/^cut\./, "")}`;
return `${apex}/app/settings`;
}
diff --git a/site/src/lib/auth.ts b/site/src/lib/auth.ts
index f55b3936..6c5fcafa 100644
--- a/site/src/lib/auth.ts
+++ b/site/src/lib/auth.ts
@@ -3,6 +3,7 @@ import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { oneTimeToken } from "better-auth/plugins";
+import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
import { macAuthRedirectOrigins } from "@/lib/mac-auth";
import { provisionSignupGrants } from "@/lib/onboarding/signup-grants";
import { prisma } from "@/lib/prisma";
@@ -61,7 +62,10 @@ const cookieDomain = crossSubDomainCookieDomain();
export const auth = betterAuth({
baseURL: process.env.BETTER_AUTH_URL,
secret: process.env.BETTER_AUTH_SECRET,
- trustedOrigins: [...macAuthRedirectOrigins(), ...cutRedirectOrigins()],
+ // 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],
// 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.ts
new file mode 100644
index 00000000..c4cc16a8
--- /dev/null
+++ b/site/src/lib/cut-auth.ts
@@ -0,0 +1,31 @@
+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,
+ });
+}