create-fluxstack 1.5.2 → 1.5.4
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/.env.example +8 -1
- package/CRYPTO-AUTH-MIDDLEWARE-GUIDE.md +475 -0
- package/CRYPTO-AUTH-MIDDLEWARES.md +473 -0
- package/CRYPTO-AUTH-USAGE.md +491 -0
- package/EXEMPLO-ROTA-PROTEGIDA.md +347 -0
- package/QUICK-START-CRYPTO-AUTH.md +221 -0
- package/app/client/src/App.tsx +4 -1
- package/app/client/src/pages/CryptoAuthPage.tsx +394 -0
- package/app/server/index.ts +4 -0
- package/app/server/live/FluxStackConfig.ts +1 -1
- package/app/server/routes/crypto-auth-demo.routes.ts +167 -0
- package/app/server/routes/example-with-crypto-auth.routes.ts +235 -0
- package/app/server/routes/exemplo-posts.routes.ts +161 -0
- package/app/server/routes/index.ts +5 -1
- package/config/index.ts +9 -1
- package/core/cli/generators/plugin.ts +324 -34
- package/core/cli/generators/template-engine.ts +5 -0
- package/core/cli/plugin-discovery.ts +33 -12
- package/core/framework/server.ts +10 -0
- package/core/plugins/dependency-manager.ts +89 -22
- package/core/plugins/index.ts +4 -0
- package/core/plugins/manager.ts +3 -2
- package/core/plugins/module-resolver.ts +216 -0
- package/core/plugins/registry.ts +28 -1
- package/core/templates/create-project.ts +7 -0
- package/core/utils/logger/index.ts +4 -0
- package/core/utils/version.ts +1 -1
- package/fluxstack.config.ts +253 -114
- package/package.json +3 -3
- package/plugins/crypto-auth/README.md +788 -0
- package/plugins/crypto-auth/ai-context.md +1282 -0
- package/plugins/crypto-auth/cli/make-protected-route.command.ts +383 -0
- package/plugins/crypto-auth/client/CryptoAuthClient.ts +302 -0
- package/plugins/crypto-auth/client/components/AuthProvider.tsx +131 -0
- package/plugins/crypto-auth/client/components/LoginButton.tsx +138 -0
- package/plugins/crypto-auth/client/components/ProtectedRoute.tsx +89 -0
- package/plugins/crypto-auth/client/components/index.ts +12 -0
- package/plugins/crypto-auth/client/index.ts +12 -0
- package/plugins/crypto-auth/config/index.ts +34 -0
- package/plugins/crypto-auth/index.ts +162 -0
- package/plugins/crypto-auth/package.json +66 -0
- package/plugins/crypto-auth/server/AuthMiddleware.ts +181 -0
- package/plugins/crypto-auth/server/CryptoAuthService.ts +186 -0
- package/plugins/crypto-auth/server/index.ts +22 -0
- package/plugins/crypto-auth/server/middlewares/cryptoAuthAdmin.ts +65 -0
- package/plugins/crypto-auth/server/middlewares/cryptoAuthOptional.ts +26 -0
- package/plugins/crypto-auth/server/middlewares/cryptoAuthPermissions.ts +76 -0
- package/plugins/crypto-auth/server/middlewares/cryptoAuthRequired.ts +45 -0
- package/plugins/crypto-auth/server/middlewares/helpers.ts +140 -0
- package/plugins/crypto-auth/server/middlewares/index.ts +22 -0
- package/plugins/crypto-auth/server/middlewares.ts +19 -0
- package/test-crypto-auth.ts +101 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crypto Auth Middleware Helpers
|
|
3
|
+
* Funções compartilhadas para validação de autenticação
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { Logger } from '@/core/utils/logger'
|
|
7
|
+
|
|
8
|
+
export interface CryptoAuthUser {
|
|
9
|
+
publicKey: string
|
|
10
|
+
isAdmin: boolean
|
|
11
|
+
permissions: string[]
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Get auth service from global
|
|
16
|
+
*/
|
|
17
|
+
export function getAuthService() {
|
|
18
|
+
const service = (global as any).cryptoAuthService
|
|
19
|
+
if (!service) {
|
|
20
|
+
throw new Error('CryptoAuthService not initialized. Make sure crypto-auth plugin is loaded.')
|
|
21
|
+
}
|
|
22
|
+
return service
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Get auth middleware from global
|
|
27
|
+
*/
|
|
28
|
+
export function getAuthMiddleware() {
|
|
29
|
+
const middleware = (global as any).cryptoAuthMiddleware
|
|
30
|
+
if (!middleware) {
|
|
31
|
+
throw new Error('AuthMiddleware not initialized. Make sure crypto-auth plugin is loaded.')
|
|
32
|
+
}
|
|
33
|
+
return middleware
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Extract and validate authentication from request
|
|
38
|
+
* Versão SÍNCRONA para evitar problemas com Elysia
|
|
39
|
+
*/
|
|
40
|
+
export function extractAuthHeaders(request: Request): {
|
|
41
|
+
publicKey: string
|
|
42
|
+
timestamp: number
|
|
43
|
+
nonce: string
|
|
44
|
+
signature: string
|
|
45
|
+
} | null {
|
|
46
|
+
const headers = request.headers
|
|
47
|
+
const publicKey = headers.get('x-public-key')
|
|
48
|
+
const timestampStr = headers.get('x-timestamp')
|
|
49
|
+
const nonce = headers.get('x-nonce')
|
|
50
|
+
const signature = headers.get('x-signature')
|
|
51
|
+
|
|
52
|
+
if (!publicKey || !timestampStr || !nonce || !signature) {
|
|
53
|
+
return null
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const timestamp = parseInt(timestampStr, 10)
|
|
57
|
+
if (isNaN(timestamp)) {
|
|
58
|
+
return null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return { publicKey, timestamp, nonce, signature }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Build message for signature verification
|
|
66
|
+
*/
|
|
67
|
+
export function buildMessage(request: Request): string {
|
|
68
|
+
const url = new URL(request.url)
|
|
69
|
+
return `${request.method}:${url.pathname}`
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Validate authentication synchronously
|
|
74
|
+
*/
|
|
75
|
+
export async function validateAuthSync(request: Request, logger?: Logger): Promise<{
|
|
76
|
+
success: boolean
|
|
77
|
+
user?: CryptoAuthUser
|
|
78
|
+
error?: string
|
|
79
|
+
}> {
|
|
80
|
+
try {
|
|
81
|
+
const authHeaders = extractAuthHeaders(request)
|
|
82
|
+
|
|
83
|
+
if (!authHeaders) {
|
|
84
|
+
return {
|
|
85
|
+
success: false,
|
|
86
|
+
error: 'Missing authentication headers'
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const authService = getAuthService()
|
|
91
|
+
const message = buildMessage(request)
|
|
92
|
+
|
|
93
|
+
const result = await authService.validateRequest({
|
|
94
|
+
publicKey: authHeaders.publicKey,
|
|
95
|
+
timestamp: authHeaders.timestamp,
|
|
96
|
+
nonce: authHeaders.nonce,
|
|
97
|
+
signature: authHeaders.signature,
|
|
98
|
+
message
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
return result
|
|
102
|
+
} catch (error) {
|
|
103
|
+
logger?.error('Auth validation error', { error })
|
|
104
|
+
return {
|
|
105
|
+
success: false,
|
|
106
|
+
error: error instanceof Error ? error.message : 'Unknown error'
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Helper: Obter usuário autenticado do request
|
|
113
|
+
*/
|
|
114
|
+
export function getCryptoAuthUser(request: Request): CryptoAuthUser | null {
|
|
115
|
+
return (request as any).user || null
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Helper: Verificar se request está autenticado
|
|
120
|
+
*/
|
|
121
|
+
export function isCryptoAuthAuthenticated(request: Request): boolean {
|
|
122
|
+
return !!(request as any).user
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Helper: Verificar se usuário é admin
|
|
127
|
+
*/
|
|
128
|
+
export function isCryptoAuthAdmin(request: Request): boolean {
|
|
129
|
+
const user = getCryptoAuthUser(request)
|
|
130
|
+
return user?.isAdmin || false
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Helper: Verificar se usuário tem permissão específica
|
|
135
|
+
*/
|
|
136
|
+
export function hasCryptoAuthPermission(request: Request, permission: string): boolean {
|
|
137
|
+
const user = getCryptoAuthUser(request)
|
|
138
|
+
if (!user) return false
|
|
139
|
+
return user.permissions.includes(permission) || user.permissions.includes('admin')
|
|
140
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crypto Auth Middlewares
|
|
3
|
+
* Exports centralizados de todos os middlewares
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// Middlewares
|
|
7
|
+
export { cryptoAuthRequired } from './cryptoAuthRequired'
|
|
8
|
+
export { cryptoAuthAdmin } from './cryptoAuthAdmin'
|
|
9
|
+
export { cryptoAuthOptional } from './cryptoAuthOptional'
|
|
10
|
+
export { cryptoAuthPermissions } from './cryptoAuthPermissions'
|
|
11
|
+
|
|
12
|
+
// Helpers
|
|
13
|
+
export {
|
|
14
|
+
getCryptoAuthUser,
|
|
15
|
+
isCryptoAuthAuthenticated,
|
|
16
|
+
isCryptoAuthAdmin,
|
|
17
|
+
hasCryptoAuthPermission,
|
|
18
|
+
type CryptoAuthUser
|
|
19
|
+
} from './helpers'
|
|
20
|
+
|
|
21
|
+
// Types
|
|
22
|
+
export type { CryptoAuthMiddlewareOptions } from './cryptoAuthRequired'
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crypto Auth Middlewares
|
|
3
|
+
* Middlewares Elysia para autenticação criptográfica
|
|
4
|
+
*
|
|
5
|
+
* Uso:
|
|
6
|
+
* ```typescript
|
|
7
|
+
* import { cryptoAuthRequired, cryptoAuthAdmin } from '@/plugins/crypto-auth/server'
|
|
8
|
+
*
|
|
9
|
+
* export const myRoutes = new Elysia()
|
|
10
|
+
* .use(cryptoAuthRequired())
|
|
11
|
+
* .get('/protected', ({ request }) => {
|
|
12
|
+
* const user = getCryptoAuthUser(request)
|
|
13
|
+
* return { user }
|
|
14
|
+
* })
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
// Re-export tudo do módulo middlewares
|
|
19
|
+
export * from './middlewares/index'
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Script de teste para validar autenticação criptográfica
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { ed25519 } from '@noble/curves/ed25519'
|
|
6
|
+
import { sha256 } from '@noble/hashes/sha256'
|
|
7
|
+
import { bytesToHex, hexToBytes } from '@noble/hashes/utils'
|
|
8
|
+
|
|
9
|
+
async function testCryptoAuth() {
|
|
10
|
+
console.log('🔐 Testando Autenticação Criptográfica Ed25519\n')
|
|
11
|
+
|
|
12
|
+
// 1. Gerar par de chaves
|
|
13
|
+
console.log('1️⃣ Gerando par de chaves Ed25519...')
|
|
14
|
+
const privateKey = ed25519.utils.randomPrivateKey()
|
|
15
|
+
const publicKeyBytes = ed25519.getPublicKey(privateKey)
|
|
16
|
+
const publicKey = bytesToHex(publicKeyBytes)
|
|
17
|
+
const privateKeyHex = bytesToHex(privateKey)
|
|
18
|
+
|
|
19
|
+
console.log(` ✅ Chave pública: ${publicKey.substring(0, 16)}...`)
|
|
20
|
+
console.log(` ✅ Chave privada: ${privateKeyHex.substring(0, 16)}... (NUNCA enviar ao servidor!)\n`)
|
|
21
|
+
|
|
22
|
+
// 2. Preparar requisição
|
|
23
|
+
console.log('2️⃣ Preparando requisição assinada...')
|
|
24
|
+
const url = '/api/crypto-auth/protected'
|
|
25
|
+
const method = 'GET'
|
|
26
|
+
const timestamp = Date.now()
|
|
27
|
+
const nonce = generateNonce()
|
|
28
|
+
|
|
29
|
+
// 3. Construir mensagem para assinar
|
|
30
|
+
const message = `${method}:${url}`
|
|
31
|
+
const fullMessage = `${publicKey}:${timestamp}:${nonce}:${message}`
|
|
32
|
+
|
|
33
|
+
console.log(` 📝 Mensagem: ${fullMessage.substring(0, 50)}...\n`)
|
|
34
|
+
|
|
35
|
+
// 4. Assinar mensagem
|
|
36
|
+
console.log('3️⃣ Assinando mensagem com chave privada...')
|
|
37
|
+
const messageHash = sha256(new TextEncoder().encode(fullMessage))
|
|
38
|
+
const signatureBytes = ed25519.sign(messageHash, privateKey)
|
|
39
|
+
const signature = bytesToHex(signatureBytes)
|
|
40
|
+
|
|
41
|
+
console.log(` ✅ Assinatura: ${signature.substring(0, 32)}...\n`)
|
|
42
|
+
|
|
43
|
+
// 5. Fazer requisição ao servidor
|
|
44
|
+
console.log('4️⃣ Enviando requisição ao servidor...')
|
|
45
|
+
const response = await fetch('http://localhost:3000/api/crypto-auth/protected', {
|
|
46
|
+
method: 'GET',
|
|
47
|
+
headers: {
|
|
48
|
+
'x-public-key': publicKey,
|
|
49
|
+
'x-timestamp': timestamp.toString(),
|
|
50
|
+
'x-nonce': nonce,
|
|
51
|
+
'x-signature': signature
|
|
52
|
+
}
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
const data = await response.json()
|
|
56
|
+
|
|
57
|
+
console.log(` 📡 Status: ${response.status}`)
|
|
58
|
+
console.log(` 📦 Resposta:`, JSON.stringify(data, null, 2))
|
|
59
|
+
|
|
60
|
+
if (data.success) {
|
|
61
|
+
console.log('\n✅ SUCESSO! Assinatura validada corretamente pelo servidor!')
|
|
62
|
+
console.log(` 👤 Dados protegidos recebidos: ${data.data?.secretInfo}`)
|
|
63
|
+
} else {
|
|
64
|
+
console.log('\n❌ ERRO! Assinatura rejeitada pelo servidor')
|
|
65
|
+
console.log(` ⚠️ Erro: ${data.error}`)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// 6. Testar replay attack (reutilizar mesma assinatura)
|
|
69
|
+
console.log('\n5️⃣ Testando proteção contra replay attack...')
|
|
70
|
+
const replayResponse = await fetch('http://localhost:3000/api/crypto-auth/protected', {
|
|
71
|
+
method: 'GET',
|
|
72
|
+
headers: {
|
|
73
|
+
'x-public-key': publicKey,
|
|
74
|
+
'x-timestamp': timestamp.toString(),
|
|
75
|
+
'x-nonce': nonce, // Mesmo nonce
|
|
76
|
+
'x-signature': signature // Mesma assinatura
|
|
77
|
+
}
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
const replayData = await replayResponse.json()
|
|
81
|
+
|
|
82
|
+
console.log(` 📡 Replay Status: ${replayResponse.status}`)
|
|
83
|
+
console.log(` 📦 Replay Response:`, JSON.stringify(replayData, null, 2))
|
|
84
|
+
|
|
85
|
+
if (!replayData.success && replayData.error?.includes('nonce')) {
|
|
86
|
+
console.log(' ✅ Proteção funcionando! Replay attack bloqueado.')
|
|
87
|
+
} else if (replayResponse.status === 401) {
|
|
88
|
+
console.log(' ✅ Proteção funcionando! Replay attack bloqueado (status 401).')
|
|
89
|
+
} else {
|
|
90
|
+
console.log(' ⚠️ ATENÇÃO: Replay attack NÃO foi bloqueado!')
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function generateNonce(): string {
|
|
95
|
+
const bytes = new Uint8Array(16)
|
|
96
|
+
crypto.getRandomValues(bytes)
|
|
97
|
+
return bytesToHex(bytes)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Executar teste
|
|
101
|
+
testCryptoAuth().catch(console.error)
|