Open source CapCut alternative.
TypeScript
feat(site): add email verification to profile settings
David Le74a172fcb257
diff --git a/site/src/app/cut/app/(home)/settings/profile/page.tsx b/site/src/app/cut/app/(home)/settings/profile/page.tsxindex e9b5649c..f2ef0e32 100644--- a/site/src/app/cut/app/(home)/settings/profile/page.tsx+++ b/site/src/app/cut/app/(home)/settings/profile/page.tsx@@ -17,6 +17,7 @@ import { UserAvatar } from "@/cut/components/UserAvatar";import {useAccountProfile,useUpdateDisplayName,+ useVerifyEmail,visibleName,} from "@/queries/accountProfile";@@ -26,6 +27,7 @@ import {export default function CutProfilePage() {const { data: profile, isPending, isError } = useAccountProfile();const update = useUpdateDisplayName();+ const verifyEmail = useVerifyEmail();// Null means "not edited yet", so the field follows the saved value until// the user types and again once a save lands.const [draft, setDraft] = useState<string | null>(null);@@ -96,6 +98,30 @@ export default function CutProfilePage() {{visibleName(profile, profile.name)}</div><div className="truncate text-sm text-muted-foreground">{profile.email}</div>+ {profile.emailVerified ? (+ <p className="mt-1 text-xs text-muted-foreground">Email verified</p>+ ) : (+ <div className="mt-2">+ <Button+ variant="outline"+ size="sm"+ disabled={verifyEmail.isPending}+ onClick={() => verifyEmail.mutate(profile.email)}+ >+ {verifyEmail.isPending ? "Sending…" : verifyEmail.isSuccess ? "Resend email" : "Verify email"}+ </Button>+ {verifyEmail.isSuccess && (+ <p role="status" className="mt-2 text-sm text-muted-foreground">+ Check your inbox for a verification link.+ </p>+ )}+ {verifyEmail.isError && (+ <p role="alert" className="mt-2 text-sm text-red-600">+ Couldn't send the verification email. Try again.+ </p>+ )}+ </div>+ )}</div></div>diff --git a/site/src/lib/account-profile.ts b/site/src/lib/account-profile.tsindex e7ea094b..379a2ad4 100644--- a/site/src/lib/account-profile.ts+++ b/site/src/lib/account-profile.ts@@ -10,7 +10,7 @@ import { prisma } from "@/lib/prisma";export async function accountProfile(userId: string) {const [user, avatar] = await Promise.all([prisma.user.findUnique({- select: { displayName: true, email: true, image: true, name: true },+ select: { displayName: true, email: true, emailVerified: true, image: true, name: true },where: { id: userId },}),prisma.userAvatar.findUnique({@@ -23,6 +23,7 @@ export async function accountProfile(userId: string) {return {displayName: user.displayName,email: user.email,+ emailVerified: user.emailVerified,image: avatar ? `/api/account/avatar?v=${avatar.updatedAt.getTime()}` : user.image,name: user.name,};diff --git a/site/src/lib/auth.ts b/site/src/lib/auth.tsindex 604e0bca..737ad539 100644--- a/site/src/lib/auth.ts+++ b/site/src/lib/auth.ts@@ -7,6 +7,7 @@ import { AUTH_COOKIE_DOMAIN, DONKEYCUT_CANONICAL, SU_ORIGIN } from "@/cut/lib/hoimport { provisionSignupGrants } from "@/lib/onboarding/signup-grants";import { prisma } from "@/lib/prisma";import { emailPasswordDisabledPaths, emailPasswordGuard, emailPasswordOptions } from "@/lib/email-password-auth";+import { sendVerificationEmail } from "@/lib/email/send-verification";// 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@@ -75,6 +76,12 @@ export const auth = betterAuth({},},emailAndPassword: emailPasswordOptions,+ emailVerification: {+ sendVerificationEmail,+ sendOnSignUp: false,+ sendOnSignIn: false,+ autoSignInAfterVerification: false,+ },disabledPaths: emailPasswordDisabledPaths,hooks: {before: emailPasswordGuard,diff --git a/site/src/lib/email-password-auth.test.ts b/site/src/lib/email-password-auth.test.tsindex 494f4a7a..0c936e75 100644--- a/site/src/lib/email-password-auth.test.ts+++ b/site/src/lib/email-password-auth.test.ts@@ -6,16 +6,24 @@ import { emailPasswordDisabledPaths, emailPasswordGuard, emailPasswordOptions }const password = "test-only-account-password-12345";const db: Record<string, Record<string, unknown>[]> = {};+let verificationUrl: string | null = null;const auth = betterAuth({baseURL: "http://localhost:3000",secret: "test-only-auth-secret-with-at-least-32-characters",database: memoryAdapter(db),emailAndPassword: emailPasswordOptions,+ emailVerification: {+ sendVerificationEmail: async ({ url }) => { verificationUrl = url; },+ sendOnSignUp: false,+ sendOnSignIn: false,+ autoSignInAfterVerification: false,+ },disabledPaths: emailPasswordDisabledPaths,hooks: { before: emailPasswordGuard },});beforeEach(async () => {+ verificationUrl = null;db.user = ["first", "second", "google-only"].map((id) => ({id, email: `${id}@example.com`, name: id, emailVerified: false,createdAt: new Date(), updatedAt: new Date(),@@ -28,6 +36,35 @@ beforeEach(async () => {db.session = [];});+test("verification requires the signed-in account and changes its status only after the email link is opened", async () => {+ const signIn = await request("/sign-in/email", { email: "[email protected]", password });+ const cookie = signIn.headers.get("set-cookie")!.split(";")[0];+ const send = (body: Record<string, unknown>, cookieValue = cookie) => auth.handler(new Request("http://localhost:3000/api/auth/send-verification-email", {+ method: "POST", headers: { "Content-Type": "application/json", Origin: "http://localhost:3000", Cookie: cookieValue },+ body: JSON.stringify(body),+ }));+ expect((await send({ email: "[email protected]" }, "")).status).toBe(401);+ expect((await send({ email: "[email protected]" })).status).toBe(401);+ expect((await send({ email: "[email protected]", callbackURL: "https://attacker.example" })).status).toBe(403);+ expect(verificationUrl).toBeNull();+ const callbackURL = "/app/settings/profile";+ expect((await send({ email: "[email protected]", callbackURL })).status).toBe(200);+ expect(db.user.find((user) => user.id === "first")!.emailVerified).toBe(false);+ expect(verificationUrl).not.toBeNull();+ const link = new URL(verificationUrl!);+ expect(link.searchParams.get("callbackURL")).toBe(callbackURL);+ const invalid = new URL(link);+ invalid.searchParams.set("token", "invalid");+ await auth.handler(new Request(invalid));+ expect(db.user.find((user) => user.id === "first")!.emailVerified).toBe(false);+ const verified = await auth.handler(new Request(link));+ expect(verified.status).toBe(302);+ expect(verified.headers.get("location")).toBe(callbackURL);+ expect(db.user.find((user) => user.id === "first")!.emailVerified).toBe(true);+ expect(db.user.find((user) => user.id === "second")!.emailVerified).toBe(false);+ expect(verified.headers.get("set-cookie")).toBeNull();+});+function request(path: string, body: Record<string, unknown>) {return auth.handler(new Request(`http://localhost:3000/api/auth${path}`, {method: "POST",diff --git a/site/src/lib/email-password-auth.ts b/site/src/lib/email-password-auth.tsindex bc25193f..5f46b7bc 100644--- a/site/src/lib/email-password-auth.ts+++ b/site/src/lib/email-password-auth.ts@@ -1,4 +1,4 @@-import { APIError, createAuthMiddleware } from "better-auth/api";+import { APIError, createAuthMiddleware, getSessionFromCtx } from "better-auth/api";export const emailPasswordOptions = {enabled: true,@@ -12,7 +12,13 @@ export const emailPasswordDisabledPaths = [];export const emailPasswordGuard = createAuthMiddleware(async (ctx) => {- if (ctx.path !== "/sign-in/email" && ctx.path !== "/sign-up/email") return;+ if (ctx.path === "/send-verification-email") {+ const session = await getSessionFromCtx(ctx);+ if (!session || typeof ctx.body?.email !== "string" || ctx.body.email.toLowerCase() !== session.user.email.toLowerCase()) {+ throw new APIError("UNAUTHORIZED", { message: "Sign in to verify your email." });+ }+ }+ if (ctx.path !== "/sign-in/email" && ctx.path !== "/sign-up/email" && ctx.path !== "/send-verification-email") return;const callback: unknown = ctx.body?.callbackURL;if (callback !== undefined && (typeof callback !== "string" ||diff --git a/site/src/lib/email/send-verification.ts b/site/src/lib/email/send-verification.tsnew file mode 100644index 00000000..e3d405a4--- /dev/null+++ b/site/src/lib/email/send-verification.ts@@ -0,0 +1,29 @@+import { APIError } from "better-auth/api";+import { emailFrom, getResend } from "@/lib/email/resend";+import { withEmailBudget } from "@/lib/email/send-budget";++/** Verification links expire; deliver within the transactional budget immediately. */+export async function sendVerificationEmail({+ user,+ url,+}: {+ user: { email: string };+ url: string;+}) {+ const from = emailFrom();+ if (!from)+ throw new Error("RESEND_FROM_EMAIL is required for verification emails.");+ const result = await withEmailBudget("transactional", () =>+ getResend().emails.send({+ from,+ to: user.email,+ subject: "Verify your Donkey Cut email",+ text: `Confirm your email address for your Donkey Cut account:\n\n${url}\n\nIf you did not request this email, you can ignore it.`,+ }),+ );+ if (!result || result.error) {+ throw new APIError("SERVICE_UNAVAILABLE", {+ message: "Could not send the verification email. Please try again.",+ });+ }+}diff --git a/site/src/queries/accountProfile.ts b/site/src/queries/accountProfile.tsindex 26a3f8d7..94f658db 100644--- a/site/src/queries/accountProfile.ts+++ b/site/src/queries/accountProfile.ts@@ -12,6 +12,7 @@ export type AccountProfile = {// The name the user chose for the product, when they've set one.displayName: string | null;email: string;+ emailVerified: boolean;image: string | null;};@@ -72,3 +73,13 @@ export function useUpdateDisplayName() {},});}++export function useVerifyEmail() {+ return useMutation({+ mutationFn: (email: string) =>+ apiFetch<{ status: boolean }>("/api/auth/send-verification-email", {+ method: "POST",+ body: JSON.stringify({ email, callbackURL: "/app/settings/profile" }),+ }),+ });+}