@riligar/auth-elysia 1.6.1 → 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.js CHANGED
@@ -6,21 +6,10 @@ require('elysia');
6
6
 
7
7
  /**
8
8
  * @module @riligar/auth-elysia
9
- * @description Auth SDK for ElysiaJS with JWT and JWKS
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,396 +19,144 @@ const DEFAULT_CONFIG = {
30
19
  httpOnly: true,
31
20
  secure: process.env.NODE_ENV === 'production',
32
21
  sameSite: 'lax',
33
- maxAge: 604800, // 7 dias (igual ao JWT)
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 { error: 'Unauthorized', message: 'Token inválido ou expirado' }
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 + this.jwksCacheTTL;
46
+ this.jwksCacheExpiry = now + 3600000;
69
47
  return this.jwksCache
70
48
  }
71
- } catch (error) {
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?.keys?.length) return null
83
-
84
- // Decode JWT header para pegar kid e alg
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
- // Preparar dados para verificação
93
- const [headerB64Url, payloadB64Url, signatureB64Url] = token.split('.');
94
- const data = new TextEncoder().encode(`${headerB64Url}.${payloadB64Url}`);
95
-
96
- const signature = new Uint8Array(Array.from(atob(signatureB64Url.replace(/-/g, '+').replace(/_/g, '/'))).map(c => c.charCodeAt(0)));
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
- console.warn('Algoritmo JWT não suportado:', header.alg);
131
- return null
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
- // Map JWT standard claims to user object format
147
- // JWT uses 'sub' for subject (user ID), but clients expect 'id'
148
- return {
149
- id: payload.sub,
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
- // Utilitário para converter base64url para ArrayBuffer
159
- base64urlToArrayBuffer(base64url) {
160
- const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
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 response = await fetch(`${this.baseUrl}/auth/session`, {
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
- if (response.ok) {
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
- try {
214
- const response = await fetch(url, {
215
- headers: {
216
- 'Content-Type': 'application/json',
217
- ...options.headers,
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.derive(async ({ request, cookie }) => {
244
- const path = new URL(request.url).pathname;
245
- // Verificar se a rota deve ser excluída da autenticação
246
- if (config.excludePaths.some(excluded => path.startsWith(excluded))) {
247
- return { user: null, authMeta: null }
248
- }
249
-
250
- // Buscar token no cookie ou header Authorization
251
- let token = cookie[config.cookieName]?.value;
252
-
253
- if (!token) {
254
- const authHeader = request.headers.get('authorization');
255
- if (authHeader?.startsWith('Bearer ')) {
256
- token = authHeader.substring(7);
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.'
257
123
  }
258
- }
259
-
260
- if (!token) {
261
- return { user: null, authMeta: null }
262
- }
263
-
264
- try {
265
- // ⚡ Verificação otimizada com JWKS local + fallback remoto
266
- const userSession = await authClient.verifySession(token);
267
-
268
- if (!userSession) {
269
- return { user: null, authMeta: null }
270
- }
271
-
272
- return {
273
- user: userSession.user,
274
- authMeta: {
275
- verified_locally: userSession.verified_locally,
276
- cached: userSession.cached,
277
- },
278
- }
279
- } catch (error) {
280
- console.warn('Auth verification error:', error.message);
281
- return { user: null, authMeta: null }
282
- }
283
- }).onBeforeHandle(({ user, set, request }) => {
284
- const path = new URL(request.url).pathname;
285
- // Verificar se a rota deve ser excluída da autenticação (guard redundante por segurança)
286
- if (config.excludePaths.some(excluded => path.startsWith(excluded))) {
287
- return
288
- }
289
-
290
- // Se não houver usuário e a rota não for excluída, bloquear
291
- if (!user) {
292
- return config.onUnauthorized(set)
293
- }
294
- });
295
-
296
- return app.group(config.prefix, app =>
297
- app
298
- // Rota de login
299
- .post('/login', async ({ body, set, cookie }) => {
300
- try {
301
- const { email, password } = body;
302
-
303
- if (!email || !password) {
304
- set.status = 400;
305
- return { error: 'Email e senha são obrigatórios' }
306
- }
307
-
308
- const response = await fetchAuth(`${config.apiUrl}/auth/sign-in/email`, {
309
- method: 'POST',
310
- body: JSON.stringify({ email, password }),
311
- headers: {
312
- 'X-API-Key': config.secretKey,
313
- },
314
- });
315
-
316
- if (response.token) {
317
- cookie[config.cookieName].set({
318
- value: response.token,
319
- ...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 },
320
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.'
321
139
  }
322
-
323
- return {
324
- message: 'Login realizado com sucesso!',
325
- user: response.user,
326
- token: response.token,
327
- session: response.session,
328
- }
329
- } catch (error) {
330
- set.status = 401;
331
- return { error: 'Login failed', message: error.message }
332
- }
333
- })
334
-
335
- // Rota de registro
336
- .post('/register', async ({ body, set }) => {
337
- try {
338
- const { email, password, name, organizationId } = body;
339
-
340
- if (!email || !password || !name) {
341
- set.status = 400;
342
- return { error: 'Email, senha e nome são obrigatórios' }
343
- }
344
-
345
- const response = await fetchAuth(`${config.apiUrl}/auth/sign-up/email`, {
346
- method: 'POST',
347
- body: JSON.stringify({
348
- email,
349
- password,
350
- name,
351
- ...(organizationId && { organizationId }),
352
- }),
353
- headers: {
354
- 'X-API-Key': config.secretKey,
355
- },
356
- });
357
-
358
- return {
359
- message: 'Usuário registrado com sucesso!',
360
- user: {
361
- id: response.user?.id,
362
- email: response.user?.email,
363
- name: response.user?.name,
364
- },
365
- }
366
- } catch (error) {
367
- set.status = 400;
368
- return { error: 'Registration failed', message: error.message }
369
- }
370
- })
371
-
372
- // Rota de logout
373
- .post('/logout', async ({ cookie, set, headers }) => {
374
- try {
375
- const token = headers.authorization?.replace('Bearer ', '') || cookie[config.cookieName]?.value;
376
-
377
- if (token) {
378
- // Fazer logout no servidor de auth
379
- 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`, {
380
144
  method: 'POST',
381
- headers: {
382
- Authorization: `Bearer ${token}`,
383
- 'X-API-Key': config.secretKey,
384
- },
385
- }).catch(() => {
386
- // Ignorar erros do logout remoto
145
+ body: JSON.stringify(body),
146
+ headers: { 'X-API-Key': config.secretKey },
387
147
  });
148
+ return { message: 'OK', user: res.user }
149
+ } catch (e) {
150
+ set.status = 400;
151
+ return 'Falha no registro.'
388
152
  }
389
-
390
- // Remover cookie local
153
+ })
154
+ .post('/logout', async ({ cookie }) => {
391
155
  cookie[config.cookieName].remove();
392
-
393
- return { message: 'Logout realizado com sucesso!' }
394
- } catch (error) {
395
- set.status = 400;
396
- return { error: 'Erro ao fazer logout', message: error.message }
397
- }
398
- })
399
-
400
- // Verificar sessão (substitui o /refresh)
401
- .get('/session', ({ user, authMeta, set }) => {
402
- if (!user) {
403
- set.status = 401;
404
- return { error: 'Not authenticated' }
405
- }
406
- return {
407
- user,
408
- meta: authMeta,
409
- verified_at: new Date().toISOString(),
410
- }
411
- })
412
-
413
- // Status do usuário atual
414
- .get('/me', ({ user, set }) => {
415
- if (!user) {
416
- set.status = 401;
417
- return { error: 'Not authenticated' }
418
- }
419
- return { user }
420
- })
421
- )
422
- }
156
+ return 'Sessão encerrada.'
157
+ })
158
+ .get('/me', ({ user, set }) => user || config.onUnauthorized(set))
159
+ )
423
160
  }
424
161
 
425
162
  exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@riligar/auth-elysia",
3
- "version": "1.6.1",
3
+ "version": "1.6.3",
4
4
  "type": "module",
5
5
  "description": "Auth SDK for ElysiaJS with JWT and JWKS",
6
6
  "main": "dist/index.js",