Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Require explicit confirm/cancel for email change instead of applying on link open.

Kiran K47e32f67673d
diff --git a/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page-client.tsx b/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page-client.tsx
index ebc9107d32..65eb445aae 100644
--- a/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page-client.tsx
+++ b/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page-client.tsx
@@ -1,44 +1,103 @@
"use client";
-import { EmptyState, LoadingSpinner } from "@dub/ui";
+import { cancelEmailChangeAction } from "@/lib/actions/cancel-email-change";
+import { confirmEmailChangeAction } from "@/lib/actions/confirm-email-change";
+import EmptyState from "@/ui/shared/empty-state";
+import { Button, InputPassword } from "@dub/ui";
import { useSession } from "next-auth/react";
+import { useAction } from "next-safe-action/hooks";
import { useRouter } from "next/navigation";
-import { useEffect, useRef } from "react";
+import { useState } from "react";
import { toast } from "sonner";
export default function ConfirmEmailChangePageClient({
- isPartnerProfile,
- redirectTo,
+ token,
+ email,
+ newEmail,
}: {
- isPartnerProfile: boolean;
- redirectTo?: "/profile" | "/account/settings";
+ token: string;
+ email: string;
+ newEmail: string;
}) {
const router = useRouter();
- const { update, status } = useSession();
- const hasUpdatedSession = useRef(false);
-
- useEffect(() => {
- if (status !== "authenticated" || hasUpdatedSession.current) {
- return;
- }
-
- async function updateSession() {
- hasUpdatedSession.current = true;
- await update();
- toast.success("Successfully updated your email!");
- router.replace(
- redirectTo ?? (isPartnerProfile ? "/profile" : "/account/settings"),
- );
- }
-
- updateSession();
- }, [status, update, isPartnerProfile, redirectTo, router]);
+ const { update } = useSession();
+ const [canceled, setCanceled] = useState(false);
+ const [confirmed, setConfirmed] = useState(false);
+
+ const { executeAsync: confirmEmailChange, isPending: isConfirming } =
+ useAction(confirmEmailChangeAction, {
+ async onSuccess({ data }) {
+ if (!data) {
+ return;
+ }
+
+ setConfirmed(true);
+
+ const redirectTo =
+ data.redirectTo ??
+ (data.isPartnerProfile ? "/profile" : "/account/settings");
+
+ await update();
+ toast.success("Successfully updated your email!");
+ router.replace(redirectTo);
+ },
+ onError({ error }) {
+ toast.error(error.serverError);
+ },
+ });
+
+ const { executeAsync: cancelEmailChange, isPending: isCanceling } = useAction(
+ cancelEmailChangeAction,
+ {
+ onSuccess() {
+ setCanceled(true);
+ },
+ onError({ error }) {
+ toast.error(error.serverError);
+ },
+ },
+ );
+
+ if (canceled) {
+ return (
+ <EmptyState
+ icon={InputPassword}
+ title="Email Change Request Canceled"
+ description="Your email change request has been canceled. No changes have been made to your account. You can close this page."
+ />
+ );
+ }
+
+ const isPending = isConfirming || isCanceling || confirmed;
return (
- <EmptyState
- icon={LoadingSpinner}
- title="Verifying Email Change"
- description="Verifying your email change request. This might take a few seconds..."
- />
+ <div className="w-full max-w-sm">
+ <h3 className="text-center text-xl font-semibold">
+ Confirm your email change
+ </h3>
+ <p className="mt-2 text-center text-sm text-neutral-500">
+ Confirm the update to your email from{" "}
+ <span className="font-medium text-neutral-700">{email}</span> to{" "}
+ <span className="font-medium text-neutral-900">{newEmail}</span>.
+ </p>
+
+ <div className="mt-8 flex gap-3">
+ <Button
+ text="Cancel request"
+ variant="secondary"
+ loading={isCanceling}
+ disabled={isPending}
+ className="flex-1"
+ onClick={() => cancelEmailChange({ token })}
+ />
+ <Button
+ text="Confirm change"
+ loading={isConfirming || confirmed}
+ disabled={isPending}
+ className="flex-1"
+ onClick={() => confirmEmailChange({ token })}
+ />
+ </div>
+ </div>
);
}
diff --git a/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page.tsx b/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page.tsx
index c7530b1453..7c1f729cb3 100644
--- a/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page.tsx
+++ b/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page.tsx
@@ -1,14 +1,14 @@
import { getSession, hashToken } from "@/lib/auth";
-import { hasPermission } from "@/lib/auth/partner-users/partner-user-permissions";
-import { syncPlainCustomerEmail } from "@/lib/plain/upsert-plain-customer";
+import {
+ assertCanConfirmEmailChange,
+ deleteEmailChangeRequest,
+ EmailChangeRequestData,
+} from "@/lib/auth/confirm-email-change";
import { prisma } from "@/lib/prisma";
import { redis } from "@/lib/upstash";
+import { AuthLayout } from "@/ui/layout/auth-layout";
import EmptyState from "@/ui/shared/empty-state";
-import { sendEmail } from "@dub/email";
-import EmailUpdated from "@dub/email/templates/email-updated";
import { InputPassword, LoadingSpinner } from "@dub/ui";
-import { VerificationToken } from "@prisma/client";
-import { waitUntil } from "@vercel/functions";
import { redirect } from "next/navigation";
import { Suspense } from "react";
import ConfirmEmailChangePageClient from "./page-client";
@@ -20,19 +20,17 @@ interface PageProps {
export default async function ConfirmEmailChangePage(props: PageProps) {
return (
- <div className="flex flex-col items-center justify-center gap-6 text-center">
- <Suspense
- fallback={
- <EmptyState
- icon={LoadingSpinner}
- title="Verifying Email Change"
- description="Verifying your email change request. This might take a few seconds..."
- />
- }
- >
- <VerifyEmailChange {...props} />
- </Suspense>
- </div>
+ <Suspense
+ fallback={
+ <EmptyState
+ icon={LoadingSpinner}
+ title="Verifying Email Change"
+ description="Verifying your email change request. This might take a few seconds..."
+ />
+ }
+ >
+ <VerifyEmailChange {...props} />
+ </Suspense>
);
}
@@ -43,6 +41,11 @@ const VerifyEmailChange = async ({ params, searchParams }: PageProps) => {
where: {
token: await hashToken(token, { secret: true }),
},
+ select: {
+ token: true,
+ expires: true,
+ identifier: true,
+ },
});
if (!tokenFound || tokenFound.expires < new Date()) {
@@ -59,7 +62,7 @@ const VerifyEmailChange = async ({ params, searchParams }: PageProps) => {
const { cancel } = await searchParams;
if (cancel && cancel === "true") {
- await deleteRequest(tokenFound);
+ await deleteEmailChangeRequest(token);
return (
<EmptyState
@@ -70,40 +73,17 @@ const VerifyEmailChange = async ({ params, searchParams }: PageProps) => {
);
}
- // Process the email change request
const session = await getSession();
if (!session) {
redirect(`/login?next=/auth/confirm-email-change/${token}`);
}
- const { id: userId } = session.user;
- const tokenIdentifier = tokenFound.identifier;
-
- if (tokenIdentifier.startsWith("pn_")) {
- const partnerUser = await prisma.partnerUser.findUnique({
- where: {
- userId_partnerId: {
- userId,
- partnerId: tokenIdentifier,
- },
- },
- select: { role: true },
- });
+ const data = await redis.get<EmailChangeRequestData>(
+ `email-change-request:token:${tokenFound.token}`,
+ );
- if (
- !partnerUser ||
- !hasPermission(partnerUser.role, "partner_profile.update")
- ) {
- return (
- <EmptyState
- icon={InputPassword}
- title="Invalid Token"
- description="This token is invalid. Please request a new one."
- />
- );
- }
- } else if (tokenIdentifier !== userId) {
+ if (!data) {
return (
<EmptyState
icon={InputPassword}
@@ -113,152 +93,34 @@ const VerifyEmailChange = async ({ params, searchParams }: PageProps) => {
);
}
- const data = await redis.get<{
- email: string;
- newEmail: string;
- isPartnerProfile?: boolean;
- syncIdentity?: boolean;
- partnerId?: string;
- redirectTo?: "/profile" | "/account/settings";
- }>(`email-change-request:token:${tokenFound.token}`);
+ try {
+ await assertCanConfirmEmailChange({
+ userId: session.user.id,
+ tokenFound,
+ data,
+ });
+ } catch (error) {
+ const message =
+ error instanceof Error
+ ? error.message
+ : "This token is invalid. Please request a new one.";
- if (!data) {
return (
<EmptyState
icon={InputPassword}
- title="Invalid Token"
- description="This token is invalid. Please request a new one."
+ title={message.includes("access") ? "Unauthorized" : "Invalid Token"}
+ description={message}
/>
);
}
- if (data.syncIdentity) {
- const syncedPartnerId = data.partnerId;
-
- if (!syncedPartnerId) {
- return (
- <EmptyState
- icon={InputPassword}
- title="Invalid Token"
- description="This token is invalid. Please request a new one."
- />
- );
- }
-
- const partnerUser = await prisma.partnerUser.findUnique({
- where: {
- userId_partnerId: {
- userId,
- partnerId: syncedPartnerId,
- },
- },
- select: { role: true },
- });
-
- if (
- !partnerUser ||
- !hasPermission(partnerUser.role, "partner_profile.update")
- ) {
- return (
- <EmptyState
- icon={InputPassword}
- title="Unauthorized"
- description="You don't have access to update the partner profile associated with this email change request."
- />
- );
- }
-
- await prisma.$transaction([
- prisma.user.update({
- where: {
- id: userId,
- },
- data: {
- email: data.newEmail,
- },
- }),
- prisma.partner.update({
- where: {
- id: syncedPartnerId,
- },
- data: {
- email: data.newEmail,
- },
- }),
- ]);
- }
-
- // Update the partner profile email
- else if (data.isPartnerProfile) {
- await prisma.partner.update({
- where: {
- id: tokenIdentifier,
- },
- data: {
- email: data.newEmail,
- },
- });
- }
-
- // Update the user email
- else {
- await prisma.user.update({
- where: {
- id: userId,
- },
- data: {
- email: data.newEmail,
- },
- });
- }
-
- const shouldSyncPlainCustomerEmail =
- !!data.syncIdentity || !data.isPartnerProfile;
-
- waitUntil(
- Promise.allSettled([
- deleteRequest(tokenFound),
-
- sendEmail({
- subject: "Your email address has been changed",
- to: data.email,
- react: EmailUpdated({
- oldEmail: data.email,
- newEmail: data.newEmail,
- isPartnerProfile: !!data.isPartnerProfile,
- syncIdentity: !!data.syncIdentity,
- }),
- }),
-
- ...(shouldSyncPlainCustomerEmail
- ? [
- syncPlainCustomerEmail({
- id: userId,
- name: session.user.name ?? null,
- email: data.newEmail,
- oldEmail: data.email,
- }),
- ]
- : []),
- ]),
- );
-
return (
- <ConfirmEmailChangePageClient
- isPartnerProfile={!!data.isPartnerProfile}
- redirectTo={data.redirectTo}
- />
+ <AuthLayout>
+ <ConfirmEmailChangePageClient
+ token={token}
+ email={data.email}
+ newEmail={data.newEmail}
+ />
+ </AuthLayout>
);
};
-
-const deleteRequest = async (tokenFound: VerificationToken) => {
- await Promise.allSettled([
- prisma.verificationToken.delete({
- where: {
- token: tokenFound.token,
- },
- }),
-
- redis.del(`email-change-request:token:${tokenFound.token}`),
- ]);
-};
diff --git a/apps/web/lib/actions/cancel-email-change.ts b/apps/web/lib/actions/cancel-email-change.ts
new file mode 100644
index 0000000000..08999ae05e
--- /dev/null
+++ b/apps/web/lib/actions/cancel-email-change.ts
@@ -0,0 +1,21 @@
+"use server";
+
+import { deleteEmailChangeRequest } from "@/lib/auth/confirm-email-change";
+import { flattenValidationErrors } from "next-safe-action";
+import * as z from "zod/v4";
+import { actionClient } from "./safe-action";
+
+const cancelEmailChangeSchema = z.object({
+ token: z.string().min(1),
+});
+
+export const cancelEmailChangeAction = actionClient
+ .inputSchema(cancelEmailChangeSchema, {
+ handleValidationErrorsShape: async (ve) =>
+ flattenValidationErrors(ve).fieldErrors,
+ })
+ .action(async ({ parsedInput }) => {
+ const { token } = parsedInput;
+
+ await deleteEmailChangeRequest(token);
+ });
diff --git a/apps/web/lib/actions/confirm-email-change.ts b/apps/web/lib/actions/confirm-email-change.ts
new file mode 100644
index 0000000000..48fecef3e7
--- /dev/null
+++ b/apps/web/lib/actions/confirm-email-change.ts
@@ -0,0 +1,164 @@
+"use server";
+
+import { hashToken } from "@/lib/auth";
+import {
+ assertCanConfirmEmailChange,
+ EmailChangeRequestData,
+} from "@/lib/auth/confirm-email-change";
+import { syncPlainCustomerEmail } from "@/lib/plain/upsert-plain-customer";
+import { prisma } from "@/lib/prisma";
+import { redis } from "@/lib/upstash";
+import { sendEmail } from "@dub/email";
+import EmailUpdated from "@dub/email/templates/email-updated";
+import { waitUntil } from "@vercel/functions";
+import { flattenValidationErrors } from "next-safe-action";
+import * as z from "zod/v4";
+import { authUserActionClient } from "./safe-action";
+
+const confirmEmailChangeSchema = z.object({
+ token: z.string().min(1),
+});
+
+export const confirmEmailChangeAction = authUserActionClient
+ .inputSchema(confirmEmailChangeSchema, {
+ handleValidationErrorsShape: async (ve) =>
+ flattenValidationErrors(ve).fieldErrors,
+ })
+ .action(async ({ parsedInput, ctx }) => {
+ const { token } = parsedInput;
+ const { user } = ctx;
+
+ const tokenFound = await prisma.verificationToken.findUnique({
+ where: {
+ token: await hashToken(token, { secret: true }),
+ },
+ select: {
+ identifier: true,
+ token: true,
+ expires: true,
+ },
+ });
+
+ if (!tokenFound || tokenFound.expires < new Date()) {
+ throw new Error(
+ "This token is invalid or expired. Please request a new one.",
+ );
+ }
+
+ const data = await redis.get<EmailChangeRequestData>(
+ `email-change-request:token:${tokenFound.token}`,
+ );
+
+ if (!data) {
+ throw new Error(
+ "This token is invalid or expired. Please request a new one.",
+ );
+ }
+
+ await assertCanConfirmEmailChange({
+ userId: user.id,
+ tokenFound,
+ data,
+ });
+
+ // Consume the token before mutating so concurrent confirms fail closed
+ const deleted = await prisma.verificationToken.deleteMany({
+ where: {
+ token: tokenFound.token,
+ expires: {
+ gte: new Date(),
+ },
+ },
+ });
+
+ if (deleted.count !== 1) {
+ throw new Error(
+ "This token is invalid or expired. Please request a new one.",
+ );
+ }
+
+ const tokenIdentifier = tokenFound.identifier;
+
+ // Sync identity: Sync the email to the partner profile
+ if (data.syncIdentity) {
+ await prisma.$transaction([
+ prisma.user.update({
+ where: {
+ id: user.id,
+ },
+ data: {
+ email: data.newEmail,
+ },
+ }),
+
+ prisma.partner.update({
+ where: {
+ id: data.partnerId!,
+ },
+ data: {
+ email: data.newEmail,
+ },
+ }),
+ ]);
+ }
+
+ // Update the partner profile email
+ else if (data.isPartnerProfile) {
+ await prisma.partner.update({
+ where: {
+ id: tokenIdentifier,
+ },
+ data: {
+ email: data.newEmail,
+ },
+ });
+ }
+
+ // Update the user email
+ else {
+ await prisma.user.update({
+ where: {
+ id: user.id,
+ },
+ data: {
+ email: data.newEmail,
+ },
+ });
+ }
+
+ const shouldSyncPlainCustomerEmail =
+ !!data.syncIdentity || !data.isPartnerProfile;
+
+ waitUntil(
+ Promise.allSettled([
+ sendEmail({
+ subject: "Your email address has been changed",
+ to: data.email,
+ react: EmailUpdated({
+ oldEmail: data.email,
+ newEmail: data.newEmail,
+ isPartnerProfile: !!data.isPartnerProfile,
+ syncIdentity: !!data.syncIdentity,
+ }),
+ }),
+
+ ...(shouldSyncPlainCustomerEmail
+ ? [
+ syncPlainCustomerEmail({
+ id: user.id,
+ name: user.name ?? null,
+ email: data.newEmail,
+ oldEmail: data.email,
+ }),
+ ]
+ : []),
+
+ redis.del(`email-change-request:token:${tokenFound.token}`),
+ ]),
+ );
+
+ return {
+ isPartnerProfile: !!data.isPartnerProfile,
+ redirectTo: data.redirectTo,
+ };
+ });
diff --git a/apps/web/lib/auth/confirm-email-change.ts b/apps/web/lib/auth/confirm-email-change.ts
new file mode 100644
index 0000000000..1488eefcce
--- /dev/null
+++ b/apps/web/lib/auth/confirm-email-change.ts
@@ -0,0 +1,90 @@
+import { prisma } from "@/lib/prisma";
+import { redis } from "@/lib/upstash";
+import { VerificationToken } from "@prisma/client";
+import { hashToken } from "./hash-token";
+import { hasPermission } from "./partner-users/partner-user-permissions";
+
+export type EmailChangeRequestData = {
+ email: string;
+ newEmail: string;
+ isPartnerProfile?: boolean;
+ syncIdentity?: boolean;
+ partnerId?: string;
+ redirectTo?: "/profile" | "/account/settings";
+};
+
+export async function deleteEmailChangeRequest(token: string) {
+ const hashedToken = await hashToken(token, { secret: true });
+
+ try {
+ await Promise.allSettled([
+ prisma.verificationToken.delete({
+ where: {
+ token: hashedToken,
+ },
+ }),
+
+ redis.del(`email-change-request:token:${hashedToken}`),
+ ]);
+ } catch {}
+}
+
+export async function assertCanConfirmEmailChange({
+ userId,
+ tokenFound,
+ data,
+}: {
+ userId: string;
+ tokenFound: Pick<VerificationToken, "identifier">;
+ data: EmailChangeRequestData;
+}) {
+ if (tokenFound.identifier.startsWith("pn_")) {
+ const partnerUser = await prisma.partnerUser.findUnique({
+ where: {
+ userId_partnerId: {
+ userId,
+ partnerId: tokenFound.identifier,
+ },
+ },
+ select: {
+ role: true,
+ },
+ });
+
+ if (
+ !partnerUser ||
+ !hasPermission(partnerUser.role, "partner_profile.update")
+ ) {
+ throw new Error("This token is invalid. Please request a new one.");
+ }
+ } else if (tokenFound.identifier !== userId) {
+ throw new Error("This token is invalid. Please request a new one.");
+ }
+
+ if (data.syncIdentity) {
+ if (!data.partnerId) {
+ throw new Error("This token is invalid. Please request a new one.");
+ }
+
+ const partnerUser = await prisma.partnerUser.findUnique({
+ where: {
+ userId_partnerId: {
+ userId,
+ partnerId: data.partnerId,
+ },
+ },
+ select: {
+ role: true,
+ },
+ });
+
+ if (
+ !partnerUser ||
+ !hasPermission(partnerUser.role, "partner_profile.update")
+ ) {
+ throw new Error(
+ "You don't have access to update the partner profile associated with this email change request.",
+ );
+ }
+ }
+}
diff --git a/apps/web/lib/auth/request-email-change.ts b/apps/web/lib/auth/request-email-change.ts
index cb34a443e1..63388a546d 100644
--- a/apps/web/lib/auth/request-email-change.ts
+++ b/apps/web/lib/auth/request-email-change.ts
@@ -67,7 +67,7 @@ export const requestEmailChange = async ({
const token = randomBytes(32).toString("hex");
const hashedToken = await hashToken(token, { secret: true });
- const expiresIn = 15 * 60 * 1000;
+ const expiresIn = 60 * 60 * 1000; // 1 hour
// Create a new verification token
await prisma.verificationToken.create({