A full-featured CRM built with React, shadcn/ui, and Supabase.
Refuse ambiguous senders and stop mislabelling DB errors as 401
Jerome649ab02f9b38
diff --git a/supabase/functions/postmark/addNoteToContact.test.ts b/supabase/functions/postmark/addNoteToContact.test.tsindex 00f8d127..a269d84e 100644--- a/supabase/functions/postmark/addNoteToContact.test.ts+++ b/supabase/functions/postmark/addNoteToContact.test.ts@@ -15,10 +15,13 @@ vi.mock("../_shared/supabaseAdmin.ts", () => ({},}));-const secondaryLookupResult = (rows: unknown[]) => ({+const secondaryLookupResult = (+ rows: unknown[],+ error: { message: string } | null = null,+) => ({neq: () => ({order: () => ({- limit: () => Promise.resolve({ data: rows, error: null }),+ limit: () => Promise.resolve({ data: error ? null : rows, error }),}),}),});@@ -394,30 +397,65 @@ 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]" };+ it("attributes to nobody when two sales share the same secondary email", async () => {+ const consoleSpy = vi+ .spyOn(console, "error")+ .mockImplementation(() => {});- mockFrom- .mockReturnValueOnce({- select: () => ({- eq: () => ({- neq: () => ({- maybeSingle: () => Promise.resolve({ data: null, error: null }),- }),- }),- }),- })- .mockReturnValueOnce({- select: () => ({- contains: () => secondaryLookupResult([firstSale, secondSale]),- }),- });+ mockFrom.mockReturnValueOnce(primaryLookupMiss).mockReturnValueOnce({+ select: () => ({+ contains: () =>+ secondaryLookupResult([+ { id: 3, email: "[email protected]" },+ { id: 9, email: "[email protected]" },+ ]),+ }),+ });const result = await findActiveSaleByEmail("[email protected]");- expect(result.data).toEqual(firstSale);+ expect(result.data).toBe(null);expect(result.error).toBe(null);++ consoleSpy.mockRestore();+ });++ it("names both sales in the logs when it refuses an ambiguous sender", async () => {+ const consoleSpy = vi+ .spyOn(console, "error")+ .mockImplementation(() => {});++ mockFrom.mockReturnValueOnce(primaryLookupMiss).mockReturnValueOnce({+ select: () => ({+ contains: () =>+ secondaryLookupResult([+ { id: 3, email: "[email protected]" },+ { id: 9, email: "[email protected]" },+ ]),+ }),+ });++ await findActiveSaleByEmail("[email protected]");++ expect(consoleSpy).toHaveBeenCalledWith(+ expect.stringContaining("[email protected]"),+ );+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("3, 9"));++ consoleSpy.mockRestore();+ });++ it("surfaces a failure of the secondary lookup instead of reporting no sale", async () => {+ mockFrom.mockReturnValueOnce(primaryLookupMiss).mockReturnValueOnce({+ select: () => ({+ contains: () => secondaryLookupResult([], { message: "DB error" }),+ }),+ });++ const result = await findActiveSaleByEmail("[email protected]");++ expect(result.data).toBe(null);+ expect(result.error).toEqual({ message: "DB error" });});it("returns no sale rather than an error when nothing matches", async () => {diff --git a/supabase/functions/postmark/addNoteToContact.ts b/supabase/functions/postmark/addNoteToContact.tsindex 1dac8e0e..f0c1441c 100644--- a/supabase/functions/postmark/addNoteToContact.ts+++ b/supabase/functions/postmark/addNoteToContact.ts@@ -130,12 +130,24 @@ export const findActiveSaleByEmail = async (salesEmail: string) => {.contains("secondary_emails", JSON.stringify([normalizedEmail])).neq("disabled", true).order("id", { ascending: true })- .limit(1);+ .limit(2);- return {- data: bySecondaryEmail.data?.[0] ?? null,- error: bySecondaryEmail.error,- };+ if (bySecondaryEmail.error) {+ return { data: null, error: bySecondaryEmail.error };+ }++ const matches = bySecondaryEmail.data ?? [];++ if (matches.length > 1) {+ console.error(+ `Ambiguous sender ${normalizedEmail}: registered as a secondary email by sales ${matches+ .map((sale: { id: number }) => sale.id)+ .join(", ")}. Refusing to attribute the note.`,+ );+ return { data: null, error: null };+ }++ return { data: matches[0] ?? null, error: null };};export const addNoteToContact = async ({diff --git a/supabase/functions/postmark/index.ts b/supabase/functions/postmark/index.tsindex 9a24255e..4cf50eae 100644--- a/supabase/functions/postmark/index.ts+++ b/supabase/functions/postmark/index.ts@@ -55,6 +55,12 @@ Deno.serve(async (req) => {const allSales = await supabaseAdmin.from("sales").select("email, secondary_emails");++ if (allSales.error) {+ console.error("Could not fetch sales emails:", allSales.error);+ return new Response("Could not fetch sales from database", { status: 500 });+ }+const salesEmails =allSales.data?.flatMap((s: { email: string; secondary_emails: string[] | null }) => [diff --git a/supabase/functions/users/index.ts b/supabase/functions/users/index.tsindex 24ca442b..e427bbf3 100644--- a/supabase/functions/users/index.ts+++ b/supabase/functions/users/index.ts@@ -6,7 +6,6 @@ import { AuthMiddleware, UserMiddleware } from "../_shared/authentication.ts";import { getUserSale } from "../_shared/getUserSale.ts";import {findInvalidEmail,- findTakenEmail,normalizeSecondaryEmails,} from "./secondaryEmails.ts";@@ -61,22 +60,29 @@ async function findEmailUsedByAnotherSale(emails: string[],excludeSalesId?: number,) {- if (!emails.length) {- return undefined;- }+ for (const email of emails) {+ let query = supabaseAdmin+ .from("sales")+ .select("id")+ .or(`email.eq.${email},secondary_emails.cs.${JSON.stringify([email])}`);++ if (excludeSalesId !== undefined) {+ query = query.neq("id", excludeSalesId);+ }- const query = supabaseAdmin.from("sales").select("email, secondary_emails");- const { data: otherSales, error: salesError } =- excludeSalesId === undefined- ? await query- : await query.neq("id", excludeSalesId);+ const { data: matches, error: salesError } = await query.limit(1);- if (salesError) {- console.error("Error fetching sales:", salesError);- throw salesError;+ if (salesError) {+ console.error("Error fetching sales:", salesError);+ throw salesError;+ }++ if (matches?.length) {+ return email;+ }}- return findTakenEmail(otherSales ?? [], emails);+ return undefined;}async function updateSaleSecondaryEmails(@@ -376,12 +382,17 @@ Deno.serve(async (req: Request) =>return createErrorResponse(401, "Unauthorized");}- if (req.method === "POST") {- return inviteUser(req, currentUserSale);- }-- if (req.method === "PATCH") {- return patchUser(req, currentUserSale);+ try {+ if (req.method === "POST") {+ return await inviteUser(req, currentUserSale);+ }++ if (req.method === "PATCH") {+ return await patchUser(req, currentUserSale);+ }+ } catch (e) {+ console.error("Unhandled error in the users function:", e);+ return createErrorResponse(500, "Internal Server Error");}return createErrorResponse(405, "Method Not Allowed");diff --git a/supabase/functions/users/secondaryEmails.test.ts b/supabase/functions/users/secondaryEmails.test.tsindex d2a671e4..84cd83b0 100644--- a/supabase/functions/users/secondaryEmails.test.ts+++ b/supabase/functions/users/secondaryEmails.test.ts@@ -1,10 +1,6 @@// @vitest-environment nodeimport { describe, it, expect } from "vitest";-import {- findInvalidEmail,- findTakenEmail,- normalizeSecondaryEmails,-} from "./secondaryEmails";+import { findInvalidEmail, normalizeSecondaryEmails } from "./secondaryEmails";describe("normalizeSecondaryEmails", () => {it("returns undefined for a non-array, so the caller rejects instead of wiping", () => {@@ -71,40 +67,8 @@ describe("findInvalidEmail", () => {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);+ it("rejects a comma, which would split the PostgREST or() filter", () => {+ expect(findInvalidEmail(["john,[email protected]"])).toBe("john,[email protected]");});});diff --git a/supabase/functions/users/secondaryEmails.ts b/supabase/functions/users/secondaryEmails.tsindex b67bbb07..5da7912c 100644--- a/supabase/functions/users/secondaryEmails.ts+++ b/supabase/functions/users/secondaryEmails.ts@@ -1,4 +1,4 @@-const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;+const EMAIL_PATTERN = /^[^\s@,]+@[^\s@,]+\.[^\s@,]+$/;export const normalizeSecondaryEmails = (secondaryEmails: unknown,@@ -18,15 +18,3 @@ export const normalizeSecondaryEmails = (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));-};