@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.
- 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/agents/audit-log-implementer.md +175 -0
- package/kit/agents/b2b-saas-architect.md +156 -0
- package/kit/agents/crm-pipeline-implementer.md +150 -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 +243 -0
- package/kit/agents/multi-tenant-rls-writer.md +262 -0
- package/kit/agents/org-onboarding-implementer.md +202 -0
- package/kit/agents/super-admin-implementer.md +182 -0
- package/kit/commands/burn-rate-status.md +237 -121
- package/kit/commands/multi-tenant.md +163 -0
- package/kit/file-manifest.json +31 -4
- package/kit/skills/_shared-multi-tenant/glossary.md +186 -0
- package/kit/skills/audit-log-multi-tenant/SKILL.md +334 -0
- package/kit/skills/b2b-saas-architecture/SKILL.md +300 -0
- package/kit/skills/crm-lead-pipeline-patterns/SKILL.md +326 -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 +312 -0
- package/kit/skills/multi-tenant-rls-hierarchy/SKILL.md +338 -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/rbac-permissions-matrix-supabase/SKILL.md +301 -0
- package/kit/skills/super-admin-platform-pattern/SKILL.md +322 -0
- package/kit/skills/whatsapp-conversation-state-machine/SKILL.md +287 -0
- package/package.json +6 -2
- package/src/mcp-server/index.js +34 -3
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: rbac-permissions-matrix-supabase
|
|
3
|
+
description: Use ao modelar RBAC granular em Supabase B2B — permission strings resource:action, matrix N:M roles ↔ permissions, regra "user só atribui roles ≤ ao próprio", 3 roles built-in (owner/admin/member) + custom permitidos.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# RBAC Permissions Matrix — Supabase B2B Multi-Tenant
|
|
7
|
+
|
|
8
|
+
## Quando usar
|
|
9
|
+
|
|
10
|
+
LLM carrega esta skill ao desenhar autorização granular em B2B SaaS multi-tenant. Trigger phrases:
|
|
11
|
+
|
|
12
|
+
- "RBAC granular", "permission matrix"
|
|
13
|
+
- "permission string resource:action", "leads:create", "members:invite"
|
|
14
|
+
- "custom roles", "role escalation rule"
|
|
15
|
+
- "owner admin member built-in"
|
|
16
|
+
- "role permissions table"
|
|
17
|
+
|
|
18
|
+
## Regras absolutas
|
|
19
|
+
|
|
20
|
+
**REGRA #1 (permission string format):** Permissions são strings `<resource>:<action>` em snake_case (ex: `leads:create`, `members:invite`, `org_settings:update`). Padrão convergente 2026 (Stripe, Linear, Auth0).
|
|
21
|
+
|
|
22
|
+
**REGRA #2 (3 roles built-in mínimo):** Toda org tem 3 roles built-in com `is_built_in = true`:
|
|
23
|
+
- `owner` — full control (criação org, billing, transfer ownership, delete org)
|
|
24
|
+
- `admin` — manage members, settings, all data
|
|
25
|
+
- `member` — operações standard (CRUD nos recursos da org)
|
|
26
|
+
|
|
27
|
+
**REGRA #3 (role escalation rule):** Usuário só pode **criar/atribuir roles ≤ ao próprio role**. Member não pode criar admin. Admin não pode criar owner. Owner pode tudo. Enforced via policy + frontend gate.
|
|
28
|
+
|
|
29
|
+
**REGRA #4 (custom roles permitidos):** Custom roles via `is_built_in = false` na mesma tabela `roles`. Org-scoped (não globais). Built-in não podem ser deletados (constraint).
|
|
30
|
+
|
|
31
|
+
**REGRA #5 (NUNCA permission string em frontend hard-coded para enforce):** Permission gate React (skill [`permission-gate-react-pattern`](../permission-gate-react-pattern/SKILL.md)) é UX apenas. Server-side enforcement obrigatório via RLS + `private.has_permission`.
|
|
32
|
+
|
|
33
|
+
## Patterns canônicos
|
|
34
|
+
|
|
35
|
+
### Permission catalog — eventos canônicos
|
|
36
|
+
|
|
37
|
+
```sql
|
|
38
|
+
-- Catálogo global (compartilhado entre orgs)
|
|
39
|
+
insert into public.permissions (action, resource, description) values
|
|
40
|
+
-- Members
|
|
41
|
+
('invite', 'members', 'Convidar novos membros via email'),
|
|
42
|
+
('remove', 'members', 'Remover membros existentes'),
|
|
43
|
+
('update', 'members', 'Atualizar role/status de membros'),
|
|
44
|
+
('list', 'members', 'Listar membros da org'),
|
|
45
|
+
|
|
46
|
+
-- Org settings
|
|
47
|
+
('update', 'org_settings', 'Atualizar configurações gerais da org'),
|
|
48
|
+
('update', 'org_billing', 'Acessar/alterar billing (Stripe)'),
|
|
49
|
+
|
|
50
|
+
-- Departments
|
|
51
|
+
('create', 'departments', 'Criar departamentos'),
|
|
52
|
+
('update', 'departments', 'Atualizar departamentos'),
|
|
53
|
+
('delete', 'departments', 'Deletar departamentos'),
|
|
54
|
+
|
|
55
|
+
-- Roles + Permissions
|
|
56
|
+
('create', 'roles', 'Criar custom roles'),
|
|
57
|
+
('update', 'roles', 'Atualizar role permissions'),
|
|
58
|
+
('delete', 'roles', 'Deletar custom roles (built-in protegidos)'),
|
|
59
|
+
|
|
60
|
+
-- Domain example: leads (CRM)
|
|
61
|
+
('create', 'leads', 'Criar leads'),
|
|
62
|
+
('update', 'leads', 'Atualizar leads'),
|
|
63
|
+
('delete', 'leads', 'Deletar leads'),
|
|
64
|
+
('export', 'leads', 'Exportar leads (CSV/JSON)'),
|
|
65
|
+
|
|
66
|
+
-- Audit
|
|
67
|
+
('view', 'audit_logs', 'Ver audit logs'),
|
|
68
|
+
('export', 'audit_logs', 'Exportar audit logs'),
|
|
69
|
+
|
|
70
|
+
-- LGPD
|
|
71
|
+
('process', 'dsr_requests', 'Processar Data Subject Requests'),
|
|
72
|
+
|
|
73
|
+
on conflict (action, resource) do nothing;
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### 3 roles built-in com permissions default
|
|
77
|
+
|
|
78
|
+
```sql
|
|
79
|
+
-- Para cada nova org (idealmente em RPC create_organization), criar built-in roles
|
|
80
|
+
-- com permissions atribuídas.
|
|
81
|
+
|
|
82
|
+
-- OWNER — todas permissions
|
|
83
|
+
insert into public.role_permissions (role_id, permission_id)
|
|
84
|
+
select
|
|
85
|
+
r.id,
|
|
86
|
+
p.id
|
|
87
|
+
from public.roles r
|
|
88
|
+
cross join public.permissions p
|
|
89
|
+
where r.org_id = '<org_id>'
|
|
90
|
+
and r.name = 'owner';
|
|
91
|
+
|
|
92
|
+
-- ADMIN — tudo exceto org_billing + delete org
|
|
93
|
+
insert into public.role_permissions (role_id, permission_id)
|
|
94
|
+
select
|
|
95
|
+
r.id,
|
|
96
|
+
p.id
|
|
97
|
+
from public.roles r
|
|
98
|
+
cross join public.permissions p
|
|
99
|
+
where r.org_id = '<org_id>'
|
|
100
|
+
and r.name = 'admin'
|
|
101
|
+
and not (p.action = 'update' and p.resource = 'org_billing');
|
|
102
|
+
|
|
103
|
+
-- MEMBER — operações CRUD em domínio (sem members management)
|
|
104
|
+
insert into public.role_permissions (role_id, permission_id)
|
|
105
|
+
select
|
|
106
|
+
r.id,
|
|
107
|
+
p.id
|
|
108
|
+
from public.roles r
|
|
109
|
+
cross join public.permissions p
|
|
110
|
+
where r.org_id = '<org_id>'
|
|
111
|
+
and r.name = 'member'
|
|
112
|
+
and p.resource in ('leads', 'departments')
|
|
113
|
+
and p.action in ('create', 'update', 'list');
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Role escalation rule — enforcement via RPC + RLS
|
|
117
|
+
|
|
118
|
+
```sql
|
|
119
|
+
-- Função que retorna o "rank" de uma role (owner=3, admin=2, member=1, custom=0)
|
|
120
|
+
create or replace function private.role_rank(p_role_name text)
|
|
121
|
+
returns int
|
|
122
|
+
language sql
|
|
123
|
+
stable
|
|
124
|
+
security invoker
|
|
125
|
+
set search_path = ''
|
|
126
|
+
as $$
|
|
127
|
+
select case p_role_name
|
|
128
|
+
when 'owner' then 3
|
|
129
|
+
when 'admin' then 2
|
|
130
|
+
when 'member' then 1
|
|
131
|
+
else 0 -- custom roles têm rank 0 (não comparáveis)
|
|
132
|
+
end;
|
|
133
|
+
$$;
|
|
134
|
+
|
|
135
|
+
-- RPC que assign role a um membro — só permite role ≤ ao próprio
|
|
136
|
+
create or replace function public.assign_role(
|
|
137
|
+
p_org_id uuid,
|
|
138
|
+
p_target_user_id uuid,
|
|
139
|
+
p_role_id uuid
|
|
140
|
+
)
|
|
141
|
+
returns void
|
|
142
|
+
language plpgsql
|
|
143
|
+
security invoker
|
|
144
|
+
set search_path = ''
|
|
145
|
+
as $$
|
|
146
|
+
declare
|
|
147
|
+
caller_role_name text;
|
|
148
|
+
target_role_name text;
|
|
149
|
+
begin
|
|
150
|
+
-- 1. Buscar role do caller na org
|
|
151
|
+
select r.name into caller_role_name
|
|
152
|
+
from public.organization_members om
|
|
153
|
+
join public.roles r on r.id = om.role_id
|
|
154
|
+
where om.org_id = p_org_id
|
|
155
|
+
and om.user_id = (select auth.uid())
|
|
156
|
+
and om.status = 'active';
|
|
157
|
+
|
|
158
|
+
if caller_role_name is null then
|
|
159
|
+
raise exception 'caller is not member of org';
|
|
160
|
+
end if;
|
|
161
|
+
|
|
162
|
+
-- 2. Buscar role alvo
|
|
163
|
+
select r.name into target_role_name
|
|
164
|
+
from public.roles r
|
|
165
|
+
where r.id = p_role_id and r.org_id = p_org_id;
|
|
166
|
+
|
|
167
|
+
if target_role_name is null then
|
|
168
|
+
raise exception 'role does not exist in org';
|
|
169
|
+
end if;
|
|
170
|
+
|
|
171
|
+
-- 3. REGRA #3: caller role rank >= target role rank
|
|
172
|
+
if private.role_rank(caller_role_name) < private.role_rank(target_role_name) then
|
|
173
|
+
raise exception
|
|
174
|
+
'role escalation forbidden: caller is %, cannot assign %',
|
|
175
|
+
caller_role_name, target_role_name;
|
|
176
|
+
end if;
|
|
177
|
+
|
|
178
|
+
-- 4. Assign
|
|
179
|
+
update public.organization_members
|
|
180
|
+
set role_id = p_role_id
|
|
181
|
+
where org_id = p_org_id and user_id = p_target_user_id;
|
|
182
|
+
end;
|
|
183
|
+
$$;
|
|
184
|
+
|
|
185
|
+
grant execute on function public.assign_role(uuid, uuid, uuid) to authenticated;
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
### Frontend — listar roles que user pode atribuir
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
// Buscar roles que current user pode atribuir (rank ≤ próprio)
|
|
192
|
+
const { data: assignableRoles } = await supabase
|
|
193
|
+
.from('roles')
|
|
194
|
+
.select('id, name, description')
|
|
195
|
+
.eq('org_id', orgId)
|
|
196
|
+
// RPC retorna apenas roles que caller pode atribuir
|
|
197
|
+
.rpc('list_assignable_roles', { p_org_id: orgId })
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### RLS policy usando `private.has_permission`
|
|
201
|
+
|
|
202
|
+
```sql
|
|
203
|
+
-- Tabela leads — INSERT requer permission leads:create
|
|
204
|
+
create policy "leads_insert_with_permission"
|
|
205
|
+
on public.leads
|
|
206
|
+
for insert
|
|
207
|
+
to authenticated
|
|
208
|
+
with check (
|
|
209
|
+
private.has_permission('create', 'leads', org_id)
|
|
210
|
+
);
|
|
211
|
+
|
|
212
|
+
-- Tabela members management — UPDATE role requer permission members:update
|
|
213
|
+
create policy "members_update_role_with_permission"
|
|
214
|
+
on public.organization_members
|
|
215
|
+
for update
|
|
216
|
+
to authenticated
|
|
217
|
+
using (
|
|
218
|
+
private.has_permission('update', 'members', org_id)
|
|
219
|
+
)
|
|
220
|
+
with check (
|
|
221
|
+
private.has_permission('update', 'members', org_id)
|
|
222
|
+
);
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
## Anti-patterns
|
|
226
|
+
|
|
227
|
+
### Anti-pattern 1: Permission string sem padrão
|
|
228
|
+
|
|
229
|
+
**Errado:**
|
|
230
|
+
```sql
|
|
231
|
+
-- Mistura formats
|
|
232
|
+
'canCreateLeads', 'leads.create', 'CREATE_LEAD', 'leads:write'
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
**Por quê:** inconsistência confunde devs (qual é a forma certa?), quebra autocomplete, dificulta migração.
|
|
236
|
+
|
|
237
|
+
**Certo:** sempre `<resource>:<action>` em snake_case (REGRA #1). Pode usar enum em TypeScript:
|
|
238
|
+
```typescript
|
|
239
|
+
type Permission = `${Resource}:${Action}`
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
### Anti-pattern 2: Hard-coded role check em vez de permission
|
|
243
|
+
|
|
244
|
+
**Errado:**
|
|
245
|
+
```typescript
|
|
246
|
+
// Permission gate frontend
|
|
247
|
+
{ user.role === 'admin' && <Button>Convidar</Button> }
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
**Por quê:** custom roles quebram (custom role com permission `members:invite` não passa no check). Acopla UI a roles built-in.
|
|
251
|
+
|
|
252
|
+
**Certo:**
|
|
253
|
+
```typescript
|
|
254
|
+
{ usePermission('invite', 'members') && <Button>Convidar</Button> }
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
E server-side: RLS com `private.has_permission`.
|
|
258
|
+
|
|
259
|
+
### Anti-pattern 3: Built-in role pode ser deletada
|
|
260
|
+
|
|
261
|
+
**Errado:**
|
|
262
|
+
```sql
|
|
263
|
+
-- Sem proteção
|
|
264
|
+
delete from public.roles where name = 'owner' and org_id = '...';
|
|
265
|
+
-- Org fica sem owner, ninguém consegue fazer nada
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
**Por quê:** org sem owner é unrecoverable sem service_role intervention. Compromete recovery.
|
|
269
|
+
|
|
270
|
+
**Certo:** policy DELETE em `roles` que rejeita built-in:
|
|
271
|
+
```sql
|
|
272
|
+
create policy "roles_delete_custom_only"
|
|
273
|
+
on public.roles
|
|
274
|
+
for delete
|
|
275
|
+
to authenticated
|
|
276
|
+
using (
|
|
277
|
+
not is_built_in
|
|
278
|
+
and private.has_permission('delete', 'roles', org_id)
|
|
279
|
+
);
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### Anti-pattern 4: Frontend permission gate sem server-side enforce
|
|
283
|
+
|
|
284
|
+
**Errado:**
|
|
285
|
+
```typescript
|
|
286
|
+
// Esconder botão UI = "segurança"
|
|
287
|
+
{ usePermission('delete', 'leads') && <DeleteButton /> }
|
|
288
|
+
// Mas API endpoint /leads/{id} aceita DELETE sem checar permission
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
**Por quê:** atacante chama API direto via curl — ignora gate frontend. Permission gate React é **UX**, não segurança.
|
|
292
|
+
|
|
293
|
+
**Certo:** REGRA #5. Server-side via RLS + `private.has_permission` é enforcement real.
|
|
294
|
+
|
|
295
|
+
## Ver também
|
|
296
|
+
|
|
297
|
+
- [multi-tenant-rls-hierarchy](../multi-tenant-rls-hierarchy/SKILL.md) — `private.has_permission` é a função canônica usada em policies
|
|
298
|
+
- [b2b-saas-architecture](../b2b-saas-architecture/SKILL.md) — schema das tabelas `roles`, `permissions`, `role_permissions`
|
|
299
|
+
- [permission-gate-react-pattern](../permission-gate-react-pattern/SKILL.md) — Phase 115, permission gate UX em React
|
|
300
|
+
- [super-admin-platform-pattern](../super-admin-platform-pattern/SKILL.md) — Phase 111, super_admin bypassa RBAC normal
|
|
301
|
+
- [_shared-multi-tenant/glossary.md](../_shared-multi-tenant/glossary.md) — termos `RBAC`, `permission matrix`, `role escalation rule`
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: super-admin-platform-pattern
|
|
3
|
+
description: Use ao implementar plataforma super-admin em B2B SaaS multi-tenant — cross-tenant view sobre todas orgs, impersonation com TTL 30min + reason obrigatório + banner visual, super_admin:bool em app_metadata via service_role apenas, audit obrigatório (BLOCKER) em toda ação super-admin.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Super-Admin Platform Pattern — B2B SaaS Multi-Tenant
|
|
7
|
+
|
|
8
|
+
## Quando usar
|
|
9
|
+
|
|
10
|
+
LLM carrega esta skill ao implementar painel de super-admin (você gerenciando todos tenants). Trigger phrases:
|
|
11
|
+
|
|
12
|
+
- "super admin platform", "platform admin"
|
|
13
|
+
- "cross-tenant view", "list all orgs"
|
|
14
|
+
- "impersonation user", "support takeover"
|
|
15
|
+
- "super_admin app_metadata"
|
|
16
|
+
- "GitHub Enterprise impersonation pattern"
|
|
17
|
+
|
|
18
|
+
## Regras absolutas
|
|
19
|
+
|
|
20
|
+
**REGRA #1 (audit obrigatório — BLOCKER):** Toda ação super-admin **DEVE** emitir evento `super_admin_action` em `audit_logs`. Sem audit log = ABORT no agent (REGRA do `super-admin-implementer`). Compliance LGPD exige rastreabilidade.
|
|
21
|
+
|
|
22
|
+
**REGRA #2 (impersonation TTL 30min):** Sessão de impersonation expira em **30 minutos** automaticamente. Após TTL, sessão revogada (`signOut` automático), super-admin precisa re-iniciar impersonation. Previne sessão zombie.
|
|
23
|
+
|
|
24
|
+
**REGRA #3 (reason obrigatório):** Impersonation requer campo `reason` text não-vazio (mín 10 chars). Registrado em audit_log para investigação posterior. Sem reason = recusar ação.
|
|
25
|
+
|
|
26
|
+
**REGRA #4 (banner visual obrigatório):** Quando super-admin está impersonando, UI mostra **banner persistente** (top da viewport) com texto "Você está vendo como <user.email> em <org.name>. Clique para sair." Cor de aviso (amarelo/vermelho), z-index máximo, não fechável.
|
|
27
|
+
|
|
28
|
+
**REGRA #5 (super_admin via service_role apenas):** `app_metadata.super_admin = true` é setado **EXCLUSIVAMENTE** via `auth.admin.updateUserById()` com `SUPABASE_SERVICE_ROLE_KEY`. Cliente NUNCA consegue mutar. Endpoint de promoção isolado em Edge Function `verify_jwt: false` ou backend admin separado.
|
|
29
|
+
|
|
30
|
+
**REGRA #6 (delete org requer dupla confirmação):** Deletar uma `organizations` (cascade dropping membros, leads, audit_logs) requer:
|
|
31
|
+
1. super-admin clica botão delete
|
|
32
|
+
2. Modal pede org.slug exato + reason text + checkbox "Entendo que isso é irreversível"
|
|
33
|
+
3. RPC `super_admin_delete_org(p_org_id, p_typed_slug, p_reason)` valida + executa + audit
|
|
34
|
+
|
|
35
|
+
## Patterns canônicos
|
|
36
|
+
|
|
37
|
+
### Cross-tenant view — RLS via PERMISSIVE
|
|
38
|
+
|
|
39
|
+
```sql
|
|
40
|
+
-- Policy permissive em organizations: super_admin vê todas
|
|
41
|
+
create policy "organizations_super_admin_view"
|
|
42
|
+
on public.organizations
|
|
43
|
+
as permissive
|
|
44
|
+
for select
|
|
45
|
+
to authenticated
|
|
46
|
+
using (private.is_super_admin());
|
|
47
|
+
|
|
48
|
+
-- Policy normal (já deve existir): owner/admin vê apenas a própria
|
|
49
|
+
create policy "organizations_select_member"
|
|
50
|
+
on public.organizations
|
|
51
|
+
for select
|
|
52
|
+
to authenticated
|
|
53
|
+
using (private.is_member_of(id));
|
|
54
|
+
|
|
55
|
+
-- Mesma lógica para todas tabelas críticas: leads, organization_members, audit_logs, etc.
|
|
56
|
+
-- Padronizar via agent multi-tenant-rls-writer (Phase 108) com super_admin_bypass=true
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Frontend — listar todos tenants (super-admin only)
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
// SuperAdminDashboard.tsx
|
|
63
|
+
import { createClient } from '@/lib/supabase/client'
|
|
64
|
+
|
|
65
|
+
export function SuperAdminDashboard() {
|
|
66
|
+
const supabase = createClient()
|
|
67
|
+
const [orgs, setOrgs] = useState<Org[]>([])
|
|
68
|
+
|
|
69
|
+
useEffect(() => {
|
|
70
|
+
// RLS retorna TODAS orgs porque user é super_admin
|
|
71
|
+
supabase.from('organizations')
|
|
72
|
+
.select('id, name, slug, plan, status, created_at, organization_members(count)')
|
|
73
|
+
.order('created_at', { ascending: false })
|
|
74
|
+
.then(({ data }) => setOrgs(data || []))
|
|
75
|
+
}, [])
|
|
76
|
+
|
|
77
|
+
return (
|
|
78
|
+
<Table>
|
|
79
|
+
{orgs.map(o => (
|
|
80
|
+
<Row key={o.id}>
|
|
81
|
+
<Cell>{o.name}</Cell>
|
|
82
|
+
<Cell>{o.slug}</Cell>
|
|
83
|
+
<Cell>{o.plan}</Cell>
|
|
84
|
+
<Cell>{o.organization_members[0].count}</Cell>
|
|
85
|
+
<Cell>
|
|
86
|
+
<Button onClick={() => startImpersonation(o.id)}>Impersonate</Button>
|
|
87
|
+
</Cell>
|
|
88
|
+
</Row>
|
|
89
|
+
))}
|
|
90
|
+
</Table>
|
|
91
|
+
)
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Impersonation — Edge Function com TTL 30min
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
// supabase/functions/super-admin-impersonate/index.ts
|
|
99
|
+
import { createClient } from 'jsr:@supabase/supabase-js@2'
|
|
100
|
+
|
|
101
|
+
Deno.serve(async (req) => {
|
|
102
|
+
const auth = req.headers.get('Authorization')
|
|
103
|
+
if (!auth) return new Response('unauthorized', { status: 401 })
|
|
104
|
+
|
|
105
|
+
// Validar caller é super_admin via JWT app_metadata
|
|
106
|
+
const supabase = createClient(
|
|
107
|
+
Deno.env.get('SUPABASE_URL')!,
|
|
108
|
+
Deno.env.get('SUPABASE_ANON_KEY')!,
|
|
109
|
+
{ global: { headers: { Authorization: auth } } }
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
const { data: { user } } = await supabase.auth.getUser()
|
|
113
|
+
if (!user || !user.app_metadata.super_admin) {
|
|
114
|
+
return new Response('forbidden', { status: 403 })
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const { target_user_id, target_org_id, reason } = await req.json()
|
|
118
|
+
|
|
119
|
+
// REGRA #3: reason obrigatório (min 10 chars)
|
|
120
|
+
if (!reason || reason.trim().length < 10) {
|
|
121
|
+
return new Response(JSON.stringify({ error: 'reason_required_min_10_chars' }), { status: 400 })
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Audit ANTES de criar sessão (se falhar audit, falha a ação)
|
|
125
|
+
await supabase.rpc('audit_log', {
|
|
126
|
+
p_event_type: 'super_admin_action',
|
|
127
|
+
p_tenant_id: target_org_id,
|
|
128
|
+
p_target_id: target_user_id,
|
|
129
|
+
p_target_type: 'user',
|
|
130
|
+
p_payload: {
|
|
131
|
+
action: 'impersonation_started',
|
|
132
|
+
reason,
|
|
133
|
+
session_ttl_minutes: 30
|
|
134
|
+
}
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
// Criar sessão impersonation via service_role
|
|
138
|
+
const admin = createClient(
|
|
139
|
+
Deno.env.get('SUPABASE_URL')!,
|
|
140
|
+
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')! // service role
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
const { data: targetUser } = await admin.auth.admin.getUserById(target_user_id)
|
|
144
|
+
if (!targetUser.user) return new Response('target_not_found', { status: 404 })
|
|
145
|
+
|
|
146
|
+
// Gerar magic link com expiry curto (30min)
|
|
147
|
+
const { data: magicLink } = await admin.auth.admin.generateLink({
|
|
148
|
+
type: 'magiclink',
|
|
149
|
+
email: targetUser.user.email!,
|
|
150
|
+
options: {
|
|
151
|
+
redirectTo: `${Deno.env.get('APP_URL')}/?impersonating=1&original_admin_id=${user.id}`
|
|
152
|
+
}
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
// Cookie marker no client side (banner visual lê isso)
|
|
156
|
+
return new Response(JSON.stringify({
|
|
157
|
+
magic_link: magicLink.properties.action_link,
|
|
158
|
+
expires_at: new Date(Date.now() + 30 * 60 * 1000).toISOString()
|
|
159
|
+
}), {
|
|
160
|
+
headers: { 'Content-Type': 'application/json' }
|
|
161
|
+
})
|
|
162
|
+
})
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
### Banner visual de impersonation (React)
|
|
166
|
+
|
|
167
|
+
```typescript
|
|
168
|
+
// app/components/ImpersonationBanner.tsx
|
|
169
|
+
'use client'
|
|
170
|
+
|
|
171
|
+
export function ImpersonationBanner() {
|
|
172
|
+
const searchParams = useSearchParams()
|
|
173
|
+
const isImpersonating = searchParams.get('impersonating') === '1'
|
|
174
|
+
const adminId = searchParams.get('original_admin_id')
|
|
175
|
+
|
|
176
|
+
if (!isImpersonating) return null
|
|
177
|
+
|
|
178
|
+
const stopImpersonation = async () => {
|
|
179
|
+
await supabase.auth.signOut()
|
|
180
|
+
window.location.href = `/super-admin?stopped_impersonation=1&original_admin_id=${adminId}`
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return (
|
|
184
|
+
<div className="fixed top-0 left-0 right-0 z-[9999] bg-yellow-400 text-black px-4 py-2 flex items-center justify-between">
|
|
185
|
+
<span>
|
|
186
|
+
⚠ Você está vendo como outro usuário (super-admin impersonation).
|
|
187
|
+
Sessão expira em <Countdown to={expiresAt} />.
|
|
188
|
+
</span>
|
|
189
|
+
<Button variant="destructive" size="sm" onClick={stopImpersonation}>
|
|
190
|
+
Parar impersonation
|
|
191
|
+
</Button>
|
|
192
|
+
</div>
|
|
193
|
+
)
|
|
194
|
+
}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
### Promover usuário a super_admin (backend admin script)
|
|
198
|
+
|
|
199
|
+
```typescript
|
|
200
|
+
// scripts/promote-super-admin.ts (NÃO Edge Function — script administrativo)
|
|
201
|
+
// Executado manualmente OU via CLI admin tool (NÃO frontend)
|
|
202
|
+
import { createClient } from '@supabase/supabase-js'
|
|
203
|
+
|
|
204
|
+
const admin = createClient(
|
|
205
|
+
process.env.SUPABASE_URL!,
|
|
206
|
+
process.env.SUPABASE_SERVICE_ROLE_KEY! // SECRET — NUNCA em frontend
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
await admin.auth.admin.updateUserById(userId, {
|
|
210
|
+
app_metadata: { super_admin: true }
|
|
211
|
+
})
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### RPC delete org com dupla confirmação
|
|
215
|
+
|
|
216
|
+
```sql
|
|
217
|
+
create or replace function public.super_admin_delete_org(
|
|
218
|
+
p_org_id uuid,
|
|
219
|
+
p_typed_slug text,
|
|
220
|
+
p_reason text
|
|
221
|
+
)
|
|
222
|
+
returns void
|
|
223
|
+
language plpgsql
|
|
224
|
+
security invoker
|
|
225
|
+
set search_path = ''
|
|
226
|
+
as $$
|
|
227
|
+
declare
|
|
228
|
+
v_org_slug text;
|
|
229
|
+
begin
|
|
230
|
+
-- Validar caller é super_admin
|
|
231
|
+
if not private.is_super_admin() then
|
|
232
|
+
raise exception 'forbidden_super_admin_only';
|
|
233
|
+
end if;
|
|
234
|
+
|
|
235
|
+
-- Validar reason
|
|
236
|
+
if length(trim(p_reason)) < 10 then
|
|
237
|
+
raise exception 'reason_required_min_10_chars';
|
|
238
|
+
end if;
|
|
239
|
+
|
|
240
|
+
-- Validar typed_slug bate com slug real (REGRA #6 dupla confirmação)
|
|
241
|
+
select slug into v_org_slug from public.organizations where id = p_org_id;
|
|
242
|
+
if v_org_slug is null then raise exception 'org_not_found'; end if;
|
|
243
|
+
if v_org_slug != p_typed_slug then
|
|
244
|
+
raise exception 'slug_mismatch_confirmation_failed';
|
|
245
|
+
end if;
|
|
246
|
+
|
|
247
|
+
-- Audit ANTES (preserva histórico)
|
|
248
|
+
perform private.audit_log(
|
|
249
|
+
'super_admin_action',
|
|
250
|
+
p_org_id,
|
|
251
|
+
null, 'org', null,
|
|
252
|
+
jsonb_build_object('action', 'delete_org', 'slug', v_org_slug, 'reason', p_reason)
|
|
253
|
+
);
|
|
254
|
+
|
|
255
|
+
-- Soft delete preferred (status = 'archived'), hard delete se realmente necessário
|
|
256
|
+
update public.organizations set status = 'archived' where id = p_org_id;
|
|
257
|
+
|
|
258
|
+
-- Hard delete (se exigido — descomenta abaixo)
|
|
259
|
+
-- delete from public.organizations where id = p_org_id;
|
|
260
|
+
-- (cascade dropa: organization_members, departments, leads, etc.; audit_logs preservado por design)
|
|
261
|
+
end;
|
|
262
|
+
$$;
|
|
263
|
+
|
|
264
|
+
grant execute on function public.super_admin_delete_org(uuid, text, text) to authenticated;
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## Anti-patterns
|
|
268
|
+
|
|
269
|
+
### Anti-pattern 1: super_admin sem audit log (BLOCKER)
|
|
270
|
+
|
|
271
|
+
**Errado:**
|
|
272
|
+
```sql
|
|
273
|
+
-- super_admin policy permite tudo, sem trigger ou helper que registra
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
**Por quê:** ação super-admin sem rastro = você (operador da plataforma) não consegue investigar incident "quem deletou todos os leads da org X em 03/04?". Compliance LGPD violation.
|
|
277
|
+
|
|
278
|
+
**Certo:** REGRA #1 — toda RPC super-admin chama `private.audit_log` ANTES de operar. Trigger AFTER em tabelas críticas dispara automaticamente para super_admin (gerado pelo `multi-tenant-rls-writer` com `audit_super_admin=true`).
|
|
279
|
+
|
|
280
|
+
### Anti-pattern 2: Impersonation sem TTL
|
|
281
|
+
|
|
282
|
+
**Errado:**
|
|
283
|
+
```typescript
|
|
284
|
+
// Sessão impersonation persiste indefinidamente
|
|
285
|
+
await supabase.auth.signInWithPassword({ email: targetUser.email, password: '...' })
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
**Por quê:** super-admin esquece, sessão fica ativa por dias, usuário target cuja "como" foi assumida nem sabe. Ataque interno trivial.
|
|
289
|
+
|
|
290
|
+
**Certo:** REGRA #2 — magic link com expiry 30min, frontend countdown + auto-logout.
|
|
291
|
+
|
|
292
|
+
### Anti-pattern 3: super_admin via user_metadata
|
|
293
|
+
|
|
294
|
+
**Errado:**
|
|
295
|
+
```sql
|
|
296
|
+
-- Policy lê super_admin de user_metadata
|
|
297
|
+
using ((auth.jwt()->'user_metadata'->>'super_admin')::boolean = true)
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
**Por quê:** `user_metadata` é editável pelo client via `supabase.auth.updateUser({ data: { super_admin: true } })`. Privilege escalation imediato — qualquer usuário se torna super-admin.
|
|
301
|
+
|
|
302
|
+
**Certo:** REGRA #5 — `app_metadata.super_admin` (set apenas via service_role).
|
|
303
|
+
|
|
304
|
+
### Anti-pattern 4: Delete org sem confirmação dupla
|
|
305
|
+
|
|
306
|
+
**Errado:**
|
|
307
|
+
```typescript
|
|
308
|
+
<Button onClick={() => deleteOrg(orgId)}>Delete</Button>
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
**Por quê:** click acidental destrói org com 100k records. Cascade delete = irreversible.
|
|
312
|
+
|
|
313
|
+
**Certo:** REGRA #6 — modal exige typed slug + reason + checkbox + RPC valida tudo server-side. Soft delete preferred.
|
|
314
|
+
|
|
315
|
+
## Ver também
|
|
316
|
+
|
|
317
|
+
- [audit-log-multi-tenant](../audit-log-multi-tenant/SKILL.md) — Phase 109, audit_logs + event `super_admin_action` (REGRA #1)
|
|
318
|
+
- [multi-tenant-rls-hierarchy](../multi-tenant-rls-hierarchy/SKILL.md) — `private.is_super_admin` + PERMISSIVE policy pattern
|
|
319
|
+
- [b2b-saas-architecture](../b2b-saas-architecture/SKILL.md) — JWT minimal `super_admin: bool` em app_metadata (REGRA #5)
|
|
320
|
+
- [supabase-edge-fn-writer](../../agents/supabase-edge-fn-writer.md) — agent invocado para Edge Function impersonation
|
|
321
|
+
- [_shared-multi-tenant/glossary.md](../_shared-multi-tenant/glossary.md) — termos `super_admin`, `impersonation`, `cross-tenant view`, `platform admin`
|
|
322
|
+
- [GitHub Enterprise — Impersonation](https://docs.github.com/en/enterprise-server@latest/admin/user-management/managing-users-in-your-enterprise/impersonating-a-user) — referência external pattern
|