create-fluxstack 1.12.0 → 1.13.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/LLMD/INDEX.md +8 -1
- package/LLMD/agent.md +867 -0
- package/LLMD/config/environment-vars.md +30 -0
- package/LLMD/resources/live-auth.md +447 -0
- package/LLMD/resources/live-components.md +79 -21
- package/LLMD/resources/live-logging.md +158 -0
- package/LLMD/resources/live-upload.md +1 -1
- package/LLMD/resources/rest-auth.md +290 -0
- package/README.md +520 -340
- package/app/client/src/App.tsx +11 -0
- package/app/client/src/components/AppLayout.tsx +1 -0
- package/app/client/src/live/AuthDemo.tsx +332 -0
- package/app/client/src/live/RoomChatDemo.tsx +24 -105
- package/app/server/auth/AuthManager.ts +213 -0
- package/app/server/auth/DevAuthProvider.ts +66 -0
- package/app/server/auth/HashManager.ts +123 -0
- package/app/server/auth/JWTAuthProvider.example.ts +101 -0
- package/app/server/auth/RateLimiter.ts +106 -0
- package/app/server/auth/contracts.ts +192 -0
- package/app/server/auth/guards/SessionGuard.ts +167 -0
- package/app/server/auth/guards/TokenGuard.ts +202 -0
- package/app/server/auth/index.ts +174 -0
- package/app/server/auth/middleware.ts +163 -0
- package/app/server/auth/providers/InMemoryProvider.ts +162 -0
- package/app/server/auth/sessions/SessionManager.ts +164 -0
- package/app/server/cache/CacheManager.ts +81 -0
- package/app/server/cache/MemoryDriver.ts +112 -0
- package/app/server/cache/contracts.ts +49 -0
- package/app/server/cache/index.ts +42 -0
- package/app/server/index.ts +14 -0
- package/app/server/live/LiveAdminPanel.ts +173 -0
- package/app/server/live/LiveCounter.ts +1 -0
- package/app/server/live/LiveLocalCounter.ts +13 -8
- package/app/server/live/LiveProtectedChat.ts +150 -0
- package/app/server/live/LiveRoomChat.ts +45 -203
- package/app/server/routes/auth.routes.ts +278 -0
- package/app/server/routes/index.ts +2 -0
- package/config/index.ts +8 -0
- package/config/system/auth.config.ts +49 -0
- package/config/system/session.config.ts +33 -0
- package/core/client/LiveComponentsProvider.tsx +76 -5
- package/core/client/components/Live.tsx +2 -1
- package/core/client/hooks/useLiveComponent.ts +47 -4
- package/core/client/index.ts +2 -1
- package/core/framework/server.ts +36 -4
- package/core/plugins/built-in/live-components/commands/create-live-component.ts +15 -8
- package/core/plugins/built-in/monitoring/index.ts +10 -3
- package/core/plugins/built-in/vite/index.ts +95 -18
- package/core/plugins/config.ts +5 -4
- package/core/plugins/discovery.ts +11 -2
- package/core/plugins/manager.ts +11 -5
- package/core/plugins/module-resolver.ts +1 -1
- package/core/plugins/registry.ts +53 -25
- package/core/server/live/ComponentRegistry.ts +79 -24
- package/core/server/live/LiveComponentPerformanceMonitor.ts +9 -8
- package/core/server/live/LiveLogger.ts +111 -0
- package/core/server/live/LiveRoomManager.ts +5 -4
- package/core/server/live/StateSignature.ts +644 -643
- package/core/server/live/auth/LiveAuthContext.ts +71 -0
- package/core/server/live/auth/LiveAuthManager.ts +304 -0
- package/core/server/live/auth/index.ts +19 -0
- package/core/server/live/auth/types.ts +179 -0
- package/core/server/live/auto-generated-components.ts +8 -2
- package/core/server/live/index.ts +16 -0
- package/core/server/live/websocket-plugin.ts +92 -16
- package/core/templates/create-project.ts +0 -3
- package/core/types/types.ts +133 -13
- package/core/utils/index.ts +17 -17
- package/core/utils/logger/index.ts +5 -2
- package/core/utils/version.ts +1 -1
- package/package.json +1 -8
- package/plugins/crypto-auth/index.ts +6 -0
- package/plugins/crypto-auth/server/CryptoAuthLiveProvider.ts +58 -0
- package/plugins/crypto-auth/server/index.ts +24 -21
- package/rest-tests/README.md +57 -0
- package/rest-tests/auth-token.http +113 -0
- package/rest-tests/auth.http +112 -0
- package/rest-tests/rooms-token.http +69 -0
- package/rest-tests/users-token.http +62 -0
- package/.dockerignore +0 -81
- package/Dockerfile +0 -70
- package/LIVE_COMPONENTS_REVIEW.md +0 -781
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# Live Logging
|
|
2
|
+
|
|
3
|
+
**Version:** 1.12.0 | **Updated:** 2025-02-12
|
|
4
|
+
|
|
5
|
+
## Quick Facts
|
|
6
|
+
|
|
7
|
+
- Per-component logging control — silent by default
|
|
8
|
+
- Opt-in via `static logging` property on LiveComponent subclasses
|
|
9
|
+
- 6 categories: `lifecycle`, `messages`, `state`, `performance`, `rooms`, `websocket`
|
|
10
|
+
- Global (non-component) logs controlled by `LIVE_LOGGING` env var
|
|
11
|
+
- `console.error` always visible regardless of config
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
### Enable Logging on a Component
|
|
16
|
+
|
|
17
|
+
```typescript
|
|
18
|
+
// app/server/live/LiveCounter.ts
|
|
19
|
+
export class LiveCounter extends LiveComponent<typeof LiveCounter.defaultState> {
|
|
20
|
+
static componentName = 'LiveCounter'
|
|
21
|
+
|
|
22
|
+
// ✅ All categories
|
|
23
|
+
static logging = true
|
|
24
|
+
|
|
25
|
+
// ✅ Specific categories only
|
|
26
|
+
static logging = ['lifecycle', 'messages', 'state', 'rooms'] as const
|
|
27
|
+
|
|
28
|
+
// ✅ Silent (default — omit property or set false)
|
|
29
|
+
// static logging = false
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### Global Logs (Non-Component)
|
|
34
|
+
|
|
35
|
+
Logs not tied to a specific component (room cleanup, key rotation, etc.) are controlled by the `LIVE_LOGGING` env var:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
# .env
|
|
39
|
+
LIVE_LOGGING=true # All global logs
|
|
40
|
+
LIVE_LOGGING=lifecycle,rooms # Specific categories only
|
|
41
|
+
# (unset or 'false') # Silent (default)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Categories
|
|
45
|
+
|
|
46
|
+
| Category | What It Logs |
|
|
47
|
+
|----------|-------------|
|
|
48
|
+
| `lifecycle` | Mount, unmount, rehydration, recovery, migration |
|
|
49
|
+
| `messages` | Received/sent WebSocket messages, file uploads |
|
|
50
|
+
| `state` | Signing, backup, compression, encryption, validation |
|
|
51
|
+
| `performance` | Monitoring init, alerts, optimization suggestions |
|
|
52
|
+
| `rooms` | Room create/join/leave, emit, broadcast |
|
|
53
|
+
| `websocket` | Connection open/close, auth |
|
|
54
|
+
|
|
55
|
+
## Type Definition
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
type LiveLogCategory = 'lifecycle' | 'messages' | 'state' | 'performance' | 'rooms' | 'websocket'
|
|
59
|
+
|
|
60
|
+
type LiveLogConfig = boolean | readonly LiveLogCategory[]
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Use `as const` on arrays to get readonly tuple type:
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
// ✅ Works with as const
|
|
67
|
+
static logging = ['lifecycle', 'messages'] as const
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## API (Framework Internal)
|
|
71
|
+
|
|
72
|
+
These functions are used by the framework — app developers only need `static logging`:
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
import { liveLog, liveWarn, registerComponentLogging, unregisterComponentLogging } from '@core/server/live'
|
|
76
|
+
|
|
77
|
+
// Log gated by component config
|
|
78
|
+
liveLog('lifecycle', componentId, '🚀 Mounted component')
|
|
79
|
+
liveLog('rooms', componentId, `📡 Joined room '${roomId}'`)
|
|
80
|
+
|
|
81
|
+
// Warn-level (for perf alerts, non-error warnings)
|
|
82
|
+
liveWarn('performance', componentId, '⚠️ Slow render detected')
|
|
83
|
+
|
|
84
|
+
// Register/unregister (called on mount/unmount by ComponentRegistry)
|
|
85
|
+
registerComponentLogging(componentId, config)
|
|
86
|
+
unregisterComponentLogging(componentId)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## How It Works
|
|
90
|
+
|
|
91
|
+
1. **Mount**: `ComponentRegistry` reads `static logging` from the class and calls `registerComponentLogging(componentId, config)`
|
|
92
|
+
2. **Runtime**: All `liveLog()`/`liveWarn()` calls check the registry before emitting
|
|
93
|
+
3. **Unmount**: `unregisterComponentLogging(componentId)` removes the entry
|
|
94
|
+
4. **Global logs**: Fall back to `LIVE_LOGGING` env var when `componentId` is `null`
|
|
95
|
+
|
|
96
|
+
## Examples
|
|
97
|
+
|
|
98
|
+
### Debug a Specific Component
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
// Only this component will show logs
|
|
102
|
+
export class LiveChat extends LiveComponent<typeof LiveChat.defaultState> {
|
|
103
|
+
static componentName = 'LiveChat'
|
|
104
|
+
static logging = true // See everything for this component
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// All other components remain silent
|
|
108
|
+
export class LiveCounter extends LiveComponent<typeof LiveCounter.defaultState> {
|
|
109
|
+
static componentName = 'LiveCounter'
|
|
110
|
+
// No static logging → silent
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Monitor Only Room Activity
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
export class LiveChat extends LiveComponent<typeof LiveChat.defaultState> {
|
|
118
|
+
static componentName = 'LiveChat'
|
|
119
|
+
static logging = ['rooms'] as const // Only room events
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Production: Silent Everywhere
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
# .env (no LIVE_LOGGING set)
|
|
127
|
+
# All components without static logging → silent
|
|
128
|
+
# Components with static logging still log (remove for production)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## Files Reference
|
|
132
|
+
|
|
133
|
+
| File | Purpose |
|
|
134
|
+
|------|---------|
|
|
135
|
+
| `core/server/live/LiveLogger.ts` | Logger implementation, registry, shouldLog logic |
|
|
136
|
+
| `core/server/live/ComponentRegistry.ts` | Reads `static logging` on mount/unmount |
|
|
137
|
+
| `core/server/live/websocket-plugin.ts` | Uses `liveLog` for WebSocket events |
|
|
138
|
+
| `core/server/live/StateSignature.ts` | Uses `liveLog`/`liveWarn` for state operations |
|
|
139
|
+
| `core/server/live/LiveRoomManager.ts` | Uses `liveLog` for room lifecycle |
|
|
140
|
+
| `core/server/live/LiveComponentPerformanceMonitor.ts` | Uses `liveLog`/`liveWarn` for perf |
|
|
141
|
+
| `core/types/types.ts` | `LiveComponent` base class with `static logging` property |
|
|
142
|
+
|
|
143
|
+
## Critical Rules
|
|
144
|
+
|
|
145
|
+
**ALWAYS:**
|
|
146
|
+
- Use `as const` on logging arrays for type safety
|
|
147
|
+
- Keep components silent by default in production
|
|
148
|
+
- Use specific categories instead of `true` when possible
|
|
149
|
+
|
|
150
|
+
**NEVER:**
|
|
151
|
+
- Use `console.log` directly in Live Component code — use `liveLog()`
|
|
152
|
+
- Forget that `console.error` is always visible (not gated)
|
|
153
|
+
|
|
154
|
+
## Related
|
|
155
|
+
|
|
156
|
+
- [Live Components](./live-components.md) - Base component system
|
|
157
|
+
- [Live Rooms](./live-rooms.md) - Room system (logged under `rooms` category)
|
|
158
|
+
- [Environment Variables](../config/environment-vars.md) - `LIVE_LOGGING` reference
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
# REST API Authentication
|
|
2
|
+
|
|
3
|
+
**Version:** 1.14.0 | **Updated:** 2026-02-14
|
|
4
|
+
|
|
5
|
+
## Quick Facts
|
|
6
|
+
|
|
7
|
+
- Dois guards disponíveis: **Session** (cookie) e **Token** (Bearer)
|
|
8
|
+
- Configuração via `AUTH_DEFAULT_GUARD` no `.env`
|
|
9
|
+
- Rate limiting automático no login (5 tentativas / 60s)
|
|
10
|
+
- Password hashing com bcrypt ou argon2id
|
|
11
|
+
- Provider in-memory por padrão (extensível para database)
|
|
12
|
+
- REST test files disponíveis em `rest-tests/`
|
|
13
|
+
|
|
14
|
+
## Endpoints
|
|
15
|
+
|
|
16
|
+
| Método | Rota | Auth | Descrição |
|
|
17
|
+
|--------|------|------|-----------|
|
|
18
|
+
| `POST` | `/api/auth/register` | Guest | Criar conta e auto-login |
|
|
19
|
+
| `POST` | `/api/auth/login` | Guest | Autenticar com email + password |
|
|
20
|
+
| `GET` | `/api/auth/me` | Required | Retorna usuário autenticado |
|
|
21
|
+
| `POST` | `/api/auth/logout` | Required | Encerrar sessão/revogar token |
|
|
22
|
+
|
|
23
|
+
## Guards
|
|
24
|
+
|
|
25
|
+
### Session Guard (padrão)
|
|
26
|
+
|
|
27
|
+
Armazena sessão no servidor e envia cookie httpOnly ao cliente.
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
Login → Servidor cria sessão → Cookie `fluxstack_session` → Browser envia automaticamente
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
**Configuração** (`.env`):
|
|
34
|
+
```bash
|
|
35
|
+
AUTH_DEFAULT_GUARD=session
|
|
36
|
+
SESSION_COOKIE=fluxstack_session
|
|
37
|
+
SESSION_LIFETIME=7200 # 2 horas
|
|
38
|
+
SESSION_HTTP_ONLY=true
|
|
39
|
+
SESSION_SECURE=false # true em produção
|
|
40
|
+
SESSION_SAME_SITE=lax
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
**Response do login** (sem campo token):
|
|
44
|
+
```json
|
|
45
|
+
{
|
|
46
|
+
"success": true,
|
|
47
|
+
"user": {
|
|
48
|
+
"id": 1,
|
|
49
|
+
"name": "John Doe",
|
|
50
|
+
"email": "john@example.com",
|
|
51
|
+
"createdAt": "2026-02-14T16:00:00.000Z"
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
**Requests autenticados**: cookie enviado automaticamente pelo browser.
|
|
57
|
+
|
|
58
|
+
### Token Guard (Bearer)
|
|
59
|
+
|
|
60
|
+
Gera token aleatório de 32 bytes, armazena hash SHA256 no cache e retorna o token plain ao cliente.
|
|
61
|
+
|
|
62
|
+
```
|
|
63
|
+
Login → Token gerado → Response inclui token → Cliente envia Authorization: Bearer <token>
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
**Configuração** (`.env`):
|
|
67
|
+
```bash
|
|
68
|
+
AUTH_DEFAULT_GUARD=token
|
|
69
|
+
AUTH_TOKEN_TTL=86400 # 24 horas
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
**Response do login** (com campo token):
|
|
73
|
+
```json
|
|
74
|
+
{
|
|
75
|
+
"success": true,
|
|
76
|
+
"user": {
|
|
77
|
+
"id": 1,
|
|
78
|
+
"name": "John Doe",
|
|
79
|
+
"email": "john@example.com",
|
|
80
|
+
"createdAt": "2026-02-14T16:00:00.000Z"
|
|
81
|
+
},
|
|
82
|
+
"token": "a1b2c3d4e5f6..."
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
**Requests autenticados**:
|
|
87
|
+
```
|
|
88
|
+
Authorization: Bearer a1b2c3d4e5f6...
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Quando usar cada guard
|
|
92
|
+
|
|
93
|
+
| Guard | Melhor para |
|
|
94
|
+
|-------|-------------|
|
|
95
|
+
| Session | SPAs web (same-origin), SSR |
|
|
96
|
+
| Token | Mobile apps, CLIs, API clients, integrações |
|
|
97
|
+
|
|
98
|
+
## Fluxos
|
|
99
|
+
|
|
100
|
+
### Register + Auto-login
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
POST /api/auth/register
|
|
104
|
+
Content-Type: application/json
|
|
105
|
+
|
|
106
|
+
{
|
|
107
|
+
"name": "John Doe",
|
|
108
|
+
"email": "john@example.com",
|
|
109
|
+
"password": "secret123"
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
# 201 Created
|
|
113
|
+
# Session guard: set-cookie header
|
|
114
|
+
# Token guard: token no body (via login automático)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Login
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
POST /api/auth/login
|
|
121
|
+
Content-Type: application/json
|
|
122
|
+
|
|
123
|
+
{
|
|
124
|
+
"email": "john@example.com",
|
|
125
|
+
"password": "secret123"
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
# 200 OK → user + token (se token guard)
|
|
129
|
+
# 401 → credenciais inválidas
|
|
130
|
+
# 429 → rate limit (Retry-After header)
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Me (Token Guard)
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
GET /api/auth/me
|
|
137
|
+
Authorization: Bearer <token>
|
|
138
|
+
|
|
139
|
+
# 200 OK → { success: true, user: {...} }
|
|
140
|
+
# 401 → não autenticado
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### Logout (Token Guard)
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
POST /api/auth/logout
|
|
147
|
+
Authorization: Bearer <token>
|
|
148
|
+
|
|
149
|
+
# 200 OK → token revogado no cache
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## Rate Limiting
|
|
153
|
+
|
|
154
|
+
Login é protegido automaticamente contra brute force:
|
|
155
|
+
|
|
156
|
+
| Config | Default | Env Var |
|
|
157
|
+
|--------|---------|---------|
|
|
158
|
+
| Max tentativas | 5 | `AUTH_RATE_LIMIT_MAX_ATTEMPTS` |
|
|
159
|
+
| Janela (segundos) | 60 | `AUTH_RATE_LIMIT_DECAY_SECONDS` |
|
|
160
|
+
|
|
161
|
+
Chave de throttle: `email|ip`. Após exceder, retorna `429 Too Many Attempts` com header `Retry-After`.
|
|
162
|
+
|
|
163
|
+
## Password Hashing
|
|
164
|
+
|
|
165
|
+
| Config | Default | Env Var |
|
|
166
|
+
|--------|---------|---------|
|
|
167
|
+
| Algoritmo | bcrypt | `AUTH_HASH_ALGORITHM` |
|
|
168
|
+
| Rounds (bcrypt) | 10 | `AUTH_BCRYPT_ROUNDS` |
|
|
169
|
+
|
|
170
|
+
Opções: `bcrypt` ou `argon2id`.
|
|
171
|
+
|
|
172
|
+
## Middleware
|
|
173
|
+
|
|
174
|
+
Três níveis de proteção disponíveis para rotas customizadas:
|
|
175
|
+
|
|
176
|
+
```typescript
|
|
177
|
+
import { auth, guest, authOptional } from '@server/auth'
|
|
178
|
+
|
|
179
|
+
// Requer autenticação (401 se não autenticado)
|
|
180
|
+
app.use(auth()).get('/protected', ({ user }) => user.toJSON())
|
|
181
|
+
|
|
182
|
+
// Requer NÃO estar autenticado (409 se já logado)
|
|
183
|
+
app.use(guest()).post('/login', loginHandler)
|
|
184
|
+
|
|
185
|
+
// Auth opcional (não bloqueia, injeta user ou null)
|
|
186
|
+
app.use(authOptional()).get('/public', ({ user }) => ({ user }))
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## Schemas TypeBox
|
|
190
|
+
|
|
191
|
+
As rotas definem schemas para validação e Swagger:
|
|
192
|
+
|
|
193
|
+
```typescript
|
|
194
|
+
// Body do register
|
|
195
|
+
RegisterBodySchema = t.Object({
|
|
196
|
+
name: t.String({ minLength: 1 }),
|
|
197
|
+
email: t.String({ format: 'email' }),
|
|
198
|
+
password: t.String({ minLength: 6 }),
|
|
199
|
+
})
|
|
200
|
+
|
|
201
|
+
// Body do login
|
|
202
|
+
LoginBodySchema = t.Object({
|
|
203
|
+
email: t.String({ format: 'email' }),
|
|
204
|
+
password: t.String({ minLength: 1 }),
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
// Response do login (token guard)
|
|
208
|
+
LoginResponseSchema = t.Object({
|
|
209
|
+
success: t.Literal(true),
|
|
210
|
+
user: t.Object({
|
|
211
|
+
id: t.Union([t.String(), t.Number()]),
|
|
212
|
+
name: t.Optional(t.String()),
|
|
213
|
+
email: t.Optional(t.String()),
|
|
214
|
+
createdAt: t.Optional(t.String()),
|
|
215
|
+
}),
|
|
216
|
+
token: t.Optional(t.String()),
|
|
217
|
+
})
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
## REST Test Files
|
|
221
|
+
|
|
222
|
+
Arquivos `.http` prontos para testar com a extensão REST Client do VSCode:
|
|
223
|
+
|
|
224
|
+
| Arquivo | Guard | Cobertura |
|
|
225
|
+
|---------|-------|-----------|
|
|
226
|
+
| `rest-tests/auth.http` | Session (cookie) | Register, Login, Me, Logout |
|
|
227
|
+
| `rest-tests/auth-token.http` | Token (Bearer) | Register, Login, Me, Logout + erros |
|
|
228
|
+
| `rest-tests/users-token.http` | Token (Bearer) | CRUD de usuários autenticado |
|
|
229
|
+
| `rest-tests/rooms-token.http` | Token (Bearer) | Mensagens e eventos em salas |
|
|
230
|
+
|
|
231
|
+
### Uso rápido
|
|
232
|
+
|
|
233
|
+
1. Configure `AUTH_DEFAULT_GUARD=token` no `.env`
|
|
234
|
+
2. `bun run dev`
|
|
235
|
+
3. Abra `rest-tests/auth-token.http` no VSCode
|
|
236
|
+
4. Execute **Register** → **Login** (captura token) → **Me** / **Logout**
|
|
237
|
+
|
|
238
|
+
> O token é capturado automaticamente via `@name login` e injetado com `{{login.response.body.token}}`.
|
|
239
|
+
|
|
240
|
+
## Configuração Completa
|
|
241
|
+
|
|
242
|
+
| Variável | Tipo | Default | Descrição |
|
|
243
|
+
|----------|------|---------|-----------|
|
|
244
|
+
| `AUTH_DEFAULT_GUARD` | enum | `session` | Guard padrão: `session` ou `token` |
|
|
245
|
+
| `AUTH_DEFAULT_PROVIDER` | enum | `memory` | Provider: `memory` ou `database` |
|
|
246
|
+
| `AUTH_HASH_ALGORITHM` | enum | `bcrypt` | Hash: `bcrypt` ou `argon2id` |
|
|
247
|
+
| `AUTH_BCRYPT_ROUNDS` | number | `10` | Rounds do bcrypt |
|
|
248
|
+
| `AUTH_RATE_LIMIT_MAX_ATTEMPTS` | number | `5` | Max tentativas de login |
|
|
249
|
+
| `AUTH_RATE_LIMIT_DECAY_SECONDS` | number | `60` | Janela do rate limit |
|
|
250
|
+
| `AUTH_TOKEN_TTL` | number | `86400` | TTL do token (segundos) |
|
|
251
|
+
| `SESSION_COOKIE` | string | `fluxstack_session` | Nome do cookie |
|
|
252
|
+
| `SESSION_LIFETIME` | number | `7200` | Duração da sessão (segundos) |
|
|
253
|
+
| `SESSION_HTTP_ONLY` | boolean | `true` | Cookie httpOnly |
|
|
254
|
+
| `SESSION_SECURE` | boolean | `false` | Cookie secure (HTTPS) |
|
|
255
|
+
| `SESSION_SAME_SITE` | enum | `lax` | SameSite policy |
|
|
256
|
+
|
|
257
|
+
## Arquivos de Referência
|
|
258
|
+
|
|
259
|
+
| Arquivo | Conteúdo |
|
|
260
|
+
|---------|----------|
|
|
261
|
+
| `app/server/routes/auth.routes.ts` | Endpoints de autenticação |
|
|
262
|
+
| `app/server/auth/middleware.ts` | Middleware `auth()`, `guest()`, `authOptional()` |
|
|
263
|
+
| `app/server/auth/guards/SessionGuard.ts` | Lógica do session guard |
|
|
264
|
+
| `app/server/auth/guards/TokenGuard.ts` | Lógica do token guard |
|
|
265
|
+
| `app/server/auth/AuthManager.ts` | Factory de guards e providers |
|
|
266
|
+
| `app/server/auth/providers/InMemoryProvider.ts` | Provider in-memory |
|
|
267
|
+
| `app/server/auth/RateLimiter.ts` | Rate limiting de login |
|
|
268
|
+
| `config/system/auth.config.ts` | Schema de configuração auth |
|
|
269
|
+
| `config/system/session.config.ts` | Schema de configuração session |
|
|
270
|
+
|
|
271
|
+
## Critical Rules
|
|
272
|
+
|
|
273
|
+
**ALWAYS:**
|
|
274
|
+
- Usar `AUTH_DEFAULT_GUARD=token` para APIs stateless
|
|
275
|
+
- Enviar `Authorization: Bearer <token>` em todos os requests autenticados
|
|
276
|
+
- Tratar `401` e `429` no frontend
|
|
277
|
+
- Armazenar token com segurança no cliente (httpOnly cookie ou secure storage)
|
|
278
|
+
|
|
279
|
+
**NEVER:**
|
|
280
|
+
- Expor token em URLs (query params)
|
|
281
|
+
- Armazenar token em localStorage sem necessidade (preferir httpOnly cookie)
|
|
282
|
+
- Ignorar rate limiting responses (`429`)
|
|
283
|
+
- Enviar passwords sem HTTPS em produção
|
|
284
|
+
|
|
285
|
+
## Related
|
|
286
|
+
|
|
287
|
+
- [Live Auth](./live-auth.md) - Autenticação para Live Components (WebSocket)
|
|
288
|
+
- [Routes with Eden Treaty](./routes-eden.md) - Criação de rotas type-safe
|
|
289
|
+
- [Environment Variables](../config/environment-vars.md) - Referência de variáveis
|
|
290
|
+
- [Troubleshooting](../reference/troubleshooting.md) - Problemas comuns
|