A full-featured CRM built with React, shadcn/ui, and Supabase.
secure note attachment cleanup trigger flow with auth middleware
Anibal Svarcas0638b663c95b
diff --git a/supabase/functions/delete_note_attachments/index.ts b/supabase/functions/delete_note_attachments/index.tsindex e0e54634..0200dbb2 100644--- a/supabase/functions/delete_note_attachments/index.ts+++ b/supabase/functions/delete_note_attachments/index.ts@@ -1,4 +1,5 @@import "jsr:@supabase/functions-js/edge-runtime.d.ts";+import { AuthMiddleware } from "../_shared/authentication.ts";import { supabaseAdmin } from "../_shared/supabaseAdmin.ts";const ATTACHMENTS_BUCKET = "attachments";@@ -19,41 +20,43 @@ type WebhookPayload = {record?: NoteRecord | null;};-Deno.serve(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);+Deno.serve(async (req: Request) =>+ AuthMiddleware(req, 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);++ if (paths.length === 0) {+ return jsonResponse({+ status: "skipped",+ reason: "no_paths_to_delete",+ type: payload.type ?? null,+ });+ }++ const { error } = await supabaseAdmin.storage+ .from(ATTACHMENTS_BUCKET)+ .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);+ }- if (paths.length === 0) {return jsonResponse({- status: "skipped",- reason: "no_paths_to_delete",- type: payload.type ?? null,- });- }-- const { error } = await supabaseAdmin.storage- .from(ATTACHMENTS_BUCKET)- .remove(paths);-- if (error) {- console.error("Failed to delete note attachments", {+ status: "ok",type: payload.type ?? null,- paths,- error,+ deletedPathsCount: paths.length,});- return jsonResponse({ error: "Failed to delete note attachments" }, 500);- }-- return jsonResponse({- status: "ok",- type: payload.type ?? null,- deletedPathsCount: paths.length,- });-});+ }),+);const getPathsToDelete = (payload: WebhookPayload): string[] => {const oldPaths = extractAttachmentPaths(payload.old_record?.attachments);diff --git a/supabase/migrations/20260220154000_note_attachments_webhooks.sql b/supabase/migrations/20260220154000_note_attachments_webhooks.sqlindex 2d4f581e..7d972d52 100644--- a/supabase/migrations/20260220154000_note_attachments_webhooks.sql+++ b/supabase/migrations/20260220154000_note_attachments_webhooks.sql@@ -5,8 +5,14 @@ BEGINEXECUTE 'DROP TRIGGER IF EXISTS on_contact_notes_changed_delete_note_attachments ON public.contact_notes';EXECUTE 'DROP TRIGGER IF EXISTS on_deal_notes_changed_delete_note_attachments ON public.deal_notes';+ EXECUTE 'DROP FUNCTION IF EXISTS public.cleanup_note_attachments()';+ EXECUTE 'DROP FUNCTION IF EXISTS public.note_attachments_webhook_url()';+ -- TODO: remove these legacy drops before merge once the old function names are no longer needed.+ EXECUTE 'DROP FUNCTION IF EXISTS public.atomic_crm_notify_note_attachment_cleanup()';+ EXECUTE 'DROP FUNCTION IF EXISTS public.atomic_crm_note_attachments_webhook_url()';+EXECUTE $url_sql$- CREATE OR REPLACE FUNCTION public.atomic_crm_note_attachments_webhook_url()+ CREATE OR REPLACE FUNCTION public.note_attachments_webhook_url()RETURNS textLANGUAGE plpgsqlAS $function$@@ -57,7 +63,7 @@ BEGIN$url_sql$;EXECUTE $cleanup_sql$- CREATE OR REPLACE FUNCTION public.atomic_crm_notify_note_attachment_cleanup()+ CREATE OR REPLACE FUNCTION public.cleanup_note_attachments()RETURNS triggerLANGUAGE plpgsqlSECURITY DEFINER@@ -65,22 +71,38 @@ BEGINAS $function$DECLAREpayload jsonb;+ request_headers jsonb;+ auth_header text;BEGIN+ request_headers := coalesce(+ nullif(current_setting('request.headers', true), '')::jsonb,+ '{}'::jsonb+ );+ auth_header := request_headers ->> 'authorization';++ IF auth_header IS NULL OR auth_header = '' THEN+ IF TG_OP = 'DELETE' THEN+ RETURN OLD;+ END IF;++ RETURN NEW;+ END IF;+payload := jsonb_build_object('old_record', OLD,'record', NEW,- 'type', TG_OP,- 'table', TG_TABLE_NAME,- 'schema', TG_TABLE_SCHEMA+ 'type', TG_OP);PERFORM net.http_post(- url := public.atomic_crm_note_attachments_webhook_url(),+ url := public.note_attachments_webhook_url(),body := payload,params := '{}'::jsonb,headers := jsonb_build_object('Content-Type',- 'application/json'+ 'application/json',+ 'Authorization',+ auth_header),timeout_milliseconds := 1000);@@ -94,7 +116,7 @@ BEGIN$function$;$cleanup_sql$;- EXECUTE 'CREATE TRIGGER on_contact_notes_changed_delete_note_attachments AFTER DELETE OR UPDATE ON public.contact_notes FOR EACH ROW EXECUTE FUNCTION public.atomic_crm_notify_note_attachment_cleanup()';- EXECUTE 'CREATE TRIGGER on_deal_notes_changed_delete_note_attachments AFTER DELETE OR UPDATE ON public.deal_notes FOR EACH ROW EXECUTE FUNCTION public.atomic_crm_notify_note_attachment_cleanup()';+ EXECUTE 'CREATE TRIGGER on_contact_notes_changed_delete_note_attachments AFTER DELETE OR UPDATE ON public.contact_notes FOR EACH ROW EXECUTE FUNCTION public.cleanup_note_attachments()';+ EXECUTE 'CREATE TRIGGER on_deal_notes_changed_delete_note_attachments AFTER DELETE OR UPDATE ON public.deal_notes FOR EACH ROW EXECUTE FUNCTION public.cleanup_note_attachments()';END;$migration$;