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.

Allow partners to change email to consumer inboxes (#4338)

Kiran Kfe4b7aaab2df
diff --git a/apps/web/lib/actions/send-otp.ts b/apps/web/lib/actions/send-otp.ts
index 82521a87c1..52652e4d22 100644
--- a/apps/web/lib/actions/send-otp.ts
+++ b/apps/web/lib/actions/send-otp.ts
@@ -1,7 +1,7 @@
"use server";
import { getIP } from "@/lib/api/utils/get-ip";
-import { isEmailDomainBlocked } from "@/lib/email/is-email-domain-blocked";
+import { getEmailDomainBlockFlags } from "@/lib/email/get-email-domain-block-flags";
import { prisma } from "@/lib/prisma";
import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
@@ -36,7 +36,10 @@ export const sendOtpAction = actionClient
identifier: [email, await getIP()],
});
- const emailDomainBlocked = await isEmailDomainBlocked(email);
+ const { isDisposable, matchesBlockedTerms } =
+ await getEmailDomainBlockFlags(email);
+
+ const emailDomainBlocked = isDisposable || matchesBlockedTerms;
// if any of the flags match, run one final edge case check, before throwing an error
if (isGenericEmail(email) || emailDomainBlocked) {
diff --git a/apps/web/lib/auth/request-email-change.ts b/apps/web/lib/auth/request-email-change.ts
index 579e2fdaf9..f7e91b261c 100644
--- a/apps/web/lib/auth/request-email-change.ts
+++ b/apps/web/lib/auth/request-email-change.ts
@@ -5,8 +5,7 @@ import { waitUntil } from "@vercel/functions";
import { randomBytes } from "crypto";
import { hashToken } from ".";
import { DubApiError } from "../api/errors";
-import { isEmailDomainBlocked } from "../email/is-email-domain-blocked";
-import { isGenericEmail } from "../email/is-generic-email";
+import { canChangeEmail } from "../email/can-change-email";
import { redis } from "../upstash";
import { assertRateLimit } from "../upstash/assert-rate-limit";
import { RATELIMIT_POLICIES } from "../upstash/ratelimit-policies";
@@ -46,12 +45,19 @@ export const requestEmailChange = async ({
policy: RATELIMIT_POLICIES.emailChangeRequest,
identifier: userId,
});
+
const user = await prisma.user.findUnique({
where: {
id: userId,
},
select: {
createdAt: true,
+ partners: {
+ select: {
+ id: true,
+ },
+ take: 1,
+ },
},
});
@@ -78,9 +84,15 @@ export const requestEmailChange = async ({
identifier: newEmail.toLowerCase(),
});
- const isGenericEmailWithPlus = email.includes("+") && isGenericEmail(email);
- const emailDomainBlocked = await isEmailDomainBlocked(newEmail);
- if (isGenericEmailWithPlus || emailDomainBlocked) {
+ const hasPartnerAccount = user.partners.length > 0;
+
+ const allowEmailChange = await canChangeEmail({
+ currentEmail: email,
+ newEmail,
+ hasPartnerAccount,
+ });
+
+ if (!allowEmailChange) {
throw new DubApiError({
code: "bad_request",
message:
diff --git a/apps/web/lib/email/can-change-email.ts b/apps/web/lib/email/can-change-email.ts
new file mode 100644
index 0000000000..ad280459c7
--- /dev/null
+++ b/apps/web/lib/email/can-change-email.ts
@@ -0,0 +1,44 @@
+import { getEmailDomainBlockFlags } from "./get-email-domain-block-flags";
+import { isGenericEmail } from "./is-generic-email";
+
+/**
+ * Disposable domains are always rejected.
+ * - Users with a partner account: consumer inboxes (gmail, outlook, etc.) are
+ * allowed even if they match emailDomainTerms; other blocked terms still
+ * apply; no +alias lock.
+ * - Users without a partner account: blocked terms apply; generic current
+ * emails with + are locked.
+ */
+export async function canChangeEmail({
+ currentEmail,
+ newEmail,
+ hasPartnerAccount,
+}: {
+ currentEmail: string;
+ newEmail: string;
+ hasPartnerAccount: boolean;
+}): Promise<boolean> {
+ const { isDisposable, matchesBlockedTerms } =
+ await getEmailDomainBlockFlags(newEmail);
+
+ if (isDisposable) {
+ return false;
+ }
+
+ if (hasPartnerAccount) {
+ if (isGenericEmail(newEmail)) {
+ return true;
+ }
+
+ return !matchesBlockedTerms;
+ }
+
+ const isGenericEmailWithPlus =
+ currentEmail.includes("+") && isGenericEmail(currentEmail);
+
+ if (isGenericEmailWithPlus) {
+ return false;
+ }
+
+ return !matchesBlockedTerms;
+}
diff --git a/apps/web/lib/email/get-email-domain-block-flags.ts b/apps/web/lib/email/get-email-domain-block-flags.ts
new file mode 100644
index 0000000000..175f245b58
--- /dev/null
+++ b/apps/web/lib/email/get-email-domain-block-flags.ts
@@ -0,0 +1,50 @@
+import { redis } from "@/lib/upstash";
+import { get } from "@vercel/edge-config";
+import { extractEmailDomain } from "./extract-email-domain";
+
+type EmailDomainBlockFlags = {
+ isDisposable: boolean;
+ matchesBlockedTerms: boolean;
+};
+
+/**
+ * Returns whether the email's domain is in Redis disposableEmailDomains
+ * and/or matches Edge Config emailDomainTerms (substring regex).
+ */
+export async function getEmailDomainBlockFlags(
+ email: string,
+): Promise<EmailDomainBlockFlags> {
+ const emailDomain = extractEmailDomain(email);
+ if (!emailDomain) {
+ return {
+ isDisposable: false,
+ matchesBlockedTerms: false,
+ };
+ }
+
+ const [isDisposable, emailDomainTerms] = await Promise.all([
+ redis.sismember("disposableEmailDomains", emailDomain),
+ process.env.EDGE_CONFIG ? get("emailDomainTerms") : [],
+ ]);
+
+ const blockedTerms = Array.isArray(emailDomainTerms)
+ ? (emailDomainTerms as unknown[])
+ .map((term) =>
+ String(term)
+ .trim()
+ .toLowerCase()
+ .replace(/[.*+?^${}()|[\]\\]/g, "\\$&"),
+ )
+ .filter((term) => term.length > 0)
+ : [];
+
+ const matchesBlockedTerms =
+ blockedTerms.length > 0
+ ? new RegExp(blockedTerms.join("|")).test(emailDomain)
+ : false;
+
+ return {
+ isDisposable: Boolean(isDisposable),
+ matchesBlockedTerms,
+ };
+}
diff --git a/apps/web/lib/email/is-email-domain-blocked.ts b/apps/web/lib/email/is-email-domain-blocked.ts
deleted file mode 100644
index e7951ac856..0000000000
--- a/apps/web/lib/email/is-email-domain-blocked.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { redis } from "@/lib/upstash";
-import { get } from "@vercel/edge-config";
-import { extractEmailDomain } from "./extract-email-domain";
-
-/**
- * True when the email's domain is in Redis disposableEmailDomains
- * or matches Edge Config emailDomainTerms (substring regex).
- */
-export async function isEmailDomainBlocked(email: string): Promise<boolean> {
- const emailDomain = extractEmailDomain(email);
- if (!emailDomain) {
- return false;
- }
-
- const [isDisposable, emailDomainTerms] = await Promise.all([
- redis.sismember("disposableEmailDomains", emailDomain),
- process.env.EDGE_CONFIG ? get("emailDomainTerms") : [],
- ]);
-
- const escapedDomainTerms =
- emailDomainTerms && Array.isArray(emailDomainTerms)
- ? emailDomainTerms
- .map((term: string) =>
- String(term)
- .trim()
- .toLowerCase()
- .replace(/[.*+?^${}()|[\]\\]/g, "\\$&"),
- )
- .filter((term) => term.length > 0)
- : [];
-
- const blacklistedEmailDomainTermsRegex =
- escapedDomainTerms.length > 0
- ? new RegExp(escapedDomainTerms.join("|"))
- : null;
-
- return Boolean(
- isDisposable ||
- (blacklistedEmailDomainTermsRegex &&
- blacklistedEmailDomainTermsRegex.test(emailDomain)),
- );
-}
diff --git a/apps/web/tests/misc/can-change-email.test.ts b/apps/web/tests/misc/can-change-email.test.ts
new file mode 100644
index 0000000000..5d1006f3ab
--- /dev/null
+++ b/apps/web/tests/misc/can-change-email.test.ts
@@ -0,0 +1,151 @@
+import { canChangeEmail } from "@/lib/email/can-change-email";
+import { getEmailDomainBlockFlags } from "@/lib/email/get-email-domain-block-flags";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/lib/email/get-email-domain-block-flags", () => ({
+ getEmailDomainBlockFlags: vi.fn(),
+}));
+
+const getEmailDomainBlockFlagsMock = vi.mocked(getEmailDomainBlockFlags);
+
+describe("canChangeEmail", () => {
+ beforeEach(() => {
+ getEmailDomainBlockFlagsMock.mockReset();
+ });
+
+ it("always rejects disposable domains", async () => {
+ getEmailDomainBlockFlagsMock.mockResolvedValue({
+ isDisposable: true,
+ matchesBlockedTerms: false,
+ });
+
+ await expect(
+ canChangeEmail({
+ currentEmail: "[email protected]",
+ newEmail: "[email protected]",
+ hasPartnerAccount: true,
+ }),
+ ).resolves.toBe(false);
+
+ await expect(
+ canChangeEmail({
+ currentEmail: "[email protected]",
+ newEmail: "[email protected]",
+ hasPartnerAccount: false,
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it("allows partners to change to consumer inboxes even when terms match", async () => {
+ getEmailDomainBlockFlagsMock.mockResolvedValue({
+ isDisposable: false,
+ matchesBlockedTerms: true,
+ });
+
+ await expect(
+ canChangeEmail({
+ currentEmail: "[email protected]",
+ newEmail: "[email protected]",
+ hasPartnerAccount: true,
+ }),
+ ).resolves.toBe(true);
+
+ await expect(
+ canChangeEmail({
+ currentEmail: "[email protected]",
+ newEmail: "[email protected]",
+ hasPartnerAccount: true,
+ }),
+ ).resolves.toBe(true);
+ });
+
+ it("rejects partners from non-consumer destinations that match terms", async () => {
+ getEmailDomainBlockFlagsMock.mockResolvedValue({
+ isDisposable: false,
+ matchesBlockedTerms: true,
+ });
+
+ await expect(
+ canChangeEmail({
+ currentEmail: "[email protected]",
+ newEmail: "[email protected]",
+ hasPartnerAccount: true,
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it("allows partners to leave a generic + alias", async () => {
+ getEmailDomainBlockFlagsMock.mockResolvedValue({
+ isDisposable: false,
+ matchesBlockedTerms: false,
+ });
+
+ await expect(
+ canChangeEmail({
+ currentEmail: "[email protected]",
+ newEmail: "[email protected]",
+ hasPartnerAccount: true,
+ }),
+ ).resolves.toBe(true);
+ });
+
+ it("allows partners to change to non-consumer destinations that do not match terms", async () => {
+ getEmailDomainBlockFlagsMock.mockResolvedValue({
+ isDisposable: false,
+ matchesBlockedTerms: false,
+ });
+
+ await expect(
+ canChangeEmail({
+ currentEmail: "[email protected]",
+ newEmail: "[email protected]",
+ hasPartnerAccount: true,
+ }),
+ ).resolves.toBe(true);
+ });
+
+ it("rejects non-partners when current email is generic with a + alias", async () => {
+ getEmailDomainBlockFlagsMock.mockResolvedValue({
+ isDisposable: false,
+ matchesBlockedTerms: false,
+ });
+
+ await expect(
+ canChangeEmail({
+ currentEmail: "[email protected]",
+ newEmail: "[email protected]",
+ hasPartnerAccount: false,
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it("rejects non-partners when new email matches blocked terms", async () => {
+ getEmailDomainBlockFlagsMock.mockResolvedValue({
+ isDisposable: false,
+ matchesBlockedTerms: true,
+ });
+
+ await expect(
+ canChangeEmail({
+ currentEmail: "[email protected]",
+ newEmail: "[email protected]",
+ hasPartnerAccount: false,
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it("allows non-partners when neither plus-alias nor terms apply", async () => {
+ getEmailDomainBlockFlagsMock.mockResolvedValue({
+ isDisposable: false,
+ matchesBlockedTerms: false,
+ });
+
+ await expect(
+ canChangeEmail({
+ currentEmail: "[email protected]",
+ newEmail: "[email protected]",
+ hasPartnerAccount: false,
+ }),
+ ).resolves.toBe(true);
+ });
+});