Open source CapCut alternative.
TypeScript
feat(site): add unlisted email signup and sign-in
David Le4663b5035548
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.mdindex 7a96c8b3..57305b03 100644--- a/docs/guides/backend-apis.md+++ b/docs/guides/backend-apis.md@@ -14,20 +14,15 @@ a handler without the wrapper and the endpoint is open to anyone.## Authentication-`withDonkeyAuth` takes a session cookie. Inside the handler, `request.donkey`-carries who the caller is. Its `method` field says how they authenticated — by-session cookie or dev bypass — and the handler branches on that, never on the-path.--A route that requires more than being signed in declares the role in the same-wrapper: `withSuperUser(handler)` rejects everyone else with a plain 403 before-the handler runs. Roles are a typed set on the auth options, so a handler never-hand-rolls its own role check.--Better Auth is the login layer, mounted at `/api/auth/[...all]` and configured-in one place. The only interactive login is Google OAuth; email-and-password-stays off unless the product deliberately adds another method. Better Auth's own-Google callback is `${BETTER_AUTH_URL}/api/auth/callback/google`.+`withDonkeyAuth` puts the caller in `request.donkey`; its `method` distinguishes+session cookies from the dev bypass.++`withSuperUser(handler)` enforces the super-user role before a handler runs.++Better Auth serves `/api/auth/[...all]`. Google OAuth returns to+`${BETTER_AUTH_URL}/api/auth/callback/google`. Adding `?method=email` to+`/sign-in` or `/sign-up` opens email/password authentication for anyone;+the default pages show Google. Password recovery remains unavailable.**Sign-out is everywhere.** Each browser holds its own session, so signing out onany surface revokes *every* session for that user (Better Auth'sdiff --git a/site/src/app/_components/landing/AuthPage.tsx b/site/src/app/_components/landing/AuthPage.tsxnew file mode 100644index 00000000..0c074572--- /dev/null+++ b/site/src/app/_components/landing/AuthPage.tsx@@ -0,0 +1,21 @@+import { Suspense } from "react";+import { AuthScreen } from "@/app/_components/landing/AuthScreen";++export type AuthSearchParams = Promise<{+ method?: string | string[];+ callbackURL?: string | string[];+}>;++type Props = { mode: "sign-in" | "sign-up"; searchParams: AuthSearchParams };++async function Form({ mode, searchParams }: Props) {+ const { method, callbackURL } = await searchParams;+ return <AuthScreen mode={mode} method={method === "email" ? "email" : "google"}+ callbackURL={typeof callbackURL === "string" ? callbackURL : undefined} />;+}++export function AuthPage(props: Props) {+ return <Suspense fallback={<AuthScreen mode={props.mode} />}>+ <Form {...props} />+ </Suspense>;+}diff --git a/site/src/app/_components/landing/AuthScreen.tsx b/site/src/app/_components/landing/AuthScreen.tsxindex 19cd55d9..b701951e 100644--- a/site/src/app/_components/landing/AuthScreen.tsx+++ b/site/src/app/_components/landing/AuthScreen.tsx@@ -5,6 +5,7 @@ import Link from "next/link";import { useCallback, useState } from "react";import { TopNav } from "@/app/_components/landing/TopNav";+import { EmailAuthForm } from "@/app/_components/landing/EmailAuthForm";import { CutFooter } from "@/app/cut/_components/landing/CutFooter";import { authClient } from "@/lib/auth-client";import { cn } from "@/lib/utils";@@ -13,6 +14,8 @@ type AuthMode = "sign-in" | "sign-up";type Props = {mode: AuthMode;+ method?: "google" | "email";+ callbackURL?: string;};const copy = {@@ -52,11 +55,15 @@ const copy = {const GOOGLE_BUTTON_HEIGHT = 56;-export function AuthScreen({ mode }: Props) {+export function AuthScreen({ mode, method = "google", callbackURL }: Props) {const [isPending, setIsPending] = useState(false);const [statusMessage, setStatusMessage] = useState<string | null>(null);const screenCopy = copy[mode];const otherMode: AuthMode = mode === "sign-in" ? "sign-up" : "sign-in";+ const alternateParams = new URLSearchParams();+ if (method === "email") alternateParams.set("method", "email");+ if (callbackURL) alternateParams.set("callbackURL", callbackURL);+ const alternateHref = `${screenCopy.alternateHref}${alternateParams.size ? `?${alternateParams}` : ""}`;const handleGoogleAuth = useCallback(async () => {const searchParams = new URLSearchParams(window.location.search);@@ -86,7 +93,7 @@ export function AuthScreen({ mode }: Props) {const formContent = (<>- <button+ {method === "email" ? <EmailAuthForm mode={mode} /> : <buttontype="button"aria-label={screenCopy.googleAlt}disabled={isPending}@@ -106,11 +113,11 @@ export function AuthScreen({ mode }: Props) {className="block h-14"style={{ width: googleButtonWidth }}/>- </button>+ </button>}<p className="mt-[18px] text-sm leading-normal text-[#555]">{screenCopy.alternateLead}{" "}<Link- href={screenCopy.alternateHref}+ href={alternateHref}className="font-semibold text-ink underline underline-offset-[3px]">{screenCopy.alternateLabel}@@ -149,14 +156,14 @@ export function AuthScreen({ mode }: Props) {<TopNavwordmark="Donkey Cut"authToggle={{- href: screenCopy.alternateHref,+ href: alternateHref,label: copy[otherMode].title,}}/><section className="mx-auto grid w-full max-w-[1400px] grid-cols-1 justify-items-center gap-16 px-6 pt-[44px] pb-[240px] text-center min-[900px]:gap-24 min-[900px]:px-12 min-[900px]:pt-[72px] min-[900px]:pb-[360px]"><div><h1 className="max-w-[920px] text-[33px] leading-[0.9] font-semibold break-words min-[900px]:text-[69px]">- {screenCopy.heading}+ {method === "email" ? (mode === "sign-in" ? "Sign in with email" : "Create your account") : screenCopy.heading}</h1></div>diff --git a/site/src/app/_components/landing/EmailAuthForm.tsx b/site/src/app/_components/landing/EmailAuthForm.tsxnew file mode 100644index 00000000..e6bd74d8--- /dev/null+++ b/site/src/app/_components/landing/EmailAuthForm.tsx@@ -0,0 +1,64 @@+"use client";++import { useState, type FormEvent } from "react";+import { authClient } from "@/lib/auth-client";++type Props = { mode: "sign-in" | "sign-up" };++export function EmailAuthForm({ mode }: Props) {+ const signingUp = mode === "sign-up";+ const [pending, setPending] = useState(false);+ const [error, setError] = useState<string | null>(null);++ async function submit(event: FormEvent<HTMLFormElement>) {+ event.preventDefault();+ const data = new FormData(event.currentTarget);+ setPending(true);+ setError(null);+ try {+ const credentials = {+ email: String(data.get("email")),+ password: String(data.get("password")),+ callbackURL: new URLSearchParams(window.location.search).get("callbackURL") ?? (signingUp ? "/app/onboarding" : "/app"),+ };+ const result = signingUp+ ? await authClient.signUp.email({ ...credentials, name: String(data.get("name")) })+ : await authClient.signIn.email(credentials);+ if (result.error) {+ setError(result.error.message ?? "Check your details and try again.");+ } else if (signingUp) {+ // OAuth callbacks can be non-React endpoints, so complete signup with a full navigation.+ window.location.href = credentials.callbackURL;+ }+ } catch {+ setError("Could not complete your request. Please try again.");+ } finally {+ setPending(false);+ }+ }++ return (+ <form onSubmit={submit} className="flex w-80 max-w-full flex-col gap-3 text-left">+ {signingUp ? <label className="flex flex-col gap-1 text-sm">+ Name+ <input name="name" autoComplete="name" required disabled={pending}+ className="rounded-lg border border-ink/30 bg-white px-3 py-2 outline-none focus:border-ink focus:ring-1 focus:ring-inset focus:ring-ink" />+ </label> : null}+ <label className="flex flex-col gap-1 text-sm">+ <input name="email" type="email" autoComplete="username" required disabled={pending}+ className="rounded-lg border border-ink/30 bg-white px-3 py-2 outline-none focus:border-ink focus:ring-1 focus:ring-inset focus:ring-ink" />+ </label>+ <label className="flex flex-col gap-1 text-sm">+ Password+ <input name="password" type="password" autoComplete={signingUp ? "new-password" : "current-password"} required disabled={pending}+ className="rounded-lg border border-ink/30 bg-white px-3 py-2 outline-none focus:border-ink focus:ring-1 focus:ring-inset focus:ring-ink" />+ </label>+ <button type="submit" disabled={pending}+ className="rounded-lg bg-ink px-4 py-2 text-background disabled:opacity-60">+ {pending ? "Please wait…" : signingUp ? "Create account" : "Sign in"}+ </button>+ {error ? <p role="alert" className="text-sm">{error}</p> : null}+ </form>+ );+}diff --git a/site/src/app/sign-in/page.tsx b/site/src/app/sign-in/page.tsxindex 7f3954b4..88315efc 100644--- a/site/src/app/sign-in/page.tsx+++ b/site/src/app/sign-in/page.tsx@@ -1,14 +1,14 @@import type { Metadata } from "next";-import { AuthScreen } from "@/app/_components/landing/AuthScreen";+import { AuthPage, type AuthSearchParams } from "@/app/_components/landing/AuthPage";export const metadata: Metadata = {title: "Log in | Donkey",- description: "Log in to Donkey with Google.",+ description: "Log in to Donkey Cut.",};export const instant = true;-export default function Page() {- return <AuthScreen mode="sign-in" />;+export default function Page({ searchParams }: { searchParams: AuthSearchParams }) {+ return <AuthPage mode="sign-in" searchParams={searchParams} />;}diff --git a/site/src/app/sign-up/page.tsx b/site/src/app/sign-up/page.tsxindex deef5222..6bc84710 100644--- a/site/src/app/sign-up/page.tsx+++ b/site/src/app/sign-up/page.tsx@@ -1,14 +1,14 @@import type { Metadata } from "next";-import { AuthScreen } from "@/app/_components/landing/AuthScreen";+import { AuthPage, type AuthSearchParams } from "@/app/_components/landing/AuthPage";export const metadata: Metadata = {title: "Sign up | Donkey",- description: "Create a Donkey account with Google.",+ description: "Create a Donkey Cut account.",};export const instant = true;-export default function Page() {- return <AuthScreen mode="sign-up" />;+export default function Page({ searchParams }: { searchParams: AuthSearchParams }) {+ return <AuthPage mode="sign-up" searchParams={searchParams} />;}diff --git a/site/src/lib/auth.ts b/site/src/lib/auth.tsindex bb4848f6..604e0bca 100644--- a/site/src/lib/auth.ts+++ b/site/src/lib/auth.ts@@ -6,6 +6,7 @@ import { bearer } from "better-auth/plugins";import { AUTH_COOKIE_DOMAIN, DONKEYCUT_CANONICAL, SU_ORIGIN } from "@/cut/lib/hosts";import { provisionSignupGrants } from "@/lib/onboarding/signup-grants";import { prisma } from "@/lib/prisma";+import { emailPasswordDisabledPaths, emailPasswordGuard, emailPasswordOptions } from "@/lib/email-password-auth";// donkeycut.com owns sign-in: the auth pages, the auth API, and the Google// OAuth callback all serve on that one origin (the proxy 308s www. to the apex@@ -73,8 +74,10 @@ export const auth = betterAuth({},},},- emailAndPassword: {- enabled: false,+ emailAndPassword: emailPasswordOptions,+ disabledPaths: emailPasswordDisabledPaths,+ hooks: {+ before: emailPasswordGuard,},socialProviders: {google: {diff --git a/site/src/lib/email-password-auth.test.ts b/site/src/lib/email-password-auth.test.tsnew file mode 100644index 00000000..494f4a7a--- /dev/null+++ b/site/src/lib/email-password-auth.test.ts@@ -0,0 +1,93 @@+import { beforeEach, expect, test } from "bun:test";+import { betterAuth } from "better-auth";+import { memoryAdapter } from "better-auth/adapters/memory";+import { hashPassword } from "better-auth/crypto";+import { emailPasswordDisabledPaths, emailPasswordGuard, emailPasswordOptions } from "@/lib/email-password-auth";++const password = "test-only-account-password-12345";+const db: Record<string, Record<string, unknown>[]> = {};+const auth = betterAuth({+ baseURL: "http://localhost:3000",+ secret: "test-only-auth-secret-with-at-least-32-characters",+ database: memoryAdapter(db),+ emailAndPassword: emailPasswordOptions,+ disabledPaths: emailPasswordDisabledPaths,+ hooks: { before: emailPasswordGuard },+});++beforeEach(async () => {+ db.user = ["first", "second", "google-only"].map((id) => ({+ id, email: `${id}@example.com`, name: id, emailVerified: false,+ createdAt: new Date(), updatedAt: new Date(),+ }));+ const hash = await hashPassword(password);+ db.account = db.user.filter((user) => user.id !== "google-only").map((user) => ({+ id: `${user.id}-credential`, userId: user.id, accountId: user.id,+ providerId: "credential", password: hash, createdAt: new Date(), updatedAt: new Date(),+ }));+ db.session = [];+});++function request(path: string, body: Record<string, unknown>) {+ return auth.handler(new Request(`http://localhost:3000/api/auth${path}`, {+ method: "POST",+ headers: { "Content-Type": "application/json", Origin: "http://localhost:3000" },+ body: JSON.stringify(body),+ }));+}++test("any account with valid password credentials receives a normal session", async () => {+ const callbackURL = "/api/chatgpt/oauth/authorize?state=test";+ for (const email of ["[email protected]", "[email protected]"]) {+ const response = await request("/sign-in/email", { email, password, callbackURL });+ expect(response.status).toBe(200);+ expect(response.headers.get("set-cookie")).toContain("session_token");+ expect((await response.json()).url).toBe(callbackURL);+ }+ expect(db.session).toHaveLength(2);+});++test("wrong passwords and accounts without password credentials are rejected", async () => {+ for (const body of [+ { email: "[email protected]", password: "wrong" },+ { email: "[email protected]", password },+ { email: "[email protected]", password },+ ]) {+ expect((await request("/sign-in/email", body)).status).toBe(401);+ }+ expect(db.session).toHaveLength(0);+});++test("email signup creates a password account that can sign in without an inbox", async () => {+ const credentials = { email: "[email protected]", password };+ const response = await request("/sign-up/email", { ...credentials, name: "New account" });+ expect(response.status).toBe(200);+ expect(response.headers.get("set-cookie")).toContain("session_token");+ const user = (await response.json()).user;+ expect(user.emailVerified).toBe(false);+ expect(db.account.find((account) => account.userId === user.id)?.password).not.toBe(password);+ expect((await request("/sign-in/email", credentials)).status).toBe(200);+});++test("signup cannot overwrite an existing account or accept a short password", async () => {+ expect((await request("/sign-up/email", { email: "[email protected]", password, name: "Other" })).ok).toBe(false);+ expect((await request("/sign-up/email", { email: "[email protected]", password: "short", name: "New" })).ok).toBe(false);+ expect(db.user).toHaveLength(3);+});++test("unconfigured password recovery and password attachment endpoints stay closed", async () => {+ for (const path of emailPasswordDisabledPaths) {+ expect((await request(path, { email: "[email protected]", password })).status).toBe(404);+ }+});++test("external callbacks are rejected for both sign-in and signup", async () => {+ for (const path of ["/sign-in/email", "/sign-up/email"]) {+ const response = await request(path, {+ email: "[email protected]", password, name: "New", callbackURL: "https://attacker.example/",+ });+ expect(response.status).toBe(403);+ }+ expect(db.user).toHaveLength(3);+ expect(db.session).toHaveLength(0);+});diff --git a/site/src/lib/email-password-auth.ts b/site/src/lib/email-password-auth.tsnew file mode 100644index 00000000..bc25193f--- /dev/null+++ b/site/src/lib/email-password-auth.ts@@ -0,0 +1,24 @@+import { APIError, createAuthMiddleware } from "better-auth/api";++export const emailPasswordOptions = {+ enabled: true,+};++// Password recovery needs an email delivery flow before it can be exposed.+export const emailPasswordDisabledPaths = [+ "/set-password",+ "/request-password-reset",+ "/reset-password",+];++export const emailPasswordGuard = createAuthMiddleware(async (ctx) => {+ if (ctx.path !== "/sign-in/email" && ctx.path !== "/sign-up/email") return;+ const callback: unknown = ctx.body?.callbackURL;+ if (callback !== undefined && (+ typeof callback !== "string" ||+ !URL.canParse(callback, ctx.context.baseURL) ||+ new URL(callback, ctx.context.baseURL).origin !== new URL(ctx.context.baseURL).origin+ )) {+ throw new APIError("FORBIDDEN", { message: "Invalid callback URL" });+ }+});