create-fluxstack 1.5.0 → 1.5.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 (50) hide show
  1. package/.env.example +1 -8
  2. package/app/client/src/App.tsx +1 -4
  3. package/app/server/index.ts +0 -4
  4. package/app/server/routes/index.ts +1 -5
  5. package/config/index.ts +1 -9
  6. package/core/cli/generators/plugin.ts +34 -324
  7. package/core/cli/generators/template-engine.ts +0 -5
  8. package/core/cli/plugin-discovery.ts +12 -33
  9. package/core/framework/server.ts +0 -10
  10. package/core/plugins/dependency-manager.ts +22 -89
  11. package/core/plugins/index.ts +0 -4
  12. package/core/plugins/manager.ts +2 -3
  13. package/core/plugins/registry.ts +1 -28
  14. package/core/utils/logger/index.ts +0 -4
  15. package/core/utils/version.ts +1 -1
  16. package/fluxstack.config.ts +114 -253
  17. package/package.json +117 -117
  18. package/CRYPTO-AUTH-MIDDLEWARE-GUIDE.md +0 -475
  19. package/CRYPTO-AUTH-MIDDLEWARES.md +0 -473
  20. package/CRYPTO-AUTH-USAGE.md +0 -491
  21. package/EXEMPLO-ROTA-PROTEGIDA.md +0 -347
  22. package/QUICK-START-CRYPTO-AUTH.md +0 -221
  23. package/app/client/src/pages/CryptoAuthPage.tsx +0 -394
  24. package/app/server/routes/crypto-auth-demo.routes.ts +0 -167
  25. package/app/server/routes/example-with-crypto-auth.routes.ts +0 -235
  26. package/app/server/routes/exemplo-posts.routes.ts +0 -161
  27. package/core/plugins/module-resolver.ts +0 -216
  28. package/plugins/crypto-auth/README.md +0 -788
  29. package/plugins/crypto-auth/ai-context.md +0 -1282
  30. package/plugins/crypto-auth/cli/make-protected-route.command.ts +0 -383
  31. package/plugins/crypto-auth/client/CryptoAuthClient.ts +0 -302
  32. package/plugins/crypto-auth/client/components/AuthProvider.tsx +0 -131
  33. package/plugins/crypto-auth/client/components/LoginButton.tsx +0 -138
  34. package/plugins/crypto-auth/client/components/ProtectedRoute.tsx +0 -89
  35. package/plugins/crypto-auth/client/components/index.ts +0 -12
  36. package/plugins/crypto-auth/client/index.ts +0 -12
  37. package/plugins/crypto-auth/config/index.ts +0 -34
  38. package/plugins/crypto-auth/index.ts +0 -162
  39. package/plugins/crypto-auth/package.json +0 -66
  40. package/plugins/crypto-auth/server/AuthMiddleware.ts +0 -181
  41. package/plugins/crypto-auth/server/CryptoAuthService.ts +0 -186
  42. package/plugins/crypto-auth/server/index.ts +0 -22
  43. package/plugins/crypto-auth/server/middlewares/cryptoAuthAdmin.ts +0 -65
  44. package/plugins/crypto-auth/server/middlewares/cryptoAuthOptional.ts +0 -26
  45. package/plugins/crypto-auth/server/middlewares/cryptoAuthPermissions.ts +0 -76
  46. package/plugins/crypto-auth/server/middlewares/cryptoAuthRequired.ts +0 -45
  47. package/plugins/crypto-auth/server/middlewares/helpers.ts +0 -140
  48. package/plugins/crypto-auth/server/middlewares/index.ts +0 -22
  49. package/plugins/crypto-auth/server/middlewares.ts +0 -19
  50. package/test-crypto-auth.ts +0 -101
