@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,349 @@
1
+ ---
2
+ name: org-switcher-react-pattern
3
+ description: Use ao implementar org switcher React em B2B SaaS multi-tenant — URL pattern /orgs/[slug]/ (Next.js App Router middleware) ou useParams() (Vite SPA + React Router v6), zustand v5 persist para active org context, validação slug → org_id ANTES de servir página, JWT stale strategy via supabase.auth.refreshSession() após role change.
4
+ ---
5
+
6
+ # Org Switcher — React Pattern Multi-Tenant
7
+
8
+ ## Quando usar
9
+
10
+ LLM carrega esta skill ao implementar org switcher em React (Next.js v16 App Router OU Vite SPA + React Router v6). Trigger phrases:
11
+
12
+ - "org switcher React", "tenant switcher"
13
+ - "URL based org context", "/orgs/[slug]"
14
+ - "Next.js middleware multi-tenant"
15
+ - "zustand org store persist"
16
+ - "JWT stale role change refresh"
17
+
18
+ ## Regras absolutas
19
+
20
+ **REGRA #1 (URL-based active org):** Active org vive na **URL** (`/orgs/[slug]/...`), não em cookie/localStorage isolado. Bookmark, share, deep-link funcionam. SSR/middleware lê slug → resolve org_id ANTES de servir página.
21
+
22
+ **REGRA #2 (zustand v5 persist global org context):** Estado global do org ativo (`active_org_id`, `active_role`, `available_orgs`) em `zustand` v5 com `persist` middleware. NÃO Context API (re-renders desnecessários) NÃO Redux (overhead).
23
+
24
+ **REGRA #3 (validação middleware/loader):** Antes de renderizar `/orgs/[slug]/...`, validar:
25
+ - Slug existe em `organizations` (ou redirect 301 via `organization_slug_history`)
26
+ - User é member da org (RLS valida no fetch, mas middleware fail-fast melhora UX)
27
+
28
+ **REGRA #4 (JWT stale após role change):** Após `assign_role()` RPC, chamar `supabase.auth.refreshSession()` imediatamente. JWT antigo válido por 1h — RLS já enforce server-side, mas refresh evita UX confuso.
29
+
30
+ **REGRA #5 (anti-pattern subdomain sem Wildcard):** `acme.app.com` requer Vercel Pro+ Wildcard Domains. Para MVP, sempre `/orgs/acme/...` (path-based). Migrate para subdomain só com white-label requirement real.
31
+
32
+ ## Patterns canônicos
33
+
34
+ ### Next.js v16 App Router — middleware
35
+
36
+ ```typescript
37
+ // middleware.ts (na raiz do projeto)
38
+ import { NextRequest, NextResponse } from 'next/server'
39
+ import { createServerClient } from '@supabase/ssr'
40
+
41
+ export async function middleware(req: NextRequest) {
42
+ const url = req.nextUrl
43
+ const pathname = url.pathname
44
+
45
+ // Match /orgs/[slug]/...
46
+ const orgsMatch = pathname.match(/^\/orgs\/([a-z0-9-]+)(\/.*)?$/)
47
+ if (!orgsMatch) return NextResponse.next()
48
+
49
+ const [, slug] = orgsMatch
50
+ let response = NextResponse.next()
51
+
52
+ // Supabase SSR client
53
+ const supabase = createServerClient(
54
+ process.env.NEXT_PUBLIC_SUPABASE_URL!,
55
+ process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
56
+ {
57
+ cookies: {
58
+ getAll: () => req.cookies.getAll(),
59
+ setAll: (cookiesToSet) => {
60
+ cookiesToSet.forEach(({ name, value, options }) => {
61
+ response.cookies.set(name, value, options)
62
+ })
63
+ }
64
+ }
65
+ }
66
+ )
67
+
68
+ // REGRA #3: validar slug existe
69
+ const { data: org } = await supabase
70
+ .from('organizations')
71
+ .select('id, slug, status')
72
+ .eq('slug', slug)
73
+ .maybeSingle()
74
+
75
+ if (!org) {
76
+ // Tentar slug history (redirect 301)
77
+ const { data: oldSlug } = await supabase
78
+ .from('organization_slug_history')
79
+ .select('new_slug')
80
+ .eq('old_slug', slug)
81
+ .order('changed_at', { ascending: false })
82
+ .maybeSingle()
83
+
84
+ if (oldSlug) {
85
+ const newPath = pathname.replace(`/orgs/${slug}`, `/orgs/${oldSlug.new_slug}`)
86
+ return NextResponse.redirect(new URL(newPath, req.url), 301)
87
+ }
88
+
89
+ return NextResponse.rewrite(new URL('/404', req.url))
90
+ }
91
+
92
+ if (org.status !== 'active') {
93
+ return NextResponse.rewrite(new URL('/orgs/suspended', req.url))
94
+ }
95
+
96
+ // REGRA #3: validar user é member
97
+ const { data: { user } } = await supabase.auth.getUser()
98
+ if (!user) {
99
+ return NextResponse.redirect(new URL('/login?redirect=' + encodeURIComponent(pathname), req.url))
100
+ }
101
+
102
+ const { data: membership } = await supabase
103
+ .from('organization_members')
104
+ .select('id, status, roles(name)')
105
+ .eq('org_id', org.id)
106
+ .eq('user_id', user.id)
107
+ .maybeSingle()
108
+
109
+ if (!membership || membership.status !== 'active') {
110
+ // User não é member — redirect ao próprio dashboard
111
+ return NextResponse.rewrite(new URL('/orgs/no-access', req.url))
112
+ }
113
+
114
+ // Pass org_id + role para Server Components via header
115
+ response.headers.set('x-org-id', org.id)
116
+ response.headers.set('x-org-slug', slug)
117
+ response.headers.set('x-active-role', (membership.roles as any).name)
118
+
119
+ return response
120
+ }
121
+
122
+ export const config = {
123
+ matcher: '/orgs/:slug/:path*'
124
+ }
125
+ ```
126
+
127
+ ### Vite SPA — React Router v6 + useParams
128
+
129
+ ```typescript
130
+ // app/Router.tsx
131
+ import { Routes, Route, useParams, Navigate } from 'react-router-dom'
132
+ import { OrgProvider } from './OrgProvider'
133
+
134
+ function OrgRoutes() {
135
+ const { slug } = useParams<{ slug: string }>()
136
+ if (!slug) return <Navigate to="/orgs" />
137
+
138
+ return (
139
+ <OrgProvider slug={slug}>
140
+ <Routes>
141
+ <Route path="dashboard" element={<Dashboard />} />
142
+ <Route path="leads" element={<Leads />} />
143
+ {/* ... */}
144
+ </Routes>
145
+ </OrgProvider>
146
+ )
147
+ }
148
+
149
+ export function Router() {
150
+ return (
151
+ <Routes>
152
+ <Route path="/orgs/:slug/*" element={<OrgRoutes />} />
153
+ {/* fallback */}
154
+ </Routes>
155
+ )
156
+ }
157
+
158
+ // OrgProvider.tsx — load org + validate via Supabase
159
+ import { createContext, useEffect, useState } from 'react'
160
+ import { supabase } from '@/lib/supabase'
161
+
162
+ const OrgContext = createContext<{ org: Org | null; role: string | null }>({ org: null, role: null })
163
+
164
+ export function OrgProvider({ slug, children }) {
165
+ const [state, setState] = useState({ org: null, role: null, loading: true })
166
+
167
+ useEffect(() => {
168
+ async function load() {
169
+ const { data: org } = await supabase
170
+ .from('organizations')
171
+ .select('id, slug, status, organization_members!inner(roles(name))')
172
+ .eq('slug', slug)
173
+ .single()
174
+
175
+ if (!org) {
176
+ setState({ org: null, role: null, loading: false })
177
+ return
178
+ }
179
+
180
+ setState({
181
+ org,
182
+ role: org.organization_members[0].roles.name,
183
+ loading: false
184
+ })
185
+ }
186
+ load()
187
+ }, [slug])
188
+
189
+ if (state.loading) return <Spinner />
190
+ if (!state.org) return <NotFound />
191
+
192
+ return <OrgContext.Provider value={state}>{children}</OrgContext.Provider>
193
+ }
194
+ ```
195
+
196
+ ### Zustand v5 store (REGRA #2)
197
+
198
+ ```typescript
199
+ // lib/stores/org-store.ts
200
+ import { create } from 'zustand'
201
+ import { persist } from 'zustand/middleware'
202
+
203
+ interface OrgStore {
204
+ activeOrgId: string | null
205
+ activeOrgSlug: string | null
206
+ activeRole: string | null
207
+ availableOrgs: { id: string; slug: string; name: string }[]
208
+ setActiveOrg: (orgId: string, slug: string, role: string) => void
209
+ setAvailableOrgs: (orgs: any[]) => void
210
+ clear: () => void
211
+ }
212
+
213
+ export const useOrgStore = create<OrgStore>()(
214
+ persist(
215
+ (set) => ({
216
+ activeOrgId: null,
217
+ activeOrgSlug: null,
218
+ activeRole: null,
219
+ availableOrgs: [],
220
+ setActiveOrg: (orgId, slug, role) => set({ activeOrgId: orgId, activeOrgSlug: slug, activeRole: role }),
221
+ setAvailableOrgs: (orgs) => set({ availableOrgs: orgs }),
222
+ clear: () => set({ activeOrgId: null, activeOrgSlug: null, activeRole: null, availableOrgs: [] })
223
+ }),
224
+ {
225
+ name: 'org-store', // localStorage key
226
+ version: 1
227
+ }
228
+ )
229
+ )
230
+ ```
231
+
232
+ ### Org switcher UI — shadcn Command palette
233
+
234
+ ```typescript
235
+ // components/OrgSwitcher.tsx
236
+ 'use client'
237
+
238
+ import { Command, CommandInput, CommandList, CommandItem, CommandEmpty } from '@/components/ui/command'
239
+ import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover'
240
+ import { useOrgStore } from '@/lib/stores/org-store'
241
+ import { useRouter } from 'next/navigation'
242
+
243
+ export function OrgSwitcher() {
244
+ const router = useRouter()
245
+ const { activeOrgSlug, availableOrgs } = useOrgStore()
246
+
247
+ return (
248
+ <Popover>
249
+ <PopoverTrigger asChild>
250
+ <Button variant="outline">{activeOrgSlug || 'Select org'}</Button>
251
+ </PopoverTrigger>
252
+ <PopoverContent className="w-[300px] p-0">
253
+ <Command>
254
+ <CommandInput placeholder="Buscar organização..." />
255
+ <CommandEmpty>Nenhuma organização encontrada.</CommandEmpty>
256
+ <CommandList>
257
+ {availableOrgs.map(org => (
258
+ <CommandItem
259
+ key={org.id}
260
+ onSelect={() => router.push(`/orgs/${org.slug}/dashboard`)}
261
+ >
262
+ {org.name}
263
+ </CommandItem>
264
+ ))}
265
+ </CommandList>
266
+ </Command>
267
+ </PopoverContent>
268
+ </Popover>
269
+ )
270
+ }
271
+ ```
272
+
273
+ ### JWT stale após role change (REGRA #4)
274
+
275
+ ```typescript
276
+ // Após assign_role RPC
277
+ async function changeUserRole(orgId: string, userId: string, roleId: string) {
278
+ const { error } = await supabase.rpc('assign_role', {
279
+ p_org_id: orgId,
280
+ p_target_user_id: userId,
281
+ p_role_id: roleId
282
+ })
283
+
284
+ if (error) throw error
285
+
286
+ // REGRA #4: refresh JWT imediatamente — UX consistent com novo role
287
+ await supabase.auth.refreshSession()
288
+ // RLS server-side enforce de qualquer forma — refresh é UX
289
+ }
290
+ ```
291
+
292
+ ## Anti-patterns
293
+
294
+ ### Anti-pattern 1: Active org em cookie/localStorage isolado
295
+
296
+ **Errado:**
297
+ ```typescript
298
+ localStorage.setItem('active_org', orgId)
299
+ // URL não muda, deep-link não funciona
300
+ ```
301
+
302
+ **Por quê:** REGRA #1 — bookmark `/dashboard` não preserva qual org. Share link manda ao dashboard mas com org diferente.
303
+
304
+ **Certo:** URL `/orgs/[slug]/dashboard` + zustand sync.
305
+
306
+ ### Anti-pattern 2: Context API para org global
307
+
308
+ **Errado:**
309
+ ```typescript
310
+ const OrgContext = createContext({ ... })
311
+ // Em cada consume → re-render Tree inteira
312
+ ```
313
+
314
+ **Por quê:** Context API re-renderiza todos consumers em qualquer mudança. Zustand re-renderiza apenas componentes que selecionam o slice mudado.
315
+
316
+ **Certo:** REGRA #2 — `useOrgStore` com selectors granulares.
317
+
318
+ ### Anti-pattern 3: Subdomain sem Wildcard Domains setup
319
+
320
+ **Errado:**
321
+ ```
322
+ acme.app.com → ❌ certificate error
323
+ ```
324
+
325
+ **Por quê:** REGRA #5 — Vercel free tier não suporta wildcard. Cada subdomain precisa cert manual.
326
+
327
+ **Certo:** path-based `/orgs/acme/...` para MVP. Subdomain só com Vercel Pro + Wildcard Domain configurado.
328
+
329
+ ### Anti-pattern 4: Middleware sem fail-fast em slug inválido
330
+
331
+ **Errado:**
332
+ ```typescript
333
+ // Middleware não valida slug, deixa página renderizar
334
+ // Página faz fetch, retorna empty → confusing UX
335
+ ```
336
+
337
+ **Por quê:** REGRA #3 — fail fast no middleware. User vê 404 imediato em vez de "loading... empty page".
338
+
339
+ **Certo:** middleware valida slug existe + user é member ANTES de servir página.
340
+
341
+ ## Ver também
342
+
343
+ - [permission-gate-react-pattern](../permission-gate-react-pattern/SKILL.md) — Phase 115 sibling
344
+ - [member-management-react-shadcn](../member-management-react-shadcn/SKILL.md) — Phase 115 sibling
345
+ - [b2b-saas-architecture](../b2b-saas-architecture/SKILL.md) — slug imutável + redirect trail
346
+ - [supabase-auth-ssr](../supabase-auth-ssr/SKILL.md) — `@supabase/ssr` middleware pattern
347
+ - [_shared-multi-tenant/glossary.md](../_shared-multi-tenant/glossary.md) — `org switcher`, `JWT stale`
348
+ - [Next.js 16 Multi-Tenant Architecture](https://nextjs.org/docs/app/guides/multi-tenant)
349
+ - [Vercel Multi-Tenant Guide](https://vercel.com/guides/nextjs-multi-tenant-application)
@@ -0,0 +1,271 @@
1
+ ---
2
+ name: permission-gate-react-pattern
3
+ description: Use ao implementar permission gates React em B2B SaaS multi-tenant — CASL `@casl/ability` 6.8 + `@casl/react` 4.x para gates declarativos `<PermissionGate permission="leads:create">`, hook `usePermission(action, resource)`, anti-pattern explícito permission check só client (server-side enforcement obrigatório via RLS).
4
+ ---
5
+
6
+ # Permission Gate — React Pattern (CASL)
7
+
8
+ ## Quando usar
9
+
10
+ LLM carrega esta skill ao implementar gates de permissão UI em React. Trigger phrases:
11
+
12
+ - "permission gate React", "PermissionGate component"
13
+ - "CASL React permissions", "@casl/ability"
14
+ - "usePermission hook", "ability check React"
15
+ - "RBAC frontend gate"
16
+ - "client-side permission anti-pattern"
17
+
18
+ ## Regras absolutas
19
+
20
+ **REGRA #1 (UX-only, NUNCA segurança):** Permission gate React é **UX apenas**. Esconde botão para evitar erro 403 visível ao user. **Server-side enforcement obrigatório** via RLS (Phase 108) + `private.has_permission`.
21
+
22
+ **REGRA #2 (CASL canônico 2026):** `@casl/ability` v6.8+ + `@casl/react` v4.x é a biblioteca canônica para React. Isomorfica (frontend + backend), bundle pequeno (~5KB), API declarativa.
23
+
24
+ **REGRA #3 (build ability do JWT):** Construir `Ability` instance **uma vez** após login a partir das permissions do user (fetched via RPC). Re-build apenas após role change.
25
+
26
+ **REGRA #4 (Hook `usePermission` + componente `<PermissionGate>`):** Padrões canônicos:
27
+ - `usePermission(action, resource)` para condicionais inline
28
+ - `<PermissionGate permission="leads:create">{children}</PermissionGate>` para wrap declarativo
29
+
30
+ **REGRA #5 (sync com server após role change):** Após `assign_role` RPC, re-fetch permissions + rebuild Ability + update store. Sem isso, UI mostra cached state stale.
31
+
32
+ ## Patterns canônicos
33
+
34
+ ### Setup CASL — definir Ability
35
+
36
+ ```typescript
37
+ // lib/abilities/build-ability.ts
38
+ import { AbilityBuilder, Ability } from '@casl/ability'
39
+
40
+ export type Action = 'create' | 'read' | 'update' | 'delete' | 'invite' | 'remove' | 'export' | 'view' | 'process'
41
+ export type Subject = 'leads' | 'members' | 'org_settings' | 'audit_logs' | 'departments' | 'roles' | 'permissions' | 'dsr_requests' | 'all'
42
+
43
+ export type AppAbility = Ability<[Action, Subject]>
44
+
45
+ interface UserPermissions {
46
+ permissions: Array<{ action: Action; resource: Subject }>
47
+ isSuperAdmin: boolean
48
+ }
49
+
50
+ export function buildAbility({ permissions, isSuperAdmin }: UserPermissions): AppAbility {
51
+ const { can, build } = new AbilityBuilder<AppAbility>(Ability)
52
+
53
+ if (isSuperAdmin) {
54
+ can('manage' as any, 'all')
55
+ return build()
56
+ }
57
+
58
+ for (const p of permissions) {
59
+ can(p.action, p.resource)
60
+ }
61
+
62
+ return build()
63
+ }
64
+ ```
65
+
66
+ ### Buscar permissions do user (RPC)
67
+
68
+ ```sql
69
+ -- supabase RPC chamada após login
70
+ create or replace function public.get_user_permissions(p_org_id uuid)
71
+ returns table(action text, resource text)
72
+ language sql
73
+ stable
74
+ security invoker
75
+ set search_path = ''
76
+ as $$
77
+ select p.action, p.resource
78
+ from public.organization_members om
79
+ join public.role_permissions rp on rp.role_id = om.role_id
80
+ join public.permissions p on p.id = rp.permission_id
81
+ where om.org_id = p_org_id
82
+ and om.user_id = (select auth.uid())
83
+ and om.status = 'active';
84
+ $$;
85
+
86
+ grant execute on function public.get_user_permissions(uuid) to authenticated;
87
+ ```
88
+
89
+ ### Provider — Ability disponível em toda app
90
+
91
+ ```typescript
92
+ // app/providers/AbilityProvider.tsx
93
+ 'use client'
94
+
95
+ import { createContext, useEffect, useState } from 'react'
96
+ import { AppAbility, buildAbility } from '@/lib/abilities/build-ability'
97
+ import { useOrgStore } from '@/lib/stores/org-store'
98
+ import { supabase } from '@/lib/supabase'
99
+
100
+ export const AbilityContext = createContext<AppAbility | null>(null)
101
+
102
+ export function AbilityProvider({ children }: { children: React.ReactNode }) {
103
+ const [ability, setAbility] = useState<AppAbility | null>(null)
104
+ const activeOrgId = useOrgStore(s => s.activeOrgId)
105
+
106
+ useEffect(() => {
107
+ if (!activeOrgId) return
108
+
109
+ async function load() {
110
+ // REGRA #3: build ability do server data
111
+ const { data: { user } } = await supabase.auth.getUser()
112
+ const isSuperAdmin = user?.app_metadata.super_admin === true
113
+
114
+ const { data: permissions } = await supabase
115
+ .rpc('get_user_permissions', { p_org_id: activeOrgId })
116
+
117
+ setAbility(buildAbility({ permissions: permissions || [], isSuperAdmin }))
118
+ }
119
+ load()
120
+ }, [activeOrgId])
121
+
122
+ return <AbilityContext.Provider value={ability}>{children}</AbilityContext.Provider>
123
+ }
124
+
125
+ // Hook para acessar ability
126
+ import { useContext } from 'react'
127
+ export function useAbility() {
128
+ const ability = useContext(AbilityContext)
129
+ if (!ability) throw new Error('useAbility must be inside AbilityProvider')
130
+ return ability
131
+ }
132
+ ```
133
+
134
+ ### Hook `usePermission` (REGRA #4)
135
+
136
+ ```typescript
137
+ // lib/hooks/use-permission.ts
138
+ import { useAbility } from '@/app/providers/AbilityProvider'
139
+ import { Action, Subject } from '@/lib/abilities/build-ability'
140
+
141
+ export function usePermission(action: Action, resource: Subject): boolean {
142
+ const ability = useAbility()
143
+ return ability.can(action, resource)
144
+ }
145
+
146
+ // Usage:
147
+ function LeadsPage() {
148
+ const canCreateLead = usePermission('create', 'leads')
149
+ return (
150
+ <div>
151
+ <h1>Leads</h1>
152
+ {canCreateLead && <Button onClick={openCreateModal}>+ Novo Lead</Button>}
153
+ </div>
154
+ )
155
+ }
156
+ ```
157
+
158
+ ### Componente `<PermissionGate>` (REGRA #4)
159
+
160
+ ```typescript
161
+ // components/PermissionGate.tsx
162
+ import { useAbility } from '@/app/providers/AbilityProvider'
163
+ import type { Action, Subject } from '@/lib/abilities/build-ability'
164
+
165
+ interface Props {
166
+ permission: `${Action}:${Subject}`
167
+ fallback?: React.ReactNode
168
+ children: React.ReactNode
169
+ }
170
+
171
+ export function PermissionGate({ permission, fallback = null, children }: Props) {
172
+ const ability = useAbility()
173
+ const [action, subject] = permission.split(':') as [Action, Subject]
174
+
175
+ if (ability.can(action, subject)) {
176
+ return <>{children}</>
177
+ }
178
+ return <>{fallback}</>
179
+ }
180
+
181
+ // Usage:
182
+ <PermissionGate permission="leads:create">
183
+ <Button onClick={openCreateModal}>+ Novo Lead</Button>
184
+ </PermissionGate>
185
+
186
+ <PermissionGate
187
+ permission="org_settings:update"
188
+ fallback={<p>Você não tem permissão para alterar configurações.</p>}
189
+ >
190
+ <SettingsForm />
191
+ </PermissionGate>
192
+ ```
193
+
194
+ ### Refresh ability após role change (REGRA #5)
195
+
196
+ ```typescript
197
+ // Em algum lugar após mudança de role (admin UI)
198
+ async function changeRole(targetUserId: string, newRoleId: string) {
199
+ await supabase.rpc('assign_role', { ... })
200
+ await supabase.auth.refreshSession() // JWT (cross-ref org-switcher)
201
+
202
+ // REGRA #5: re-fetch + rebuild ability
203
+ // Trigger AbilityProvider re-fetch via mudança em activeOrgId timestamp
204
+ // (use store version increment)
205
+ useOrgStore.getState().bumpVersion()
206
+ }
207
+ ```
208
+
209
+ ## Anti-patterns
210
+
211
+ ### Anti-pattern 1: Permission check SÓ frontend (sem RLS)
212
+
213
+ **Errado:**
214
+ ```typescript
215
+ { ability.can('delete', 'leads') && <DeleteButton onClick={() => api.delete(`/leads/${id}`)} /> }
216
+ // Mas API endpoint não checa permission server-side
217
+ ```
218
+
219
+ **Por quê:** REGRA #1 — atacante chama `curl -X DELETE /leads/...` direto, ignora gate React. Frontend gate é segurança teatro.
220
+
221
+ **Certo:** RLS no Supabase com `private.has_permission` (Phase 108) + frontend gate como UX redundância.
222
+
223
+ ### Anti-pattern 2: Hard-coded role check em vez de permission
224
+
225
+ **Errado:**
226
+ ```typescript
227
+ { user.role === 'admin' && <Button>Convidar</Button> }
228
+ ```
229
+
230
+ **Por quê:** custom roles quebram. Custom role com permission `members:invite` deveria mostrar botão, mas não passa no check `=== 'admin'`. Acopla UI a role names.
231
+
232
+ **Certo:** `usePermission('invite', 'members')` — funciona com qualquer role que tenha a permission.
233
+
234
+ ### Anti-pattern 3: Re-fetch permissions a cada render
235
+
236
+ **Errado:**
237
+ ```typescript
238
+ function MyComponent() {
239
+ const [perms, setPerms] = useState([])
240
+ useEffect(() => {
241
+ supabase.rpc('get_user_permissions', { ... }).then(setPerms)
242
+ }) // sem deps array — re-fetch infinito
243
+ }
244
+ ```
245
+
246
+ **Por quê:** N requests/min para Supabase, performance terrível.
247
+
248
+ **Certo:** REGRA #3 — build Ability uma vez no Provider, consume via `useAbility()` hook.
249
+
250
+ ### Anti-pattern 4: Esquecer fallback em PermissionGate
251
+
252
+ **Errado:**
253
+ ```typescript
254
+ <PermissionGate permission="org_settings:update">
255
+ <SettingsForm />
256
+ </PermissionGate>
257
+ // User sem permission vê página vazia, sem feedback
258
+ ```
259
+
260
+ **Por quê:** UX confusa — user não entende por que página é em branco.
261
+
262
+ **Certo:** sempre passar `fallback` com mensagem clara ("Você não tem permissão...").
263
+
264
+ ## Ver também
265
+
266
+ - [org-switcher-react-pattern](../org-switcher-react-pattern/SKILL.md) — sibling, OrgProvider + zustand store
267
+ - [member-management-react-shadcn](../member-management-react-shadcn/SKILL.md) — sibling, usa PermissionGate
268
+ - [rbac-permissions-matrix-supabase](../rbac-permissions-matrix-supabase/SKILL.md) — Phase 108, modelagem permissions
269
+ - [multi-tenant-rls-hierarchy](../multi-tenant-rls-hierarchy/SKILL.md) — Phase 108, server-side RLS enforcement
270
+ - [_shared-multi-tenant/glossary.md](../_shared-multi-tenant/glossary.md) — `permission gate`, `CASL`, `JWT stale`
271
+ - [CASL Documentation](https://casl.js.org/)