@adaptive-js/extension-auth 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/README.md +412 -3
- package/dist/api-adapter.d.ts +2 -0
- package/dist/api-adapter.js +8 -0
- package/dist/api-adapter.js.map +1 -0
- package/dist/client.d.ts +41 -0
- package/dist/client.js +128 -0
- package/dist/client.js.map +1 -0
- package/dist/cookies.d.ts +10 -0
- package/dist/cookies.js +107 -0
- package/dist/cookies.js.map +1 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +11 -0
- package/dist/errors.js.map +1 -0
- package/dist/external-adapter.d.ts +93 -0
- package/dist/external-adapter.js +235 -0
- package/dist/external-adapter.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/intended-url.d.ts +18 -0
- package/dist/intended-url.js +55 -0
- package/dist/intended-url.js.map +1 -0
- package/dist/memory-adapter.d.ts +16 -0
- package/dist/memory-adapter.js +112 -0
- package/dist/memory-adapter.js.map +1 -0
- package/dist/rate-limit.d.ts +28 -0
- package/dist/rate-limit.js +104 -0
- package/dist/rate-limit.js.map +1 -0
- package/dist/server.d.ts +54 -0
- package/dist/server.js +745 -0
- package/dist/server.js.map +1 -0
- package/dist/types.d.ts +225 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/docs/01-getting-started.md +347 -0
- package/docs/02-server-actions.md +176 -0
- package/docs/03-protecting-pages.md +144 -0
- package/docs/04-session-lifecycle.md +169 -0
- package/docs/05-adapters.md +242 -0
- package/docs/06-client.md +126 -0
- package/docs/07-security-checklist.md +93 -0
- package/docs/08-integration.md +134 -0
- package/docs/09-troubleshooting.md +96 -0
- package/docs/README.md +17 -0
- package/package.json +72 -4
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
# 05 — Adapters
|
|
2
|
+
|
|
3
|
+
No `@adaptive-js/extension-auth`, **tudo é baseado em Adapters**. Você passa um único adapter para `createAuth({ adapter })`.
|
|
4
|
+
|
|
5
|
+
Existem 3 formas de usar adapters:
|
|
6
|
+
1. **Adapter Interno** — Armazena usuários e sessões localmente no seu banco de dados ou memória (Memory, Postgres, Redis).
|
|
7
|
+
2. **Adapter Externo** — Conecta diretamente a APIs e microserviços externos (Rust Axum, Go, FastAPI), cuidando de login, tokens e sessões locais para o SSR.
|
|
8
|
+
3. **Custom Adapter** — Você implementa a interface `AuthAdapter` com a lógica específica da sua infraestrutura.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Contrato `AuthAdapter`
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
export interface AuthAdapter<
|
|
16
|
+
TUser extends AuthUser = AuthUser,
|
|
17
|
+
TData extends AuthSessionData = AuthSessionData
|
|
18
|
+
> {
|
|
19
|
+
// Obrigatórios (Lifecycle de Sessão e Usuário)
|
|
20
|
+
getUser(userId: string): MaybePromise<TUser | null>;
|
|
21
|
+
getSession(sessionId: string): MaybePromise<StoredAuthSession<TData> | null>;
|
|
22
|
+
createSession(session: StoredAuthSession<TData>): MaybePromise<void>;
|
|
23
|
+
updateSession(session: StoredAuthSession<TData>): MaybePromise<void>;
|
|
24
|
+
deleteSession(sessionId: string): MaybePromise<void>;
|
|
25
|
+
|
|
26
|
+
// Opcionais (Device management / Logout global)
|
|
27
|
+
deleteUserSessions?(userId: string): MaybePromise<void>;
|
|
28
|
+
deleteUserSessionsExcept?(userId: string, exceptSessionId: string): MaybePromise<void>;
|
|
29
|
+
listUserSessions?(userId: string): MaybePromise<ManagedUserSession[]>;
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`StoredAuthSession` inclui `csrfToken` e (opcionalmente) `binding`.
|
|
34
|
+
**Nunca** devolva `csrfToken` em APIs públicas ou no client.
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## 2. Adapter Externo (`createExternalAuthAdapter`)
|
|
39
|
+
|
|
40
|
+
Quando a autenticação do seu sistema vive em uma **API externa** (como um microserviço em Rust Axum, Go ou Python), você usa `createExternalAuthAdapter`.
|
|
41
|
+
|
|
42
|
+
Ele implementa o contrato `AuthAdapter`, gerencia as sessões locais no servidor AdaptiveJS para SSR rápido e seguro, e expõe métodos para autenticar contra a API externa:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { createAuth } from "@adaptive-js/extension-auth/server";
|
|
46
|
+
import { createExternalAuthAdapter } from "@adaptive-js/extension-auth/external-adapter";
|
|
47
|
+
|
|
48
|
+
export const adapter = createExternalAuthAdapter({
|
|
49
|
+
baseUrl: process.env.AUTH_SERVICE_URL ?? "http://localhost:3001",
|
|
50
|
+
loginPath: "/api/v1/auth/login",
|
|
51
|
+
registerPath: "/api/v1/auth/register",
|
|
52
|
+
mapUser: (res: any) => ({
|
|
53
|
+
id: res.user.id,
|
|
54
|
+
email: res.user.email,
|
|
55
|
+
name: res.user.name,
|
|
56
|
+
roles: res.user.roles ?? [],
|
|
57
|
+
}),
|
|
58
|
+
mapToken: (res: any) => res.token,
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
export const auth = createAuth({
|
|
62
|
+
adapter, // <-- Único ponto de configuração! Sem providers.
|
|
63
|
+
csrf: { allowedOrigins: ["http://localhost:3000"] },
|
|
64
|
+
});
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Operações com o Adapter Externo:
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
// 1. Login na API externa:
|
|
71
|
+
const { user, token } = await adapter.login({ email, password });
|
|
72
|
+
const { session, cookie } = await auth.createSession(user, {
|
|
73
|
+
data: { authToken: token },
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
// 2. Ou login direto via helper:
|
|
77
|
+
const { session, cookie } = await auth.login({ email, password }, request);
|
|
78
|
+
|
|
79
|
+
// 3. Registro de novo usuário:
|
|
80
|
+
const { user, token } = await adapter.register({ email, password, name });
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## 3. Adapters Internos (Memory / Banco de Dados)
|
|
86
|
+
|
|
87
|
+
### Memory (Apenas Dev e Testes)
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import { createMemoryAuthAdapter } from "@adaptive-js/extension-auth/memory-adapter";
|
|
91
|
+
|
|
92
|
+
const adapter = createMemoryAuthAdapter({
|
|
93
|
+
users: [{ id: "u1", email: "admin@example.com", roles: ["admin"] }],
|
|
94
|
+
cleanupIntervalMs: 60_000,
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
> **Aviso:** Dados em memória são descartados ao reiniciar o processo. Use apenas em desenvolvimento ou testes.
|
|
99
|
+
|
|
100
|
+
### Exemplo Postgres
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import type { AuthAdapter, StoredAuthSession, AuthUser } from "@adaptive-js/extension-auth";
|
|
104
|
+
import { pool } from "./db";
|
|
105
|
+
|
|
106
|
+
export function createPostgresAuthAdapter(): AuthAdapter<AuthUser> {
|
|
107
|
+
return {
|
|
108
|
+
async getUser(userId) {
|
|
109
|
+
const { rows } = await pool.query(
|
|
110
|
+
`select id, email, name, roles from users where id = $1`,
|
|
111
|
+
[userId]
|
|
112
|
+
);
|
|
113
|
+
return rows[0] ?? null;
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
async getSession(sessionId) {
|
|
117
|
+
const { rows } = await pool.query(
|
|
118
|
+
`select id, user_id, data, created_at, expires_at, absolute_expires_at, csrf_token, binding
|
|
119
|
+
from sessions where id = $1`,
|
|
120
|
+
[sessionId]
|
|
121
|
+
);
|
|
122
|
+
const row = rows[0];
|
|
123
|
+
if (!row) return null;
|
|
124
|
+
return {
|
|
125
|
+
id: row.id,
|
|
126
|
+
userId: row.user_id,
|
|
127
|
+
data: row.data ?? {},
|
|
128
|
+
createdAt: row.created_at,
|
|
129
|
+
expiresAt: row.expires_at,
|
|
130
|
+
absoluteExpiresAt: row.absolute_expires_at,
|
|
131
|
+
csrfToken: row.csrf_token,
|
|
132
|
+
binding: row.binding ?? undefined,
|
|
133
|
+
};
|
|
134
|
+
},
|
|
135
|
+
|
|
136
|
+
async createSession(session) {
|
|
137
|
+
await pool.query(
|
|
138
|
+
`insert into sessions
|
|
139
|
+
(id, user_id, data, created_at, expires_at, absolute_expires_at, csrf_token, binding)
|
|
140
|
+
values ($1,$2,$3,$4,$5,$6,$7,$8)`,
|
|
141
|
+
[
|
|
142
|
+
session.id,
|
|
143
|
+
session.userId,
|
|
144
|
+
JSON.stringify(session.data),
|
|
145
|
+
session.createdAt,
|
|
146
|
+
session.expiresAt,
|
|
147
|
+
session.absoluteExpiresAt,
|
|
148
|
+
session.csrfToken,
|
|
149
|
+
session.binding ? JSON.stringify(session.binding) : null,
|
|
150
|
+
]
|
|
151
|
+
);
|
|
152
|
+
},
|
|
153
|
+
|
|
154
|
+
async updateSession(session) {
|
|
155
|
+
await pool.query(
|
|
156
|
+
`update sessions set
|
|
157
|
+
data = $2,
|
|
158
|
+
expires_at = $3,
|
|
159
|
+
absolute_expires_at = $4,
|
|
160
|
+
csrf_token = $5,
|
|
161
|
+
binding = $6
|
|
162
|
+
where id = $1`,
|
|
163
|
+
[
|
|
164
|
+
session.id,
|
|
165
|
+
JSON.stringify(session.data),
|
|
166
|
+
session.expiresAt,
|
|
167
|
+
session.absoluteExpiresAt,
|
|
168
|
+
session.csrfToken,
|
|
169
|
+
session.binding ? JSON.stringify(session.binding) : null,
|
|
170
|
+
]
|
|
171
|
+
);
|
|
172
|
+
},
|
|
173
|
+
|
|
174
|
+
async deleteSession(sessionId) {
|
|
175
|
+
await pool.query(`delete from sessions where id = $1`, [sessionId]);
|
|
176
|
+
},
|
|
177
|
+
|
|
178
|
+
async deleteUserSessions(userId) {
|
|
179
|
+
await pool.query(`delete from sessions where user_id = $1`, [userId]);
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
async deleteUserSessionsExcept(userId, exceptSessionId) {
|
|
183
|
+
await pool.query(
|
|
184
|
+
`delete from sessions where user_id = $1 and id <> $2`,
|
|
185
|
+
[userId, exceptSessionId]
|
|
186
|
+
);
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
async listUserSessions(userId) {
|
|
190
|
+
const { rows } = await pool.query(
|
|
191
|
+
`select id, user_id, created_at, expires_at, absolute_expires_at
|
|
192
|
+
from sessions where user_id = $1 order by created_at desc`,
|
|
193
|
+
[userId]
|
|
194
|
+
);
|
|
195
|
+
return rows.map((r) => ({
|
|
196
|
+
id: r.id,
|
|
197
|
+
userId: r.user_id,
|
|
198
|
+
createdAt: r.created_at,
|
|
199
|
+
expiresAt: r.expires_at,
|
|
200
|
+
absoluteExpiresAt: r.absolute_expires_at,
|
|
201
|
+
}));
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
---
|
|
208
|
+
|
|
209
|
+
## 4. Custom Adapter (Faça você mesmo)
|
|
210
|
+
|
|
211
|
+
Qualquer objeto que satisfaça `AuthAdapter` é um adapter válido. Você pode integrar com Redis, MongoDB, DynamoDB, Supabase, Firebase ou sua própria API corporativa:
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
import type { AuthAdapter } from "@adaptive-js/extension-auth";
|
|
215
|
+
|
|
216
|
+
export const myCustomAdapter: AuthAdapter = {
|
|
217
|
+
async getUser(id) { /* busca usuário */ },
|
|
218
|
+
async getSession(id) { /* busca sessão */ },
|
|
219
|
+
async createSession(session) { /* salva sessão */ },
|
|
220
|
+
async updateSession(session) { /* atualiza sessão */ },
|
|
221
|
+
async deleteSession(id) { /* deleta sessão */ },
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
export const auth = createAuth({
|
|
225
|
+
adapter: myCustomAdapter,
|
|
226
|
+
csrf: { allowedOrigins: ["https://app.example.com"] },
|
|
227
|
+
});
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
---
|
|
231
|
+
|
|
232
|
+
## 5. Adapter no Contexto de Server Actions
|
|
233
|
+
|
|
234
|
+
Dentro de qualquer Server Action protegida com `auth.action`, o adapter configurado fica disponível no contexto:
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
export const updateProfile = auth.action(async ({ session, adapter, formData }) => {
|
|
238
|
+
// Acesse diretamente seu adapter (interno, externo ou custom):
|
|
239
|
+
// adapter.getUser(...), adapter.request(...), etc.
|
|
240
|
+
return { ok: true };
|
|
241
|
+
});
|
|
242
|
+
```
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# 06 — Client (UI hidratada)
|
|
2
|
+
|
|
3
|
+
O client **não** é autoridade. Ele só reflete estado para a UI.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Setup
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
// src/auth-client.ts
|
|
11
|
+
"hydrate";
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
createAuthClient,
|
|
15
|
+
toAuthClientState,
|
|
16
|
+
isAuthStateExpired,
|
|
17
|
+
getAuthStateExpiresInMs,
|
|
18
|
+
} from "@adaptive-js/extension-auth/client";
|
|
19
|
+
|
|
20
|
+
export const { AuthProvider, useAuth } = createAuthClient();
|
|
21
|
+
export { toAuthClientState, isAuthStateExpired, getAuthStateExpiresInMs };
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## Provider com estado inicial do server
|
|
27
|
+
|
|
28
|
+
```tsx
|
|
29
|
+
// layout / root (server)
|
|
30
|
+
import { AuthProvider, toAuthClientState } from "./auth-client";
|
|
31
|
+
import { auth } from "./auth";
|
|
32
|
+
|
|
33
|
+
export default async function Root({ request, children }) {
|
|
34
|
+
const { session, freshCookie } = await auth.readSession(request);
|
|
35
|
+
// propague freshCookie na resposta HTTP se existir
|
|
36
|
+
|
|
37
|
+
return (
|
|
38
|
+
<AuthProvider initialState={toAuthClientState(session)}>
|
|
39
|
+
{children}
|
|
40
|
+
</AuthProvider>
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`toAuthClientState` por padrão só expõe `id`, `email`, `name`, `roles`.
|
|
46
|
+
Para mais campos seguros:
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
toAuthClientState(session, (user) => ({
|
|
50
|
+
id: user.id,
|
|
51
|
+
email: user.email,
|
|
52
|
+
name: user.name,
|
|
53
|
+
roles: user.roles,
|
|
54
|
+
avatarUrl: user.avatarUrl, // campo que você considera seguro
|
|
55
|
+
}));
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
**Nunca** selecione `passwordHash`, tokens, etc.
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## useAuth
|
|
63
|
+
|
|
64
|
+
```tsx
|
|
65
|
+
"hydrate";
|
|
66
|
+
import { useAuth, isAuthStateExpired } from "../auth-client";
|
|
67
|
+
|
|
68
|
+
export function UserMenu() {
|
|
69
|
+
const auth = useAuth();
|
|
70
|
+
|
|
71
|
+
if (!auth.authenticated()) {
|
|
72
|
+
return <a href="/login">Entrar</a>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const state = auth.state();
|
|
76
|
+
if (isAuthStateExpired(state)) {
|
|
77
|
+
auth.clear();
|
|
78
|
+
// redirecione ou mostre “sessão expirada”
|
|
79
|
+
return <a href="/login">Sessão expirada — entrar de novo</a>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return (
|
|
83
|
+
<div>
|
|
84
|
+
<span>{auth.user()?.name}</span>
|
|
85
|
+
<form action="/logout" method="post">
|
|
86
|
+
<button>Sair</button>
|
|
87
|
+
</form>
|
|
88
|
+
</div>
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### API do hook
|
|
94
|
+
|
|
95
|
+
| Método | Descrição |
|
|
96
|
+
|--------|-----------|
|
|
97
|
+
| `state()` | Snapshot `{ authenticated, user, expiresAt }` |
|
|
98
|
+
| `user()` | `user` ou `null` |
|
|
99
|
+
| `authenticated()` | boolean |
|
|
100
|
+
| `setState(state)` | atualiza (ex.: após login client-side) |
|
|
101
|
+
| `clear()` | volta ao estado vazio |
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## Expiração
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
const ms = getAuthStateExpiresInMs(auth.state());
|
|
109
|
+
// null se não autenticado / sem expiresAt
|
|
110
|
+
|
|
111
|
+
if (isAuthStateExpired(auth.state())) {
|
|
112
|
+
auth.clear();
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Hoje a reatividade (auto-clear / redirect) fica a cargo do app.
|
|
117
|
+
Você pode combinar com um `setTimeout` baseado em `getAuthStateExpiresInMs` se quiser UX mais automática.
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## Regras de ouro
|
|
122
|
+
|
|
123
|
+
1. **Nenhuma decisão de autorização só no client.**
|
|
124
|
+
2. Após login via action, atualize o provider (`setState`) **ou** faça navigation completa para re-ler a sessão no server.
|
|
125
|
+
3. Logout deve invalidar no server e limpar o estado client (`clear` + cookie blank).
|
|
126
|
+
4. Não espelhe `csrfToken` no client state global — leia do server na hora de montar o form.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# 07 — Checklist de segurança (produção)
|
|
2
|
+
|
|
3
|
+
Use este checklist antes de cada release. Itens marcados com **P0** são bloqueantes.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Boot e configuração
|
|
8
|
+
|
|
9
|
+
- [ ] **P0** — `csrf.allowedOrigins` com origins HTTPS reais (sem wildcard)
|
|
10
|
+
- [ ] **P0** — Adapter de produção (não memory)
|
|
11
|
+
- [ ] **P0** — Cookie com `Secure` + `HttpOnly` (default `__Host-adaptive-session`)
|
|
12
|
+
- [ ] **P0** — `onAuditEvent` configurado (warning em prod se faltar)
|
|
13
|
+
- [ ] Cookie name sem `Domain` quando usar prefixo `__Host-`
|
|
14
|
+
- [ ] `sessionDuration` / `absoluteSessionDuration` conscientes do risco do produto
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## Sessão e cookie
|
|
19
|
+
|
|
20
|
+
- [ ] **P0** — Toda resposta que pode renovar sessão propaga `freshCookie`
|
|
21
|
+
- [ ] Preferir `auth.withSession` / `auth.action` / `protectPage` para não esquecer cookie
|
|
22
|
+
- [ ] Logout devolve cookie em branco
|
|
23
|
+
- [ ] “Sair de todos os dispositivos” chama `logoutEverywhere` / `passwordChanged` conforme o caso
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## CSRF e mutações
|
|
28
|
+
|
|
29
|
+
- [ ] **P0** — Toda mutação autenticada passa por `auth.action` **ou** `requireSession` + `requireCsrf`
|
|
30
|
+
- [ ] Forms enviam token CSRF (hidden ou header)
|
|
31
|
+
- [ ] Requests de action têm header `Origin` válido
|
|
32
|
+
- [ ] Nenhuma mutação via GET
|
|
33
|
+
- [ ] Não usar `protectAction` sozinho para escrita (ele não exige CSRF)
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## Autorização
|
|
38
|
+
|
|
39
|
+
- [ ] **P0** — Roles checadas no server (`auth.action` / `protectPage` / `requireRole`)
|
|
40
|
+
- [ ] UI esconde botões por UX, mas nunca é a única barreira
|
|
41
|
+
- [ ] Após elevação de role → `roleElevated(userId)`
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Eventos de risco
|
|
46
|
+
|
|
47
|
+
- [ ] **P0** — Reset/troca de senha → `passwordChanged`
|
|
48
|
+
- [ ] Ativação de MFA → `mfaEnabled`
|
|
49
|
+
- [ ] Compromisso / atividade suspeita → `forceReauth`
|
|
50
|
+
- [ ] Session binding só se o produto realmente precisar (cuidado com IP)
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## Rate limiting
|
|
55
|
+
|
|
56
|
+
- [ ] Rate limit em `createSession` (auth) **ou** no endpoint de login
|
|
57
|
+
- [ ] Rate limit de superfície (IP / `/_action`) via `@adaptive-js/extension-security`
|
|
58
|
+
- [ ] Em multi-instância: storage Redis (não memory) nos dois módulos
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## Client
|
|
63
|
+
|
|
64
|
+
- [ ] `toAuthClientState` não vaza campos sensíveis
|
|
65
|
+
- [ ] Expiração tratada na UI (clear / redirect)
|
|
66
|
+
- [ ] CSRF token não fica em estado global desnecessário
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## Integração
|
|
71
|
+
|
|
72
|
+
- [ ] **P0** — Mesma lista `ALLOWED_ORIGINS` em auth e security
|
|
73
|
+
- [ ] Security plugin registrado no Nitro (`setSecurityPlugin` / `asNitroPlugin`)
|
|
74
|
+
- [ ] CSP com nonce alinhado ao script de hidratação
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
|
|
78
|
+
## Testes
|
|
79
|
+
|
|
80
|
+
- [ ] CSRF rejeita origin inválido / token inválido
|
|
81
|
+
- [ ] Sessão expirada não autoriza
|
|
82
|
+
- [ ] Role insuficiente → 403/404 conforme config
|
|
83
|
+
- [ ] `sanitizeReturnTo` rejeita URL externa
|
|
84
|
+
- [ ] Cookie flags em produção (Secure/HttpOnly)
|
|
85
|
+
- [ ] Race de renovação (grace) não desloga request paralela
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## Operação
|
|
90
|
+
|
|
91
|
+
- [ ] Logs/audit de `session.rejected`, `csrf.rejected`, `session.invalidated`
|
|
92
|
+
- [ ] Job de limpeza de sessões expiradas no storage
|
|
93
|
+
- [ ] Rotação de segredos / procedimento de incidente documentado (invalidar todas as sessões)
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
# 08 — Integração: auth + security + Nitro
|
|
2
|
+
|
|
3
|
+
Este é o desenho recomendado para um app AdaptiveJS em produção.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Responsabilidades
|
|
8
|
+
|
|
9
|
+
| Módulo | Cuida de |
|
|
10
|
+
|--------|----------|
|
|
11
|
+
| `@adaptive-js/extension-auth` | Sessão, cookie, CSRF, roles, invalidação, `auth.action` |
|
|
12
|
+
| `@adaptive-js/extension-security` | Headers (CSP, HSTS, …), rate limit por IP/rota, nonce de hidratação |
|
|
13
|
+
| Adapter Nitro / core | Wiring de request/response, plugin de security, Server Actions |
|
|
14
|
+
|
|
15
|
+
Eles **não** se substituem. Auth não seta CSP; security não valida CSRF de sessão.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Arquivos canônicos
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
// src/config/origins.ts
|
|
23
|
+
export const ALLOWED_ORIGINS = ["https://app.example.com"] as const;
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
// src/auth.ts
|
|
28
|
+
import { createAuth } from "@adaptive-js/extension-auth/server";
|
|
29
|
+
import { createPostgresAuthAdapter } from "./auth-adapter";
|
|
30
|
+
import { ALLOWED_ORIGINS } from "./config/origins";
|
|
31
|
+
|
|
32
|
+
export const auth = createAuth({
|
|
33
|
+
adapter: createPostgresAuthAdapter(),
|
|
34
|
+
csrf: { allowedOrigins: [...ALLOWED_ORIGINS] },
|
|
35
|
+
rateLimit: {
|
|
36
|
+
createSession: { max: 10, windowMs: 15 * 60 * 1000 },
|
|
37
|
+
},
|
|
38
|
+
onAuditEvent(event) {
|
|
39
|
+
// envie para seu logger / SIEM
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
// src/security.ts
|
|
46
|
+
import { createSecurity } from "@adaptive-js/extension-security";
|
|
47
|
+
import { ALLOWED_ORIGINS } from "./config/origins";
|
|
48
|
+
|
|
49
|
+
export const security = createSecurity({
|
|
50
|
+
allowedOrigins: [...ALLOWED_ORIGINS],
|
|
51
|
+
// rateLimit: { storage: redisStorage } em multi-instância
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
// server/entry.ts (ou bootstrap Nitro)
|
|
57
|
+
import { setSecurityPlugin } from "@adaptive-js/adapter-nitro";
|
|
58
|
+
import { security } from "../src/security";
|
|
59
|
+
|
|
60
|
+
setSecurityPlugin(security.asNitroPlugin());
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
A partir daí, em cada SSR:
|
|
64
|
+
|
|
65
|
+
1. Nonce aleatório por request
|
|
66
|
+
2. Nonce no `<script>` de hidratação
|
|
67
|
+
3. Mesmo nonce em `Content-Security-Policy: script-src 'nonce-…'`
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## Ordem sugerida no handler (uso manual)
|
|
72
|
+
|
|
73
|
+
Se não usar o plugin automático:
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
export default eventHandler(async (event) => {
|
|
77
|
+
security.applyHeaders(event); // 1. headers
|
|
78
|
+
await security.rateLimit(event); // 2. rate limit global
|
|
79
|
+
|
|
80
|
+
if (event.method === "POST" && event.path === "/_action") {
|
|
81
|
+
await security.protectAction(event, {
|
|
82
|
+
actionName: /* do body */,
|
|
83
|
+
});
|
|
84
|
+
// dentro da action: auth.action já faz sessão + CSRF
|
|
85
|
+
return handleAction(event);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return handleSsr(event);
|
|
89
|
+
});
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Login end-to-end (visão única)
|
|
95
|
+
|
|
96
|
+
1. User POST `/login` com email/senha
|
|
97
|
+
2. Seu código valida credencial
|
|
98
|
+
3. `auth.login(user, request)` → cookie de sessão
|
|
99
|
+
4. Security já limitou tentativas por IP (e auth pode limitar por user/IP no `createSession`)
|
|
100
|
+
5. Redirect para `sanitizeReturnTo(returnTo) ?? "/dashboard"`
|
|
101
|
+
6. Dashboard usa `auth.protectPage`
|
|
102
|
+
7. Form de perfil usa `auth.action` + hidden CSRF
|
|
103
|
+
8. Security aplica CSP/headers em todas as respostas
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
## Dev vs produção
|
|
108
|
+
|
|
109
|
+
| Tema | Dev | Produção |
|
|
110
|
+
|------|-----|----------|
|
|
111
|
+
| Origin | `http://localhost:3000` | HTTPS reais |
|
|
112
|
+
| Cookie | nome sem `__Host-`, `secure: false` | default `__Host-` |
|
|
113
|
+
| Adapter | memory | Postgres/Redis |
|
|
114
|
+
| Rate limit storage | memory | Redis |
|
|
115
|
+
| HSTS (security) | off | on (só HTTPS) |
|
|
116
|
+
| Audit | console | logger real |
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
## Erros frequentes de integração
|
|
121
|
+
|
|
122
|
+
1. **Origins diferentes** entre auth e security → CSRF passa, ou rate limit/CORS mental fica inconsistente.
|
|
123
|
+
2. **Esquecer `setSecurityPlugin`** → CSP sem nonce, scripts de hidratação bloqueados.
|
|
124
|
+
3. **Memory adapter em prod** → sessões somem no deploy.
|
|
125
|
+
4. **Rate limit só no security** → login ainda pode ser abuseado por userId se não houver limite no `createSession`.
|
|
126
|
+
5. **Action sem `auth.action`** → CSRF esquecido.
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## Próximos docs
|
|
131
|
+
|
|
132
|
+
- Auth: [01 Getting Started](./01-getting-started.md), [07 Checklist](./07-security-checklist.md)
|
|
133
|
+
- Security: veja `extension/security/docs/`
|
|
134
|
+
- Visão unificada do monorepo: `docs/security-and-auth.md`
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# 09 — Troubleshooting
|
|
2
|
+
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
## “CSRF_ORIGIN_INVALID”
|
|
6
|
+
|
|
7
|
+
**Causas comuns**
|
|
8
|
+
|
|
9
|
+
- Request sem header `Origin` (alguns clientes, redirects, ferramentas)
|
|
10
|
+
- Origin não está em `csrf.allowedOrigins` (http vs https, www vs apex, porta)
|
|
11
|
+
- Typo na lista de origins
|
|
12
|
+
|
|
13
|
+
**O que fazer**
|
|
14
|
+
|
|
15
|
+
- Confirme no DevTools o header `Origin` da action
|
|
16
|
+
- Normalize: `createAuth` já valida e normaliza via `URL.origin`
|
|
17
|
+
- Em dev, inclua `http://localhost:PORT` explicitamente
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## “CSRF_TOKEN_INVALID”
|
|
22
|
+
|
|
23
|
+
- Token não foi enviado (faltou hidden input ou header)
|
|
24
|
+
- Token de **outra** sessão (usuário com duas abas, sessão renovada e form antigo)
|
|
25
|
+
- Comparação falhou (encoding, espaços)
|
|
26
|
+
|
|
27
|
+
**Mitigação**
|
|
28
|
+
|
|
29
|
+
- Sempre ler token fresco do server ao renderizar o form
|
|
30
|
+
- Preferir header `x-adaptive-csrf-token` em clients SPA se o form for longe da renderização
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## Sessão “some” após alguns requests
|
|
35
|
+
|
|
36
|
+
- `freshCookie` não foi aplicado na resposta → browser continua com id antigo já invalidado (após grace)
|
|
37
|
+
- Use `auth.action`, `protectPage` ou `withSession` para não esquecer
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## “AUTHENTICATION_REQUIRED” logo após login
|
|
42
|
+
|
|
43
|
+
- `Set-Cookie` não foi enviado ou foi sobrescrito
|
|
44
|
+
- Cookie `Secure` em página HTTP
|
|
45
|
+
- Path/Domain do cookie não batem com a URL
|
|
46
|
+
- Prefixo `__Host-` em HTTP local → use cookie de dev
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## Rate limit 429 inesperado
|
|
51
|
+
|
|
52
|
+
- IP extraído de `X-Forwarded-For` sem proxy confiável (IP do proxy ou de atacante)
|
|
53
|
+
- Configure o trust do proxy no edge e teste `extractClientIp`
|
|
54
|
+
- Storage memory reinicia com o processo (contadores zeram) — em prod use Redis
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## Role nunca autoriza
|
|
59
|
+
|
|
60
|
+
- `user.roles` não vem do adapter (`getUser` incompleto)
|
|
61
|
+
- String diferente (`Admin` vs `admin`) — comparação é exata
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## protectPage sempre 404
|
|
66
|
+
|
|
67
|
+
- Session null (cookie não chega no server component)
|
|
68
|
+
- Role faltando com default `onForbidden: "404"`
|
|
69
|
+
- `readSession` lançou `AuthError` (user deleted) → tratado como unauthenticated
|
|
70
|
+
|
|
71
|
+
Teste com `onUnauthenticated: "401"` temporariamente para distinguir.
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## CSP bloqueia hidratação
|
|
76
|
+
|
|
77
|
+
- Security plugin não registrado → nonce no script ≠ nonce no header (ou sem nonce)
|
|
78
|
+
- `script-src` custom sem incluir o nonce
|
|
79
|
+
- Confirme `setSecurityPlugin(security.asNitroPlugin())`
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## Audit não aparece
|
|
84
|
+
|
|
85
|
+
- Handler não configurado
|
|
86
|
+
- Handler lançou (é best-effort — erro é engolido)
|
|
87
|
+
- Você filtrou o tipo errado no logger
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## Como debugar rápido
|
|
92
|
+
|
|
93
|
+
1. Logar `event.type` em `onAuditEvent`
|
|
94
|
+
2. Inspecionar `Set-Cookie` e `Origin` nas actions
|
|
95
|
+
3. `auth.readSession(request)` num endpoint de debug (só em dev)
|
|
96
|
+
4. Rodar a suíte `npm test` no pacote `extension-auth` (csrf, sessions, security)
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Documentação — `@adaptive-js/extension-auth`
|
|
2
|
+
|
|
3
|
+
Guias em português. O [README do pacote](../README.md) continua sendo a referência rápida de API.
|
|
4
|
+
|
|
5
|
+
| Doc | Conteúdo |
|
|
6
|
+
|-----|----------|
|
|
7
|
+
| [01 — Getting Started](./01-getting-started.md) | Happy path: login, página, action, logout |
|
|
8
|
+
| [02 — Server Actions](./02-server-actions.md) | `auth.action`, CSRF, roles |
|
|
9
|
+
| [03 — Proteger páginas](./03-protecting-pages.md) | `protectPage`, redirect, returnTo |
|
|
10
|
+
| [04 — Ciclo de vida da sessão](./04-session-lifecycle.md) | Renovação, invalidação, binding, audit |
|
|
11
|
+
| [05 — Adapters](./05-adapters.md) | Memory, Postgres, Redis |
|
|
12
|
+
| [06 — Client](./06-client.md) | `AuthProvider`, `useAuth`, expiração |
|
|
13
|
+
| [07 — Checklist de segurança](./07-security-checklist.md) | Produção (P0) |
|
|
14
|
+
| [08 — Integração](./08-integration.md) | auth + security + Nitro |
|
|
15
|
+
| [09 — Troubleshooting](./09-troubleshooting.md) | Erros comuns |
|
|
16
|
+
|
|
17
|
+
Visão unificada do monorepo: [docs/security-and-auth.md](../../../docs/security-and-auth.md)
|