@@ -1,491 +0,0 @@
1
- # 🔐 Como Usar Crypto Auth no Servidor
2
-
3
- ## 📋 Índice
4
- 1. [Middlewares Disponíveis](#middlewares-disponíveis)
5
- 2. [Uso Básico](#uso-básico)
6
- 3. [Acessar Dados do Usuário](#acessar-dados-do-usuário)
7
- 4. [Verificar Permissões](#verificar-permissões)
8
- 5. [Exemplos Completos](#exemplos-completos)
9
- 6. [Helper Functions](#helper-functions)
10
-
11
- ---
12
-
13
- ## 🚀 Middlewares Disponíveis
14
-
15
- ### 1️⃣ `cryptoAuthRequired()` - Requer Autenticação
16
-
17
- Valida assinatura e **bloqueia** acesso se não autenticado.
18
-
19
- ```typescript
20
- import { cryptoAuthRequired, getCryptoAuthUser } from '@/plugins/crypto-auth/server'
21
-
22
- export const protectedRoutes = new Elysia()
23
- .use(cryptoAuthRequired()) // ✅ Todas as rotas protegidas
24
-
25
- .get('/profile', ({ request }) => {
26
- const user = getCryptoAuthUser(request)!
27
- return {
28
- publicKey: user.publicKey,
29
- isAdmin: user.isAdmin,
30
- permissions: user.permissions
31
- }
32
- })
33
- ```
34
-
35
- **Retorno se não autenticado**: `401 Unauthorized`
36
-
37
- ---
38
-
39
- ### 2️⃣ `cryptoAuthAdmin()` - Requer Admin
40
-
41
- Valida autenticação E verifica se usuário é admin.
42
-
43
- ```typescript
44
- import { cryptoAuthAdmin } from '@/plugins/crypto-auth/server'
45
-
46
- export const adminRoutes = new Elysia()
47
- .use(cryptoAuthAdmin()) // ✅ Apenas admins
48
-
49
- .get('/admin/stats', () => ({
50
- totalUsers: 100,
51
- systemHealth: 'optimal'
52
- }))
53
-
54
- .delete('/admin/users/:id', ({ params }) => ({
55
- deleted: params.id
56
- }))
57
- ```
58
-
59
- **Retorno se não for admin**: `403 Forbidden`
60
-
61
- ---
62
-
63
- ### 3️⃣ `cryptoAuthPermissions(permissions)` - Requer Permissões
64
-
65
- Valida autenticação E verifica permissões específicas.
66
-
67
- ```typescript
68
- import { cryptoAuthPermissions } from '@/plugins/crypto-auth/server'
69
-
70
- export const writeRoutes = new Elysia()
71
- .use(cryptoAuthPermissions(['write'])) // ✅ Requer permissão 'write'
72
-
73
- .put('/posts/:id', ({ params, body }) => ({
74
- updated: params.id,
75
- data: body
76
- }))
77
- ```
78
-
79
- **Múltiplas permissões**:
80
- ```typescript
81
- .use(cryptoAuthPermissions(['write', 'publish']))
82
- ```
83
-
84
- ---
85
-
86
- ### 4️⃣ `cryptoAuthOptional()` - Autenticação Opcional
87
-
88
- Adiciona `user` se autenticado, mas **NÃO bloqueia** se não autenticado.
89
-
90
- ```typescript
91
- import { cryptoAuthOptional, getCryptoAuthUser } from '@/plugins/crypto-auth/server'
92
-
93
- export const mixedRoutes = new Elysia()
94
- .use(cryptoAuthOptional()) // ✅ Opcional
95
-
96
- .get('/posts/:id', ({ request, params }) => {
97
- const user = getCryptoAuthUser(request)
98
-
99
- return {
100
- post: {
101
- id: params.id,
102
- title: 'Post Title',
103
- // Conteúdo completo apenas se autenticado
104
- content: user ? 'Full content...' : 'Preview...'
105
- },
106
- viewer: user ? {
107
- publicKey: user.publicKey,
108
- canEdit: user.isAdmin
109
- } : null
110
- }
111
- })
112
- ```
113
-
114
- ---
115
-
116
- ## 🛠️ Uso Básico
117
-
118
- ### Aplicar Middleware a Todas as Rotas
119
-
120
- ```typescript
121
- import { Elysia } from 'elysia'
122
- import { cryptoAuthRequired } from '@/plugins/crypto-auth/server'
123
-
124
- export const myRoutes = new Elysia()
125
- // ✅ Aplica autenticação a todas as rotas
126
- .use(cryptoAuthRequired())
127
-
128
- .get('/users', ({ request }) => {
129
- const user = (request as any).user
130
- return { users: [], requestedBy: user.publicKey }
131
- })
132
-
133
- .post('/users', ({ request, body }) => {
134
- const user = (request as any).user
135
- return { created: body, by: user.publicKey }
136
- })
137
- ```
138
-
139
- ---
140
-
141
- ### Aplicar a Grupos Específicos
142
-
143
- ```typescript
144
- export const apiRoutes = new Elysia()
145
- // Rotas públicas
146
- .get('/health', () => ({ status: 'ok' }))
147
- .get('/posts', () => ({ posts: [] }))
148
-
149
- // Grupo protegido
150
- .group('/users', (app) => app
151
- .use(cryptoAuthRequired())
152
- .get('/', () => ({ users: [] }))
153
- .post('/', ({ body }) => ({ created: body }))
154
- )
155
-
156
- // Grupo admin
157
- .group('/admin', (app) => app
158
- .use(cryptoAuthAdmin())
159
- .get('/stats', () => ({ stats: {} }))
160
- )
161
- ```
162
-
163
- ---
164
-
165
- ## 📦 Acessar Dados do Usuário
166
-
167
- ### Interface `CryptoAuthUser`
168
-
169
- ```typescript
170
- interface CryptoAuthUser {
171
- publicKey: string // Chave pública (ID único)
172
- isAdmin: boolean // Se é admin
173
- permissions: string[] // [\"read\"] ou [\"admin\", \"read\", \"write\", \"delete\"]
174
- }
175
- ```
176
-
177
- ### Acessar no Handler
178
-
179
- ```typescript
180
- import { getCryptoAuthUser } from '@/plugins/crypto-auth/server'
181
-
182
- .get('/me', ({ request }) => {
183
- const user = getCryptoAuthUser(request)! // ! porque já passou pelo middleware
184
-
185
- return {
186
- id: user.publicKey,
187
- isAdmin: user.isAdmin,
188
- permissions: user.permissions
189
- }
190
- })
191
- ```
192
-
193
- ---
194
-
195
- ## 🔒 Verificar Permissões
196
-
197
- ### Verificar se é Admin
198
-
199
- ```typescript
200
- import { isCryptoAuthAdmin } from '@/plugins/crypto-auth/server'
201
-
202
- .delete('/posts/:id', ({ request, params, set }) => {
203
- if (!isCryptoAuthAdmin(request)) {
204
- set.status = 403
205
- return { error: 'Admin only' }
206
- }
207
-
208
- return { deleted: params.id }
209
- })
210
- ```
211
-
212
- ---
213
-
214
- ### Verificar Permissão Específica
215
-
216
- ```typescript
217
- import { hasCryptoAuthPermission } from '@/plugins/crypto-auth/server'
218
-
219
- .put('/posts/:id', ({ request, params, set }) => {
220
- if (!hasCryptoAuthPermission(request, 'write')) {
221
- set.status = 403
222
- return { error: 'Write permission required' }
223
- }
224
-
225
- return { updated: params.id }
226
- })
227
- ```
228
-
229
- ---
230
-
231
- ## 🎯 Exemplos Completos
232
-
233
- ### Exemplo 1: CRUD de Posts
234
-
235
- ```typescript
236
- import { Elysia, t } from 'elysia'
237
- import {
238
- cryptoAuthRequired,
239
- cryptoAuthAdmin,
240
- cryptoAuthOptional,
241
- getCryptoAuthUser
242
- } from '@/plugins/crypto-auth/server'
243
-
244
- export const postsRoutes = new Elysia()
245
-
246
- // ✅ PÚBLICO - Listar posts
247
- .get('/posts', () => ({
248
- posts: [
249
- { id: 1, title: 'Post 1', author: 'João' },
250
- { id: 2, title: 'Post 2', author: 'Maria' }
251
- ]
252
- }))
253
-
254
- // 🔒 PROTEGIDO - Criar post
255
- .post('/posts', ({ request, body }) => {
256
- const user = getCryptoAuthUser(request)!
257
- const { title, content } = body as { title: string; content: string }
258
-
259
- return {
260
- success: true,
261
- post: {
262
- title,
263
- content,
264
- author: user.publicKey,
265
- createdAt: new Date()
266
- }
267
- }
268
- }, {
269
- body: t.Object({
270
- title: t.String(),
271
- content: t.String()
272
- })
273
- })
274
- .use(cryptoAuthRequired()) // Aplica apenas ao .post acima
275
-
276
- // 🔒 ADMIN - Deletar post
277
- .delete('/posts/:id', ({ params }) => ({
278
- success: true,
279
- message: `Post ${params.id} deletado`
280
- }))
281
- .use(cryptoAuthAdmin()) // Aplica apenas ao .delete acima
282
- ```
283
-
284
- ---
285
-
286
- ### Exemplo 2: Rotas Condicionais
287
-
288
- ```typescript
289
- export const mixedRoutes = new Elysia()
290
- .use(cryptoAuthOptional())
291
-
292
- .get('/posts/:id', ({ request, params }) => {
293
- const user = getCryptoAuthUser(request)
294
-
295
- // Post básico (público)
296
- const post = {
297
- id: params.id,
298
- title: 'Título do Post',
299
- excerpt: 'Prévia do conteúdo...'
300
- }
301
-
302
- // Se autenticado, retorna conteúdo completo
303
- if (user) {
304
- return {
305
- ...post,
306
- fullContent: 'Conteúdo completo do post...',
307
- comments: [/* comentários */],
308
- viewer: {
309
- publicKey: user.publicKey,
310
- canEdit: user.isAdmin
311
- }
312
- }
313
- }
314
-
315
- // Se não autenticado, apenas prévia
316
- return post
317
- })
318
- ```
319
-
320
- ---
321
-
322
- ### Exemplo 3: Middleware Cascata
323
-
324
- ```typescript
325
- export const routes = new Elysia()
326
- // Aplica a todas as rotas
327
- .use(cryptoAuthRequired())
328
-
329
- .get('/profile', () => ({ profile: {} }))
330
-
331
- // Sub-grupo com restrição adicional
332
- .group('/admin', (app) => app
333
- .use(cryptoAuthAdmin()) // Admin adicional ao required
334
- .get('/users', () => ({ users: [] }))
335
- )
336
- ```
337
-
338
- ---
339
-
340
- ## 🛠️ Helper Functions
341
-
342
- ### `getCryptoAuthUser(request)` - Obter Usuário
343
-
344
- ```typescript
345
- import { getCryptoAuthUser } from '@/plugins/crypto-auth/server'
346
-
347
- .get('/me', ({ request }) => {
348
- const user = getCryptoAuthUser(request)
349
-
350
- if (!user) {
351
- return { error: 'Not authenticated' }
352
- }
353
-
354
- return { user }
355
- })
356
- ```
357
-
358
- ---
359
-
360
- ### `isCryptoAuthAuthenticated(request)` - Verificar se Autenticado
361
-
362
- ```typescript
363
- import { isCryptoAuthAuthenticated } from '@/plugins/crypto-auth/server'
364
-
365
- .get('/posts/:id', ({ request, params }) => {
366
- const isAuth = isCryptoAuthAuthenticated(request)
367
-
368
- return {
369
- post: { id: params.id },
370
- canComment: isAuth
371
- }
372
- })
373
- ```
374
-
375
- ---
376
-
377
- ### `isCryptoAuthAdmin(request)` - Verificar se é Admin
378
-
379
- ```typescript
380
- import { isCryptoAuthAdmin } from '@/plugins/crypto-auth/server'
381
-
382
- .get('/posts/:id', ({ request, params, set }) => {
383
- if (!isCryptoAuthAdmin(request)) {
384
- set.status = 403
385
- return { error: 'Admin only' }
386
- }
387
-
388
- return { post: params.id }
389
- })
390
- ```
391
-
392
- ---
393
-
394
- ### `hasCryptoAuthPermission(request, permission)` - Verificar Permissão
395
-
396
- ```typescript
397
- import { hasCryptoAuthPermission } from '@/plugins/crypto-auth/server'
398
-
399
- .put('/posts/:id', ({ request, params, set }) => {
400
- if (!hasCryptoAuthPermission(request, 'write')) {
401
- set.status = 403
402
- return { error: 'Write permission required' }
403
- }
404
-
405
- return { updated: params.id }
406
- })
407
- ```
408
-
409
- ---
410
-
411
- ## 🔍 Debugging
412
-
413
- ### Log de Autenticação
414
-
415
- ```typescript
416
- import { cryptoAuthRequired } from '@/plugins/crypto-auth/server'
417
-
418
- export const routes = new Elysia()
419
- .use(cryptoAuthRequired({
420
- logger: yourLogger // ✅ Passar logger para debug
421
- }))
422
-
423
- .get('/users', ({ request }) => {
424
- const user = (request as any).user
425
- console.log('User:', user)
426
- return { users: [] }
427
- })
428
- ```
429
-
430
- ---
431
-
432
- ### Rota de Debug
433
-
434
- ```typescript
435
- export const debugRoutes = new Elysia()
436
- .use(cryptoAuthOptional())
437
-
438
- .get('/debug/auth', ({ request }) => {
439
- const user = getCryptoAuthUser(request)
440
-
441
- return {
442
- authenticated: !!user,
443
- user: user || null,
444
- headers: {
445
- publicKey: request.headers.get('x-public-key'),
446
- timestamp: request.headers.get('x-timestamp'),
447
- nonce: request.headers.get('x-nonce'),
448
- signature: request.headers.get('x-signature')?.substring(0, 16) + '...'
449
- }
450
- }
451
- })
452
- ```
453
-
454
- ---
455
-
456
- ## ⚠️ Importante
457
-
458
- 1. **Ordem importa**: Aplique middlewares antes de definir rotas
459
- ```typescript
460
- .use(cryptoAuthRequired()) // ✅ Primeiro
461
- .get('/users', ...) // ✅ Depois
462
- ```
463
-
464
- 2. **Grupos herdam middlewares**:
465
- ```typescript
466
- .use(cryptoAuthRequired())
467
- .group('/api', ...) // ✅ Herda cryptoAuthRequired
468
- ```
469
-
470
- 3. **User object sempre disponível**: Em rotas com `cryptoAuthRequired`, `cryptoAuthAdmin` ou `cryptoAuthPermissions`
471
-
472
- 4. **Null check necessário**: Em rotas com `cryptoAuthOptional`:
473
- ```typescript
474
- const user = getCryptoAuthUser(request)
475
- if (user) { // ✅ Verificar antes de usar
476
- ...
477
- }
478
- ```
479
-
480
- ---
481
-
482
- ## 📚 Ver Mais
483
-
484
- - **Documentação completa de middlewares**: `CRYPTO-AUTH-MIDDLEWARES.md`
485
- - **Exemplo completo**: `app/server/routes/example-with-crypto-auth.routes.ts`
486
- - **Documentação AI**: `plugins/crypto-auth/ai-context.md`
487
- - **Demo rotas**: `app/server/routes/crypto-auth-demo.routes.ts`
488
-
489
- ---
490
-
491
- **Última atualização**: Janeiro 2025