A full-featured CRM built with React, shadcn/ui, and Supabase.
Guard secondary emails against duplicates and malformed input
Jeromefcf5ad63cd09
diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.ts b/src/components/atomic-crm/providers/supabase/dataProvider.tsindex 374c7083..c2edd1e5 100644--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts@@ -167,8 +167,17 @@ const getDataProviderWithCustomMethods = () => {});if (!updatedData || error) {- console.error("salesCreate.error", error);- throw new Error("Failed to update account manager");+ console.error("salesUpdate.error", error);+ const errorDetails = await (async () => {+ try {+ return (await error?.context?.json()) ?? {};+ } catch {+ return {};+ }+ })();+ throw new Error(+ errorDetails?.message || "Failed to update account manager",+ );}return updatedData.data;diff --git a/supabase/functions/postmark/addNoteToContact.test.ts b/supabase/functions/postmark/addNoteToContact.test.tsindex e63ea199..a9bade91 100644--- a/supabase/functions/postmark/addNoteToContact.test.ts+++ b/supabase/functions/postmark/addNoteToContact.test.ts@@ -379,6 +379,38 @@ describe("addNoteToContact", () => {);});+ it("lowercases the sender, since the jsonb lookup is case sensitive unlike the citext column", async () => {+ const salesRecord = {+ id: 1,+ email: "[email protected]",+ secondary_emails: ["[email protected]"],+ };+ const eq = vi.fn().mockReturnValue({+ neq: () => ({+ maybeSingle: () => Promise.resolve({ data: null, error: null }),+ }),+ });+ const contains = vi.fn().mockReturnValue({+ neq: () => ({+ maybeSingle: () =>+ Promise.resolve({ data: salesRecord, error: null }),+ }),+ });++ mockFrom+ .mockReturnValueOnce({ select: () => ({ eq }) })+ .mockReturnValueOnce({ select: () => ({ contains }) });++ const result = await findActiveSaleByEmail(" [email protected] ");++ expect(eq).toHaveBeenCalledWith("email", "[email protected]");+ expect(contains).toHaveBeenCalledWith(+ "secondary_emails",+ '["[email protected]"]',+ );+ expect(result.data).toEqual(salesRecord);+ });+it("does not look up the secondary emails when the first query fails", async () => {mockFrom.mockReturnValueOnce({select: () => ({diff --git a/supabase/functions/postmark/addNoteToContact.ts b/supabase/functions/postmark/addNoteToContact.tsindex a5615f57..d24b7457 100644--- a/supabase/functions/postmark/addNoteToContact.ts+++ b/supabase/functions/postmark/addNoteToContact.ts@@ -111,10 +111,12 @@ export const getOrCreateContactFromEmailInfo = async ({};export const findActiveSaleByEmail = async (salesEmail: string) => {+ const normalizedEmail = salesEmail.trim().toLowerCase();+const byPrimaryEmail = await supabaseAdmin.from("sales").select("*")- .eq("email", salesEmail)+ .eq("email", normalizedEmail).neq("disabled", true).maybeSingle();@@ -125,7 +127,7 @@ export const findActiveSaleByEmail = async (salesEmail: string) => {return await supabaseAdmin.from("sales").select("*")- .contains("secondary_emails", JSON.stringify([salesEmail]))+ .contains("secondary_emails", JSON.stringify([normalizedEmail])).neq("disabled", true).maybeSingle();};diff --git a/supabase/functions/users/index.ts b/supabase/functions/users/index.tsindex 9c666653..9eff2ff6 100644--- a/supabase/functions/users/index.ts+++ b/supabase/functions/users/index.ts@@ -4,7 +4,11 @@ import { corsHeaders, OptionsMiddleware } from "../_shared/cors.ts";import { createErrorResponse } from "../_shared/utils.ts";import { AuthMiddleware, UserMiddleware } from "../_shared/authentication.ts";import { getUserSale } from "../_shared/getUserSale.ts";-import { normalizeSecondaryEmails } from "./normalizeSecondaryEmails.ts";+import {+ findInvalidEmail,+ findTakenEmail,+ normalizeSecondaryEmails,+} from "./secondaryEmails.ts";async function updateSaleDisabled(user_id: string, disabled: boolean) {return await supabaseAdmin@@ -53,13 +57,34 @@ async function createSale(return sales.at(0);}+async function findSecondaryEmailUsedByAnotherSale(+ sales_id: number,+ secondary_emails: string[],+) {+ if (!secondary_emails.length) {+ return undefined;+ }++ const { data: otherSales, error: salesError } = await supabaseAdmin+ .from("sales")+ .select("email, secondary_emails")+ .neq("id", sales_id);++ if (salesError) {+ console.error("Error fetching sales:", salesError);+ throw salesError;+ }++ return findTakenEmail(otherSales ?? [], secondary_emails);+}+async function updateSaleSecondaryEmails(user_id: string,- secondary_emails: unknown,+ secondary_emails: string[],) {const { error: salesError } = await supabaseAdmin.from("sales")- .update({ secondary_emails: normalizeSecondaryEmails(secondary_emails) })+ .update({ secondary_emails }).eq("user_id", user_id);if (salesError) {@@ -220,6 +245,30 @@ async function patchUser(req: Request, currentUserSale: any) {return createErrorResponse(401, "Not Authorized");}+ let normalizedSecondaryEmails: string[] | undefined;+ if (secondary_emails !== undefined) {+ normalizedSecondaryEmails = normalizeSecondaryEmails(secondary_emails);++ const invalidEmail = findInvalidEmail(normalizedSecondaryEmails);+ if (invalidEmail) {+ return createErrorResponse(+ 400,+ `Invalid secondary email: ${invalidEmail}`,+ );+ }++ const takenEmail = await findSecondaryEmailUsedByAnotherSale(+ sales_id,+ normalizedSecondaryEmails,+ );+ if (takenEmail) {+ return createErrorResponse(+ 409,+ `Secondary email already used by another user: ${takenEmail}`,+ );+ }+ }+const { data, error: userError } =await supabaseAdmin.auth.admin.updateUserById(sale.user_id, {email,@@ -236,8 +285,8 @@ async function patchUser(req: Request, currentUserSale: any) {await updateSaleAvatar(data.user.id, avatar);}- if (secondary_emails !== undefined) {- await updateSaleSecondaryEmails(data.user.id, secondary_emails);+ if (normalizedSecondaryEmails) {+ await updateSaleSecondaryEmails(data.user.id, normalizedSecondaryEmails);}// Only administrators can update the administrator and disabled statusdiff --git a/supabase/functions/users/normalizeSecondaryEmails.test.ts b/supabase/functions/users/normalizeSecondaryEmails.test.tsdeleted file mode 100644index 8f2f2599..00000000--- a/supabase/functions/users/normalizeSecondaryEmails.test.ts+++ /dev/null@@ -1,35 +0,0 @@-// @vitest-environment node-import { describe, it, expect } from "vitest";-import { normalizeSecondaryEmails } from "./normalizeSecondaryEmails";--describe("normalizeSecondaryEmails", () => {- it("returns an empty array when the value is not an array", () => {- expect(normalizeSecondaryEmails(undefined)).toEqual([]);- expect(normalizeSecondaryEmails(null)).toEqual([]);- expect(normalizeSecondaryEmails("[email protected]")).toEqual([]);- });-- it("trims and lowercases every address", () => {- expect(normalizeSecondaryEmails([" [email protected] "])).toEqual([- "[email protected]",- ]);- });-- it("removes addresses that differ only by case or spacing", () => {- expect(- normalizeSecondaryEmails(["[email protected]", " [email protected] "]),- ).toEqual(["[email protected]"]);- });-- it("drops empty entries and non-string values", () => {- expect(- normalizeSecondaryEmails(["[email protected]", "", " ", 42, null]),- ).toEqual(["[email protected]"]);- });-- it("preserves the order of the remaining addresses", () => {- expect(- });-});diff --git a/supabase/functions/users/normalizeSecondaryEmails.ts b/supabase/functions/users/normalizeSecondaryEmails.tsdeleted file mode 100644index 7b7360ae..00000000--- a/supabase/functions/users/normalizeSecondaryEmails.ts+++ /dev/null@@ -1,15 +0,0 @@-export const normalizeSecondaryEmails = (- secondaryEmails: unknown,-): string[] => {- if (!Array.isArray(secondaryEmails)) {- return [];- }- return [- ...new Set(- secondaryEmails- .filter((email): email is string => typeof email === "string")- .map((email) => email.trim().toLowerCase())- .filter(Boolean),- ),- ];-};diff --git a/supabase/functions/users/secondaryEmails.test.ts b/supabase/functions/users/secondaryEmails.test.tsnew file mode 100644index 00000000..562f8944--- /dev/null+++ b/supabase/functions/users/secondaryEmails.test.ts@@ -0,0 +1,105 @@+// @vitest-environment node+import { describe, it, expect } from "vitest";+import {+ findInvalidEmail,+ findTakenEmail,+ normalizeSecondaryEmails,+} from "./secondaryEmails";++describe("normalizeSecondaryEmails", () => {+ it("returns an empty array when the value is not an array", () => {+ expect(normalizeSecondaryEmails(undefined)).toEqual([]);+ expect(normalizeSecondaryEmails(null)).toEqual([]);+ expect(normalizeSecondaryEmails("[email protected]")).toEqual([]);+ });++ it("trims and lowercases every address", () => {+ expect(normalizeSecondaryEmails([" [email protected] "])).toEqual([+ "[email protected]",+ ]);+ });++ it("removes addresses that differ only by case or spacing", () => {+ expect(+ normalizeSecondaryEmails(["[email protected]", " [email protected] "]),+ ).toEqual(["[email protected]"]);+ });++ it("drops empty entries and non-string values", () => {+ expect(+ normalizeSecondaryEmails(["[email protected]", "", " ", 42, null]),+ ).toEqual(["[email protected]"]);+ });++ it("preserves the order of the remaining addresses", () => {+ expect(+ });+});++describe("findInvalidEmail", () => {+ it("returns undefined when every address is well formed", () => {+ expect(+ findInvalidEmail(["[email protected]", "[email protected]"]),+ ).toBe(undefined);+ });++ it("returns undefined for an empty list", () => {+ expect(findInvalidEmail([])).toBe(undefined);+ });++ it("reports an address with no domain", () => {+ expect(findInvalidEmail(["[email protected]", "not-an-email"])).toBe(+ "not-an-email",+ );+ });++ it("reports an address with no top level domain", () => {+ expect(findInvalidEmail(["john@localhost"])).toBe("john@localhost");+ });++ it("reports an address containing a space", () => {+ expect(findInvalidEmail(["john [email protected]"])).toBe("john [email protected]");+ });++ it("reports the first offending address so the caller can name it", () => {+ expect(findInvalidEmail(["bad-one", "bad-two"])).toBe("bad-one");+ });+});++describe("findTakenEmail", () => {+ const otherSales = [+ { email: "[email protected]", secondary_emails: ["[email protected]"] },+ { email: "[email protected]", secondary_emails: null },+ ];++ it("returns undefined when no address is used by another sale", () => {+ expect(findTakenEmail(otherSales, ["[email protected]"])).toBe(undefined);+ });++ it("reports an address already used as another sale's secondary email", () => {+ expect(findTakenEmail(otherSales, ["[email protected]"])).toBe(+ "[email protected]",+ );+ });++ it("reports an address already used as another sale's primary email", () => {+ expect(findTakenEmail(otherSales, ["[email protected]"])).toBe(+ "[email protected]",+ );+ });++ it("matches regardless of the case stored in the other sale", () => {+ expect(+ findTakenEmail(+ [{ email: "[email protected]", secondary_emails: null }],+ ["[email protected]"],+ ),+ ).toBe("[email protected]");+ });++ it("returns undefined when there is no other sale", () => {+ expect(findTakenEmail([], ["[email protected]"])).toBe(undefined);+ });+});diff --git a/supabase/functions/users/secondaryEmails.ts b/supabase/functions/users/secondaryEmails.tsnew file mode 100644index 00000000..f041bf1d--- /dev/null+++ b/supabase/functions/users/secondaryEmails.ts@@ -0,0 +1,32 @@+const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;++export const normalizeSecondaryEmails = (+ secondaryEmails: unknown,+): string[] => {+ if (!Array.isArray(secondaryEmails)) {+ return [];+ }+ return [+ ...new Set(+ secondaryEmails+ .filter((email): email is string => typeof email === "string")+ .map((email) => email.trim().toLowerCase())+ .filter(Boolean),+ ),+ ];+};++export const findInvalidEmail = (emails: string[]): string | undefined =>+ emails.find((email) => !EMAIL_PATTERN.test(email));++export const findTakenEmail = (+ otherSales: { email: string; secondary_emails: string[] | null }[],+ emails: string[],+): string | undefined => {+ const takenEmails = new Set(+ otherSales+ .flatMap((sale) => [sale.email, ...(sale.secondary_emails ?? [])])+ .map((email) => email.toLowerCase()),+ );+ return emails.find((email) => takenEmails.has(email));+};