@luanpdd/kit-mcp 1.19.0 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +1 -1
  2. package/gates/dept-cycle-prevention.md +179 -0
  3. package/gates/multi-tenant-rls-coverage.md +102 -0
  4. package/gates/service-role-not-in-user-facing.md +113 -0
  5. package/kit/agents/audit-log-implementer.md +175 -0
  6. package/kit/agents/b2b-saas-architect.md +156 -0
  7. package/kit/agents/crm-pipeline-implementer.md +150 -0
  8. package/kit/agents/evolution-go-integrator.md +179 -0
  9. package/kit/agents/invite-flow-implementer.md +137 -0
  10. package/kit/agents/lgpd-compliance-auditor.md +206 -0
  11. package/kit/agents/multi-tenant-isolation-auditor.md +243 -0
  12. package/kit/agents/multi-tenant-rls-writer.md +262 -0
  13. package/kit/agents/org-onboarding-implementer.md +202 -0
  14. package/kit/agents/super-admin-implementer.md +182 -0
  15. package/kit/commands/burn-rate-status.md +237 -121
  16. package/kit/commands/multi-tenant.md +163 -0
  17. package/kit/file-manifest.json +31 -4
  18. package/kit/skills/_shared-multi-tenant/glossary.md +186 -0
  19. package/kit/skills/audit-log-multi-tenant/SKILL.md +334 -0
  20. package/kit/skills/b2b-saas-architecture/SKILL.md +300 -0
  21. package/kit/skills/crm-lead-pipeline-patterns/SKILL.md +326 -0
  22. package/kit/skills/evolution-go-whatsapp-integration/SKILL.md +322 -0
  23. package/kit/skills/lgpd-multi-tenant-compliance/SKILL.md +340 -0
  24. package/kit/skills/member-invite-flow/SKILL.md +305 -0
  25. package/kit/skills/member-management-react-shadcn/SKILL.md +328 -0
  26. package/kit/skills/multi-tenant-performance-scaling/SKILL.md +312 -0
  27. package/kit/skills/multi-tenant-rls-hierarchy/SKILL.md +338 -0
  28. package/kit/skills/org-onboarding-flow/SKILL.md +257 -0
  29. package/kit/skills/org-switcher-react-pattern/SKILL.md +349 -0
  30. package/kit/skills/permission-gate-react-pattern/SKILL.md +271 -0
  31. package/kit/skills/rbac-permissions-matrix-supabase/SKILL.md +301 -0
  32. package/kit/skills/super-admin-platform-pattern/SKILL.md +322 -0
  33. package/kit/skills/whatsapp-conversation-state-machine/SKILL.md +287 -0
  34. package/package.json +6 -2
  35. package/src/mcp-server/index.js +34 -3
