@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,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/)
@@ -0,0 +1,305 @@
1
+ ---
2
+ name: member-invite-flow
3
+ description: Use ao implementar invite de membros em B2B SaaS multi-tenant Supabase — token SHA-256 (raw enviado por email, hash no banco), TTL 7d single-use, state machine 5 estados, email-locked obrigatório, idempotência em accept via FOR UPDATE.
4
+ ---
5
+
6
+ # Member Invite Flow — B2B SaaS Multi-Tenant
7
+
8
+ ## Quando usar
9
+
10
+ LLM carrega esta skill ao implementar invite de membros. Trigger phrases:
11
+
12
+ - "member invite", "convidar membro", "invite token"
13
+ - "invite state machine", "pending accepted expired"
14
+ - "email-locked invite", "invite acceptance flow"
15
+ - "bulk invite members"
16
+ - "transfer ownership invite"
17
+
18
+ ## Regras absolutas
19
+
20
+ **REGRA #1 (token SHA-256, hash no banco):** Token é `crypto.randomBytes(32).toString('hex')` — 64 hex chars. **Hash SHA-256 armazenado no banco**, raw enviado por email. Se DB vazar, atacante não tem tokens válidos.
21
+
22
+ **REGRA #2 (single-use + TTL 7d):** Token expira em 7 dias OR primeiro accept (single-use). State machine impede uso múltiplo.
23
+
24
+ **REGRA #3 (email-locked):** Aceitar invite requer user **logado com email destino**. Link compartilhável sem email-lock = qualquer um aceita. Validação no Edge Function ou RPC.
25
+
26
+ **REGRA #4 (idempotência via FOR UPDATE):** RPC accept_invite usa `SELECT ... FOR UPDATE` para race protection. 2 requests simultâneos: primeiro processa, segundo retorna `already_accepted`.
27
+
28
+ **REGRA #5 (state machine 5 estados):** `pending → accepted | rejected | cancelled | expired`. Transições enforced via trigger ou check constraint.
29
+
30
+ **REGRA #6 (audit log obrigatório):** Cada criação/accept/reject/cancel/expire emite evento em `audit_logs` (Phase 109).
31
+
32
+ ## Patterns canônicos
33
+
34
+ ### Tabela `org_invites`
35
+
36
+ ```sql
37
+ create table public.org_invites (
38
+ id uuid primary key default gen_random_uuid(),
39
+ org_id uuid not null references public.organizations(id) on delete cascade,
40
+ invited_by_id uuid not null references auth.users(id) on delete cascade,
41
+ invited_email text not null check (invited_email ~ '^.+@.+\..+$'),
42
+ role_id uuid not null references public.roles(id) on delete restrict,
43
+ token_hash text not null unique, -- REGRA #1
44
+ state text not null default 'pending'
45
+ check (state in ('pending', 'accepted', 'rejected', 'cancelled', 'expired')),
46
+ expires_at timestamptz not null default (now() + interval '7 days'), -- REGRA #2
47
+ accepted_by_id uuid references auth.users(id) on delete set null,
48
+ accepted_at timestamptz,
49
+ rejected_at timestamptz,
50
+ cancelled_at timestamptz,
51
+ created_at timestamptz not null default now()
52
+ );
53
+
54
+ create index org_invites_org_state_idx on public.org_invites (org_id, state);
55
+ create index org_invites_email_state_idx on public.org_invites (invited_email, state);
56
+ create unique index org_invites_pending_unique
57
+ on public.org_invites (org_id, invited_email)
58
+ where state = 'pending'; -- previne 2 invites pending pro mesmo email mesma org
59
+
60
+ alter table public.org_invites enable row level security;
61
+
62
+ -- RLS: members com permission members:invite veem invites da org
63
+ create policy "org_invites_select_member" on public.org_invites
64
+ for select to authenticated
65
+ using (private.has_permission('invite', 'members', org_id));
66
+
67
+ create policy "org_invites_insert_with_permission" on public.org_invites
68
+ for insert to authenticated
69
+ with check (private.has_permission('invite', 'members', org_id));
70
+
71
+ -- super_admin bypass
72
+ create policy "org_invites_super_admin" on public.org_invites
73
+ as permissive for all to authenticated
74
+ using (private.is_super_admin())
75
+ with check (private.is_super_admin());
76
+ ```
77
+
78
+ ### RPC `create_invite` — gera token + hash + envia email
79
+
80
+ ```sql
81
+ create or replace function public.create_invite(
82
+ p_org_id uuid,
83
+ p_email text,
84
+ p_role_name text
85
+ )
86
+ returns text -- retorna o token RAW (única vez! enviar por email)
87
+ language plpgsql
88
+ security invoker
89
+ set search_path = ''
90
+ as $$
91
+ declare
92
+ v_role_id uuid;
93
+ v_token text;
94
+ v_token_hash text;
95
+ begin
96
+ -- 1. Resolver role_id
97
+ select id into v_role_id
98
+ from public.roles
99
+ where org_id = p_org_id and name = p_role_name;
100
+
101
+ if v_role_id is null then
102
+ raise exception 'role % not found in org', p_role_name;
103
+ end if;
104
+
105
+ -- 2. Gerar token raw (32 bytes = 64 hex chars)
106
+ v_token := encode(gen_random_bytes(32), 'hex');
107
+ v_token_hash := encode(digest(v_token, 'sha256'), 'hex');
108
+
109
+ -- 3. Insert (RLS check: caller tem permission members:invite)
110
+ insert into public.org_invites (org_id, invited_by_id, invited_email, role_id, token_hash)
111
+ values (p_org_id, (select auth.uid()), p_email, v_role_id, v_token_hash);
112
+
113
+ -- 4. Audit log
114
+ perform private.audit_log(
115
+ 'member_invited',
116
+ p_org_id,
117
+ null, 'member', p_email,
118
+ jsonb_build_object('role', p_role_name)
119
+ );
120
+
121
+ -- 5. Retornar token RAW (chamador envia por email — único momento que existe)
122
+ return v_token;
123
+ end;
124
+ $$;
125
+
126
+ grant execute on function public.create_invite(uuid, text, text) to authenticated;
127
+ ```
128
+
129
+ ### RPC `accept_invite` — idempotente via FOR UPDATE
130
+
131
+ ```sql
132
+ create or replace function public.accept_invite(p_token text)
133
+ returns jsonb
134
+ language plpgsql
135
+ security invoker
136
+ set search_path = ''
137
+ as $$
138
+ declare
139
+ v_token_hash text;
140
+ v_invite record;
141
+ v_user_email text;
142
+ begin
143
+ v_token_hash := encode(digest(p_token, 'sha256'), 'hex');
144
+
145
+ -- REGRA #4: FOR UPDATE para race protection
146
+ select * into v_invite
147
+ from public.org_invites
148
+ where token_hash = v_token_hash
149
+ for update;
150
+
151
+ if v_invite is null then
152
+ raise exception 'invite_not_found';
153
+ end if;
154
+
155
+ -- Idempotência: se já aceito por este user, retorna sucesso (não erro)
156
+ if v_invite.state = 'accepted' then
157
+ if v_invite.accepted_by_id = (select auth.uid()) then
158
+ return jsonb_build_object('status', 'already_accepted', 'org_id', v_invite.org_id);
159
+ else
160
+ raise exception 'invite_already_used';
161
+ end if;
162
+ end if;
163
+
164
+ -- Estado != pending → erro
165
+ if v_invite.state != 'pending' then
166
+ raise exception 'invite_state_invalid: %', v_invite.state;
167
+ end if;
168
+
169
+ -- Expirado?
170
+ if v_invite.expires_at < now() then
171
+ update public.org_invites set state = 'expired' where id = v_invite.id;
172
+ raise exception 'invite_expired';
173
+ end if;
174
+
175
+ -- REGRA #3: email-locked — user logado deve match
176
+ select email into v_user_email from auth.users where id = (select auth.uid());
177
+ if lower(v_user_email) != lower(v_invite.invited_email) then
178
+ raise exception 'invite_email_mismatch';
179
+ end if;
180
+
181
+ -- Aceitar: criar membership + atualizar invite
182
+ insert into public.organization_members (org_id, user_id, role_id, status)
183
+ values (v_invite.org_id, (select auth.uid()), v_invite.role_id, 'active')
184
+ on conflict (org_id, user_id) do update
185
+ set role_id = excluded.role_id, status = 'active';
186
+
187
+ update public.org_invites
188
+ set state = 'accepted',
189
+ accepted_by_id = (select auth.uid()),
190
+ accepted_at = now()
191
+ where id = v_invite.id;
192
+
193
+ -- Audit
194
+ perform private.audit_log(
195
+ 'member_invited', -- mesmo evento, payload distingue
196
+ v_invite.org_id,
197
+ (select auth.uid()), 'member', v_user_email,
198
+ jsonb_build_object('action', 'accepted', 'invite_id', v_invite.id)
199
+ );
200
+
201
+ return jsonb_build_object('status', 'accepted', 'org_id', v_invite.org_id);
202
+ end;
203
+ $$;
204
+
205
+ grant execute on function public.accept_invite(text) to authenticated;
206
+ ```
207
+
208
+ ### Bulk invite — N invites em batch
209
+
210
+ ```typescript
211
+ // Frontend
212
+ async function bulkInvite(orgId: string, invites: { email: string; role: string }[]) {
213
+ const results = await Promise.allSettled(
214
+ invites.map(i =>
215
+ supabase.rpc('create_invite', {
216
+ p_org_id: orgId,
217
+ p_email: i.email,
218
+ p_role_name: i.role
219
+ })
220
+ )
221
+ )
222
+
223
+ return results.map((r, i) => ({
224
+ email: invites[i].email,
225
+ status: r.status === 'fulfilled' ? 'invited' : 'error',
226
+ error: r.status === 'rejected' ? r.reason.message : null,
227
+ token: r.status === 'fulfilled' ? r.value.data : null
228
+ }))
229
+
230
+ // Frontend envia email para cada invite com token retornado
231
+ }
232
+ ```
233
+
234
+ ### Cron expiração — pg_cron diário
235
+
236
+ ```sql
237
+ select cron.schedule(
238
+ 'expire-pending-invites',
239
+ '0 1 * * *',
240
+ $$
241
+ update public.org_invites
242
+ set state = 'expired'
243
+ where state = 'pending' and expires_at < now();
244
+ $$
245
+ );
246
+ ```
247
+
248
+ ## Anti-patterns
249
+
250
+ ### Anti-pattern 1: Token raw armazenado no banco
251
+
252
+ **Errado:**
253
+ ```sql
254
+ insert into public.org_invites (token, ...) values (v_token, ...); -- raw!
255
+ ```
256
+
257
+ **Por quê:** vazamento de DB = todos tokens válidos. Atacante aceita invites pendentes para ganhar acesso.
258
+
259
+ **Certo:** hash SHA-256 (REGRA #1). Raw enviado uma vez por email.
260
+
261
+ ### Anti-pattern 2: Link compartilhável sem email-lock
262
+
263
+ **Errado:**
264
+ ```typescript
265
+ // URL: https://app.com/invite/<token>
266
+ // Quem clicar primeiro aceita (sem checar email)
267
+ ```
268
+
269
+ **Por quê:** se Alice encaminha email para Bob (acidentalmente ou maliciosamente), Bob aceita. Bob nunca foi convidado.
270
+
271
+ **Certo:** REGRA #3 — accept exige user autenticado com email = invited_email.
272
+
273
+ ### Anti-pattern 3: Sem FOR UPDATE em accept (race)
274
+
275
+ **Errado:**
276
+ ```sql
277
+ select state from public.org_invites where token_hash = $1; -- sem lock
278
+ -- ... process ...
279
+ update public.org_invites set state = 'accepted' where id = $1;
280
+ ```
281
+
282
+ **Por quê:** 2 requests simultâneos: ambos leem `state = 'pending'`, ambos processam, criam 2 memberships duplicadas.
283
+
284
+ **Certo:** REGRA #4 — FOR UPDATE bloqueia row, segundo request espera + relê estado atualizado.
285
+
286
+ ### Anti-pattern 4: Bulk invite sem limit
287
+
288
+ **Errado:**
289
+ ```typescript
290
+ // User cola 10000 emails de spam
291
+ await bulkInvite(orgId, hugeList)
292
+ ```
293
+
294
+ **Por quê:** envio massivo de emails = listas de spam, IP do mailing service blacklisted, emails legítimos param de chegar.
295
+
296
+ **Certo:** rate limit no Edge Function (max 50 invites/hora por org) + check de domínio email (block free providers se necessário).
297
+
298
+ ## Ver também
299
+
300
+ - [b2b-saas-architecture](../b2b-saas-architecture/SKILL.md) — schema `organization_members` + `roles`
301
+ - [multi-tenant-rls-hierarchy](../multi-tenant-rls-hierarchy/SKILL.md) — `private.has_permission` usado em RLS
302
+ - [audit-log-multi-tenant](../audit-log-multi-tenant/SKILL.md) — events `member_invited` (Phase 109)
303
+ - [org-onboarding-flow](../org-onboarding-flow/SKILL.md) — fluxo signup que precede invites
304
+ - [rbac-permissions-matrix-supabase](../rbac-permissions-matrix-supabase/SKILL.md) — permission `invite:members`
305
+ - [_shared-multi-tenant/glossary.md](../_shared-multi-tenant/glossary.md) — termos `invitation token`, `invite state machine`, `email-locked`