@adaptive-js/extension-auth 0.0.0-stage → 0.0.2

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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +412 -3
  3. package/dist/api-adapter.d.ts +2 -0
  4. package/dist/api-adapter.js +8 -0
  5. package/dist/api-adapter.js.map +1 -0
  6. package/dist/client.d.ts +41 -0
  7. package/dist/client.js +128 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/cookies.d.ts +10 -0
  10. package/dist/cookies.js +107 -0
  11. package/dist/cookies.js.map +1 -0
  12. package/dist/errors.d.ts +6 -0
  13. package/dist/errors.js +11 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/external-adapter.d.ts +93 -0
  16. package/dist/external-adapter.js +235 -0
  17. package/dist/external-adapter.js.map +1 -0
  18. package/dist/index.d.ts +7 -0
  19. package/dist/index.js +8 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/intended-url.d.ts +18 -0
  22. package/dist/intended-url.js +55 -0
  23. package/dist/intended-url.js.map +1 -0
  24. package/dist/memory-adapter.d.ts +16 -0
  25. package/dist/memory-adapter.js +112 -0
  26. package/dist/memory-adapter.js.map +1 -0
  27. package/dist/rate-limit.d.ts +28 -0
  28. package/dist/rate-limit.js +104 -0
  29. package/dist/rate-limit.js.map +1 -0
  30. package/dist/server.d.ts +54 -0
  31. package/dist/server.js +745 -0
  32. package/dist/server.js.map +1 -0
  33. package/dist/types.d.ts +225 -0
  34. package/dist/types.js +2 -0
  35. package/dist/types.js.map +1 -0
  36. package/docs/01-getting-started.md +347 -0
  37. package/docs/02-server-actions.md +176 -0
  38. package/docs/03-protecting-pages.md +144 -0
  39. package/docs/04-session-lifecycle.md +169 -0
  40. package/docs/05-adapters.md +242 -0
  41. package/docs/06-client.md +126 -0
  42. package/docs/07-security-checklist.md +93 -0
  43. package/docs/08-integration.md +134 -0
  44. package/docs/09-troubleshooting.md +96 -0
  45. package/docs/README.md +17 -0
  46. package/package.json +72 -4
