@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.esm.js CHANGED
@@ -2,21 +2,10 @@ import 'elysia';
2
2
 
3
3
  /**
4
4
  * @module @riligar/auth-elysia
5
- * @description Auth SDK for ElysiaJS with JWT and JWKS
6
- * @version See package.json
7
- * @since 1.0.0
8
- * @copyright 2024-2026 Riligar
9
- *
10
- * @license MIT
11
- * @author Riligar
12
- * @see https://github.com/riligar-solutions/auth
13
- * @see https://www.npmjs.com/package/@riligar/auth-elysia
5
+ * @description Auth SDK for ElysiaJS
14
6
  */
15
7
 
16
8
 
17
- /**
18
- * Configuração padrão do plugin
19
- */
20
9
  const DEFAULT_CONFIG = {
21
10
  prefix: '/auth',
22
11
  secretKey: process.env.AUTH_SECRET_KEY || 'your-secret-key',
@@ -26,396 +15,144 @@ const DEFAULT_CONFIG = {
26
15
  httpOnly: true,
27
16
  secure: process.env.NODE_ENV === 'production',
28
17
  sameSite: 'lax',
29
- maxAge: 604800, // 7 dias (igual ao JWT)
18
+ maxAge: 604800,
30
19
  },
31
20
  excludePaths: ['/auth/login', '/auth/register', '/auth/session'],
32
21
  onUnauthorized: set => {
33
22
  set.status = 401;
34
- return { error: 'Unauthorized', message: 'Token inválido ou expirado' }
23
+ return 'Sessão inválida ou expirada.'
35
24
  },
36
25
  };
37
26
 
38
- /**
39
- * Cliente Auth com verificação JWT local + JWKS
40
- */
41
27
  class RiLiGarAuthClient {
42
28
  constructor(baseUrl, secretKey) {
43
29
  this.baseUrl = baseUrl;
44
30
  this.secretKey = secretKey;
45
- // 🚀 Cache para JWKS (chaves públicas)
46
31
  this.jwksCache = null;
47
32
  this.jwksCacheExpiry = 0;
48
- this.jwksCacheTTL = 3600000; // 1 hora em ms
49
33
  }
50
34
 
51
- // 🔑 Buscar e cachear JWKS
52
35
  async getJWKS() {
53
36
  const now = Date.now();
54
-
55
- // Retorna cache se ainda válido
56
- if (this.jwksCache && now < this.jwksCacheExpiry) {
57
- return this.jwksCache
58
- }
59
-
37
+ if (this.jwksCache && now < this.jwksCacheExpiry) return this.jwksCache
60
38
  try {
61
39
  const response = await fetch(`${this.baseUrl}/.well-known/jwks.json`);
62
40
  if (response.ok) {
63
41
  this.jwksCache = await response.json();
64
- this.jwksCacheExpiry = now + this.jwksCacheTTL;
42
+ this.jwksCacheExpiry = now + 3600000;
65
43
  return this.jwksCache
66
44
  }
67
- } catch (error) {
68
- console.warn('JWKS fetch failed, falling back to remote verification:', error.message);
69
- }
70
-
45
+ } catch (e) {}
71
46
  return null
72
47
  }
73
48
 
