@luanpdd/kit-mcp 1.31.0 → 1.33.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/kit/COMPATIBILITY.md +5 -0
- package/kit/agents/designer-ui.md +216 -0
- package/kit/agents/supabase-auth-bootstrapper.md +15 -1
- package/kit/agents/supabase-auth-hook-writer.md +418 -0
- package/kit/agents/supabase-mfa-implementer.md +439 -0
- package/kit/agents/supabase-oauth-server-implementer.md +507 -0
- package/kit/agents/supabase-social-auth-implementer.md +451 -0
- package/kit/agents/supabase-sso-saml-architect.md +549 -0
- package/kit/commands/supabase.md +21 -1
- package/kit/file-manifest.json +29 -6
- package/kit/skills/supabase-auth-hardening/SKILL.md +674 -0
- package/kit/skills/supabase-auth-hooks/SKILL.md +875 -0
- package/kit/skills/supabase-auth-methods/SKILL.md +486 -0
- package/kit/skills/supabase-auth-sessions/SKILL.md +579 -0
- package/kit/skills/supabase-auth-ssr/SKILL.md +60 -14
- package/kit/skills/supabase-enterprise-sso-saml/SKILL.md +545 -0
- package/kit/skills/supabase-jwt-signing-keys/SKILL.md +399 -0
- package/kit/skills/supabase-mfa/SKILL.md +488 -0
- package/kit/skills/supabase-oauth-server/SKILL.md +537 -0
- package/kit/skills/supabase-social-oauth/SKILL.md +480 -0
- package/kit/skills/supabase-third-party-auth/SKILL.md +450 -0
- package/kit/skills/ui-anti-padroes-ia/SKILL.md +261 -0
- package/kit/skills/ui-contexto-produto/SKILL.md +248 -0
- package/kit/skills/ui-cor-estrategia/SKILL.md +213 -0
- package/kit/skills/ui-critica-auditoria/SKILL.md +260 -0
- package/kit/skills/ui-motion-funcional/SKILL.md +264 -0
- package/kit/skills/ui-ritmo-espacial/SKILL.md +259 -0
- package/kit/skills/ui-tipografia/SKILL.md +211 -0
- package/package.json +1 -1
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: supabase-oauth-server
|
|
3
|
+
description: Use ao implementar OAuth 2.1 Server com Supabase como identity provider, incluindo autenticação MCP, PKCE, OIDC, registro de clients e RLS por client_id.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Supabase — OAuth 2.1 Server (Identity Provider & MCP Auth)
|
|
7
|
+
|
|
8
|
+
## Quando usar
|
|
9
|
+
|
|
10
|
+
LLM carrega esta skill quando o projeto precisar do **Supabase como identity provider OAuth 2.1 / OIDC** — seja para autenticar agentes de IA via MCP, apps mobile/desktop, developer platforms ou enterprise SSO.
|
|
11
|
+
|
|
12
|
+
Trigger phrases:
|
|
13
|
+
|
|
14
|
+
- "OAuth 2.1 server Supabase", "Supabase as identity provider"
|
|
15
|
+
- "Sign in with my app", "MCP authentication"
|
|
16
|
+
- "OAuth client registration", "authorization endpoint Supabase"
|
|
17
|
+
- "OIDC server", "supabase.auth.oauth"
|
|
18
|
+
- "Model Context Protocol auth", "agente MCP autenticado"
|
|
19
|
+
- "dynamic client registration Supabase"
|
|
20
|
+
|
|
21
|
+
## Princípio canônico
|
|
22
|
+
|
|
23
|
+
O Supabase OAuth Server transforma seu projeto Supabase em um **authorization server OAuth 2.1 + OIDC completo**. Em vez de apenas consumir provedores OAuth externos (Google, GitHub), seu app **se torna** o provedor — os usuários fazem login com a sua plataforma.
|
|
24
|
+
|
|
25
|
+
**Casos de uso principais:**
|
|
26
|
+
|
|
27
|
+
| Caso | Descrição |
|
|
28
|
+
|------|-----------|
|
|
29
|
+
| Developer platform | "Login com MinhaPlatforma" para apps de terceiros |
|
|
30
|
+
| MCP Server auth | Agentes de IA se autenticam como usuários existentes |
|
|
31
|
+
| Apps mobile/desktop | Token-based auth sem secret key exposto |
|
|
32
|
+
| Enterprise SSO | Federar autenticação via OIDC para ferramentas internas |
|
|
33
|
+
|
|
34
|
+
**Padrões suportados:**
|
|
35
|
+
|
|
36
|
+
- **OAuth 2.1** com PKCE obrigatório (código de autorização + PKCE — fluxo implícito removido na v2.1)
|
|
37
|
+
- **OIDC** — ID tokens, endpoint UserInfo, discovery automático
|
|
38
|
+
- **Scopes**: `openid`, `email`, `profile`, `phone`
|
|
39
|
+
- **Dynamic Client Registration** — clients se registram programaticamente
|
|
40
|
+
- **JWKS** — validação de chaves públicas
|
|
41
|
+
- **Authorization Code + Refresh Token** flows
|
|
42
|
+
|
|
43
|
+
## Habilitando o OAuth Server
|
|
44
|
+
|
|
45
|
+
### Via Dashboard
|
|
46
|
+
|
|
47
|
+
`Authentication > OAuth Server` → habilitar toggle.
|
|
48
|
+
|
|
49
|
+
### Via `config.toml` (desenvolvimento local)
|
|
50
|
+
|
|
51
|
+
```toml
|
|
52
|
+
[auth.oauth_server]
|
|
53
|
+
enabled = true
|
|
54
|
+
authorization_url_path = "/authorize" # rota da UI de consentimento no seu app
|
|
55
|
+
allow_dynamic_registration = true # clients se registram via API
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
`authorization_url_path` aponta para a rota do **seu app** que renderiza a UI de consentimento. Supabase redireciona o usuário para lá com `?authorization_id=<uuid>` na URL.
|
|
59
|
+
|
|
60
|
+
## Endpoints expostos automaticamente
|
|
61
|
+
|
|
62
|
+
| Endpoint | Função |
|
|
63
|
+
|----------|--------|
|
|
64
|
+
| `GET /auth/v1/oauth/authorize` | Inicia o fluxo de autorização |
|
|
65
|
+
| `POST /auth/v1/oauth/token` | Troca code por tokens / refresh |
|
|
66
|
+
| `GET /auth/v1/.well-known/jwks.json` | Chaves públicas para validação de JWT |
|
|
67
|
+
| `GET /auth/v1/.well-known/openid-configuration` | Discovery OIDC |
|
|
68
|
+
| `GET /auth/v1/.well-known/oauth-authorization-server/auth/v1` | Discovery OAuth — **MCP usa este** |
|
|
69
|
+
| `GET /auth/v1/oauth/userinfo` | Dados do usuário autenticado (OIDC) |
|
|
70
|
+
|
|
71
|
+
O endpoint de **MCP discovery** (`/auth/v1/.well-known/oauth-authorization-server/auth/v1`) é detectado automaticamente por clientes MCP como o Claude Desktop e implementações FastMCP.
|
|
72
|
+
|
|
73
|
+
## Authorization UI — página de consentimento
|
|
74
|
+
|
|
75
|
+
Supabase redireciona o browser do usuário para `authorization_url_path?authorization_id=<uuid>`. Você deve criar esta rota no seu app.
|
|
76
|
+
|
|
77
|
+
```tsx
|
|
78
|
+
// app/authorize/page.tsx (Next.js App Router)
|
|
79
|
+
import { createClient } from '@/lib/supabase/server'
|
|
80
|
+
|
|
81
|
+
interface Props {
|
|
82
|
+
searchParams: { authorization_id?: string }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export default async function AuthorizePage({ searchParams }: Props) {
|
|
86
|
+
const authorizationId = searchParams.authorization_id
|
|
87
|
+
if (!authorizationId) return <p>Parâmetro inválido.</p>
|
|
88
|
+
|
|
89
|
+
// IMPORTANTE: inicializar client DENTRO do request handler
|
|
90
|
+
const supabase = await createClient()
|
|
91
|
+
|
|
92
|
+
const { data, error } = await supabase.auth.oauth.getAuthorizationDetails(authorizationId)
|
|
93
|
+
if (error || !data) return <p>Autorização inválida ou expirada.</p>
|
|
94
|
+
|
|
95
|
+
const { client, scopes } = data
|
|
96
|
+
|
|
97
|
+
return (
|
|
98
|
+
<div className="max-w-md mx-auto mt-20 p-6 border rounded-lg shadow">
|
|
99
|
+
<h1 className="text-xl font-bold mb-4">Autorizar acesso</h1>
|
|
100
|
+
<p className="mb-2">
|
|
101
|
+
<strong>{client.name}</strong> está solicitando acesso à sua conta.
|
|
102
|
+
</p>
|
|
103
|
+
<p className="text-sm text-gray-500 mb-6">
|
|
104
|
+
Permissões solicitadas: {scopes.join(', ')}
|
|
105
|
+
</p>
|
|
106
|
+
|
|
107
|
+
<ConsentForm authorizationId={authorizationId} />
|
|
108
|
+
</div>
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
```tsx
|
|
114
|
+
// app/authorize/ConsentForm.tsx — Client Component
|
|
115
|
+
'use client'
|
|
116
|
+
import { createClient } from '@/lib/supabase/client'
|
|
117
|
+
|
|
118
|
+
export function ConsentForm({ authorizationId }: { authorizationId: string }) {
|
|
119
|
+
const supabase = createClient()
|
|
120
|
+
|
|
121
|
+
async function handleApprove() {
|
|
122
|
+
const { data, error } = await supabase.auth.oauth.approveAuthorization(authorizationId)
|
|
123
|
+
if (error) { alert('Erro ao aprovar: ' + error.message); return }
|
|
124
|
+
// data.redirect_uri — redirecionar o browser para esta URL
|
|
125
|
+
window.location.href = data.redirect_uri
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function handleDeny() {
|
|
129
|
+
const { data, error } = await supabase.auth.oauth.denyAuthorization(authorizationId)
|
|
130
|
+
if (error) { alert('Erro ao negar: ' + error.message); return }
|
|
131
|
+
window.location.href = data.redirect_uri
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return (
|
|
135
|
+
<div className="flex gap-4">
|
|
136
|
+
<button onClick={handleApprove} className="btn-primary">Autorizar</button>
|
|
137
|
+
<button onClick={handleDeny} className="btn-secondary">Negar</button>
|
|
138
|
+
</div>
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
**Fluxo da UI de consentimento:**
|
|
144
|
+
|
|
145
|
+
1. `getAuthorizationDetails(id)` — busca dados do client e scopes solicitados
|
|
146
|
+
2. Renderiza UI para o usuário revisar
|
|
147
|
+
3. `approveAuthorization(id)` → retorna `redirect_uri` com `code` → browser navega
|
|
148
|
+
4. `denyAuthorization(id)` → retorna `redirect_uri` com `error=access_denied`
|
|
149
|
+
|
|
150
|
+
## Registro de OAuth Clients
|
|
151
|
+
|
|
152
|
+
### Via Admin API (server-side com service_role)
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
// lib/oauth-clients.ts — executar no backend
|
|
156
|
+
import { createClient } from '@supabase/supabase-js'
|
|
157
|
+
|
|
158
|
+
const supabaseAdmin = createClient(
|
|
159
|
+
process.env.SUPABASE_URL!,
|
|
160
|
+
process.env.SUPABASE_SERVICE_ROLE_KEY! // nunca expor no cliente
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
// Client público (apps mobile/desktop, MCP servers sem secret)
|
|
164
|
+
const { data: publicClient, error } = await supabaseAdmin.auth.admin.oauth.createClient({
|
|
165
|
+
name: 'Meu App Mobile',
|
|
166
|
+
redirect_uris: ['myapp://oauth/callback'],
|
|
167
|
+
client_type: 'public', // sem client_secret
|
|
168
|
+
token_endpoint_auth_method: 'none', // PKCE obrigatório
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
console.log(publicClient?.client_id) // sb_publishable_...
|
|
172
|
+
|
|
173
|
+
// Client confidencial (server-side apps com secret)
|
|
174
|
+
const { data: confidentialClient } = await supabaseAdmin.auth.admin.oauth.createClient({
|
|
175
|
+
name: 'API Server Parceiro',
|
|
176
|
+
redirect_uris: ['https://parceiro.exemplo.com/auth/callback'],
|
|
177
|
+
client_type: 'confidential',
|
|
178
|
+
token_endpoint_auth_method: 'client_secret_basic', // ou 'client_secret_post'
|
|
179
|
+
})
|
|
180
|
+
|
|
181
|
+
console.log(confidentialClient?.client_id) // identificador
|
|
182
|
+
console.log(confidentialClient?.client_secret) // guardar com segurança — exibido UMA VEZ
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Client types
|
|
186
|
+
|
|
187
|
+
| Tipo | `token_endpoint_auth_method` | Uso |
|
|
188
|
+
|------|------------------------------|-----|
|
|
189
|
+
| `public` | `none` | Mobile, desktop, MCP, SPA |
|
|
190
|
+
| `confidential` | `client_secret_basic` (padrão) | Server-side |
|
|
191
|
+
| `confidential` | `client_secret_post` | Body params em vez de header |
|
|
192
|
+
|
|
193
|
+
## Fluxo Authorization Code + PKCE
|
|
194
|
+
|
|
195
|
+
### Passo 1: Gerar PKCE
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
// utils/pkce.ts
|
|
199
|
+
function base64urlEncode(buffer: ArrayBuffer): string {
|
|
200
|
+
return btoa(String.fromCharCode(...new Uint8Array(buffer)))
|
|
201
|
+
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export async function generatePKCE() {
|
|
205
|
+
// code_verifier: string aleatório de 43-128 chars
|
|
206
|
+
const codeVerifier = base64urlEncode(crypto.getRandomValues(new Uint8Array(32)))
|
|
207
|
+
|
|
208
|
+
// code_challenge: SHA-256(code_verifier) em Base64-URL
|
|
209
|
+
const encoder = new TextEncoder()
|
|
210
|
+
const data = encoder.encode(codeVerifier)
|
|
211
|
+
const digest = await crypto.subtle.digest('SHA-256', data)
|
|
212
|
+
const codeChallenge = base64urlEncode(digest)
|
|
213
|
+
|
|
214
|
+
return { codeVerifier, codeChallenge }
|
|
215
|
+
}
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
### Passo 2: Iniciar autorização
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
const { codeVerifier, codeChallenge } = await generatePKCE()
|
|
222
|
+
|
|
223
|
+
// Armazenar code_verifier de forma segura (sessão ou localStorage criptografado)
|
|
224
|
+
sessionStorage.setItem('oauth_code_verifier', codeVerifier)
|
|
225
|
+
|
|
226
|
+
const params = new URLSearchParams({
|
|
227
|
+
response_type: 'code',
|
|
228
|
+
client_id: 'meu-client-id',
|
|
229
|
+
redirect_uri: 'https://meuapp.com/auth/callback',
|
|
230
|
+
scope: 'openid email profile',
|
|
231
|
+
state: crypto.randomUUID(), // CSRF protection
|
|
232
|
+
code_challenge: codeChallenge,
|
|
233
|
+
code_challenge_method: 'S256', // único método suportado
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
// Redireciona para Supabase
|
|
237
|
+
window.location.href = `${SUPABASE_URL}/auth/v1/oauth/authorize?${params}`
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
### Passo 3: Trocar código por tokens (callback)
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
// app/auth/callback/route.ts
|
|
244
|
+
export async function GET(request: Request) {
|
|
245
|
+
const url = new URL(request.url)
|
|
246
|
+
const code = url.searchParams.get('code')
|
|
247
|
+
const state = url.searchParams.get('state')
|
|
248
|
+
const codeVerifier = sessionStorage.getItem('oauth_code_verifier')!
|
|
249
|
+
|
|
250
|
+
const tokenResponse = await fetch(`${SUPABASE_URL}/auth/v1/oauth/token`, {
|
|
251
|
+
method: 'POST',
|
|
252
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
253
|
+
body: new URLSearchParams({
|
|
254
|
+
grant_type: 'authorization_code',
|
|
255
|
+
client_id: 'meu-client-id',
|
|
256
|
+
code: code!,
|
|
257
|
+
redirect_uri: 'https://meuapp.com/auth/callback',
|
|
258
|
+
code_verifier: codeVerifier, // PKCE — valida o challenge original
|
|
259
|
+
}),
|
|
260
|
+
})
|
|
261
|
+
|
|
262
|
+
const tokens = await tokenResponse.json()
|
|
263
|
+
// tokens.access_token, tokens.refresh_token, tokens.id_token (se openid scope)
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
### Passo 4: Refresh Token
|
|
268
|
+
|
|
269
|
+
```ts
|
|
270
|
+
const refreshResponse = await fetch(`${SUPABASE_URL}/auth/v1/oauth/token`, {
|
|
271
|
+
method: 'POST',
|
|
272
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
273
|
+
body: new URLSearchParams({
|
|
274
|
+
grant_type: 'refresh_token',
|
|
275
|
+
client_id: 'meu-client-id',
|
|
276
|
+
refresh_token: storedRefreshToken,
|
|
277
|
+
}),
|
|
278
|
+
})
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
## MCP Authentication — Destaque Especial
|
|
282
|
+
|
|
283
|
+
Este kit-mcp é em si um **servidor MCP** — esta seção é especialmente relevante.
|
|
284
|
+
|
|
285
|
+
### Por que Supabase + MCP funciona
|
|
286
|
+
|
|
287
|
+
O protocolo MCP 2025 exige que servidores exponham um endpoint de discovery OAuth compatível com RFC 8414. O Supabase expõe automaticamente:
|
|
288
|
+
|
|
289
|
+
```
|
|
290
|
+
GET https://<project>.supabase.co/auth/v1/.well-known/oauth-authorization-server/auth/v1
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Clientes MCP (Claude Desktop, FastMCP, SDK oficial) detectam este endpoint e executam o fluxo OAuth 2.1 automaticamente — sem configuração manual de endpoints.
|
|
294
|
+
|
|
295
|
+
### MCP Server com FastMCP autenticado
|
|
296
|
+
|
|
297
|
+
```ts
|
|
298
|
+
// server.ts — MCP server com autenticação Supabase OAuth
|
|
299
|
+
import { FastMCP } from 'fastmcp'
|
|
300
|
+
import { createClient } from '@supabase/supabase-js'
|
|
301
|
+
|
|
302
|
+
const server = new FastMCP({
|
|
303
|
+
name: 'meu-mcp-server',
|
|
304
|
+
version: '1.0.0',
|
|
305
|
+
// FastMCP detecta o discovery automático do Supabase
|
|
306
|
+
oauth: {
|
|
307
|
+
issuer: process.env.SUPABASE_URL + '/auth/v1',
|
|
308
|
+
clientId: process.env.MCP_OAUTH_CLIENT_ID!,
|
|
309
|
+
scopes: ['openid', 'email', 'profile'],
|
|
310
|
+
},
|
|
311
|
+
})
|
|
312
|
+
|
|
313
|
+
server.addTool({
|
|
314
|
+
name: 'get-my-data',
|
|
315
|
+
description: 'Retorna dados do usuário autenticado',
|
|
316
|
+
execute: async (args, context) => {
|
|
317
|
+
// context.accessToken — JWT do usuário autenticado via OAuth
|
|
318
|
+
const supabase = createClient(
|
|
319
|
+
process.env.SUPABASE_URL!,
|
|
320
|
+
process.env.SUPABASE_ANON_KEY!, // usar sb_publishable_... em novos projetos
|
|
321
|
+
{ global: { headers: { Authorization: `Bearer ${context.accessToken}` } } }
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
const { data, error } = await supabase.from('my_table').select('*')
|
|
325
|
+
return data
|
|
326
|
+
},
|
|
327
|
+
})
|
|
328
|
+
|
|
329
|
+
server.start({ transportType: 'stdio' })
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
### Registrar o client MCP no Supabase
|
|
333
|
+
|
|
334
|
+
```ts
|
|
335
|
+
// scripts/register-mcp-client.ts
|
|
336
|
+
const { data } = await supabaseAdmin.auth.admin.oauth.createClient({
|
|
337
|
+
name: 'MCP Server - Produção',
|
|
338
|
+
redirect_uris: ['http://localhost:3333/callback'], // FastMCP local server
|
|
339
|
+
client_type: 'public', // sem secret — PKCE protege
|
|
340
|
+
token_endpoint_auth_method: 'none',
|
|
341
|
+
})
|
|
342
|
+
|
|
343
|
+
console.log('MCP_OAUTH_CLIENT_ID=' + data?.client_id)
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
### Dynamic Client Registration (DCR)
|
|
347
|
+
|
|
348
|
+
Com `allow_dynamic_registration = true`, clientes MCP se registram automaticamente:
|
|
349
|
+
|
|
350
|
+
```bash
|
|
351
|
+
# Clientes chamam este endpoint automaticamente (RFC 7591)
|
|
352
|
+
POST https://<project>.supabase.co/auth/v1/oauth/clients
|
|
353
|
+
Content-Type: application/json
|
|
354
|
+
|
|
355
|
+
{
|
|
356
|
+
"client_name": "Claude Desktop",
|
|
357
|
+
"redirect_uris": ["http://localhost:63856/callback"],
|
|
358
|
+
"token_endpoint_auth_method": "none"
|
|
359
|
+
}
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
## Access Token Claims
|
|
363
|
+
|
|
364
|
+
O access token JWT gerado pelo OAuth Server contém o claim especial `client_id`:
|
|
365
|
+
|
|
366
|
+
```json
|
|
367
|
+
{
|
|
368
|
+
"sub": "user-uuid",
|
|
369
|
+
"role": "authenticated",
|
|
370
|
+
"client_id": "meu-client-id", // identifica QUAL client OAuth emitiu o token
|
|
371
|
+
"email": "user@exemplo.com",
|
|
372
|
+
"iat": 1700000000,
|
|
373
|
+
"exp": 1700003600
|
|
374
|
+
}
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
Use `client_id` em políticas RLS para controlar acesso por client OAuth.
|
|
378
|
+
|
|
379
|
+
## OIDC — ID Tokens
|
|
380
|
+
|
|
381
|
+
Ao incluir o scope `openid`, o token endpoint retorna um `id_token` além do `access_token`.
|
|
382
|
+
|
|
383
|
+
**Requisito crítico:** ID tokens **exigem** algoritmo assimétrico (RS256 ou ES256). Configure signing keys assimétricas — veja skill [supabase-jwt-signing-keys](../supabase-jwt-signing-keys/SKILL.md).
|
|
384
|
+
|
|
385
|
+
```ts
|
|
386
|
+
// Decodificar ID token (client-side)
|
|
387
|
+
import { jwtDecode } from 'jwt-decode'
|
|
388
|
+
|
|
389
|
+
const idTokenClaims = jwtDecode(tokens.id_token)
|
|
390
|
+
// { sub, email, name, picture, phone, iat, exp, aud, iss }
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
## Token Security + RLS por client_id
|
|
394
|
+
|
|
395
|
+
Scopes controlam **quais dados OIDC** são retornados (email, profile, phone). Scopes **NÃO** controlam acesso ao banco de dados — isso é responsabilidade do RLS.
|
|
396
|
+
|
|
397
|
+
Use o claim `client_id` em políticas para separar acesso por client OAuth:
|
|
398
|
+
|
|
399
|
+
```sql
|
|
400
|
+
-- Conceder acesso apenas a um client OAuth específico
|
|
401
|
+
create policy "Apenas client parceiro pode ler dados_parceiro" on public.dados_parceiro
|
|
402
|
+
for select to authenticated
|
|
403
|
+
using (
|
|
404
|
+
(auth.jwt() ->> 'client_id') = 'client-id-do-parceiro'
|
|
405
|
+
);
|
|
406
|
+
|
|
407
|
+
-- Restringir dados sensíveis de qualquer client OAuth
|
|
408
|
+
create policy "Dados financeiros apenas via sessão direta" on public.dados_financeiros
|
|
409
|
+
for select to authenticated
|
|
410
|
+
using (
|
|
411
|
+
-- NULL client_id = sessão direta (não OAuth); presença = token OAuth
|
|
412
|
+
(auth.jwt() ->> 'client_id') IS NULL
|
|
413
|
+
);
|
|
414
|
+
|
|
415
|
+
-- Separar políticas: sessão direta vs qualquer client OAuth
|
|
416
|
+
create policy "Acesso direto ou client autorizado" on public.perfil_publico
|
|
417
|
+
for select to authenticated
|
|
418
|
+
using (
|
|
419
|
+
(auth.jwt() ->> 'client_id') IS NULL -- sessão direta
|
|
420
|
+
OR (auth.jwt() ->> 'client_id') = 'client-aprovado' -- client OAuth específico
|
|
421
|
+
);
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
## Custom Access Token Hook por client_id
|
|
425
|
+
|
|
426
|
+
Use o Auth Hook para personalizar `audience` ou claims com base no `client_id`:
|
|
427
|
+
|
|
428
|
+
```sql
|
|
429
|
+
create or replace function public.custom_access_token_hook(event jsonb)
|
|
430
|
+
returns jsonb
|
|
431
|
+
language plpgsql
|
|
432
|
+
stable
|
|
433
|
+
as $$
|
|
434
|
+
declare
|
|
435
|
+
claims jsonb;
|
|
436
|
+
client_id text;
|
|
437
|
+
begin
|
|
438
|
+
claims := event->'claims';
|
|
439
|
+
client_id := claims ->> 'client_id';
|
|
440
|
+
|
|
441
|
+
-- Adicionar audience específica por client
|
|
442
|
+
if client_id = 'parceiro-externo-id' then
|
|
443
|
+
claims := jsonb_set(claims, '{aud}', '"parceiro-externo"');
|
|
444
|
+
claims := jsonb_set(claims, '{custom_plan}', '"enterprise"');
|
|
445
|
+
end if;
|
|
446
|
+
|
|
447
|
+
event := jsonb_set(event, '{claims}', claims);
|
|
448
|
+
return event;
|
|
449
|
+
end;
|
|
450
|
+
$$;
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
## Gerenciar Grants do Usuário
|
|
454
|
+
|
|
455
|
+
```ts
|
|
456
|
+
// Listar todos os clients OAuth com acesso concedido pelo usuário
|
|
457
|
+
const { data: grants } = await supabase.auth.oauth.getUserGrants()
|
|
458
|
+
// [{ client_id, client_name, scopes, granted_at }]
|
|
459
|
+
|
|
460
|
+
// Revogar acesso de um client específico
|
|
461
|
+
const { error } = await supabase.auth.oauth.revokeGrant('client-id-para-revogar')
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
## Regras absolutas
|
|
465
|
+
|
|
466
|
+
1. **PKCE obrigatório** — OAuth 2.1 remove fluxo implícito; todo client usa `code_challenge_method: 'S256'`
|
|
467
|
+
2. **Signing keys assimétricas (RS256/ES256)** — ID tokens **falham** com HS256; configure antes de habilitar OIDC
|
|
468
|
+
3. **Redirect URIs com match exato** — sem wildcards em produção; cada URI deve ser cadastrada explicitamente
|
|
469
|
+
4. **Nunca expor `service_role` key no cliente** — registro de clients via Admin API é sempre server-side
|
|
470
|
+
5. **Inicializar client Supabase DENTRO do request handler** — nunca em escopo de módulo (vazamento entre requests em Vercel Fluid compute / Edge Functions com conexões reutilizadas)
|
|
471
|
+
6. **RLS com `client_id` controla acesso ao banco** — scopes controlam apenas dados OIDC (email, profile); RLS é a única barreira real para dados do banco
|
|
472
|
+
7. **Separar clients por ambiente** — client de dev ≠ client de produção; redirect URIs não podem cruzar ambientes
|
|
473
|
+
|
|
474
|
+
## Anti-patterns
|
|
475
|
+
|
|
476
|
+
### Anti-pattern 1: Usar HS256 para ID tokens
|
|
477
|
+
|
|
478
|
+
**Errado:**
|
|
479
|
+
```toml
|
|
480
|
+
[auth]
|
|
481
|
+
jwt_secret = "meu-secret-compartilhado" # HS256 — ID tokens FALHAM
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
**Por quê:** a especificação OIDC exige algoritmo assimétrico para ID tokens — HS256 é shared secret e não permite validação por terceiros sem expor o secret. Supabase rejeita ID token com HS256.
|
|
485
|
+
|
|
486
|
+
**Certo:** configurar signing key assimétrica (ES256 recomendado) antes de habilitar o OAuth Server com scope `openid`.
|
|
487
|
+
|
|
488
|
+
### Anti-pattern 2: Redirect URI com wildcard em produção
|
|
489
|
+
|
|
490
|
+
**Errado:**
|
|
491
|
+
```ts
|
|
492
|
+
await supabaseAdmin.auth.admin.oauth.createClient({
|
|
493
|
+
redirect_uris: ['https://*.meuapp.com/callback'], // wildcard — BLOQUEADO
|
|
494
|
+
})
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
**Por quê:** wildcards em redirect URIs são vetores de open redirect — atacante pode redirecionar o code para domínio controlado.
|
|
498
|
+
|
|
499
|
+
**Certo:** listar cada URI explicitamente; para previews Vercel, use allowlist na configuração de auth, não wildcards no client OAuth.
|
|
500
|
+
|
|
501
|
+
### Anti-pattern 3: Client Supabase em escopo de módulo
|
|
502
|
+
|
|
503
|
+
**Errado:**
|
|
504
|
+
```ts
|
|
505
|
+
// lib/supabase.ts — ERRADO para Edge Functions / Vercel
|
|
506
|
+
const supabase = createClient(URL, KEY) // escopo de módulo — vaza entre requests
|
|
507
|
+
|
|
508
|
+
export default supabase
|
|
509
|
+
```
|
|
510
|
+
|
|
511
|
+
**Por quê:** em ambientes serverless com conexões reutilizadas (Vercel Fluid compute, Edge Functions), o client é compartilhado entre requests de usuários diferentes — vazamento de sessão.
|
|
512
|
+
|
|
513
|
+
**Certo:** sempre `const supabase = await createClient()` dentro do request handler ou Server Component.
|
|
514
|
+
|
|
515
|
+
### Anti-pattern 4: Achar que scopes restringem o banco
|
|
516
|
+
|
|
517
|
+
**Errado:**
|
|
518
|
+
```ts
|
|
519
|
+
// developer pensa que scope: 'email' significa "client só acessa emails"
|
|
520
|
+
await supabaseAdmin.auth.admin.oauth.createClient({
|
|
521
|
+
// ...
|
|
522
|
+
})
|
|
523
|
+
// E não cria nenhuma RLS policy — ERRO: client acessa TODO o banco
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
**Por quê:** scopes em OAuth controlam apenas quais claims OIDC (email, phone, profile) o `id_token`/`userinfo` retorna. O `access_token` tem role `authenticated` e acessa o banco segundo as RLS policies — não tem restrição automática por scope.
|
|
527
|
+
|
|
528
|
+
**Certo:** sempre escrever RLS policies usando `(auth.jwt() ->> 'client_id')` para controlar quais clients acessam quais tabelas.
|
|
529
|
+
|
|
530
|
+
## Ver também
|
|
531
|
+
|
|
532
|
+
- [supabase-jwt-signing-keys](../supabase-jwt-signing-keys/SKILL.md) — configurar ES256/RS256 antes de habilitar OIDC
|
|
533
|
+
- [supabase-auth-hooks](../supabase-auth-hooks/SKILL.md) — Custom Access Token Hook para claims por client_id
|
|
534
|
+
- [supabase-rls-policies](../supabase-rls-policies/SKILL.md) — patterns RLS com claim client_id
|
|
535
|
+
- [supabase-edge-functions-mcp-server](../supabase-edge-functions-mcp-server/SKILL.md) — MCP server em Edge Functions
|
|
536
|
+
- [supabase-oauth-server-implementer](../../agents/supabase-oauth-server-implementer.md) — agente que materializa setup completo
|
|
537
|
+
- [supabase-auth-ssr](../supabase-auth-ssr/SKILL.md) — @supabase/ssr e getClaims() no servidor
|