A full-featured CRM built with React, shadcn/ui, and Supabase.
Stop trusting the payload in delete_note_attachments
François Zaninotto17f8b48b38a6
diff --git a/AGENTS.md b/AGENTS.mdindex 50e7cb3e..f62240ef 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -166,6 +166,7 @@ When modifying contact or company data structures:7. Don't forget to update the related view (`contacts_summary`, `companies_summary`) in `03_views.sql`8. Don't forget the export functions9. Don't forget the contact merge logic+10. If the new field stores files uploaded to the attachments bucket, add its column to the reference list in `supabase/functions/delete_note_attachments/index.ts`, otherwise these files get deleted as orphans### Running with Test Datadiff --git a/doc/src/content/docs/developers/custom-fields.mdx b/doc/src/content/docs/developers/custom-fields.mdxindex 785cbdb4..a367cf36 100644--- a/doc/src/content/docs/developers/custom-fields.mdx+++ b/doc/src/content/docs/developers/custom-fields.mdx@@ -174,4 +174,8 @@ export const ContactAside = ({ link = "edit" }: { link?: "edit" | "show" }) => {This will display the "Referred By" information in the contact sidebar when available.+:::caution+If your custom field stores files (e.g. with a `<FileInput>` or `<ImageInput>` uploaded to the attachments bucket), add its column to the reference list in `supabase/functions/delete_note_attachments/index.ts`. This function regularly deletes the files of the bucket that no column references anymore, so files stored in an unlisted column can be deleted as soon as one hour after their upload.+:::+\ No newline at end of filediff --git a/supabase/functions/delete_note_attachments/index.ts b/supabase/functions/delete_note_attachments/index.tsindex 545b639a..94ec52a7 100644--- a/supabase/functions/delete_note_attachments/index.ts+++ b/supabase/functions/delete_note_attachments/index.ts@@ -1,39 +1,36 @@import "jsr:@supabase/functions-js/edge-runtime.d.ts";+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";const ATTACHMENTS_BUCKET =Deno.env.get("VITE_ATTACHMENTS_BUCKET") || "attachments";-type NoteAttachment = {- path?: string | null;- src?: string | null;-};--type NoteRecord = {- id?: number | string | null;- attachments?: NoteAttachment[] | null;-};+// Leaves time for a freshly uploaded file to be saved in its note, logo or avatar.+const ORPHAN_GRACE_PERIOD = "1 hour";+const MAX_FILES_PER_CALL = 1000;-type WebhookPayload = {- type?: string | null;- old_record?: NoteRecord | null;- record?: NoteRecord | null;-};--const deleteNoteAttachments = async (req: Request) => {+// Called by the note triggers, but the request body is ignored on purpose:+// any authenticated user can call this endpoint, so it must never let the caller+// pick which files to delete. Instead it removes every file of the bucket that no+// row references anymore, which also catches files orphaned by changes the+// triggers never see (MCP or SQL edits, lost webhook calls, replaced logos).+const deleteOrphanAttachments = async (req: Request) => {if (req.method !== "POST") {return jsonResponse({ error: "Method Not Allowed" }, 405);}- const payload = (await req.json()) as WebhookPayload;- const paths = getPathsToDelete(payload);+ let paths: string[];+ try {+ paths = await getOrphanPaths();+ } catch (error) {+ console.error("Failed to list orphan attachments", { error });+ return jsonResponse({ error: "Failed to list orphan attachments" }, 500);+ }if (paths.length === 0) {- return jsonResponse({- status: "skipped",- reason: "no_paths_to_delete",- });+ return jsonResponse({ status: "skipped", reason: "no_orphan_files" });}const { error } = await supabaseAdmin.storage@@ -41,114 +38,47 @@ const deleteNoteAttachments = async (req: Request) => {.remove(paths);if (error) {- console.error("Failed to delete note attachments", {- type: payload.type ?? null,- paths,- error,- });- return jsonResponse({ error: "Failed to delete note attachments" }, 500);+ console.error("Failed to delete orphan attachments", { paths, error });+ return jsonResponse({ error: "Failed to delete orphan attachments" }, 500);}- return jsonResponse({- status: "ok",- });+ return jsonResponse({ status: "ok", deleted: paths.length });};Deno.serve(async (req: Request) =>- AuthMiddleware(req, async (req: Request) => deleteNoteAttachments(req)),+ AuthMiddleware(req, async (req: Request) => deleteOrphanAttachments(req)),);-const getPathsToDelete = (payload: WebhookPayload): string[] => {- const oldPaths = extractAttachmentPaths(payload.old_record?.attachments);- const newPaths = extractAttachmentPaths(payload.record?.attachments);-- if (payload.type === "UPDATE") {- const newPathsSet = new Set(newPaths);- return oldPaths.filter((path) => !newPathsSet.has(path));- }-- if (payload.type === "DELETE") {- return oldPaths;- }-- return [];-};--const extractAttachmentPaths = (- attachments?: NoteAttachment[] | null,-): string[] => {- const paths = attachments- ?.map((attachment) => extractAttachmentPath(attachment))- .filter((path): path is string => path != null && path.length > 0);-- return paths ? Array.from(new Set(paths)) : [];-};--const extractAttachmentPath = (attachment?: NoteAttachment | null) => {- if (!attachment) {- return null;- }-- if (attachment.path) {- return normalizeStoragePath(attachment.path);- }-- if (!attachment.src) {- return null;- }-- const pathname = getPathname(attachment.src);- if (!pathname) {- return null;- }-- const bucketSegment = `/${ATTACHMENTS_BUCKET}/`;- const bucketIndex = pathname.lastIndexOf(bucketSegment);- if (bucketIndex < 0) {- return null;- }-- const path = pathname.slice(bucketIndex + bucketSegment.length);- return normalizeStoragePath(path);-};--const getPathname = (value: string) => {- try {- return new URL(value, "http://localhost").pathname;- } catch {- return null;- }-};--const safelyDecodePath = (path: string) => {- try {- return decodeURIComponent(path);- } catch {- return path;- }-};--const normalizeStoragePath = (path: string) => {- const trimmedPath = path.trim();- if (trimmedPath.length === 0) {- return null;- }-- const parsedPath = getPathname(trimmedPath);- const candidatePath = parsedPath ?? trimmedPath;-- const bucketSegment = `/${ATTACHMENTS_BUCKET}/`;- const bucketIndex = candidatePath.lastIndexOf(bucketSegment);- const withoutBucket =- bucketIndex >= 0- ? candidatePath.slice(bucketIndex + bucketSegment.length)- : candidatePath.replace(/^\/+/, "").replace(/^attachments\//, "");-- if (withoutBucket.length === 0) {- return null;- }-- return safelyDecodePath(withoutBucket);+// Uploads are named `${Math.random()}${extension}`. A file is referenced when its+// numeric stem (`0.8262106278726917`) appears in a column that stores uploaded+// files: the extension may be URL-encoded in a stored `src`, so it is ignored.+// Every column holding uploaded files MUST be listed here, otherwise its files+// get deleted. Files not named that way are never deleted.+const getOrphanPaths = async (): Promise<string[]> => {+ const { rows } = await sql<{ name: string }>`+ with refs as (+ select attachments::text as text from public.contact_notes+ union all select attachments::text from public.deal_notes+ union all select logo::text from public.companies+ union all select avatar::text from public.contacts+ union all select avatar::text from public.sales+ union all select config::text from public.configuration+ ),+ referenced_stems as (+ select distinct match[1] as stem+ from refs, regexp_matches(refs.text, '(0\\.[0-9]+)', 'g') as match+ )+ select o.name+ from storage.objects o+ where o.bucket_id = ${ATTACHMENTS_BUCKET}+ and o.created_at < now() - ${ORPHAN_GRACE_PERIOD}::interval+ and substring(o.name from '^0\\.[0-9]+') not in (+ select stem from referenced_stems+ )+ limit ${MAX_FILES_PER_CALL}+ `.execute(db);++ return rows.map((row) => row.name);};const jsonResponse = (data: unknown, status = 200) =>