@luanpdd/kit-mcp 1.20.0 → 1.22.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.
- package/README.md +1 -1
- package/gates/dept-cycle-prevention.md +179 -0
- package/gates/multi-tenant-rls-coverage.md +102 -0
- package/gates/service-role-not-in-user-facing.md +113 -0
- package/kit/README.md +24 -0
- package/kit/agents/audit-log-implementer.md +175 -0
- package/kit/agents/auditor-consistencia-isolamento.md +380 -0
- package/kit/agents/b2b-saas-architect.md +156 -0
- package/kit/agents/crm-pipeline-implementer.md +167 -0
- package/kit/agents/detector-tenant-quente.md +337 -0
- package/kit/agents/evolution-go-integrator.md +179 -0
- package/kit/agents/invite-flow-implementer.md +137 -0
- package/kit/agents/lgpd-compliance-auditor.md +206 -0
- package/kit/agents/multi-tenant-isolation-auditor.md +253 -0
- package/kit/agents/multi-tenant-rls-writer.md +262 -0
- package/kit/agents/org-onboarding-implementer.md +202 -0
- package/kit/agents/supabase-architect.md +10 -0
- package/kit/agents/supabase-migration-writer.md +12 -0
- package/kit/agents/super-admin-implementer.md +182 -0
- package/kit/agents/validador-evolucao-schema.md +335 -0
- package/kit/commands/dados-distribuidos.md +188 -0
- package/kit/commands/multi-tenant.md +163 -0
- package/kit/file-manifest.json +48 -9
- package/kit/skills/_shared-dados-distribuidos/glossary.md +224 -0
- package/kit/skills/_shared-multi-tenant/glossary.md +186 -0
- package/kit/skills/armadilhas-sistemas-distribuidos/SKILL.md +447 -0
- package/kit/skills/audit-log-multi-tenant/SKILL.md +340 -0
- package/kit/skills/b2b-saas-architecture/SKILL.md +300 -0
- package/kit/skills/cascading-failures/SKILL.md +4 -0
- package/kit/skills/consistencia-leitura-replica/SKILL.md +385 -0
- package/kit/skills/crm-lead-pipeline-patterns/SKILL.md +343 -0
- package/kit/skills/escolha-modelo-consistencia/SKILL.md +495 -0
- package/kit/skills/evolucao-schema-compativel/SKILL.md +448 -0
- package/kit/skills/evolution-go-whatsapp-integration/SKILL.md +322 -0
- package/kit/skills/lgpd-multi-tenant-compliance/SKILL.md +340 -0
- package/kit/skills/member-invite-flow/SKILL.md +305 -0
- package/kit/skills/member-management-react-shadcn/SKILL.md +328 -0
- package/kit/skills/multi-tenant-performance-scaling/SKILL.md +316 -0
- package/kit/skills/multi-tenant-rls-hierarchy/SKILL.md +342 -0
- package/kit/skills/org-onboarding-flow/SKILL.md +257 -0
- package/kit/skills/org-switcher-react-pattern/SKILL.md +349 -0
- package/kit/skills/permission-gate-react-pattern/SKILL.md +271 -0
- package/kit/skills/postgres-isolamento-concorrencia/SKILL.md +552 -0
- package/kit/skills/rbac-permissions-matrix-supabase/SKILL.md +301 -0
- package/kit/skills/streams-eventos-cdc/SKILL.md +712 -0
- package/kit/skills/supabase-cron-queues/SKILL.md +9 -0
- package/kit/skills/supabase-migrations/SKILL.md +10 -0
- package/kit/skills/super-admin-platform-pattern/SKILL.md +326 -0
- package/kit/skills/tenant-quente-mitigacao/SKILL.md +605 -0
- package/kit/skills/whatsapp-conversation-state-machine/SKILL.md +287 -0
- package/package.json +1 -1
|
@@ -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)
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: lgpd-multi-tenant-compliance
|
|
3
|
+
description: Use ao implementar compliance LGPD (Lei 13.709/2018) per-tenant em B2B SaaS Supabase — 9 direitos Art. 18 com workflow per-org, DSR SLA 15 dias Art. 19 + alert pg_cron D-3, consent management granular default opt-out (Art. 8 §5), erasure via anonymization (não hard delete), cross-border config Brasil-UE adequacy jan/2026.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# LGPD Multi-Tenant Compliance — Lei 13.709/2018
|
|
7
|
+
|
|
8
|
+
## Quando usar
|
|
9
|
+
|
|
10
|
+
LLM carrega esta skill ao implementar compliance LGPD em B2B SaaS Brasil. Trigger phrases:
|
|
11
|
+
|
|
12
|
+
- "LGPD compliance", "Lei 13.709"
|
|
13
|
+
- "DSR data subject request"
|
|
14
|
+
- "consent management granular"
|
|
15
|
+
- "erasure anonymization LGPD"
|
|
16
|
+
- "cross-border data transfer Brazil"
|
|
17
|
+
- "ANPD adequacy decision"
|
|
18
|
+
|
|
19
|
+
## Regras absolutas
|
|
20
|
+
|
|
21
|
+
**REGRA #1 (DSR SLA 15 dias — Art. 19):** Toda DSR (Data Subject Request) deve ser processada em **15 dias corridos** (Art. 19 LGPD). Tabela `data_subject_requests` com `deadline_at = created_at + 15 days`. Pg_cron D-3 alerta requests próximas do prazo.
|
|
22
|
+
|
|
23
|
+
**REGRA #2 (consent default opt-out — Art. 8 §5):** Consentimento LGPD deve ser **livre, informado, inequívoco**. Default opt-in é **ilegal** (Art. 8 §5). UI deve apresentar checkboxes desmarcados por default. Multa: até R$50M ou 2% faturamento.
|
|
24
|
+
|
|
25
|
+
**REGRA #3 (consent granular):** Consentimento separado por **finalidade** — analytics ≠ marketing ≠ third-party-share ≠ profiling. User pode aceitar uma e rejeitar outra. Consent bundling (uma checkbox para tudo) é vedado.
|
|
26
|
+
|
|
27
|
+
**REGRA #4 (erasure via anonymization):** Direito à eliminação (Art. 18 VI) implementado via **anonymization**: preservar UUID (chave opaca), apagar PII (`name → NULL`, `email → SHA-256 hash`, `phone → NULL`). Hard delete destrói audit trail necessário para outras compliance obrigations.
|
|
28
|
+
|
|
29
|
+
**REGRA #5 (cross-border config):** Para apps com clientes brasileiros, Vercel deploy region `gru1` (São Paulo) + Supabase project region `sa-east-1` mantêm dados em repouso no Brasil. Adequacy decision Brasil-UE estabelecida em janeiro/2026 permite EU regions sem SCCs adicionais.
|
|
30
|
+
|
|
31
|
+
**REGRA #6 (per-tenant — não global):** Cada org tem sua própria política de retention/consent. App é controlador de dados em alguns casos, operador em outros (Art. 5). Per-tenant implementação respeita esta diversidade.
|
|
32
|
+
|
|
33
|
+
## Patterns canônicos
|
|
34
|
+
|
|
35
|
+
### Tabela `consent_records`
|
|
36
|
+
|
|
37
|
+
```sql
|
|
38
|
+
create table public.consent_records (
|
|
39
|
+
id uuid primary key default gen_random_uuid(),
|
|
40
|
+
org_id uuid not null references public.organizations(id) on delete cascade,
|
|
41
|
+
user_id uuid not null references auth.users(id) on delete cascade,
|
|
42
|
+
purpose text not null
|
|
43
|
+
check (purpose in (
|
|
44
|
+
'analytics', -- analytics próprio (PostHog, Mixpanel)
|
|
45
|
+
'marketing_email', -- envio email marketing
|
|
46
|
+
'marketing_whatsapp', -- envio WhatsApp marketing
|
|
47
|
+
'third_party_share', -- compartilhamento com parceiros
|
|
48
|
+
'profiling', -- perfilamento comportamental
|
|
49
|
+
'cookies_optional' -- cookies não-essenciais
|
|
50
|
+
) or purpose like 'custom\_%'),
|
|
51
|
+
granted boolean not null,
|
|
52
|
+
granted_at timestamptz not null default now(),
|
|
53
|
+
revoked_at timestamptz,
|
|
54
|
+
source text not null default 'app_settings'
|
|
55
|
+
check (source in ('app_settings', 'cookie_banner', 'signup_form', 'api')),
|
|
56
|
+
ip_address inet,
|
|
57
|
+
user_agent text,
|
|
58
|
+
unique (org_id, user_id, purpose, granted_at) -- histórico audited
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
create index consent_records_org_user_purpose_idx
|
|
62
|
+
on public.consent_records (org_id, user_id, purpose, granted_at desc);
|
|
63
|
+
|
|
64
|
+
alter table public.consent_records enable row level security;
|
|
65
|
+
|
|
66
|
+
create policy "consent_records_select_own" on public.consent_records
|
|
67
|
+
for select to authenticated
|
|
68
|
+
using (user_id = (select auth.uid()));
|
|
69
|
+
|
|
70
|
+
create policy "consent_records_insert_own" on public.consent_records
|
|
71
|
+
for insert to authenticated
|
|
72
|
+
with check (user_id = (select auth.uid()));
|
|
73
|
+
|
|
74
|
+
create policy "consent_records_admin_view" on public.consent_records
|
|
75
|
+
for select to authenticated
|
|
76
|
+
using (private.has_permission('process', 'dsr_requests', org_id));
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### Helper `current_consent`
|
|
80
|
+
|
|
81
|
+
```sql
|
|
82
|
+
create or replace function private.current_consent(p_org_id uuid, p_user_id uuid, p_purpose text)
|
|
83
|
+
returns boolean
|
|
84
|
+
language sql
|
|
85
|
+
stable
|
|
86
|
+
security invoker
|
|
87
|
+
set search_path = ''
|
|
88
|
+
as $$
|
|
89
|
+
select coalesce(
|
|
90
|
+
(select granted from public.consent_records
|
|
91
|
+
where org_id = p_org_id and user_id = p_user_id and purpose = p_purpose
|
|
92
|
+
order by granted_at desc limit 1),
|
|
93
|
+
false -- REGRA #2: default opt-out se não houver registro
|
|
94
|
+
);
|
|
95
|
+
$$;
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Tabela `data_subject_requests`
|
|
99
|
+
|
|
100
|
+
```sql
|
|
101
|
+
create table public.data_subject_requests (
|
|
102
|
+
id uuid primary key default gen_random_uuid(),
|
|
103
|
+
org_id uuid not null references public.organizations(id) on delete cascade,
|
|
104
|
+
requester_user_id uuid references auth.users(id) on delete set null,
|
|
105
|
+
requester_email text not null,
|
|
106
|
+
request_type text not null
|
|
107
|
+
check (request_type in (
|
|
108
|
+
'confirmation', -- Art. 18 I — confirmação da existência de tratamento
|
|
109
|
+
'access', -- Art. 18 II — acesso aos dados
|
|
110
|
+
'correction', -- Art. 18 III — correção
|
|
111
|
+
'anonymization', -- Art. 18 IV — anonimização/bloqueio/eliminação parcial
|
|
112
|
+
'portability', -- Art. 18 V — portabilidade
|
|
113
|
+
'erasure', -- Art. 18 VI — eliminação completa
|
|
114
|
+
'sharing_info', -- Art. 18 VII — informação sobre compartilhamento
|
|
115
|
+
'consent_revoke', -- Art. 18 IX — revogação consentimento
|
|
116
|
+
'automated_review' -- Art. 18 — revisão decisão automatizada
|
|
117
|
+
)),
|
|
118
|
+
description text,
|
|
119
|
+
status text not null default 'pending'
|
|
120
|
+
check (status in ('pending', 'in_progress', 'completed', 'rejected', 'expired')),
|
|
121
|
+
deadline_at timestamptz not null default (now() + interval '15 days'), -- REGRA #1 Art. 19
|
|
122
|
+
completed_at timestamptz,
|
|
123
|
+
rejected_reason text,
|
|
124
|
+
result jsonb, -- payload de resposta (export, etc.)
|
|
125
|
+
created_at timestamptz not null default now()
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
create index dsr_org_status_deadline_idx on public.data_subject_requests (org_id, status, deadline_at);
|
|
129
|
+
|
|
130
|
+
alter table public.data_subject_requests enable row level security;
|
|
131
|
+
|
|
132
|
+
-- Apenas users com permission process:dsr_requests
|
|
133
|
+
create policy "dsr_select_with_permission" on public.data_subject_requests
|
|
134
|
+
for select to authenticated
|
|
135
|
+
using (private.has_permission('process', 'dsr_requests', org_id));
|
|
136
|
+
|
|
137
|
+
-- Insert: qualquer authenticated pode criar request para si próprio
|
|
138
|
+
create policy "dsr_insert_self" on public.data_subject_requests
|
|
139
|
+
for insert to authenticated
|
|
140
|
+
with check (
|
|
141
|
+
requester_user_id = (select auth.uid())
|
|
142
|
+
or requester_email = (select email from auth.users where id = (select auth.uid()))
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
create policy "dsr_super_admin" on public.data_subject_requests
|
|
146
|
+
as permissive for all to authenticated
|
|
147
|
+
using (private.is_super_admin())
|
|
148
|
+
with check (private.is_super_admin());
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### Cron alert D-3 (3 dias antes do prazo)
|
|
152
|
+
|
|
153
|
+
```sql
|
|
154
|
+
select cron.schedule(
|
|
155
|
+
'dsr-deadline-alert-d3',
|
|
156
|
+
'0 9 * * *', -- diário 9:00 UTC
|
|
157
|
+
$$
|
|
158
|
+
-- Notificar admin (via Edge Function notification) sobre DSRs próximas do prazo
|
|
159
|
+
insert into public.notifications (org_id, type, payload)
|
|
160
|
+
select
|
|
161
|
+
org_id,
|
|
162
|
+
'dsr_deadline_warning',
|
|
163
|
+
jsonb_build_object(
|
|
164
|
+
'request_id', id,
|
|
165
|
+
'days_remaining', extract(day from deadline_at - now()),
|
|
166
|
+
'request_type', request_type
|
|
167
|
+
)
|
|
168
|
+
from public.data_subject_requests
|
|
169
|
+
where status in ('pending', 'in_progress')
|
|
170
|
+
and deadline_at < now() + interval '3 days'
|
|
171
|
+
and deadline_at >= now()
|
|
172
|
+
and id not in (
|
|
173
|
+
select (payload->>'request_id')::uuid from public.notifications
|
|
174
|
+
where type = 'dsr_deadline_warning'
|
|
175
|
+
and created_at > now() - interval '24 hours'
|
|
176
|
+
);
|
|
177
|
+
$$
|
|
178
|
+
);
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### Erasure via anonymization (REGRA #4)
|
|
182
|
+
|
|
183
|
+
```sql
|
|
184
|
+
-- RPC chamada quando admin processa DSR de erasure
|
|
185
|
+
create or replace function public.process_erasure_request(p_dsr_id uuid)
|
|
186
|
+
returns void
|
|
187
|
+
language plpgsql
|
|
188
|
+
security invoker
|
|
189
|
+
set search_path = ''
|
|
190
|
+
as $$
|
|
191
|
+
declare
|
|
192
|
+
v_dsr record;
|
|
193
|
+
v_user_id uuid;
|
|
194
|
+
begin
|
|
195
|
+
-- Validar permission
|
|
196
|
+
select * into v_dsr from public.data_subject_requests where id = p_dsr_id;
|
|
197
|
+
if v_dsr is null then raise exception 'dsr_not_found'; end if;
|
|
198
|
+
if not private.has_permission('process', 'dsr_requests', v_dsr.org_id) then
|
|
199
|
+
raise exception 'forbidden';
|
|
200
|
+
end if;
|
|
201
|
+
|
|
202
|
+
v_user_id := v_dsr.requester_user_id;
|
|
203
|
+
if v_user_id is null then
|
|
204
|
+
raise exception 'erasure_requires_user_id';
|
|
205
|
+
end if;
|
|
206
|
+
|
|
207
|
+
-- Anonymize across all tenant tables (preservar UUID)
|
|
208
|
+
-- 1. organization_members
|
|
209
|
+
update public.organization_members
|
|
210
|
+
set status = 'left'
|
|
211
|
+
where user_id = v_user_id and org_id = v_dsr.org_id;
|
|
212
|
+
|
|
213
|
+
-- 2. leads (owner_id e contact data)
|
|
214
|
+
update public.leads
|
|
215
|
+
set
|
|
216
|
+
owner_id = null, -- preserva FK opcional
|
|
217
|
+
contact_email = encode(digest(coalesce(contact_email, ''), 'sha256'), 'hex'),
|
|
218
|
+
contact_phone = null,
|
|
219
|
+
contact_name = '[anonymized]'
|
|
220
|
+
where org_id = v_dsr.org_id
|
|
221
|
+
and (owner_id = v_user_id); -- leads owned por este user
|
|
222
|
+
|
|
223
|
+
-- 3. audit_logs — preservar (REGRA #4: não destruir trail), apenas anonimizar
|
|
224
|
+
update public.audit_logs
|
|
225
|
+
set
|
|
226
|
+
actor_id = null,
|
|
227
|
+
actor_email_hash = '[anonymized]',
|
|
228
|
+
payload = payload - 'actor_email' - 'ip_address'
|
|
229
|
+
where actor_id = v_user_id and tenant_id = v_dsr.org_id;
|
|
230
|
+
|
|
231
|
+
-- 4. (em audit_logs com legal_hold = true não anonimizar — preservar evidence)
|
|
232
|
+
-- (já filtrado pelo update acima — apenas tocá-lo após legal hold ser liberado)
|
|
233
|
+
|
|
234
|
+
-- 5. Marcar DSR como completed
|
|
235
|
+
update public.data_subject_requests
|
|
236
|
+
set status = 'completed', completed_at = now(), result = jsonb_build_object('anonymized', true)
|
|
237
|
+
where id = p_dsr_id;
|
|
238
|
+
|
|
239
|
+
-- 6. Audit
|
|
240
|
+
perform private.audit_log(
|
|
241
|
+
'data_exported',
|
|
242
|
+
v_dsr.org_id,
|
|
243
|
+
v_user_id, 'user', v_dsr.requester_email,
|
|
244
|
+
jsonb_build_object('action', 'erasure_completed', 'dsr_id', p_dsr_id)
|
|
245
|
+
);
|
|
246
|
+
end;
|
|
247
|
+
$$;
|
|
248
|
+
|
|
249
|
+
grant execute on function public.process_erasure_request(uuid) to authenticated;
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
### Cross-border config (REGRA #5)
|
|
253
|
+
|
|
254
|
+
```typescript
|
|
255
|
+
// next.config.js (Vercel)
|
|
256
|
+
module.exports = {
|
|
257
|
+
// Edge Functions só rodam em São Paulo
|
|
258
|
+
experimental: {
|
|
259
|
+
serverActions: {
|
|
260
|
+
allowedOrigins: ['*.vercel.app']
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
// Force region para Edge runtime
|
|
264
|
+
runtime: 'edge',
|
|
265
|
+
regions: ['gru1'] // São Paulo
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Supabase project criado em sa-east-1 (São Paulo) — escolher na criação
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
## Anti-patterns
|
|
272
|
+
|
|
273
|
+
### Anti-pattern 1: Hard delete em erasure flow
|
|
274
|
+
|
|
275
|
+
**Errado:**
|
|
276
|
+
```sql
|
|
277
|
+
delete from auth.users where id = '<user>' cascade;
|
|
278
|
+
-- audit_logs cascade deletado, evidence destroyed
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
**Por quê:** destrói audit trail necessário para outras obrigações compliance (investigação fraudulenta, anti-money-laundering, registros fiscais 5 anos).
|
|
282
|
+
|
|
283
|
+
**Certo:** REGRA #4 — anonymization. UUID preservado, PII apagada.
|
|
284
|
+
|
|
285
|
+
### Anti-pattern 2: Consent default opt-in
|
|
286
|
+
|
|
287
|
+
**Errado:**
|
|
288
|
+
```html
|
|
289
|
+
<input type="checkbox" name="marketing" checked> <!-- pre-marked -->
|
|
290
|
+
<label>Aceito receber emails de marketing</label>
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
**Por quê:** Art. 8 §5 LGPD: consentimento deve ser livre, informado, inequívoco. Pre-checked = bundle implícito = ilegal.
|
|
294
|
+
|
|
295
|
+
**Certo:** REGRA #2 — checkbox unchecked, user precisa clicar explicitamente.
|
|
296
|
+
|
|
297
|
+
### Anti-pattern 3: Consent bundling
|
|
298
|
+
|
|
299
|
+
**Errado:**
|
|
300
|
+
```html
|
|
301
|
+
<input type="checkbox" name="all_consents">
|
|
302
|
+
<label>Aceito termos, privacy policy, marketing, analytics e third-party share</label>
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
**Por quê:** REGRA #3 — consentimentos devem ser separados por finalidade. User não pode "aceitar tudo" via 1 checkbox.
|
|
306
|
+
|
|
307
|
+
**Certo:** N checkboxes individuais para cada `consent_records.purpose`.
|
|
308
|
+
|
|
309
|
+
### Anti-pattern 4: DSR sem deadline tracking
|
|
310
|
+
|
|
311
|
+
**Errado:**
|
|
312
|
+
```sql
|
|
313
|
+
-- Tabela sem deadline_at
|
|
314
|
+
-- Admin esquece request, prazo 15 dias passa, ANPD multa
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
**Por quê:** Art. 19 prazo legal — descumprimento = multa.
|
|
318
|
+
|
|
319
|
+
**Certo:** REGRA #1 — `deadline_at` automático + pg_cron alert D-3.
|
|
320
|
+
|
|
321
|
+
### Anti-pattern 5: PII em audit_logs raw
|
|
322
|
+
|
|
323
|
+
**Errado:**
|
|
324
|
+
```sql
|
|
325
|
+
insert into audit_logs (actor_email, payload) values ('user@email.com', '{"phone":"+5511999"}');
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
**Por quê:** quando user solicita erasure, audit_logs também precisa anonimizar. Mas hash = não há referência à PII original.
|
|
329
|
+
|
|
330
|
+
**Certo:** já desde início, hash actor_email + sanitize payload (cross-ref Phase 109 audit-log-multi-tenant REGRA #4).
|
|
331
|
+
|
|
332
|
+
## Ver também
|
|
333
|
+
|
|
334
|
+
- [audit-log-multi-tenant](../audit-log-multi-tenant/SKILL.md) — Phase 109, PII sanitization + legal_hold flag
|
|
335
|
+
- [b2b-saas-architecture](../b2b-saas-architecture/SKILL.md) — schema base
|
|
336
|
+
- [supabase-cron-queues](../supabase-cron-queues/SKILL.md) — pg_cron pattern para alert D-3
|
|
337
|
+
- [super-admin-platform-pattern](../super-admin-platform-pattern/SKILL.md) — Phase 111, super_admin process DSR
|
|
338
|
+
- [_shared-multi-tenant/glossary.md](../_shared-multi-tenant/glossary.md) — `LGPD`, `DSR`, `9 direitos LGPD`, `anonymization`, `consent grain`, `adequacy decision`
|
|
339
|
+
- [LGPD — Lei 13.709/2018](https://www.planalto.gov.br/ccivil_03/_ato2015-2018/2018/lei/l13709.htm)
|
|
340
|
+
- [ANPD — International Data Transfers](https://www.gov.br/anpd/)
|