@@ -0,0 +1,326 @@
1
+ ---
2
+ name: crm-lead-pipeline-patterns
3
+ description: Use ao implementar CRM lead pipeline em B2B SaaS Supabase — 6 stages canônicos lead→qualified→proposal→negotiation→won|lost, trigger PG BEFORE UPDATE valida transições (CHECK constraint não basta), ownership transfer com notification+audit, lead dedup via unique(org_id, phone)+(org_id, email), integração WhatsApp lookup contact_phone.
4
+ ---
5
+
6
+ # CRM Lead Pipeline — Patterns Canônicos
7
+
8
+ ## Quando usar
9
+
10
+ LLM carrega esta skill ao implementar CRM lead pipeline em B2B multi-tenant. Trigger phrases:
11
+
12
+ - "CRM lead pipeline", "sales pipeline stages"
13
+ - "lead state machine Postgres", "transition validation"
14
+ - "ownership transfer lead", "lead assignment"
15
+ - "lead dedup phone email"
16
+ - "integração WhatsApp CRM lead"
17
+
18
+ ## Regras absolutas
19
+
20
+ **REGRA #1 (6 stages canônicos):** Pipeline tem 6 stages: `lead → qualified → proposal → negotiation → won | lost`. Custom stages permitidos via prefix `custom_*` mas estes 6 são obrigatórios.
21
+
22
+ **REGRA #2 (trigger PG > CHECK constraint):** Validar transições via **trigger BEFORE UPDATE** com `RAISE EXCEPTION`, não apenas CHECK constraint. CHECK valida valor, mas não valida **transição** (lead → won direto = bug, deve passar por qualified+proposal+negotiation).
23
+
24
+ **REGRA #3 (ownership transfer com audit):** Mudança em `leads.owner_id` SEMPRE dispara: (a) notificação ao novo owner, (b) entry em audit_logs com `previous_owner_id, new_owner_id, reason`. Trigger AFTER UPDATE.
25
+
26
+ **REGRA #4 (dedup unique constraints):** `unique(org_id, contact_phone)` + `unique(org_id, contact_email)` em `leads`. Insert duplicado falha — app code precisa fazer lookup ANTES.
27
+
28
+ **REGRA #5 (lookup ANTES de criar via WhatsApp):** Webhook handler WhatsApp inbound: `SELECT id FROM leads WHERE org_id=$1 AND contact_phone=$2`. Se existe, append message à conversa do lead. Se não existe, criar lead novo com `source='whatsapp_inbound'`.
29
+
30
+ ## Patterns canônicos
31
+
32
+ ### Tabela `leads`
33
+
34
+ ```sql
35
+ create table public.leads (
36
+ id uuid primary key default gen_random_uuid(),
37
+ org_id uuid not null references public.organizations(id) on delete cascade,
38
+ dept_id uuid references public.departments(id) on delete set null,
39
+
40
+ -- Contato
41
+ contact_name text not null,
42
+ contact_email text,
43
+ contact_phone text,
44
+ contact_company text,
45
+
46
+ -- Pipeline
47
+ stage text not null default 'lead'
48
+ check (stage in ('lead', 'qualified', 'proposal', 'negotiation', 'won', 'lost')
49
+ or stage like 'custom\_%'),
50
+ source text, -- 'whatsapp_inbound', 'website_form', 'manual', etc.
51
+
52
+ -- Ownership
53
+ owner_id uuid references auth.users(id) on delete set null,
54
+
55
+ -- Dados financeiros
56
+ expected_value numeric(12, 2),
57
+ expected_close_date date,
58
+ closed_at timestamptz,
59
+ closed_reason text,
60
+
61
+ -- Metadata
62
+ metadata jsonb not null default '{}'::jsonb,
63
+ created_at timestamptz not null default now(),
64
+ updated_at timestamptz not null default now(),
65
+
66
+ -- REGRA #4: dedup
67
+ unique (org_id, contact_phone),
68
+ unique (org_id, contact_email)
69
+ );
70
+
71
+ create index leads_org_stage_idx on public.leads (org_id, stage);
72
+ create index leads_org_owner_idx on public.leads (org_id, owner_id) where owner_id is not null;
73
+ create index leads_org_dept_idx on public.leads (org_id, dept_id) where dept_id is not null;
74
+
75
+ -- RLS: aplicar pattern multi-tenant-rls-hierarchy
76
+ alter table public.leads enable row level security;
77
+
78
+ create policy "leads_select_member" on public.leads
79
+ for select to authenticated
80
+ using (private.is_member_of(org_id));
81
+
82
+ create policy "leads_insert_with_permission" on public.leads
83
+ for insert to authenticated
84
+ with check (private.has_permission('create', 'leads', org_id));
85
+
86
+ create policy "leads_update_with_permission_or_owner" on public.leads
87
+ for update to authenticated
88
+ using (
89
+ private.has_permission('update', 'leads', org_id)
90
+ or owner_id = (select auth.uid())
91
+ )
92
+ with check (
93
+ private.has_permission('update', 'leads', org_id)
94
+ or owner_id = (select auth.uid())
95
+ );
96
+
97
+ create policy "leads_delete_admin" on public.leads
98
+ for delete to authenticated
99
+ using (private.has_role(org_id, 'admin') or private.has_role(org_id, 'owner'));
100
+
101
+ create policy "leads_super_admin_bypass" on public.leads
102
+ as permissive for all to authenticated
103
+ using (private.is_super_admin())
104
+ with check (private.is_super_admin());
105
+ ```
106
+
107
+ ### Trigger validação de transição (REGRA #2)
108
+
109
+ ```sql
110
+ -- Tabela de transições permitidas (data-driven)
111
+ create table public.lead_stage_transitions (
112
+ from_stage text not null,
113
+ to_stage text not null,
114
+ primary key (from_stage, to_stage)
115
+ );
116
+
117
+ -- Insert transições canônicas
118
+ insert into public.lead_stage_transitions (from_stage, to_stage) values
119
+ ('lead', 'qualified'),
120
+ ('lead', 'lost'),
121
+ ('qualified', 'proposal'),
122
+ ('qualified', 'lost'),
123
+ ('proposal', 'negotiation'),
124
+ ('proposal', 'lost'),
125
+ ('negotiation', 'won'),
126
+ ('negotiation', 'lost'),
127
+ ('negotiation', 'proposal'), -- back-step permitido
128
+ ('won', 'closed'),
129
+ ('lost', 'lead'), -- reativar lost
130
+ -- self-transition (no-op) sempre permitida
131
+ ('lead', 'lead'), ('qualified', 'qualified'), ('proposal', 'proposal'),
132
+ ('negotiation', 'negotiation'), ('won', 'won'), ('lost', 'lost')
133
+ on conflict do nothing;
134
+
135
+ -- Trigger BEFORE UPDATE valida transição
136
+ create or replace function private.validate_lead_stage_transition()
137
+ returns trigger
138
+ language plpgsql
139
+ security invoker
140
+ set search_path = ''
141
+ as $$
142
+ begin
143
+ if new.stage = old.stage then
144
+ return new; -- no-op
145
+ end if;
146
+
147
+ -- Custom stages: aceitar qualquer transição (admin responsibility)
148
+ if new.stage like 'custom\_%' or old.stage like 'custom\_%' then
149
+ return new;
150
+ end if;
151
+
152
+ -- Validar transição na tabela
153
+ if not exists (
154
+ select 1 from public.lead_stage_transitions
155
+ where from_stage = old.stage and to_stage = new.stage
156
+ ) then
157
+ raise exception 'invalid_lead_transition: % → % not allowed', old.stage, new.stage;
158
+ end if;
159
+
160
+ -- Auto-popular closed_at em won/lost
161
+ if new.stage in ('won', 'lost') and new.closed_at is null then
162
+ new.closed_at := now();
163
+ end if;
164
+
165
+ return new;
166
+ end;
167
+ $$;
168
+
169
+ create trigger validate_lead_stage_transition_trigger
170
+ before update of stage on public.leads
171
+ for each row execute function private.validate_lead_stage_transition();
172
+ ```
173
+
174
+ ### Trigger ownership transfer (REGRA #3)
175
+
176
+ ```sql
177
+ create or replace function private.audit_lead_ownership_change()
178
+ returns trigger
179
+ language plpgsql
180
+ security definer -- precisa escrever em audit_logs mesmo sem permission do user
181
+ set search_path = ''
182
+ as $$
183
+ begin
184
+ if old.owner_id is distinct from new.owner_id then
185
+ -- Audit log
186
+ perform private.audit_log(
187
+ 'custom_lead_ownership_transfer',
188
+ new.org_id,
189
+ new.id, 'lead', null,
190
+ jsonb_build_object(
191
+ 'previous_owner_id', old.owner_id,
192
+ 'new_owner_id', new.owner_id,
193
+ 'lead_stage', new.stage,
194
+ 'lead_value', new.expected_value
195
+ )
196
+ );
197
+
198
+ -- TODO: notificar novo owner (delegar para Edge Function de notification)
199
+ -- perform net.http_post('<edge_fn_url>', ...);
200
+ end if;
201
+ return new;
202
+ end;
203
+ $$;
204
+
205
+ create trigger audit_lead_ownership_change_trigger
206
+ after update of owner_id on public.leads
207
+ for each row execute function private.audit_lead_ownership_change();
208
+ ```
209
+
210
+ ### Lookup contact → lead (integração WhatsApp — REGRA #5)
211
+
212
+ ```typescript
213
+ // supabase/functions/whatsapp-webhook/index.ts (cross-ref Phase 112)
214
+ import { createClient } from 'jsr:@supabase/supabase-js@2'
215
+
216
+ async function handleInboundWhatsApp(orgId: string, contactPhone: string, contactName: string, content: string) {
217
+ const admin = createClient(
218
+ Deno.env.get('SUPABASE_URL')!,
219
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
220
+ )
221
+
222
+ // REGRA #5: lookup ANTES de criar
223
+ const { data: existingLead } = await admin
224
+ .from('leads')
225
+ .select('id, owner_id, stage')
226
+ .eq('org_id', orgId)
227
+ .eq('contact_phone', contactPhone)
228
+ .maybeSingle()
229
+
230
+ if (existingLead) {
231
+ // Append message à conversa existente do lead (não criar novo)
232
+ return existingLead
233
+ }
234
+
235
+ // Criar lead novo
236
+ const { data: newLead } = await admin
237
+ .from('leads')
238
+ .insert({
239
+ org_id: orgId,
240
+ contact_phone: contactPhone,
241
+ contact_name: contactName,
242
+ source: 'whatsapp_inbound',
243
+ stage: 'lead',
244
+ metadata: { first_message: content, channel: 'whatsapp' }
245
+ })
246
+ .select()
247
+ .single()
248
+
249
+ return newLead
250
+ }
251
+ ```
252
+
253
+ ### Frontend kanban — drag&drop entre stages
254
+
255
+ ```typescript
256
+ // LeadsKanban.tsx (sketch para Phase 115)
257
+ async function moveLead(leadId: string, toStage: string) {
258
+ const { error } = await supabase
259
+ .from('leads')
260
+ .update({ stage: toStage })
261
+ .eq('id', leadId)
262
+
263
+ if (error?.message.includes('invalid_lead_transition')) {
264
+ toast.error('Transição inválida — siga ordem do funil')
265
+ }
266
+ }
267
+ ```
268
+
269
+ ## Anti-patterns
270
+
271
+ ### Anti-pattern 1: Apenas CHECK constraint (sem trigger)
272
+
273
+ **Errado:**
274
+ ```sql
275
+ stage text check (stage in ('lead', 'qualified', 'proposal', 'negotiation', 'won', 'lost'))
276
+ -- Update lead diretamente lead → won (sem passar pelos intermediários)
277
+ ```
278
+
279
+ **Por quê:** CHECK valida valor final, não transição. Lead pula etapas → métricas erradas (conversion rate por stage), forecasting quebrado.
280
+
281
+ **Certo:** REGRA #2 — trigger BEFORE UPDATE valida `lead_stage_transitions`.
282
+
283
+ ### Anti-pattern 2: Ownership transfer sem notification
284
+
285
+ **Errado:**
286
+ ```sql
287
+ update leads set owner_id = '<new_owner>' where id = '<lead>';
288
+ -- Owner antigo não sabe que perdeu lead, novo não sabe que ganhou
289
+ ```
290
+
291
+ **Por quê:** transferência silenciosa = lead "esquecido", ninguém follow up, SLA perdido.
292
+
293
+ **Certo:** REGRA #3 — trigger AFTER UPDATE dispara notification (Slack, email, in-app) via Edge Function.
294
+
295
+ ### Anti-pattern 3: Lead duplicate sem dedup
296
+
297
+ **Errado:**
298
+ ```sql
299
+ -- Sem unique constraints
300
+ -- WhatsApp inbound + website form mesmo phone = 2 leads
301
+ ```
302
+
303
+ **Por quê:** vendedor liga 2× mesmo contato, dashboard com count errado, embaraçoso para client.
304
+
305
+ **Certo:** REGRA #4 — `unique(org_id, contact_phone)` + lookup before insert (REGRA #5).
306
+
307
+ ### Anti-pattern 4: Hard delete lead com pipeline activities órfãs
308
+
309
+ **Errado:**
310
+ ```sql
311
+ delete from public.leads where id = '<lead_id>';
312
+ -- pipeline_activities (FK lead_id) ficam órfãs ou cascade deleta histórico
313
+ ```
314
+
315
+ **Por quê:** atividades históricas perdidas = audit trail compromised + analytics afetada.
316
+
317
+ **Certo:** soft delete (`status = 'archived'`) ou FK CASCADE com cuidado + audit log antes.
318
+
319
+ ## Ver também
320
+
321
+ - [b2b-saas-architecture](../b2b-saas-architecture/SKILL.md) — schema base
322
+ - [multi-tenant-rls-hierarchy](../multi-tenant-rls-hierarchy/SKILL.md) — RLS policies
323
+ - [evolution-go-whatsapp-integration](../evolution-go-whatsapp-integration/SKILL.md) — Phase 112, integração inbound
324
+ - [whatsapp-conversation-state-machine](../whatsapp-conversation-state-machine/SKILL.md) — Phase 112, conversa.action_taken → lead
325
+ - [audit-log-multi-tenant](../audit-log-multi-tenant/SKILL.md) — Phase 109, eventos `custom_lead_*`
326
+ - [_shared-multi-tenant/glossary.md](../_shared-multi-tenant/glossary.md) — `lead`, `stages canônicos`, `ownership transfer`, `lead dedup`
@@ -0,0 +1,322 @@
1
+ ---
2
+ name: evolution-go-whatsapp-integration
3
+ description: Use ao integrar Evolution Go (whatsmeow) ou Meta Cloud API com Supabase B2B multi-tenant — webhook handler com tenant_id no URL path, HMAC-SHA256 (Meta) ou API key + IP whitelist (Evolution Go), idempotência via unique(org_id, message_id), rate limit Meta 80 msg/s, throttle Evolution Go 1 msg/s.
4
+ ---
5
+
6
+ # Evolution Go + WhatsApp — Integração Multi-Tenant Supabase
7
+
8
+ ## Quando usar
9
+
10
+ LLM carrega esta skill ao integrar WhatsApp em B2B SaaS multi-tenant. Trigger phrases:
11
+
12
+ - "Evolution Go integration", "evolution-api whatsmeow"
13
+ - "WhatsApp Cloud API Meta", "WhatsApp Business API"
14
+ - "webhook signature HMAC SHA256"
15
+ - "tenant identification webhook"
16
+ - "whatsapp idempotency message_id"
17
+ - "rate limit Meta 80 msg/s", "Evolution Go throttle"
18
+
19
+ ## Regras absolutas
20
+
21
+ **REGRA #1 (HMAC validation antes de JSON.parse — Meta):** Meta envia `X-Hub-Signature-256: sha256=<hmac>` header. Validar HMAC sobre **raw body** **ANTES** de parse JSON. Middleware que parseia primeiro = signature inválida (body mutado).
22
+
23
+ **REGRA #2 (timing-safe comparison):** HMAC validation usa `crypto.timingSafeEqual` (Node) ou `crypto.subtle.timingSafeEqual` (Deno). Comparação `===` direta = timing attack — atacante deduz HMAC byte-a-byte por timing.
24
+
25
+ **REGRA #3 (tenant identification):** Webhook URL contém `org_id`: `/functions/v1/whatsapp/{org_id}/webhook`. Edge Function valida UUID format ANTES de qualquer processamento. Para Evolution Go, alternativa é `instance_name` no payload → lookup `org_id` em tabela `org_whatsapp_configs`.
26
+
27
+ **REGRA #4 (idempotência via unique constraint):** Tabela `whatsapp_messages` tem `unique(org_id, message_id)`. INSERT usa `ON CONFLICT DO NOTHING`. Meta entrega at-least-once com retry 7 dias — duplicatas SÃO normais, não excessões.
28
+
29
+ **REGRA #5 (rate limit Meta — 80 msg/s):** Meta Cloud API: 80 msg/s default por número. Erro 131056 quando exceder, escala para 24h ban se persistir. Throttle server-side via `pgmq` queue ou rate limiter Edge.
30
+
31
+ **REGRA #6 (throttle Evolution Go — 1 msg/s):** Evolution Go usa whatsmeow (protocolo WhatsApp Web não-oficial). WhatsApp Web bane número se enviar massivamente. Default conservador: 1 msg/s manual no app code (biblioteca não enforce).
32
+
33
+ **REGRA #7 (HMAC secret per-org):** Cada org tem `hmac_secret` próprio (gerado no setup, armazenado em `org_whatsapp_configs`). Vazamento de secret de uma org não compromete outras.
34
+
35
+ ## Patterns canônicos
36
+
37
+ ### Tabela `org_whatsapp_configs`
38
+
39
+ ```sql
40
+ create table public.org_whatsapp_configs (
41
+ org_id uuid primary key references public.organizations(id) on delete cascade,
42
+ provider text not null check (provider in ('meta_cloud', 'evolution_go')),
43
+ phone_number_id text, -- Meta Cloud API phone_number_id
44
+ evolution_instance_name text, -- Evolution Go instance name (alternative)
45
+ hmac_secret text, -- per-org webhook HMAC (Meta) — REGRA #7
46
+ api_key_vault_ref text, -- Vault secret reference (não armazenar key direto)
47
+ enabled boolean not null default true,
48
+ created_at timestamptz not null default now()
49
+ );
50
+
51
+ alter table public.org_whatsapp_configs enable row level security;
52
+
53
+ -- RLS: members com permission update:org_settings
54
+ create policy "org_whatsapp_configs_select" on public.org_whatsapp_configs
55
+ for select to authenticated
56
+ using (private.is_member_of(org_id));
57
+
58
+ create policy "org_whatsapp_configs_update" on public.org_whatsapp_configs
59
+ for update to authenticated
60
+ using (private.has_permission('update', 'org_settings', org_id))
61
+ with check (private.has_permission('update', 'org_settings', org_id));
62
+ ```
63
+
64
+ ### Tabela `whatsapp_messages` — idempotency built-in
65
+
66
+ ```sql
67
+ create table public.whatsapp_messages (
68
+ id uuid primary key default gen_random_uuid(),
69
+ org_id uuid not null references public.organizations(id) on delete cascade,
70
+ message_id text not null, -- ID do WhatsApp (provider)
71
+ direction text not null check (direction in ('inbound', 'outbound')),
72
+ contact_phone text not null,
73
+ contact_name text,
74
+ content text,
75
+ message_type text check (message_type in ('text', 'image', 'audio', 'document', 'location', 'contact', 'reaction')),
76
+ payload jsonb, -- raw payload do provider
77
+ status text default 'received' check (status in ('received', 'sent', 'delivered', 'read', 'failed')),
78
+ conversation_id uuid, -- FK para conversations (state machine)
79
+ received_at timestamptz not null default now(),
80
+ unique (org_id, message_id) -- REGRA #4: idempotency
81
+ );
82
+
83
+ create index whatsapp_messages_org_phone_idx on public.whatsapp_messages (org_id, contact_phone, received_at desc);
84
+ create index whatsapp_messages_conversation_idx on public.whatsapp_messages (conversation_id) where conversation_id is not null;
85
+
86
+ alter table public.whatsapp_messages enable row level security;
87
+ -- RLS standard multi-tenant (members lê todas, super_admin bypass)
88
+ ```
89
+
90
+ ### Webhook handler — Edge Function (Meta Cloud)
91
+
92
+ ```typescript
93
+ // supabase/functions/whatsapp-webhook/index.ts
94
+ import { createClient } from 'jsr:@supabase/supabase-js@2'
95
+ import { encodeHex } from 'jsr:@std/encoding@1/hex'
96
+
97
+ // REGRA #2: timing-safe comparison nativo Deno
98
+ async function verifyHmac(rawBody: string, signature: string, secret: string): Promise<boolean> {
99
+ const key = await crypto.subtle.importKey(
100
+ 'raw',
101
+ new TextEncoder().encode(secret),
102
+ { name: 'HMAC', hash: 'SHA-256' },
103
+ false,
104
+ ['sign']
105
+ )
106
+
107
+ const computedSig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(rawBody))
108
+ const expected = encodeHex(new Uint8Array(computedSig))
109
+
110
+ // Timing-safe comparison
111
+ if (signature.length !== expected.length) return false
112
+ let result = 0
113
+ for (let i = 0; i < signature.length; i++) {
114
+ result |= signature.charCodeAt(i) ^ expected.charCodeAt(i)
115
+ }
116
+ return result === 0
117
+ }
118
+
119
+ Deno.serve(async (req) => {
120
+ // REGRA #3: extract org_id from URL path
121
+ const url = new URL(req.url)
122
+ const pathParts = url.pathname.split('/')
123
+ const orgId = pathParts[pathParts.length - 2] // /whatsapp/<org_id>/webhook
124
+ if (!orgId.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)) {
125
+ return new Response('invalid_org_id', { status: 400 })
126
+ }
127
+
128
+ // REGRA #1: read raw body BEFORE parse
129
+ const rawBody = await req.text()
130
+
131
+ // service_role para acessar org_whatsapp_configs (webhook não tem JWT user)
132
+ const admin = createClient(
133
+ Deno.env.get('SUPABASE_URL')!,
134
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
135
+ )
136
+
137
+ // Buscar HMAC secret da org
138
+ const { data: config } = await admin
139
+ .from('org_whatsapp_configs')
140
+ .select('hmac_secret, provider, enabled')
141
+ .eq('org_id', orgId)
142
+ .single()
143
+
144
+ if (!config || !config.enabled) {
145
+ return new Response('config_not_found_or_disabled', { status: 404 })
146
+ }
147
+
148
+ // Validar HMAC (Meta) — REGRA #1 + #2
149
+ if (config.provider === 'meta_cloud') {
150
+ const sigHeader = req.headers.get('x-hub-signature-256') || ''
151
+ const sig = sigHeader.replace('sha256=', '')
152
+ if (!await verifyHmac(rawBody, sig, config.hmac_secret)) {
153
+ return new Response('invalid_signature', { status: 403 })
154
+ }
155
+ } else if (config.provider === 'evolution_go') {
156
+ // Evolution Go usa API key + IP whitelist (HMAC não documentada)
157
+ const apiKey = req.headers.get('apikey')
158
+ if (apiKey !== Deno.env.get('EVOLUTION_GO_API_KEY')) {
159
+ return new Response('invalid_api_key', { status: 403 })
160
+ }
161
+ // Optional: validar IP origem em allowlist
162
+ }
163
+
164
+ // Agora parse JSON (signature já validada)
165
+ const payload = JSON.parse(rawBody)
166
+
167
+ // Extrair message do payload (formato varia por provider)
168
+ const messages = config.provider === 'meta_cloud'
169
+ ? payload.entry?.[0]?.changes?.[0]?.value?.messages || []
170
+ : payload.data?.messages || [payload.data]
171
+
172
+ // REGRA #4: idempotent insert
173
+ for (const msg of messages) {
174
+ const { error } = await admin.from('whatsapp_messages').insert({
175
+ org_id: orgId,
176
+ message_id: msg.id,
177
+ direction: 'inbound',
178
+ contact_phone: msg.from,
179
+ contact_name: msg.profile?.name,
180
+ content: msg.text?.body || null,
181
+ message_type: msg.type,
182
+ payload: msg
183
+ })
184
+ // ON CONFLICT (org_id, message_id) DO NOTHING — duplicate ignored silently
185
+ // (Postgres returns 0 rows affected, no error)
186
+ }
187
+
188
+ // Audit log inbound
189
+ await admin.rpc('audit_log', {
190
+ p_event_type: 'custom_whatsapp_webhook_received',
191
+ p_tenant_id: orgId,
192
+ p_payload: { message_count: messages.length, provider: config.provider }
193
+ })
194
+
195
+ // Meta espera 200 OK rapidamente (timeout 20s — processamento longo deve ser async)
196
+ return new Response('ok', { status: 200 })
197
+ })
198
+ ```
199
+
200
+ ### Send message com rate limit (Meta Cloud)
201
+
202
+ ```typescript
203
+ // supabase/functions/whatsapp-send/index.ts
204
+ // PT-BR: rate limiter via pgmq (queue + worker) para respeitar 80 msg/s Meta
205
+ // REGRA #5
206
+
207
+ Deno.serve(async (req) => {
208
+ const auth = req.headers.get('Authorization')
209
+ // ... validate JWT, extract org_id ...
210
+
211
+ const { to, message } = await req.json()
212
+
213
+ // Em vez de enviar direto, enfilera em pgmq (rate limit no consumer)
214
+ await admin.rpc('pgmq_send', {
215
+ queue_name: `whatsapp_outbound_${orgId.replace(/-/g, '_')}`,
216
+ msg: { to, message, sent_by: caller.id, timestamp: new Date() }
217
+ })
218
+
219
+ return new Response(JSON.stringify({ queued: true }), { status: 202 })
220
+ })
221
+
222
+ // Worker separado (cron 1s) consome queue e chama Meta API respeitando 80 msg/s
223
+ // (Edge Function `whatsapp-send-worker` invocada por pg_cron a cada 1s)
224
+ ```
225
+
226
+ ### Lookup contact → lead (integração CRM)
227
+
228
+ ```typescript
229
+ // Em handler webhook, após inserir whatsapp_messages, criar/lookup lead
230
+ const { data: existingLead } = await admin
231
+ .from('leads')
232
+ .select('id, owner_id')
233
+ .eq('org_id', orgId)
234
+ .eq('contact_phone', msg.from)
235
+ .maybeSingle()
236
+
237
+ if (!existingLead) {
238
+ // Auto-create lead (Phase 113)
239
+ await admin.from('leads').insert({
240
+ org_id: orgId,
241
+ contact_phone: msg.from,
242
+ contact_name: msg.profile?.name,
243
+ stage: 'lead',
244
+ source: 'whatsapp_inbound'
245
+ })
246
+ }
247
+ ```
248
+
249
+ ## Anti-patterns
250
+
251
+ ### Anti-pattern 1: HMAC validation depois de JSON.parse
252
+
253
+ **Errado:**
254
+ ```typescript
255
+ const payload = await req.json() // body já parsed e mutado
256
+ if (!verifyHmac(JSON.stringify(payload), sig, secret)) { ... } // signature inválida!
257
+ ```
258
+
259
+ **Por quê:** `JSON.stringify(JSON.parse(body))` não retorna bytes idênticos ao original (espaço, ordem keys, números). Hash diferente. Validação sempre falha (ou nunca falha, dependendo do bug).
260
+
261
+ **Certo:** `req.text()` para raw body, validar HMAC, depois `JSON.parse(rawBody)`.
262
+
263
+ ### Anti-pattern 2: Comparação `===` em HMAC
264
+
265
+ **Errado:**
266
+ ```typescript
267
+ if (computedSig === providedSig) { ... }
268
+ ```
269
+
270
+ **Por quê:** comparação JS faz short-circuit no primeiro byte diferente. Atacante mede tempo de resposta, deduz HMAC byte-a-byte ao longo de horas.
271
+
272
+ **Certo:** REGRA #2 — `crypto.subtle.timingSafeEqual` ou loop XOR-only.
273
+
274
+ ### Anti-pattern 3: Webhook sem idempotency
275
+
276
+ **Errado:**
277
+ ```typescript
278
+ await admin.from('whatsapp_messages').insert({ ..., message_id: msg.id })
279
+ // Sem ON CONFLICT — segundo retry duplica
280
+ ```
281
+
282
+ **Por quê:** Meta retry behavior at-least-once por 7 dias. Sem dedup, mesma mensagem entra N vezes na DB → CRM com leads duplicadas, contagens erradas, cobrança errada.
283
+
284
+ **Certo:** REGRA #4 — `unique(org_id, message_id)` + `ON CONFLICT DO NOTHING`.
285
+
286
+ ### Anti-pattern 4: Send direto sem rate limit
287
+
288
+ **Errado:**
289
+ ```typescript
290
+ // Loop enviando 1000 mensagens
291
+ for (const lead of leads) {
292
+ await fetch('https://graph.facebook.com/.../messages', { body: ... })
293
+ }
294
+ // → 80 msg/s exceeded → erro 131056 → 24h ban do número
295
+ ```
296
+
297
+ **Por quê:** Meta enforce rigoroso. Penalty é severa (24h sem usar o número = perda de cliente real ligando).
298
+
299
+ **Certo:** REGRA #5 — pgmq queue + worker com rate limit 80 msg/s. Para Evolution Go, REGRA #6 — 1 msg/s manual.
300
+
301
+ ### Anti-pattern 5: HMAC secret compartilhado entre orgs
302
+
303
+ **Errado:**
304
+ ```typescript
305
+ const secret = Deno.env.get('META_HMAC_SECRET') // global, mesmo para todas orgs
306
+ ```
307
+
308
+ **Por quê:** vazamento via uma org = comprometimento de todas. Compliance multi-tenant exige isolation.
309
+
310
+ **Certo:** REGRA #7 — `hmac_secret` em `org_whatsapp_configs` per-org. Generate no setup do Meta App per-org.
311
+
312
+ ## Ver também
313
+
314
+ - [whatsapp-conversation-state-machine](../whatsapp-conversation-state-machine/SKILL.md) — Phase 112 sibling, modelagem de conversas
315
+ - [crm-lead-pipeline-patterns](../crm-lead-pipeline-patterns/SKILL.md) — Phase 113, lookup contact→lead
316
+ - [audit-log-multi-tenant](../audit-log-multi-tenant/SKILL.md) — Phase 109, eventos `custom_whatsapp_*`
317
+ - [supabase-cron-queues](../supabase-cron-queues/SKILL.md) — pgmq queue + worker pattern para rate limit
318
+ - [supabase-edge-fn-writer](../../agents/supabase-edge-fn-writer.md) — agent que escreve Edge Functions
319
+ - [_shared-multi-tenant/glossary.md](../_shared-multi-tenant/glossary.md) — `Evolution Go`, `Meta Cloud API`, `HMAC-SHA256`, `idempotency key`, `rate limit Meta`
320
+ - [Meta Developers — WhatsApp Webhooks](https://developers.facebook.com/docs/whatsapp/cloud-api/guides/set-up-webhooks/)
321
+ - [Meta Developers — Messaging Limits](https://developers.facebook.com/docs/whatsapp/messaging-limits/)
322
+ - [Evolution API Documentation](https://doc.evolution-api.com/v2/en/configuration/webhooks)