74
- // ⚡ Verificação JWT local (usando crypto nativo do Bun)
75
49
  async verifyJWTLocal(token) {
76
50
  try {
77
51
  const jwks = await this.getJWKS();
78
- if (!jwks?.keys?.length) return null
79
-
80
- // Decode JWT header para pegar kid e alg
81
- const [headerB64] = token.split('.');
82
- const header = JSON.parse(atob(headerB64));
83
-
84
- // Encontrar a chave correspondente
52
+ if (!jwks) return null
53
+ const [h, p, s] = token.split('.');
54
+ const header = JSON.parse(atob(h));
85
55
  const jwk = jwks.keys.find(k => k.kid === header.kid || k.alg === header.alg);
86
56
  if (!jwk) return null
87
-
88
- // Preparar dados para verificação
89
- const [headerB64Url, payloadB64Url, signatureB64Url] = token.split('.');
90
- const data = new TextEncoder().encode(`${headerB64Url}.${payloadB64Url}`);
91
-
92
- const signature = new Uint8Array(Array.from(atob(signatureB64Url.replace(/-/g, '+').replace(/_/g, '/'))).map(c => c.charCodeAt(0)));
93
-
94
- let key;
95
- let algorithm;
96
-
97
- // Suporte para diferentes algoritmos
98
- if (header.alg === 'HS256' || jwk.kty === 'oct') {
99
- // HMAC com secret key
100
- const secret = new TextEncoder().encode(this.secretKey);
101
- key = await crypto.subtle.importKey('raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
102
- algorithm = 'HMAC';
103
- } else if (header.alg === 'RS256' || jwk.kty === 'RSA') {
104
- // RSA com chave pública JWKS
105
- if (!jwk.n || !jwk.e) return null
106
-
107
- // Converter base64url para ArrayBuffer
108
- const nBuffer = this.base64urlToArrayBuffer(jwk.n);
109
- const eBuffer = this.base64urlToArrayBuffer(jwk.e);
110
-
111
- key = await crypto.subtle.importKey(
112
- 'jwk',
113
- {
114
- kty: 'RSA',
115
- n: jwk.n,
116
- e: jwk.e,
117
- alg: 'RS256',
118
- use: 'sig',
119
- },
120
- { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
121
- false,
122
- ['verify']
123
- );
124
- algorithm = 'RSASSA-PKCS1-v1_5';
57
+ const data = new TextEncoder().encode(`${h}.${p}`);
58
+ const sig = Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0));
59
+ let key, algo;
60
+ if (header.alg === 'HS256') {
61
+ key = await crypto.subtle.importKey('raw', new TextEncoder().encode(this.secretKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
62
+ algo = 'HMAC';
125
63
  } else {
126
- console.warn('Algoritmo JWT não suportado:', header.alg);
127
- return null
128
- }
129
-
130
- // Verificar assinatura
131
- const isValid = await crypto.subtle.verify(algorithm, key, signature, data);
132
- if (!isValid) return null
133
-
134
- // Decode payload
135
- const payload = JSON.parse(atob(payloadB64Url));
136
-
137
- // Verificar expiração
138
- if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {
139
- return null
64
+ 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']);
65
+ algo = 'RSASSA-PKCS1-v1_5';
140
66
  }
141
-
142
- // Map JWT standard claims to user object format
143
- // JWT uses 'sub' for subject (user ID), but clients expect 'id'
144
- return {
145
- id: payload.sub,
146
- ...payload,
147
- }
148
- } catch (error) {
149
- console.warn('JWT local verification failed:', error.message);
67
+ if (!(await crypto.subtle.verify(algo, key, sig, data))) return null
68
+ const payload = JSON.parse(atob(p));
69
+ if (payload.exp && payload.exp < Date.now() / 1000) return null
70
+ return { id: payload.sub, ...payload }
71
+ } catch (e) {
150
72
  return null
151
73
  }
152
74
  }
153
75
 
154
- // Utilitário para converter base64url para ArrayBuffer
155
- base64urlToArrayBuffer(base64url) {
156
- const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
157
- const padding = '='.repeat((4 - (base64.length % 4)) % 4);
158
- const base64WithPadding = base64 + padding;
159
-
160
- const binaryString = atob(base64WithPadding);
161
- const bytes = new Uint8Array(binaryString.length);
162
- for (let i = 0; i < binaryString.length; i++) {
163
- bytes[i] = binaryString.charCodeAt(i);
164
- }
165
- return bytes.buffer
166
- }
167
-
168
- // ⚡ Verificar sessão OTIMIZADA (local + fallback remoto)
169
- async verifySession(sessionToken) {
170
- // 🚀 Primeira tentativa: Verificação local com JWKS
171
- const localResult = await this.verifyJWTLocal(sessionToken);
172
- if (localResult) {
173
- return {
174
- user: localResult,
175
- verified_locally: true,
176
- cached: true,
177
- }
178
- }
179
-
180
- // 🔄 Fallback: Verificação remota
76
+ async verifySession(token) {
77
+ const local = await this.verifyJWTLocal(token);
78
+ if (local) return { user: local }
181
79
  try {
182
- const response = await fetch(`${this.baseUrl}/auth/session`, {
183
- headers: {
184
- Authorization: `Bearer ${sessionToken}`,
185
- 'X-API-Key': this.secretKey,
186
- },
80
+ const res = await fetch(`${this.baseUrl}/auth/session`, {
81
+ headers: { Authorization: `Bearer ${token}`, 'X-API-Key': this.secretKey },
187
82
  });
188
-
189
- if (response.ok) {
190
- const result = await response.json();
191
- return {
192
- ...result,
193
- verified_locally: false,
194
- cached: false,
195
- }
196
- }
197
- } catch (error) {
198
- console.warn('Remote session verification failed:', error.message);
199
- }
200
-
83
+ if (res.ok) return await res.json()
84
+ } catch (e) {}
201
85
  return null
202
86
  }
203
87
  }
204
88
 
205
- /**
206
- * Utilitário para fazer requisições HTTP
207
- */
208
89
  async function fetchAuth(url, options = {}) {
209
- try {
210
- const response = await fetch(url, {
211
- headers: {
212
- 'Content-Type': 'application/json',
213
- ...options.headers,
214
- },
215
- ...options,
216
- });
217
-
218
- if (!response.ok) {
219
- throw new Error(`HTTP ${response.status}: ${response.statusText}`)
220
- }
221
-
222
- return await response.json()
223
- } catch (error) {
224
- console.error('Auth fetch error:', error);
225
- throw error
226
- }
90
+ const res = await fetch(url, {
91
+ headers: { 'Content-Type': 'application/json', ...options.headers },
92
+ ...options,
93
+ });
94
+ if (!res.ok) throw new Error(res.status)
95
+ return await res.json()
227
96
  }
228
97
 
229
- /**
230
- * Plugin principal de autenticação
231
- */
232
98
  function authPlugin(userConfig = {}) {
233
99
  const config = { ...DEFAULT_CONFIG, ...userConfig };
234
-
235
- // Instanciar cliente Auth
236
100
  const authClient = new RiLiGarAuthClient(config.apiUrl, config.secretKey);
237
101
 
238
- return app => {
239
- app.derive(async ({ request, cookie }) => {
240
- const path = new URL(request.url).pathname;
241
- // Verificar se a rota deve ser excluída da autenticação
242
- if (config.excludePaths.some(excluded => path.startsWith(excluded))) {
243
- return { user: null, authMeta: null }
244
- }
245
-
246
- // Buscar token no cookie ou header Authorization
247
- let token = cookie[config.cookieName]?.value;
248
-
249
- if (!token) {
250
- const authHeader = request.headers.get('authorization');
251
- if (authHeader?.startsWith('Bearer ')) {
252
- token = authHeader.substring(7);
102
+ return app =>
103
+ app
104
+ .derive({ as: 'global' }, async ({ request, cookie }) => {
105
+ const token = cookie[config.cookieName]?.value || request.headers.get('authorization')?.split(' ')[1];
106
+ if (!token) return { user: null }
107
+ const session = await authClient.verifySession(token);
108
+ return { user: session?.user || null }
109
+ })
110
+ .onBeforeHandle({ as: 'global' }, ({ user, set, request }) => {
111
+ const path = new URL(request.url).pathname;
112
+ if (config.excludePaths.some(p => path.startsWith(p))) return
113
+ if (!user) return config.onUnauthorized(set)
114
+ })
115
+ .error(({ error, set }) => {
116
+ if (String(error).includes('user.id') || String(error).includes('of null')) {
117
+ set.status = 401;
118
+ return 'Sessão inválida ou expirada.'
253
119
  }
254
- }
255
-
256
- if (!token) {
257
- return { user: null, authMeta: null }
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 }
266
- }
267
-
268
- return {
269
- user: userSession.user,
270
- authMeta: {
271
- verified_locally: userSession.verified_locally,
272
- cached: userSession.cached,
273
- },
274
- }
275
- } catch (error) {
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
- // Verificar se a rota deve ser excluída da autenticação (guard redundante por segurança)
282
- if (config.excludePaths.some(excluded => path.startsWith(excluded))) {
283
- return
284
- }
285
-
286
- // Se não houver usuário e a rota não for excluída, bloquear
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,
120
+ })
121
+ .group(config.prefix, app =>
122
+ app
123
+ .post('/login', async ({ body, set, cookie }) => {
124
+ try {
125
+ const res = await fetchAuth(`${config.apiUrl}/auth/sign-in/email`, {
126
+ method: 'POST',
127
+ body: JSON.stringify(body),
128
+ headers: { 'X-API-Key': config.secretKey },
316
129
  });
130
+ cookie[config.cookieName].set({ value: res.token, ...config.cookieOptions });
131
+ return { message: 'OK', user: res.user, token: res.token }
132
+ } catch (e) {
133
+ set.status = 401;
134
+ return 'Falha no login.'
317
135
  }
318
-
319
- return {
320
- message: 'Login realizado com sucesso!',
321
- user: response.user,
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`, {
136
+ })
137
+ .post('/register', async ({ body, set }) => {
138
+ try {
139
+ const res = await fetchAuth(`${config.apiUrl}/auth/sign-up/email`, {
376
140
  method: 'POST',
377
- headers: {
378
- Authorization: `Bearer ${token}`,
379
- 'X-API-Key': config.secretKey,
380
- },
381
- }).catch(() => {
382
- // Ignorar erros do logout remoto
141
+ body: JSON.stringify(body),
142
+ headers: { 'X-API-Key': config.secretKey },
383
143
  });
144
+ return { message: 'OK', user: res.user }
145
+ } catch (e) {
146
+ set.status = 400;
147
+ return 'Falha no registro.'
384
148
  }
385
-
386
- // Remover cookie local
149
+ })
150
+ .post('/logout', async ({ cookie }) => {
387
151
  cookie[config.cookieName].remove();
388
-
389
- return { message: 'Logout realizado com sucesso!' }
390
- } catch (error) {
391
- set.status = 400;
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
- }
152
+ return 'Sessão encerrada.'
153
+ })
154
+ .get('/me', ({ user, set }) => user || config.onUnauthorized(set))
155
+ )
419
156
  }
420
157
 
421
158
  export { DEFAULT_CONFIG, RiLiGarAuthClient, authPlugin, authPlugin as default, fetchAuth };