A full-featured CRM built with React, shadcn/ui, and Supabase.
Use webhook secret auth for note attachment cleanup
Anibal Svarcas320cb0287795
diff --git a/supabase/functions/delete_note_attachments/index.ts b/supabase/functions/delete_note_attachments/index.tsindex 00a68e1e..c6923019 100644--- a/supabase/functions/delete_note_attachments/index.ts+++ b/supabase/functions/delete_note_attachments/index.ts@@ -1,8 +1,9 @@import "jsr:@supabase/functions-js/edge-runtime.d.ts";-import { AuthMiddleware } from "../_shared/authentication.ts";import { supabaseAdmin } from "../_shared/supabaseAdmin.ts";import { ATTACHMENTS_BUCKET } from "../../../src/components/atomic-crm/providers/commons/attachments.ts";+const DEFAULT_WEBHOOK_SECRET = "atomic-crm-note-attachments-webhook-secret";+type NoteAttachment = {path?: string | null;src?: string | null;@@ -31,7 +32,6 @@ const deleteNoteAttachments = async (req: Request) => {return jsonResponse({status: "skipped",reason: "no_paths_to_delete",- type: payload.type ?? null,});}@@ -50,14 +50,28 @@ const deleteNoteAttachments = async (req: Request) => {return jsonResponse({status: "ok",- type: payload.type ?? null,- deletedPathsCount: paths.length,});};-Deno.serve(async (req: Request) =>- AuthMiddleware(req, async (req: Request) => deleteNoteAttachments(req)),-);+Deno.serve(async (req: Request) => {+ if (!isWebhookRequestAuthenticated(req)) {+ return jsonResponse({ error: "Unauthorized" }, 401);+ }++ return deleteNoteAttachments(req);+});++const isWebhookRequestAuthenticated = (req: Request) => {+ const providedSecret = req.headers.get("x-webhook-secret");+ if (!providedSecret) {+ return false;+ }++ const expectedSecret =+ Deno.env.get("ATTACHMENTS_WEBHOOK_SECRET") ?? DEFAULT_WEBHOOK_SECRET;++ return providedSecret === expectedSecret;+};const getPathsToDelete = (payload: WebhookPayload): string[] => {const oldPaths = extractAttachmentPaths(payload.old_record?.attachments);@@ -91,7 +105,7 @@ const extractAttachmentPath = (attachment?: NoteAttachment | null) => {}if (attachment.path) {- return attachment.path;+ return normalizeStoragePath(attachment.path);}if (!attachment.src) {@@ -110,7 +124,7 @@ const extractAttachmentPath = (attachment?: NoteAttachment | null) => {}const path = pathname.slice(bucketIndex + bucketSegment.length);- return path.length > 0 ? safelyDecodePath(path) : null;+ return normalizeStoragePath(path);};const getPathname = (value: string) => {@@ -129,6 +143,29 @@ const safelyDecodePath = (path: string) => {}};+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);+};+const jsonResponse = (data: unknown, status = 200) =>new Response(JSON.stringify(data), {status,diff --git a/supabase/migrations/20260220154000_note_attachments_webhooks.sql b/supabase/migrations/20260220154000_note_attachments_webhooks.sqlindex ce47fc36..aafd9b9c 100644--- a/supabase/migrations/20260220154000_note_attachments_webhooks.sql+++ b/supabase/migrations/20260220154000_note_attachments_webhooks.sql@@ -6,8 +6,8 @@ DO $migration$BEGINEXECUTE $url_sql$-- SQL triggers cannot read Edge Function env vars directly. Resolve the- -- function URL from request context for hosted projects, and keep a local- -- fallback for dockerized local development.+ -- function URL from request context first, then fallback to project_ref+ -- for hosted projects, and host.docker.internal for local Docker.CREATE OR REPLACE FUNCTION public.note_attachments_webhook_url()RETURNS textLANGUAGE plpgsql@@ -17,7 +17,16 @@ BEGINproject_ref text;function_url text;BEGIN- issuer := nullif(current_setting('request.jwt.claim.iss', true), '');+ issuer := coalesce(+ nullif(current_setting('request.jwt.claim.iss', true), ''),+ (+ coalesce(+ nullif(current_setting('request.jwt.claims', true), ''),+ '{}'+ )::jsonb ->> 'iss'+ )+ );+ issuer := nullif(issuer, '');IF issuer IS NOT NULL THENissuer := rtrim(issuer, '/');@@ -67,22 +76,12 @@ BEGINAS $function$DECLAREpayload jsonb;- request_headers jsonb;- auth_header text;+ webhook_secret text;BEGIN- request_headers := coalesce(- nullif(current_setting('request.headers', true), '')::jsonb,- '{}'::jsonb+ webhook_secret := coalesce(+ nullif(current_setting('app.settings.attachments_webhook_secret', true), ''),+ 'atomic-crm-note-attachments-webhook-secret');- 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,@@ -97,8 +96,8 @@ BEGINheaders := jsonb_build_object('Content-Type','application/json',- 'Authorization',- auth_header+ 'X-Webhook-Secret',+ webhook_secret),timeout_milliseconds := 10000);