@riligar/auth-elysia 1.6.2 → 1.6.3
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/dist/index.esm.js +82 -341
- package/dist/index.js +82 -341
- package/package.json +1 -1
- package/src/index.js +82 -344
package/dist/index.js
CHANGED
|
@@ -6,21 +6,10 @@ require('elysia');
|
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* @module @riligar/auth-elysia
|
|
9
|
-
* @description Auth SDK for ElysiaJS
|
|
10
|
-
* @version See package.json
|
|
11
|
-
* @since 1.0.0
|
|
12
|
-
* @copyright 2024-2026 Riligar
|
|
13
|
-
*
|
|
14
|
-
* @license MIT
|
|
15
|
-
* @author Riligar
|
|
16
|
-
* @see https://github.com/riligar-solutions/auth
|
|
17
|
-
* @see https://www.npmjs.com/package/@riligar/auth-elysia
|
|
9
|
+
* @description Auth SDK for ElysiaJS
|
|
18
10
|
*/
|
|
19
11
|
|
|
20
12
|
|
|
21
|
-
/**
|
|
22
|
-
* Configuração padrão do plugin
|
|
23
|
-
*/
|
|
24
13
|
const DEFAULT_CONFIG = {
|
|
25
14
|
prefix: '/auth',
|
|
26
15
|
secretKey: process.env.AUTH_SECRET_KEY || 'your-secret-key',
|
|
@@ -30,392 +19,144 @@ const DEFAULT_CONFIG = {
|
|
|
30
19
|
httpOnly: true,
|
|
31
20
|
secure: process.env.NODE_ENV === 'production',
|
|
32
21
|
sameSite: 'lax',
|
|
33
|
-
maxAge: 604800,
|
|
22
|
+
maxAge: 604800,
|
|
34
23
|
},
|
|
35
24
|
excludePaths: ['/auth/login', '/auth/register', '/auth/session'],
|
|
36
25
|
onUnauthorized: set => {
|
|
37
26
|
set.status = 401;
|
|
38
|
-
return
|
|
27
|
+
return 'Sessão inválida ou expirada.'
|
|
39
28
|
},
|
|
40
29
|
};
|
|
41
30
|
|
|
42
|
-
/**
|
|
43
|
-
* Cliente Auth com verificação JWT local + JWKS
|
|
44
|
-
*/
|
|
45
31
|
class RiLiGarAuthClient {
|
|
46
32
|
constructor(baseUrl, secretKey) {
|
|
47
33
|
this.baseUrl = baseUrl;
|
|
48
34
|
this.secretKey = secretKey;
|
|
49
|
-
// 🚀 Cache para JWKS (chaves públicas)
|
|
50
35
|
this.jwksCache = null;
|
|
51
36
|
this.jwksCacheExpiry = 0;
|
|
52
|
-
this.jwksCacheTTL = 3600000; // 1 hora em ms
|
|
53
37
|
}
|
|
54
38
|
|
|
55
|
-
// 🔑 Buscar e cachear JWKS
|
|
56
39
|
async getJWKS() {
|
|
57
40
|
const now = Date.now();
|
|
58
|
-
|
|
59
|
-
// Retorna cache se ainda válido
|
|
60
|
-
if (this.jwksCache && now < this.jwksCacheExpiry) {
|
|
61
|
-
return this.jwksCache
|
|
62
|
-
}
|
|
63
|
-
|
|
41
|
+
if (this.jwksCache && now < this.jwksCacheExpiry) return this.jwksCache
|
|
64
42
|
try {
|
|
65
43
|
const response = await fetch(`${this.baseUrl}/.well-known/jwks.json`);
|
|
66
44
|
if (response.ok) {
|
|
67
45
|
this.jwksCache = await response.json();
|
|
68
|
-
this.jwksCacheExpiry = now +
|
|
46
|
+
this.jwksCacheExpiry = now + 3600000;
|
|
69
47
|
return this.jwksCache
|
|
70
48
|
}
|
|
71
|
-
} catch (
|
|
72
|
-
console.warn('JWKS fetch failed, falling back to remote verification:', error.message);
|
|
73
|
-
}
|
|
74
|
-
|
|
49
|
+
} catch (e) {}
|
|
75
50
|
return null
|
|
76
51
|
}
|
|
77
52
|
|
|
78
|
-
// ⚡ Verificação JWT local (usando crypto nativo do Bun)
|
|
79
53
|
async verifyJWTLocal(token) {
|
|
80
54
|
try {
|
|
81
55
|
const jwks = await this.getJWKS();
|
|
82
|
-
if (!jwks
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
const [headerB64] = token.split('.');
|
|
86
|
-
const header = JSON.parse(atob(headerB64));
|
|
87
|
-
|
|
88
|
-
// Encontrar a chave correspondente
|
|
56
|
+
if (!jwks) return null
|
|
57
|
+
const [h, p, s] = token.split('.');
|
|
58
|
+
const header = JSON.parse(atob(h));
|
|
89
59
|
const jwk = jwks.keys.find(k => k.kid === header.kid || k.alg === header.alg);
|
|
90
60
|
if (!jwk) return null
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
let key;
|
|
99
|
-
let algorithm;
|
|
100
|
-
|
|
101
|
-
// Suporte para diferentes algoritmos
|
|
102
|
-
if (header.alg === 'HS256' || jwk.kty === 'oct') {
|
|
103
|
-
// HMAC com secret key
|
|
104
|
-
const secret = new TextEncoder().encode(this.secretKey);
|
|
105
|
-
key = await crypto.subtle.importKey('raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
|
|
106
|
-
algorithm = 'HMAC';
|
|
107
|
-
} else if (header.alg === 'RS256' || jwk.kty === 'RSA') {
|
|
108
|
-
// RSA com chave pública JWKS
|
|
109
|
-
if (!jwk.n || !jwk.e) return null
|
|
110
|
-
|
|
111
|
-
// Converter base64url para ArrayBuffer
|
|
112
|
-
const nBuffer = this.base64urlToArrayBuffer(jwk.n);
|
|
113
|
-
const eBuffer = this.base64urlToArrayBuffer(jwk.e);
|
|
114
|
-
|
|
115
|
-
key = await crypto.subtle.importKey(
|
|
116
|
-
'jwk',
|
|
117
|
-
{
|
|
118
|
-
kty: 'RSA',
|
|
119
|
-
n: jwk.n,
|
|
120
|
-
e: jwk.e,
|
|
121
|
-
alg: 'RS256',
|
|
122
|
-
use: 'sig',
|
|
123
|
-
},
|
|
124
|
-
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
|
|
125
|
-
false,
|
|
126
|
-
['verify']
|
|
127
|
-
);
|
|
128
|
-
algorithm = 'RSASSA-PKCS1-v1_5';
|
|
61
|
+
const data = new TextEncoder().encode(`${h}.${p}`);
|
|
62
|
+
const sig = Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0));
|
|
63
|
+
let key, algo;
|
|
64
|
+
if (header.alg === 'HS256') {
|
|
65
|
+
key = await crypto.subtle.importKey('raw', new TextEncoder().encode(this.secretKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
|
|
66
|
+
algo = 'HMAC';
|
|
129
67
|
} else {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
// Verificar assinatura
|
|
135
|
-
const isValid = await crypto.subtle.verify(algorithm, key, signature, data);
|
|
136
|
-
if (!isValid) return null
|
|
137
|
-
|
|
138
|
-
// Decode payload
|
|
139
|
-
const payload = JSON.parse(atob(payloadB64Url));
|
|
140
|
-
|
|
141
|
-
// Verificar expiração
|
|
142
|
-
if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {
|
|
143
|
-
return null
|
|
68
|
+
key = await crypto.subtle.importKey('jwk', { kty: 'RSA', n: jwk.n, e: jwk.e, alg: 'RS256', use: 'sig' }, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']);
|
|
69
|
+
algo = 'RSASSA-PKCS1-v1_5';
|
|
144
70
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
return {
|
|
149
|
-
|
|
150
|
-
...payload,
|
|
151
|
-
}
|
|
152
|
-
} catch (error) {
|
|
153
|
-
console.warn('JWT local verification failed:', error.message);
|
|
71
|
+
if (!(await crypto.subtle.verify(algo, key, sig, data))) return null
|
|
72
|
+
const payload = JSON.parse(atob(p));
|
|
73
|
+
if (payload.exp && payload.exp < Date.now() / 1000) return null
|
|
74
|
+
return { id: payload.sub, ...payload }
|
|
75
|
+
} catch (e) {
|
|
154
76
|
return null
|
|
155
77
|
}
|
|
156
78
|
}
|
|
157
79
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
const padding = '='.repeat((4 - (base64.length % 4)) % 4);
|
|
162
|
-
const base64WithPadding = base64 + padding;
|
|
163
|
-
|
|
164
|
-
const binaryString = atob(base64WithPadding);
|
|
165
|
-
const bytes = new Uint8Array(binaryString.length);
|
|
166
|
-
for (let i = 0; i < binaryString.length; i++) {
|
|
167
|
-
bytes[i] = binaryString.charCodeAt(i);
|
|
168
|
-
}
|
|
169
|
-
return bytes.buffer
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
// ⚡ Verificar sessão OTIMIZADA (local + fallback remoto)
|
|
173
|
-
async verifySession(sessionToken) {
|
|
174
|
-
// 🚀 Primeira tentativa: Verificação local com JWKS
|
|
175
|
-
const localResult = await this.verifyJWTLocal(sessionToken);
|
|
176
|
-
if (localResult) {
|
|
177
|
-
return {
|
|
178
|
-
user: localResult,
|
|
179
|
-
verified_locally: true,
|
|
180
|
-
cached: true,
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// 🔄 Fallback: Verificação remota
|
|
80
|
+
async verifySession(token) {
|
|
81
|
+
const local = await this.verifyJWTLocal(token);
|
|
82
|
+
if (local) return { user: local }
|
|
185
83
|
try {
|
|
186
|
-
const
|
|
187
|
-
headers: {
|
|
188
|
-
Authorization: `Bearer ${sessionToken}`,
|
|
189
|
-
'X-API-Key': this.secretKey,
|
|
190
|
-
},
|
|
84
|
+
const res = await fetch(`${this.baseUrl}/auth/session`, {
|
|
85
|
+
headers: { Authorization: `Bearer ${token}`, 'X-API-Key': this.secretKey },
|
|
191
86
|
});
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
const result = await response.json();
|
|
195
|
-
return {
|
|
196
|
-
...result,
|
|
197
|
-
verified_locally: false,
|
|
198
|
-
cached: false,
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
} catch (error) {
|
|
202
|
-
console.warn('Remote session verification failed:', error.message);
|
|
203
|
-
}
|
|
204
|
-
|
|
87
|
+
if (res.ok) return await res.json()
|
|
88
|
+
} catch (e) {}
|
|
205
89
|
return null
|
|
206
90
|
}
|
|
207
91
|
}
|
|
208
92
|
|
|
209
|
-
/**
|
|
210
|
-
* Utilitário para fazer requisições HTTP
|
|
211
|
-
*/
|
|
212
93
|
async function fetchAuth(url, options = {}) {
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
...options,
|
|
220
|
-
});
|
|
221
|
-
|
|
222
|
-
if (!response.ok) {
|
|
223
|
-
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
return await response.json()
|
|
227
|
-
} catch (error) {
|
|
228
|
-
console.error('Auth fetch error:', error);
|
|
229
|
-
throw error
|
|
230
|
-
}
|
|
94
|
+
const res = await fetch(url, {
|
|
95
|
+
headers: { 'Content-Type': 'application/json', ...options.headers },
|
|
96
|
+
...options,
|
|
97
|
+
});
|
|
98
|
+
if (!res.ok) throw new Error(res.status)
|
|
99
|
+
return await res.json()
|
|
231
100
|
}
|
|
232
101
|
|
|
233
|
-
/**
|
|
234
|
-
* Plugin principal de autenticação
|
|
235
|
-
*/
|
|
236
102
|
function authPlugin(userConfig = {}) {
|
|
237
103
|
const config = { ...DEFAULT_CONFIG, ...userConfig };
|
|
238
|
-
|
|
239
|
-
// Instanciar cliente Auth
|
|
240
104
|
const authClient = new RiLiGarAuthClient(config.apiUrl, config.secretKey);
|
|
241
105
|
|
|
242
|
-
return app =>
|
|
243
|
-
app
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
try {
|
|
261
|
-
// ⚡ Verificação otimizada com JWKS local + fallback remoto
|
|
262
|
-
const userSession = await authClient.verifySession(token);
|
|
263
|
-
|
|
264
|
-
if (!userSession) {
|
|
265
|
-
return { user: null, authMeta: null }
|
|
106
|
+
return app =>
|
|
107
|
+
app
|
|
108
|
+
.derive({ as: 'global' }, async ({ request, cookie }) => {
|
|
109
|
+
const token = cookie[config.cookieName]?.value || request.headers.get('authorization')?.split(' ')[1];
|
|
110
|
+
if (!token) return { user: null }
|
|
111
|
+
const session = await authClient.verifySession(token);
|
|
112
|
+
return { user: session?.user || null }
|
|
113
|
+
})
|
|
114
|
+
.onBeforeHandle({ as: 'global' }, ({ user, set, request }) => {
|
|
115
|
+
const path = new URL(request.url).pathname;
|
|
116
|
+
if (config.excludePaths.some(p => path.startsWith(p))) return
|
|
117
|
+
if (!user) return config.onUnauthorized(set)
|
|
118
|
+
})
|
|
119
|
+
.error(({ error, set }) => {
|
|
120
|
+
if (String(error).includes('user.id') || String(error).includes('of null')) {
|
|
121
|
+
set.status = 401;
|
|
122
|
+
return 'Sessão inválida ou expirada.'
|
|
266
123
|
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
console.warn('Auth verification error:', error.message);
|
|
277
|
-
return { user: null, authMeta: null }
|
|
278
|
-
}
|
|
279
|
-
}).onBeforeHandle(({ user, set, request }) => {
|
|
280
|
-
const path = new URL(request.url).pathname;
|
|
281
|
-
|
|
282
|
-
// Verificar se a rota deve ser excluída da autenticação
|
|
283
|
-
const isExcluded = config.excludePaths.some(excluded => path.startsWith(excluded));
|
|
284
|
-
if (isExcluded) return
|
|
285
|
-
|
|
286
|
-
// Bloquear se não houver usuário
|
|
287
|
-
if (!user) {
|
|
288
|
-
return config.onUnauthorized(set)
|
|
289
|
-
}
|
|
290
|
-
});
|
|
291
|
-
|
|
292
|
-
return app.group(config.prefix, app =>
|
|
293
|
-
app
|
|
294
|
-
// Rota de login
|
|
295
|
-
.post('/login', async ({ body, set, cookie }) => {
|
|
296
|
-
try {
|
|
297
|
-
const { email, password } = body;
|
|
298
|
-
|
|
299
|
-
if (!email || !password) {
|
|
300
|
-
set.status = 400;
|
|
301
|
-
return { error: 'Email e senha são obrigatórios' }
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
const response = await fetchAuth(`${config.apiUrl}/auth/sign-in/email`, {
|
|
305
|
-
method: 'POST',
|
|
306
|
-
body: JSON.stringify({ email, password }),
|
|
307
|
-
headers: {
|
|
308
|
-
'X-API-Key': config.secretKey,
|
|
309
|
-
},
|
|
310
|
-
});
|
|
311
|
-
|
|
312
|
-
if (response.token) {
|
|
313
|
-
cookie[config.cookieName].set({
|
|
314
|
-
value: response.token,
|
|
315
|
-
...config.cookieOptions,
|
|
124
|
+
})
|
|
125
|
+
.group(config.prefix, app =>
|
|
126
|
+
app
|
|
127
|
+
.post('/login', async ({ body, set, cookie }) => {
|
|
128
|
+
try {
|
|
129
|
+
const res = await fetchAuth(`${config.apiUrl}/auth/sign-in/email`, {
|
|
130
|
+
method: 'POST',
|
|
131
|
+
body: JSON.stringify(body),
|
|
132
|
+
headers: { 'X-API-Key': config.secretKey },
|
|
316
133
|
});
|
|
134
|
+
cookie[config.cookieName].set({ value: res.token, ...config.cookieOptions });
|
|
135
|
+
return { message: 'OK', user: res.user, token: res.token }
|
|
136
|
+
} catch (e) {
|
|
137
|
+
set.status = 401;
|
|
138
|
+
return 'Falha no login.'
|
|
317
139
|
}
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
token: response.token,
|
|
323
|
-
session: response.session,
|
|
324
|
-
}
|
|
325
|
-
} catch (error) {
|
|
326
|
-
set.status = 401;
|
|
327
|
-
return { error: 'Login failed', message: error.message }
|
|
328
|
-
}
|
|
329
|
-
})
|
|
330
|
-
|
|
331
|
-
// Rota de registro
|
|
332
|
-
.post('/register', async ({ body, set }) => {
|
|
333
|
-
try {
|
|
334
|
-
const { email, password, name, organizationId } = body;
|
|
335
|
-
|
|
336
|
-
if (!email || !password || !name) {
|
|
337
|
-
set.status = 400;
|
|
338
|
-
return { error: 'Email, senha e nome são obrigatórios' }
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
const response = await fetchAuth(`${config.apiUrl}/auth/sign-up/email`, {
|
|
342
|
-
method: 'POST',
|
|
343
|
-
body: JSON.stringify({
|
|
344
|
-
email,
|
|
345
|
-
password,
|
|
346
|
-
name,
|
|
347
|
-
...(organizationId && { organizationId }),
|
|
348
|
-
}),
|
|
349
|
-
headers: {
|
|
350
|
-
'X-API-Key': config.secretKey,
|
|
351
|
-
},
|
|
352
|
-
});
|
|
353
|
-
|
|
354
|
-
return {
|
|
355
|
-
message: 'Usuário registrado com sucesso!',
|
|
356
|
-
user: {
|
|
357
|
-
id: response.user?.id,
|
|
358
|
-
email: response.user?.email,
|
|
359
|
-
name: response.user?.name,
|
|
360
|
-
},
|
|
361
|
-
}
|
|
362
|
-
} catch (error) {
|
|
363
|
-
set.status = 400;
|
|
364
|
-
return { error: 'Registration failed', message: error.message }
|
|
365
|
-
}
|
|
366
|
-
})
|
|
367
|
-
|
|
368
|
-
// Rota de logout
|
|
369
|
-
.post('/logout', async ({ cookie, set, headers }) => {
|
|
370
|
-
try {
|
|
371
|
-
const token = headers.authorization?.replace('Bearer ', '') || cookie[config.cookieName]?.value;
|
|
372
|
-
|
|
373
|
-
if (token) {
|
|
374
|
-
// Fazer logout no servidor de auth
|
|
375
|
-
await fetchAuth(`${config.apiUrl}/auth/sign-out`, {
|
|
140
|
+
})
|
|
141
|
+
.post('/register', async ({ body, set }) => {
|
|
142
|
+
try {
|
|
143
|
+
const res = await fetchAuth(`${config.apiUrl}/auth/sign-up/email`, {
|
|
376
144
|
method: 'POST',
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
'X-API-Key': config.secretKey,
|
|
380
|
-
},
|
|
381
|
-
}).catch(() => {
|
|
382
|
-
// Ignorar erros do logout remoto
|
|
145
|
+
body: JSON.stringify(body),
|
|
146
|
+
headers: { 'X-API-Key': config.secretKey },
|
|
383
147
|
});
|
|
148
|
+
return { message: 'OK', user: res.user }
|
|
149
|
+
} catch (e) {
|
|
150
|
+
set.status = 400;
|
|
151
|
+
return 'Falha no registro.'
|
|
384
152
|
}
|
|
385
|
-
|
|
386
|
-
|
|
153
|
+
})
|
|
154
|
+
.post('/logout', async ({ cookie }) => {
|
|
387
155
|
cookie[config.cookieName].remove();
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
return { error: 'Erro ao fazer logout', message: error.message }
|
|
393
|
-
}
|
|
394
|
-
})
|
|
395
|
-
|
|
396
|
-
// Verificar sessão (substitui o /refresh)
|
|
397
|
-
.get('/session', ({ user, authMeta, set }) => {
|
|
398
|
-
if (!user) {
|
|
399
|
-
set.status = 401;
|
|
400
|
-
return { error: 'Not authenticated' }
|
|
401
|
-
}
|
|
402
|
-
return {
|
|
403
|
-
user,
|
|
404
|
-
meta: authMeta,
|
|
405
|
-
verified_at: new Date().toISOString(),
|
|
406
|
-
}
|
|
407
|
-
})
|
|
408
|
-
|
|
409
|
-
// Status do usuário atual
|
|
410
|
-
.get('/me', ({ user, set }) => {
|
|
411
|
-
if (!user) {
|
|
412
|
-
set.status = 401;
|
|
413
|
-
return { error: 'Not authenticated' }
|
|
414
|
-
}
|
|
415
|
-
return { user }
|
|
416
|
-
})
|
|
417
|
-
)
|
|
418
|
-
}
|
|
156
|
+
return 'Sessão encerrada.'
|
|
157
|
+
})
|
|
158
|
+
.get('/me', ({ user, set }) => user || config.onUnauthorized(set))
|
|
159
|
+
)
|
|
419
160
|
}
|
|
420
161
|
|
|
421
162
|
exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
|