A full-featured CRM built with React, shadcn/ui, and Supabase.
Test the attachment name filter of delete_note_attachments
François Zaninottoe20b403e51a1
diff --git a/supabase/functions/delete_note_attachments/candidateNames.test.ts b/supabase/functions/delete_note_attachments/candidateNames.test.tsnew file mode 100644index 00000000..ff24d6ba--- /dev/null+++ b/supabase/functions/delete_note_attachments/candidateNames.test.ts@@ -0,0 +1,90 @@+// @vitest-environment node+import { afterEach, describe, it, expect, vi } from "vitest";+import { getCandidateNames, type WebhookPayload } from "./candidateNames";++const BUCKET_URL =+ "http://127.0.0.1:54321/storage/v1/object/public/attachments";++const payloadWith = (attachments: unknown[]) =>+ ({ old_record: { attachments } }) as WebhookPayload;++describe("getCandidateNames", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("returns the file names stored in the attachments paths", () => {+ const payload = payloadWith([+ { path: "0.8262106278726917.pdf" },+ { path: "0.1234" },+ ]);++ expect(getCandidateNames(payload)).toEqual([+ "0.8262106278726917.pdf",+ "0.1234",+ ]);+ });++ it("reads the name from the src URL when the path is missing or empty", () => {+ const payload = payloadWith([+ { src: `${BUCKET_URL}/0.11.pdf` },+ { path: "", src: `${BUCKET_URL}/0.22.png` },+ { path: null, src: `${BUCKET_URL}/0.33.my%20ext` },+ ]);++ expect(getCandidateNames(payload)).toEqual([+ "0.11.pdf",+ "0.22.png",+ "0.33.my ext",+ ]);+ });++ it("ignores names that do not look like files uploaded by the app", () => {+ const payload = payloadWith([+ { path: "../0.1.txt" },+ { path: "dir/0.12.txt" },+ { path: "attachments/0.13.txt" },+ { path: "logo.png" },+ { path: "0.14.tar.gz" },+ { path: "9.5e-7.pdf" },+ { src: `${BUCKET_URL}/logo.png` },+ { src: `${BUCKET_URL}/..%2F0.15.txt` },+ { src: "not a url" },+ ]);++ expect(getCandidateNames(payload)).toEqual([]);+ });++ it("returns each name once", () => {+ const payload = payloadWith([+ { path: "0.5.pdf" },+ { path: "0.5.pdf", src: `${BUCKET_URL}/0.5.pdf` },+ ]);++ expect(getCandidateNames(payload)).toEqual(["0.5.pdf"]);+ });++ it("returns no names when the payload has no usable attachments", () => {+ expect(getCandidateNames({})).toEqual([]);+ expect(getCandidateNames({ old_record: null })).toEqual([]);+ expect(+ getCandidateNames({+ old_record: { attachments: "0.1.pdf" },+ } as unknown as WebhookPayload),+ ).toEqual([]);+ expect(getCandidateNames(payloadWith([null, 42, {}]))).toEqual([]);+ });++ it("checks at most 100 names per call", () => {+ vi.spyOn(console, "warn").mockImplementation(() => {});+ const payload = payloadWith(+ Array.from({ length: 120 }, (_, i) => ({ path: `0.${i + 1}.pdf` })),+ );++ const names = getCandidateNames(payload);++ expect(names).toHaveLength(100);+ expect(names[0]).toBe("0.1.pdf");+ expect(names[99]).toBe("0.100.pdf");+ });+});diff --git a/supabase/functions/delete_note_attachments/candidateNames.ts b/supabase/functions/delete_note_attachments/candidateNames.tsnew file mode 100644index 00000000..fca3e0fe--- /dev/null+++ b/supabase/functions/delete_note_attachments/candidateNames.ts@@ -0,0 +1,73 @@+const MAX_CANDIDATES_PER_CALL = 100;++// The app uploads every file at the root of the bucket, named+// `${Math.random()}${extension}`, e.g. `0.8262106278726917.pdf`.+const UPLOADED_FILE_NAME = /^0\.[0-9]+(\.[^./]*)?$/;++type NoteAttachment = {+ path?: string | null;+ src?: string | null;+};++export type WebhookPayload = {+ old_record?: { attachments?: NoteAttachment[] | null } | null;+};++// Returns the names of the files attached to the note before the change: the+// files we may delete. The payload is not trusted, so only names that look like+// files uploaded by the app are returned, at most MAX_CANDIDATES_PER_CALL.+export const getCandidateNames = (payload: WebhookPayload): string[] => {+ const attachments = payload?.old_record?.attachments;+ if (!Array.isArray(attachments)) {+ return [];+ }++ const names = Array.from(+ new Set(+ attachments+ .map(getFileName)+ .filter((name): name is string => name != null),+ ),+ );++ if (names.length > MAX_CANDIDATES_PER_CALL) {+ console.warn("Too many note attachments, only checking the first ones", {+ count: names.length,+ checked: MAX_CANDIDATES_PER_CALL,+ });+ }++ return names.slice(0, MAX_CANDIDATES_PER_CALL);+};++// Returns the file name of an attachment, read from its `path`, or from the end+// of its `src` URL when it has no path. Returns null for anything that does not+// look like a file uploaded by the app (e.g. `dir/0.1.pdf` or `../logo.png`),+// so the caller cannot point at other files of the bucket.+const getFileName = (attachment?: NoteAttachment | null) => {+ const name =+ typeof attachment?.path === "string" && attachment.path !== ""+ ? attachment.path+ : getLastPathSegment(attachment?.src);+ return name != null && UPLOADED_FILE_NAME.test(name) ? name : null;+};++const getLastPathSegment = (src?: string | null) => {+ if (typeof src !== "string") {+ return null;+ }+ try {+ const pathname = new URL(src).pathname;+ return safelyDecodePath(pathname.slice(pathname.lastIndexOf("/") + 1));+ } catch {+ return null;+ }+};++const safelyDecodePath = (path: string) => {+ try {+ return decodeURIComponent(path);+ } catch {+ return path;+ }+};diff --git a/supabase/functions/delete_note_attachments/index.ts b/supabase/functions/delete_note_attachments/index.tsindex 925b7151..06f2b7a7 100644--- a/supabase/functions/delete_note_attachments/index.ts+++ b/supabase/functions/delete_note_attachments/index.ts@@ -3,25 +3,11 @@ import { sql } from "https://esm.sh/[email protected]";import { AuthMiddleware } from "../_shared/authentication.ts";import { db } from "../_shared/db.ts";import { supabaseAdmin } from "../_shared/supabaseAdmin.ts";+import { getCandidateNames, type WebhookPayload } from "./candidateNames.ts";const ATTACHMENTS_BUCKET =Deno.env.get("VITE_ATTACHMENTS_BUCKET") || "attachments";-const MAX_CANDIDATES_PER_CALL = 100;--// The app uploads every file at the root of the bucket, named-// `${Math.random()}${extension}`, e.g. `0.8262106278726917.pdf`.-const UPLOADED_FILE_NAME = /^0\.[0-9]+(\.[^./]*)?$/;--type NoteAttachment = {- path?: string | null;- src?: string | null;-};--type WebhookPayload = {- old_record?: { attachments?: NoteAttachment[] | null } | null;-};-// The note triggers call this function when a note is updated or deleted,// sending the note as it was before the change.//@@ -77,51 +63,6 @@ Deno.serve(async (req: Request) =>AuthMiddleware(req, async (req: Request) => deleteNoteAttachments(req)),);-const getCandidateNames = (payload: WebhookPayload): string[] => {- const attachments = payload?.old_record?.attachments;- if (!Array.isArray(attachments)) {- return [];- }-- const names = attachments- .map(getFileName)- .filter((name): name is string => name != null);-- return Array.from(new Set(names)).slice(0, MAX_CANDIDATES_PER_CALL);-};--// Returns the file name of an attachment, read from its `path`, or from the end-// of its `src` URL when it has no path. Returns null for anything that does not-// look like a file uploaded by the app (e.g. `dir/0.1.pdf` or `../logo.png`),-// so the caller cannot point at other files of the bucket.-const getFileName = (attachment?: NoteAttachment | null) => {- const name =- typeof attachment?.path === "string"- ? attachment.path- : getLastPathSegment(attachment?.src);- return name != null && UPLOADED_FILE_NAME.test(name) ? name : null;-};--const getLastPathSegment = (src?: string | null) => {- if (typeof src !== "string") {- return null;- }- try {- const pathname = new URL(src).pathname;- return safelyDecodePath(pathname.slice(pathname.lastIndexOf("/") + 1));- } catch {- return null;- }-};--const safelyDecodePath = (path: string) => {- try {- return decodeURIComponent(path);- } catch {- return path;- }-};-// Returns the files that no row uses anymore, among the given ones.//// A file counts as used when its number (`0.8262106278726917` for