Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Harden secondary email validation and the sale lookup

Jeromee4fa6d05e46e
diff --git a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
index 9260f23d..0b973711 100644
--- a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
@@ -531,7 +531,10 @@ export const englishCrmMessages = {
},
profile: {
add_secondary_email: "Add an email",
+ email_taken: "%{email} is already used by another user",
no_secondary_emails: "None",
+ secondary_email_invalid: "%{email} is not a valid email address",
+ secondary_email_taken: "%{email} is already used by another user",
secondary_emails_help:
"Other addresses you send emails from. Leave one empty to remove it.",
inbound: {
diff --git a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
index 5577df0c..089c82ea 100644
--- a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
@@ -538,7 +538,11 @@ export const frenchCrmMessages = {
},
profile: {
add_secondary_email: "Ajouter un e-mail",
+ email_taken: "%{email} est déjà utilisée par un autre utilisateur",
no_secondary_emails: "Aucun",
+ secondary_email_invalid: "%{email} n'est pas une adresse e-mail valide",
+ secondary_email_taken:
+ "%{email} est déjà utilisée par un autre utilisateur",
secondary_emails_help:
"Autres adresses depuis lesquelles vous envoyez des e-mails. Laissez-en une vide pour la supprimer.",
inbound: {
diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.ts b/src/components/atomic-crm/providers/supabase/dataProvider.ts
index c2edd1e5..2d902856 100644
--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts
+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts
@@ -175,8 +175,11 @@ const getDataProviderWithCustomMethods = () => {
return {};
}
})();
- throw new Error(
- errorDetails?.message || "Failed to update account manager",
+ throw Object.assign(
+ new Error(
+ errorDetails?.message || "Failed to update account manager",
+ ),
+ { code: errorDetails?.code, email: errorDetails?.email },
);
}
diff --git a/src/components/atomic-crm/sales/salesUpdateError.test.ts b/src/components/atomic-crm/sales/salesUpdateError.test.ts
new file mode 100644
index 00000000..94b14e15
--- /dev/null
+++ b/src/components/atomic-crm/sales/salesUpdateError.test.ts
@@ -0,0 +1,53 @@
+import { describe, it, expect } from "vitest";
+import { getSalesUpdateNotification } from "./salesUpdateError";
+
+describe("getSalesUpdateNotification", () => {
+ it("names the address rejected as already taken", () => {
+ expect(
+ getSalesUpdateNotification(
+ Object.assign(new Error("Secondary email already used"), {
+ code: "secondary_email_taken",
+ email: "[email protected]",
+ }),
+ ),
+ ).toEqual({
+ message: "crm.profile.secondary_email_taken",
+ args: { email: "[email protected]" },
+ });
+ });
+
+ it("names the address rejected as malformed", () => {
+ expect(
+ getSalesUpdateNotification(
+ Object.assign(new Error("Invalid secondary email"), {
+ code: "invalid_secondary_email",
+ email: "not-an-email",
+ }),
+ ),
+ ).toEqual({
+ message: "crm.profile.secondary_email_invalid",
+ args: { email: "not-an-email" },
+ });
+ });
+
+ it("falls back to the generic message for an unknown code", () => {
+ expect(
+ getSalesUpdateNotification(
+ Object.assign(new Error("boom"), { code: "something_else" }),
+ ).message,
+ ).toBe("crm.profile.update_error");
+ });
+
+ it("falls back to the generic message for an error carrying no code", () => {
+ expect(getSalesUpdateNotification(new Error("boom")).message).toBe(
+ "crm.profile.update_error",
+ );
+ });
+
+ it("does not throw when there is no error object at all", () => {
+ expect(getSalesUpdateNotification(undefined)).toEqual({
+ message: "crm.profile.update_error",
+ args: { email: "" },
+ });
+ });
+});
diff --git a/src/components/atomic-crm/sales/salesUpdateError.ts b/src/components/atomic-crm/sales/salesUpdateError.ts
new file mode 100644
index 00000000..25b322f6
--- /dev/null
+++ b/src/components/atomic-crm/sales/salesUpdateError.ts
@@ -0,0 +1,23 @@
+export type SalesUpdateNotification = {
+ message: string;
+ args: Record<string, string>;
+};
+
+const MESSAGE_BY_CODE: Record<string, string> = {
+ email_taken: "crm.profile.email_taken",
+ secondary_email_taken: "crm.profile.secondary_email_taken",
+ invalid_secondary_email: "crm.profile.secondary_email_invalid",
+ invalid_secondary_emails_payload: "crm.profile.update_error",
+};
+
+export const getSalesUpdateNotification = (
+ error: unknown,
+): SalesUpdateNotification => {
+ const { code, email } = (error ?? {}) as { code?: string; email?: string };
+ const message = code ? MESSAGE_BY_CODE[code] : undefined;
+
+ return {
+ message: message ?? "crm.profile.update_error",
+ args: { email: email ?? "" },
+ };
+};
diff --git a/src/components/atomic-crm/settings/ProfilePage.tsx b/src/components/atomic-crm/settings/ProfilePage.tsx
index 5cea2177..5f1e8b22 100644
--- a/src/components/atomic-crm/settings/ProfilePage.tsx
+++ b/src/components/atomic-crm/settings/ProfilePage.tsx
@@ -36,6 +36,7 @@ import {
import ImageEditorField from "../misc/ImageEditorField";
import type { CrmDataProvider } from "../providers/types";
+import { getSalesUpdateNotification } from "../sales/salesUpdateError";
import type { Sale, SalesFormData } from "../types";
export const ProfilePage = () => {
@@ -70,12 +71,11 @@ export const ProfilePage = () => {
},
});
},
- onError: (_) => {
- notify("crm.profile.update_error", {
+ onError: (error) => {
+ const { message, args } = getSalesUpdateNotification(error);
+ notify(message, {
type: "error",
- messageArgs: {
- _: "An error occurred. Please try again",
- },
+ messageArgs: { ...args, _: "An error occurred. Please try again" },
});
},
});
diff --git a/src/components/atomic-crm/settings/SettingsPageMobile.tsx b/src/components/atomic-crm/settings/SettingsPageMobile.tsx
index 7e4f2baf..b091a424 100644
--- a/src/components/atomic-crm/settings/SettingsPageMobile.tsx
+++ b/src/components/atomic-crm/settings/SettingsPageMobile.tsx
@@ -21,6 +21,7 @@ import {
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { Check, Copy, LogOut, Moon, Smartphone, Sun } from "lucide-react";
import {
+ email,
Form,
Translate,
useAuthProvider,
@@ -46,6 +47,7 @@ import MobileHeader from "../layout/MobileHeader";
import { ChangelogPage } from "../misc/ChangelogPage";
import ImageEditorField from "../misc/ImageEditorField";
import type { CrmDataProvider } from "../providers/types";
+import { getSalesUpdateNotification } from "../sales/salesUpdateError";
import type { SalesFormData } from "../types";
const ChangePasswordButton = () => {
@@ -175,11 +177,12 @@ const ProfileSection = () => {
notify("crm.profile.updated", {
messageArgs: { _: "Your profile has been updated" },
});
- } catch {
+ } catch (error) {
queryClient.setQueryData(queryKey, previousData);
- notify("crm.profile.update_error", {
+ const { message, args } = getSalesUpdateNotification(error);
+ notify(message, {
type: "error",
- messageArgs: { _: "An error occurred. Please try again" },
+ messageArgs: { ...args, _: "An error occurred. Please try again" },
});
}
},
@@ -272,6 +275,8 @@ const ProfileSection = () => {
);
};
+const validateEmail = email();
+
const SecondaryEmailRows = ({
emails,
onSave,
@@ -280,8 +285,23 @@ const SecondaryEmailRows = ({
onSave: (emails: string[]) => void;
}) => {
const translate = useTranslate();
+ const notify = useNotify();
const label = translate("resources.sales.fields.secondary_email");
+ const saveValidated = useCallback(
+ (value: string, nextEmails: string[]) => {
+ if (value && validateEmail(value, {})) {
+ notify("crm.profile.secondary_email_invalid", {
+ type: "error",
+ messageArgs: { email: value },
+ });
+ return;
+ }
+ onSave(nextEmails);
+ },
+ [notify, onSave],
+ );
+
return (
<>
{emails.map((email, index) => (
@@ -292,7 +312,8 @@ const SecondaryEmailRows = ({
value={email}
type="email"
onSave={(value) =>
- onSave(
+ saveValidated(
+ value,
value
? emails.map((current, i) => (i === index ? value : current))
: emails.filter((_, i) => i !== index),
@@ -307,7 +328,7 @@ const SecondaryEmailRows = ({
label={translate("crm.profile.add_secondary_email")}
value=""
type="email"
- onSave={(value) => onSave([...emails, value])}
+ onSave={(value) => saveValidated(value, [...emails, value])}
/>
</>
);
diff --git a/supabase/functions/postmark/addNoteToContact.test.ts b/supabase/functions/postmark/addNoteToContact.test.ts
index a9bade91..00f8d127 100644
--- a/supabase/functions/postmark/addNoteToContact.test.ts
+++ b/supabase/functions/postmark/addNoteToContact.test.ts
@@ -15,6 +15,24 @@ vi.mock("../_shared/supabaseAdmin.ts", () => ({
},
}));
+const secondaryLookupResult = (rows: unknown[]) => ({
+ neq: () => ({
+ order: () => ({
+ limit: () => Promise.resolve({ data: rows, error: null }),
+ }),
+ }),
+});
+
+const primaryLookupMiss = {
+ select: () => ({
+ eq: () => ({
+ neq: () => ({
+ maybeSingle: () => Promise.resolve({ data: null, error: null }),
+ }),
+ }),
+ }),
+};
+
describe("addNoteToContact", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -351,12 +369,9 @@ describe("addNoteToContact", () => {
secondary_emails: ["[email protected]"],
};
- const contains = vi.fn().mockReturnValue({
- neq: () => ({
- maybeSingle: () =>
- Promise.resolve({ data: salesRecord, error: null }),
- }),
- });
+ const contains = vi
+ .fn()
+ .mockReturnValue(secondaryLookupResult([salesRecord]));
mockFrom
.mockReturnValueOnce({
@@ -379,6 +394,53 @@ describe("addNoteToContact", () => {
);
});
+ it("picks the lowest id instead of failing when two sales share a secondary email", async () => {
+ const firstSale = { id: 3, email: "[email protected]" };
+ const secondSale = { id: 9, email: "[email protected]" };
+
+ mockFrom
+ .mockReturnValueOnce({
+ select: () => ({
+ eq: () => ({
+ neq: () => ({
+ maybeSingle: () => Promise.resolve({ data: null, error: null }),
+ }),
+ }),
+ }),
+ })
+ .mockReturnValueOnce({
+ select: () => ({
+ contains: () => secondaryLookupResult([firstSale, secondSale]),
+ }),
+ });
+
+ const result = await findActiveSaleByEmail("[email protected]");
+
+ expect(result.data).toEqual(firstSale);
+ expect(result.error).toBe(null);
+ });
+
+ it("returns no sale rather than an error when nothing matches", async () => {
+ mockFrom
+ .mockReturnValueOnce({
+ select: () => ({
+ eq: () => ({
+ neq: () => ({
+ maybeSingle: () => Promise.resolve({ data: null, error: null }),
+ }),
+ }),
+ }),
+ })
+ .mockReturnValueOnce({
+ select: () => ({ contains: () => secondaryLookupResult([]) }),
+ });
+
+ const result = await findActiveSaleByEmail("[email protected]");
+
+ expect(result.data).toBe(null);
+ expect(result.error).toBe(null);
+ });
+
it("lowercases the sender, since the jsonb lookup is case sensitive unlike the citext column", async () => {
const salesRecord = {
id: 1,
@@ -390,12 +452,9 @@ describe("addNoteToContact", () => {
maybeSingle: () => Promise.resolve({ data: null, error: null }),
}),
});
- const contains = vi.fn().mockReturnValue({
- neq: () => ({
- maybeSingle: () =>
- Promise.resolve({ data: salesRecord, error: null }),
- }),
- });
+ const contains = vi
+ .fn()
+ .mockReturnValue(secondaryLookupResult([salesRecord]));
mockFrom
.mockReturnValueOnce({ select: () => ({ eq }) })
@@ -505,25 +564,11 @@ describe("addNoteToContact", () => {
const insertNote = vi.fn().mockResolvedValue({ error: null });
mockFrom
- .mockReturnValueOnce({
- // 1st call: fetch sales by primary email → not found
- select: () => ({
- eq: () => ({
- neq: () => ({
- maybeSingle: () => Promise.resolve({ data: null, error: null }),
- }),
- }),
- }),
- })
+ .mockReturnValueOnce(primaryLookupMiss)
.mockReturnValueOnce({
// 2nd call: fetch sales by secondary emails → found
select: () => ({
- contains: () => ({
- neq: () => ({
- maybeSingle: () =>
- Promise.resolve({ data: salesRecord, error: null }),
- }),
- }),
+ contains: () => secondaryLookupResult([salesRecord]),
}),
})
.mockReturnValueOnce({
diff --git a/supabase/functions/postmark/addNoteToContact.ts b/supabase/functions/postmark/addNoteToContact.ts
index d24b7457..1dac8e0e 100644
--- a/supabase/functions/postmark/addNoteToContact.ts
+++ b/supabase/functions/postmark/addNoteToContact.ts
@@ -124,12 +124,18 @@ export const findActiveSaleByEmail = async (salesEmail: string) => {
return byPrimaryEmail;
}
- return await supabaseAdmin
+ const bySecondaryEmail = await supabaseAdmin
.from("sales")
.select("*")
.contains("secondary_emails", JSON.stringify([normalizedEmail]))
.neq("disabled", true)
- .maybeSingle();
+ .order("id", { ascending: true })
+ .limit(1);
+
+ return {
+ data: bySecondaryEmail.data?.[0] ?? null,
+ error: bySecondaryEmail.error,
+ };
};
export const addNoteToContact = async ({
diff --git a/supabase/functions/users/index.ts b/supabase/functions/users/index.ts
index 9eff2ff6..24ca442b 100644
--- a/supabase/functions/users/index.ts
+++ b/supabase/functions/users/index.ts
@@ -57,25 +57,26 @@ async function createSale(
return sales.at(0);
}
-async function findSecondaryEmailUsedByAnotherSale(
- sales_id: number,
- secondary_emails: string[],
+async function findEmailUsedByAnotherSale(
+ emails: string[],
+ excludeSalesId?: number,
) {
- if (!secondary_emails.length) {
+ if (!emails.length) {
return undefined;
}
- const { data: otherSales, error: salesError } = await supabaseAdmin
- .from("sales")
- .select("email, secondary_emails")
- .neq("id", sales_id);
+ const query = supabaseAdmin.from("sales").select("email, secondary_emails");
+ const { data: otherSales, error: salesError } =
+ excludeSalesId === undefined
+ ? await query
+ : await query.neq("id", excludeSalesId);
if (salesError) {
console.error("Error fetching sales:", salesError);
throw salesError;
}
- return findTakenEmail(otherSales ?? [], secondary_emails);
+ return findTakenEmail(otherSales ?? [], emails);
}
async function updateSaleSecondaryEmails(
@@ -115,6 +116,17 @@ async function inviteUser(req: Request, currentUserSale: any) {
return createErrorResponse(401, "Not Authorized");
}
+ const takenEmail = await findEmailUsedByAnotherSale(
+ email ? [email.trim().toLowerCase()] : [],
+ );
+ if (takenEmail) {
+ return createErrorResponse(
+ 409,
+ `Email already used by another user: ${takenEmail}`,
+ { code: "email_taken", email: takenEmail },
+ );
+ }
+
const { data, error: userError } = await supabaseAdmin.auth.admin.createUser({
email,
password,
@@ -245,26 +257,47 @@ async function patchUser(req: Request, currentUserSale: any) {
return createErrorResponse(401, "Not Authorized");
}
+ if (email && email.trim().toLowerCase() !== sale.email.toLowerCase()) {
+ const takenEmail = await findEmailUsedByAnotherSale(
+ [email.trim().toLowerCase()],
+ sales_id,
+ );
+ if (takenEmail) {
+ return createErrorResponse(
+ 409,
+ `Email already used by another user: ${takenEmail}`,
+ { code: "email_taken", email: takenEmail },
+ );
+ }
+ }
+
let normalizedSecondaryEmails: string[] | undefined;
if (secondary_emails !== undefined) {
normalizedSecondaryEmails = normalizeSecondaryEmails(secondary_emails);
+ if (!normalizedSecondaryEmails) {
+ return createErrorResponse(400, "secondary_emails must be an array", {
+ code: "invalid_secondary_emails_payload",
+ });
+ }
const invalidEmail = findInvalidEmail(normalizedSecondaryEmails);
if (invalidEmail) {
return createErrorResponse(
400,
`Invalid secondary email: ${invalidEmail}`,
+ { code: "invalid_secondary_email", email: invalidEmail },
);
}
- const takenEmail = await findSecondaryEmailUsedByAnotherSale(
- sales_id,
+ const takenEmail = await findEmailUsedByAnotherSale(
normalizedSecondaryEmails,
+ sales_id,
);
if (takenEmail) {
return createErrorResponse(
409,
`Secondary email already used by another user: ${takenEmail}`,
+ { code: "secondary_email_taken", email: takenEmail },
);
}
}
@@ -281,12 +314,17 @@ async function patchUser(req: Request, currentUserSale: any) {
return createErrorResponse(500, "Internal Server Error");
}
- if (avatar) {
- await updateSaleAvatar(data.user.id, avatar);
- }
+ try {
+ if (avatar) {
+ await updateSaleAvatar(data.user.id, avatar);
+ }
- if (normalizedSecondaryEmails) {
- await updateSaleSecondaryEmails(data.user.id, normalizedSecondaryEmails);
+ if (normalizedSecondaryEmails) {
+ await updateSaleSecondaryEmails(data.user.id, normalizedSecondaryEmails);
+ }
+ } catch (e) {
+ console.error("Error patching sale:", e);
+ return createErrorResponse(500, "Internal Server Error");
}
// Only administrators can update the administrator and disabled status
diff --git a/supabase/functions/users/secondaryEmails.test.ts b/supabase/functions/users/secondaryEmails.test.ts
index 562f8944..d2a671e4 100644
--- a/supabase/functions/users/secondaryEmails.test.ts
+++ b/supabase/functions/users/secondaryEmails.test.ts
@@ -7,10 +7,15 @@ import {
} 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("returns undefined for a non-array, so the caller rejects instead of wiping", () => {
+ expect(normalizeSecondaryEmails(undefined)).toBe(undefined);
+ expect(normalizeSecondaryEmails(null)).toBe(undefined);
+ expect(normalizeSecondaryEmails("[email protected]")).toBe(undefined);
+ expect(normalizeSecondaryEmails({ 0: "[email protected]" })).toBe(undefined);
+ });
+
+ it("returns an empty array for an empty array, which clears the addresses", () => {
+ expect(normalizeSecondaryEmails([])).toEqual([]);
});
it("trims and lowercases every address", () => {
diff --git a/supabase/functions/users/secondaryEmails.ts b/supabase/functions/users/secondaryEmails.ts
index f041bf1d..b67bbb07 100644
--- a/supabase/functions/users/secondaryEmails.ts
+++ b/supabase/functions/users/secondaryEmails.ts
@@ -2,9 +2,9 @@ const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
export const normalizeSecondaryEmails = (
secondaryEmails: unknown,
-): string[] => {
+): string[] | undefined => {
if (!Array.isArray(secondaryEmails)) {
- return [];
+ return undefined;
}
return [
...new Set(
diff --git a/supabase/migrations/20260812093000_sales_secondary_emails_is_array.sql b/supabase/migrations/20260812093000_sales_secondary_emails_is_array.sql
new file mode 100644
index 00000000..03e5f264
--- /dev/null
+++ b/supabase/migrations/20260812093000_sales_secondary_emails_is_array.sql
@@ -0,0 +1,3 @@
+alter table "public"."sales" add constraint "sales_secondary_emails_is_array" check (jsonb_typeof(secondary_emails) = 'array') not valid;
+
+alter table "public"."sales" validate constraint "sales_secondary_emails_is_array";
diff --git a/supabase/schemas/01_tables.sql b/supabase/schemas/01_tables.sql
index d6cc5f80..bdb383c4 100644
--- a/supabase/schemas/01_tables.sql
+++ b/supabase/schemas/01_tables.sql
@@ -98,7 +98,8 @@ create table public.sales (
user_id uuid not null,
avatar jsonb,
disabled boolean not null default false,
- secondary_emails jsonb not null default '[]'::jsonb
+ secondary_emails jsonb not null default '[]'::jsonb,
+ constraint sales_secondary_emails_is_array check (jsonb_typeof(secondary_emails) = 'array')
);
create unique index uq__sales__user_id on public.sales using btree (user_id);