@@ -0,0 +1,176 @@
1
+ # 02 — Server Actions
2
+
3
+ Como proteger mutações de forma que o desenvolvedor **não consiga esquecer** CSRF ou sessão.
4
+
5
+ ---
6
+
7
+ ## Por que `auth.action` existe
8
+
9
+ O erro mais comum (e mais perigoso) em apps com sessão + cookie é:
10
+
11
+ ```ts
12
+ // ❌ ERRADO — sessão ok, CSRF esquecido
13
+ export async function updateProfile(formData: FormData, request: Request) {
14
+ const { session } = await auth.requireSession(request);
15
+ // ... mutação sem requireCsrf
16
+ }
17
+ ```
18
+
19
+ `auth.action` fecha esse buraco:
20
+
21
+ ```ts
22
+ export const updateProfile = auth.action(async ({ session, formData }) => {
23
+ // CSRF + sessão já validados
24
+ });
25
+ ```
26
+
27
+ Ordem interna garantida:
28
+
29
+ 1. `requireSession`
30
+ 2. `requireRole` (se você passou `roles`)
31
+ 3. `requireCsrf` (Origin + token)
32
+ 4. Anexa `freshCookie` se a sessão foi renovada
33
+ 5. Executa o seu handler
34
+
35
+ ---
36
+
37
+ ## Uso básico
38
+
39
+ ```ts
40
+ import { auth } from "../auth";
41
+
42
+ export const updateProfile = auth.action(async ({ session, formData, request }) => {
43
+ const name = String(formData?.get("name") ?? "").trim();
44
+ if (!name) throw new Error("Name required");
45
+
46
+ await db.users.update(session.userId, { name });
47
+ return { ok: true };
48
+ });
49
+ ```
50
+
51
+ ### Com role
52
+
53
+ ```ts
54
+ export const deleteUser = auth.action(
55
+ { roles: ["admin"] },
56
+ async ({ session, formData }) => {
57
+ const targetId = String(formData?.get("userId"));
58
+ await db.users.delete(targetId);
59
+ return { ok: true };
60
+ }
61
+ );
62
+ ```
63
+
64
+ ---
65
+
66
+ ## Enviando o token CSRF
67
+
68
+ ### Form HTML / Server Action clássica
69
+
70
+ ```tsx
71
+ const { session } = await auth.requireSession(request);
72
+ const csrfToken = await auth.getCsrfToken(session);
73
+
74
+ <form action={updateProfile}>
75
+ <input type="hidden" name="csrfToken" value={csrfToken} />
76
+ <input name="name" />
77
+ <button>Salvar</button>
78
+ </form>
79
+ ```
80
+
81
+ O helper tenta ler o token de:
82
+
83
+ - campo `csrfToken` / `csrf` no `FormData`
84
+ - header `x-adaptive-csrf-token` (nome configurável)
85
+
86
+ ### Fetch / JSON
87
+
88
+ ```ts
89
+ await fetch("/_action", {
90
+ method: "POST",
91
+ headers: {
92
+ "Content-Type": "application/json",
93
+ "x-adaptive-csrf-token": csrfToken,
94
+ },
95
+ body: JSON.stringify({ action: "updateProfile", name: "Ada" }),
96
+ credentials: "include",
97
+ });
98
+ ```
99
+
100
+ A request **precisa** ter header `Origin` válido (bate com `allowedOrigins`). Sem Origin → rejeitado.
101
+
102
+ ---
103
+
104
+ ## `protectAction` vs `auth.action`
105
+
106
+ | Helper | Sessão | Roles | CSRF | Quando usar |
107
+ |--------|--------|-------|------|-------------|
108
+ | `auth.action` | ✅ | ✅ opcional | ✅ | **Mutações** (recomendado) |
109
+ | `auth.protectAction` | ✅ | ✅ opcional | ❌ | Só leitura autenticada / casos especiais |
110
+
111
+ Se a action muda estado, prefira sempre `auth.action`.
112
+
113
+ ---
114
+
115
+ ## Renovação de cookie dentro da action
116
+
117
+ Se a sessão estiver perto de expirar, `requireSession` pode rotacionar o id e devolver `freshCookie`.
118
+
119
+ `auth.action` tenta aplicar esse cookie no contexto (Response / `appendSetCookie`).
120
+ Se o runtime do AdaptiveJS expuser outro mecanismo, use `withSession` manualmente:
121
+
122
+ ```ts
123
+ return auth.withSession(request, async ({ session, freshCookie }) => {
124
+ // ...
125
+ const res = Response.json({ ok: true });
126
+ if (freshCookie) res.headers.append("Set-Cookie", freshCookie.header);
127
+ return res;
128
+ });
129
+ ```
130
+
131
+ ---
132
+
133
+ ## Erros que você vai ver
134
+
135
+ | Código | Status | Causa típica |
136
+ |--------|--------|--------------|
137
+ | `AUTHENTICATION_REQUIRED` | 401 | Sem cookie / sessão expirada |
138
+ | `AUTHORIZATION_FAILED` | 403 | Role insuficiente |
139
+ | `CSRF_ORIGIN_INVALID` | 403 | Origin ausente ou não listado |
140
+ | `CSRF_TOKEN_INVALID` | 403 | Token ausente ou errado |
141
+ | `CSRF_CONFIGURATION_INVALID` | 500 | `allowedOrigins` mal configurado no boot |
142
+
143
+ Trate `AuthError` no boundary de actions e devolva JSON consistente:
144
+
145
+ ```ts
146
+ import { AuthError } from "@adaptive-js/extension-auth";
147
+
148
+ try {
149
+ return await updateProfile(formData, event);
150
+ } catch (err) {
151
+ if (err instanceof AuthError) {
152
+ return Response.json(
153
+ { ok: false, error: err.code, message: err.message },
154
+ { status: err.status }
155
+ );
156
+ }
157
+ throw err;
158
+ }
159
+ ```
160
+
161
+ ---
162
+
163
+ ## Anti-patterns
164
+
165
+ 1. **Mutação com GET** — nunca.
166
+ 2. **Confiar só em SameSite** — insuficiente sozinho.
167
+ 3. **CSRF token no localStorage** — use cookie de sessão + token por sessão no form/header.
168
+ 4. **`protectAction` em escrita** — falta CSRF.
169
+ 5. **Validar role só no client** — role sempre no server (`auth.action` / `requireRole`).
170
+
171
+ ---
172
+
173
+ ## Próximo
174
+
175
+ - [03 — Proteger páginas](./03-protecting-pages.md)
176
+ - [04 — Ciclo de vida da sessão](./04-session-lifecycle.md)
@@ -0,0 +1,144 @@
1
+ # 03 — Protegendo páginas
2
+
3
+ `auth.protectPage` roda **no server**, antes de qualquer HTML de página protegida ser enviado.
4
+
5
+ ---
6
+
7
+ ## Uso mínimo
8
+
9
+ ```tsx
10
+ import { auth } from "../auth";
11
+
12
+ export default auth.protectPage(async ({ session }) => {
13
+ return <h1>Olá, {session.user.name}</h1>;
14
+ });
15
+ ```
16
+
17
+ Sem sessão → resposta de **não encontrado** (404) por padrão.
18
+ Isso evita vazar a existência da rota para usuários anônimos.
19
+
20
+ ---
21
+
22
+ ## Roles
23
+
24
+ ```tsx
25
+ export default auth.protectPage(
26
+ async ({ session }) => <AdminPanel user={session.user} />,
27
+ { roles: ["admin"] }
28
+ );
29
+ ```
30
+
31
+ Se o usuário está autenticado mas sem a role → comportamento de `onForbidden` (default: 404).
32
+
33
+ ---
34
+
35
+ ## Comportamentos configuráveis
36
+
37
+ ```ts
38
+ type ProtectPageOptions = {
39
+ roles?: string[];
40
+ onUnauthenticated?: "404" | "401" | "redirect" | ((ctx) => any);
41
+ onForbidden?: "404" | "403" | ((ctx) => any);
42
+ redirectTo?: string;
43
+ returnTo?: boolean; // usa sanitizeReturnTo automaticamente
44
+ };
45
+ ```
46
+
47
+ ### Exemplos
48
+
49
+ **Redirect para login guardando o destino:**
50
+
51
+ ```tsx
52
+ export default auth.protectPage(
53
+ async ({ session }) => <PrivatePage />,
54
+ {
55
+ onUnauthenticated: "redirect",
56
+ redirectTo: "/login",
57
+ returnTo: true,
58
+ }
59
+ );
60
+ ```
61
+
62
+ **401 explícito (APIs / JSON):**
63
+
64
+ ```tsx
65
+ export default auth.protectPage(
66
+ async ({ session }) => <ApiStylePage />,
67
+ { onUnauthenticated: "401" }
68
+ );
69
+ ```
70
+
71
+ **Handler custom:**
72
+
73
+ ```tsx
74
+ export default auth.protectPage(
75
+ async ({ session }) => <Page />,
76
+ {
77
+ onUnauthenticated: (ctx) => {
78
+ return { __type: "redirect", location: "/login" };
79
+ },
80
+ }
81
+ );
82
+ ```
83
+
84
+ ---
85
+
86
+ ## Return URL seguro
87
+
88
+ Nunca redirecione para URL vinda do query string sem sanitizar.
89
+
90
+ ```ts
91
+ import {
92
+ buildLoginReturnUrl,
93
+ readReturnToFromSearchParams,
94
+ sanitizeReturnTo,
95
+ } from "@adaptive-js/extension-auth/server";
96
+
97
+ // Montar link de login
98
+ const loginUrl = buildLoginReturnUrl("/login", "/dashboard/settings");
99
+ // → /login?returnTo=%2Fdashboard%2Fsettings
100
+
101
+ // Depois do login
102
+ const raw = readReturnToFromSearchParams(url.searchParams);
103
+ const safe = sanitizeReturnTo(raw); // null se for externo / perigoso
104
+ const destination = safe ?? "/dashboard";
105
+ ```
106
+
107
+ `sanitizeReturnTo` **só aceita paths relativos same-origin**.
108
+ `https://evil.com` → `null`.
109
+
110
+ ---
111
+
112
+ ## Cookie renovado na página
113
+
114
+ Se a sessão for renovada durante o `readSession`, `protectPage` chama `context.appendSetCookie` quando disponível.
115
+ Garanta que o runtime da página exponha esse callback (o adapter Nitro / core do AdaptiveJS costuma fazer isso).
116
+
117
+ ---
118
+
119
+ ## O que `protectPage` NÃO substitui
120
+
121
+ - Não protege Server Actions → use `auth.action`.
122
+ - Não é middleware global de todas as rotas → proteja página a página (ou componha um helper de layout).
123
+ - Não valida CSRF (páginas GET de leitura não precisam; mutações sim).
124
+
125
+ ---
126
+
127
+ ## Padrão recomendado de pastas
128
+
129
+ ```text
130
+ src/pages/
131
+ login.tsx ← pública
132
+ dashboard.tsx ← auth.protectPage(...)
133
+ admin/
134
+ index.tsx ← auth.protectPage(..., { roles: ["admin"] })
135
+ ```
136
+
137
+ Nunca faça a checagem só no client:
138
+
139
+ ```tsx
140
+ // ❌ ERRADO
141
+ if (!useAuth().authenticated()) return <Login />;
142
+ ```
143
+
144
+ O HTML/dados sensíveis já teriam sido renderizados no server ou vazado na hidratação.
@@ -0,0 +1,169 @@
1
+ # 04 — Ciclo de vida da sessão
2
+
3
+ ---
4
+
5
+ ## Tempos
6
+
7
+ | Opção | Default | Significado |
8
+ |-------|---------|-------------|
9
+ | `sessionDuration` | 30 dias | Idle timeout (renovável) |
10
+ | `absoluteSessionDuration` | 90 dias | Teto absoluto (não renova além disso) |
11
+ | `renewBefore` | 7 dias | Quando `remaining <= renewBefore`, rotaciona o id |
12
+
13
+ Uma sessão ativa pode ser renovada várias vezes, mas **nunca** passa de `absoluteExpiresAt`.
14
+
15
+ ---
16
+
17
+ ## Criação
18
+
19
+ ```ts
20
+ const { session, cookie } = await auth.login(user, request);
21
+ // ou
22
+ const { session, cookie } = await auth.createSession(user, { data: { theme: "dark" } }, request);
23
+
24
+ response.headers.append("Set-Cookie", cookie.header);
25
+ ```
26
+
27
+ ### Rate limit na criação
28
+
29
+ ```ts
30
+ export const auth = createAuth({
31
+ adapter,
32
+ csrf: { allowedOrigins: [...] },
33
+ rateLimit: {
34
+ createSession: {
35
+ max: 10,
36
+ windowMs: 15 * 60 * 1000, // 15 min
37
+ // key default: combina IP + userId quando possível
38
+ },
39
+ },
40
+ });
41
+ ```
42
+
43
+ Isso protege o ponto de entrada de sessão (brute force / credential stuffing no endpoint que chama `createSession`).
44
+ Complementa o rate limit por IP do `@adaptive-js/extension-security`.
45
+
46
+ ---
47
+
48
+ ## Leitura e renovação
49
+
50
+ ```ts
51
+ const { session, freshCookie } = await auth.readSession(request);
52
+ // session pode ser null
53
+
54
+ const { session, freshCookie } = await auth.requireSession(request);
55
+ // lança AuthError se não houver sessão
56
+ ```
57
+
58
+ ### Race condition e grace window
59
+
60
+ Quando várias requests paralelas disparam renovação ao mesmo tempo, o módulo:
61
+
62
+ 1. Serializa a renovação por `sessionId` (`renewalInFlight`)
63
+ 2. Mantém o id antigo aceito por ~15s (`renewalGraceCache`)
64
+
65
+ Assim o browser não fica com cookie “órfão” de uma sessão já deletada.
66
+
67
+ **Sempre** propague `freshCookie` quando existir:
68
+
69
+ ```ts
70
+ if (freshCookie) {
71
+ response.headers.append("Set-Cookie", freshCookie.header);
72
+ }
73
+ ```
74
+
75
+ Ou use o helper:
76
+
77
+ ```ts
78
+ return auth.withSession(request, async ({ session }) => {
79
+ return Response.json({ user: session.user });
80
+ // freshCookie aplicado automaticamente quando possível
81
+ });
82
+ ```
83
+
84
+ ---
85
+
86
+ ## Dados na sessão
87
+
88
+ ```ts
89
+ // Guardar progresso de MFA, preferências, etc. sem rotacionar o id
90
+ await auth.updateSessionData(session.id, { mfaStep: "totp" });
91
+ await auth.updateSessionData(session.id, (prev) => ({
92
+ cart: [...(prev.cart as any[] ?? []), item],
93
+ }));
94
+ ```
95
+
96
+ O `csrfToken` **nunca** entra no tipo público `AuthSession` nem em `listUserSessions`.
97
+
98
+ ---
99
+
100
+ ## Invalidação
101
+
102
+ | Método | Efeito |
103
+ |--------|--------|
104
+ | `logout(request)` | Invalida sessão do cookie atual + cookie em branco |
105
+ | `logoutEverywhere(userId)` | Todas as sessões do usuário |
106
+ | `invalidateUserSessionsExcept(userId, currentId)` | Outros dispositivos, mantém o atual |
107
+ | `passwordChanged(userId)` | Todas + audit + hook |
108
+ | `roleElevated(userId)` | Todas + audit + hook |
109
+ | `mfaEnabled(userId)` | Todas + audit + hook |
110
+ | `forceReauth(userId)` | Todas + audit |
111
+
112
+ ### Quando invalidar
113
+
114
+ | Evento | Chamada recomendada |
115
+ |--------|---------------------|
116
+ | Reset / troca de senha | `passwordChanged` |
117
+ | Mudança de role privilegiada | `roleElevated` |
118
+ | Ativação de MFA | `mfaEnabled` |
119
+ | Compromisso suspeito | `forceReauth` ou `suspiciousActivity` (via hook) |
120
+ | “Sair de todos os dispositivos” na UI | `logoutEverywhere` |
121
+
122
+ ---
123
+
124
+ ## Session binding (anti-sequestro)
125
+
126
+ Opt-in:
127
+
128
+ ```ts
129
+ createAuth({
130
+ adapter,
131
+ csrf: { allowedOrigins: [...] },
132
+ sessionBinding: {
133
+ userAgent: true,
134
+ // ip: true, // evite em mobile/CGNAT
135
+ // fingerprint: true // se o app enviar header x-client-fingerprint
136
+ },
137
+ });
138
+ ```
139
+
140
+ Se o binding não bater na `requireSession` / renovação → sessão invalidada + audit `session.rejected`.
141
+
142
+ ---
143
+
144
+ ## Listar sessões (UI de dispositivos)
145
+
146
+ ```ts
147
+ const sessions = await auth.listUserSessions(userId);
148
+ // [{ id, userId, createdAt, expiresAt, absoluteExpiresAt }, ...]
149
+ // sem csrfToken
150
+ ```
151
+
152
+ Requer que o adapter implemente `listUserSessions`.
153
+
154
+ ---
155
+
156
+ ## Audit
157
+
158
+ ```ts
159
+ createAuth({
160
+ // ...
161
+ onAuditEvent(event) {
162
+ // event.type: session.created | session.renewed | session.invalidated | ...
163
+ logger.info(event);
164
+ },
165
+ });
166
+ ```
167
+
168
+ - Em produção, ausência de `onAuditEvent` gera **warning** no boot.
169
+ - Falhas no handler de audit **não** quebram o fluxo de autenticação (best-effort).