@vatts/auth 1.0.2-alpha.1 → 1.0.2-alpha.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/client.js CHANGED
@@ -26,7 +26,7 @@ async function getSession() {
26
26
  return data.session || null;
27
27
  }
28
28
  catch (error) {
29
- console.error('[hweb-auth] Error fetching session:', error);
29
+ console.error('[vatts-auth] Error fetching session:', error);
30
30
  return null;
31
31
  }
32
32
  }
@@ -45,7 +45,7 @@ async function getCsrfToken() {
45
45
  return data.csrfToken || null;
46
46
  }
47
47
  catch (error) {
48
- console.error('[hweb-auth] Error fetching CSRF token:', error);
48
+ console.error('[vatts-auth] Error fetching CSRF token:', error);
49
49
  return null;
50
50
  }
51
51
  }
@@ -64,7 +64,7 @@ async function getProviders() {
64
64
  return data.providers || [];
65
65
  }
66
66
  catch (error) {
67
- console.error('[hweb-auth] Error searching for providers:', error);
67
+ console.error('[vatts-auth] Error searching for providers:', error);
68
68
  return null;
69
69
  }
70
70
  }
@@ -119,7 +119,7 @@ async function signIn(provider = 'credentials', options = {}) {
119
119
  }
120
120
  }
121
121
  catch (error) {
122
- console.error('[hweb-auth] Error on signIn:', error);
122
+ console.error('[vatts-auth] Error on signIn:', error);
123
123
  return {
124
124
  error: 'Network error',
125
125
  status: 500,
@@ -141,6 +141,6 @@ async function signOut(options = {}) {
141
141
  }
142
142
  }
143
143
  catch (error) {
144
- console.error('[hweb-auth] Error on signOut:', error);
144
+ console.error('[vatts-auth] Error on signOut:', error);
145
145
  }
146
146
  }
package/dist/core.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { VattsRequest, VattsResponse } from 'vatts';
2
2
  import type { AuthConfig, AuthProviderClass, Session } from './types';
3
- export declare class HWebAuth {
3
+ export declare class VattsAuth {
4
4
  private config;
5
5
  private sessionManager;
6
6
  constructor(config: AuthConfig);
package/dist/core.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HWebAuth = void 0;
3
+ exports.VattsAuth = void 0;
4
4
  /*
5
5
  * This file is part of the Vatts.js Project.
6
6
  * Copyright (c) 2026 itsmuzin
@@ -19,7 +19,7 @@ exports.HWebAuth = void 0;
19
19
  */
20
20
  const vatts_1 = require("vatts");
21
21
  const jwt_1 = require("./jwt");
22
- class HWebAuth {
22
+ class VattsAuth {
23
23
  constructor(config) {
24
24
  this.config = {
25
25
  session: { strategy: 'jwt', maxAge: 86400, ...config.session },
@@ -48,7 +48,7 @@ class HWebAuth {
48
48
  async signIn(providerId, credentials) {
49
49
  const provider = this.config.providers.find(p => p.id === providerId);
50
50
  if (!provider) {
51
- console.error(`[hweb-auth] Provider not found: ${providerId}`);
51
+ console.error(`[vatts-auth] Provider not found: ${providerId}`);
52
52
  return null;
53
53
  }
54
54
  try {
@@ -76,7 +76,7 @@ class HWebAuth {
76
76
  return sessionResult;
77
77
  }
78
78
  catch (error) {
79
- console.error(`[hweb-auth] Error signing in with provider ${providerId}:`, error);
79
+ console.error(`[vatts-auth] Error signing in with provider ${providerId}:`, error);
80
80
  return null;
81
81
  }
82
82
  }
@@ -93,13 +93,13 @@ class HWebAuth {
93
93
  await provider.handleSignOut();
94
94
  }
95
95
  catch (error) {
96
- console.error(`[hweb-auth] Signout error on provider ${provider.id}:`, error);
96
+ console.error(`[vatts-auth] Signout error on provider ${provider.id}:`, error);
97
97
  }
98
98
  }
99
99
  }
100
100
  return vatts_1.VattsResponse
101
101
  .json({ success: true })
102
- .clearCookie('hweb-auth-token', {
102
+ .clearCookie('vatts-auth-token', {
103
103
  path: '/',
104
104
  httpOnly: true,
105
105
  secure: this.config.secureCookies || false,
@@ -157,7 +157,7 @@ class HWebAuth {
157
157
  createAuthResponse(token, data) {
158
158
  return vatts_1.VattsResponse
159
159
  .json(data)
160
- .cookie('hweb-auth-token', token, {
160
+ .cookie('vatts-auth-token', token, {
161
161
  httpOnly: true,
162
162
  secure: this.config.secureCookies || false, // Always secure, even in development
163
163
  sameSite: 'strict', // Prevent CSRF attacks
@@ -165,17 +165,21 @@ class HWebAuth {
165
165
  path: '/',
166
166
  domain: undefined // Let browser set automatically for security
167
167
  })
168
+ // SECURITY: Comprehensive security headers
168
169
  .header('X-Content-Type-Options', 'nosniff')
169
170
  .header('X-Frame-Options', 'DENY')
170
171
  .header('X-XSS-Protection', '1; mode=block')
171
- .header('Referrer-Policy', 'strict-origin-when-cross-origin');
172
+ .header('Referrer-Policy', 'strict-origin-when-cross-origin')
173
+ .header('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self'; frame-ancestors 'none';")
174
+ .header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')
175
+ .header('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');
172
176
  }
173
177
  /**
174
178
  * Extrai token da requisição (cookie ou header)
175
179
  */
176
180
  getTokenFromRequest(req) {
177
181
  // Primeiro tenta pegar do cookie
178
- const cookieToken = req.cookie('hweb-auth-token');
182
+ const cookieToken = req.cookie('vatts-auth-token');
179
183
  if (cookieToken)
180
184
  return cookieToken;
181
185
  // Depois tenta do header Authorization
@@ -186,4 +190,4 @@ class HWebAuth {
186
190
  return null;
187
191
  }
188
192
  }
189
- exports.HWebAuth = HWebAuth;
193
+ exports.VattsAuth = VattsAuth;
package/dist/jwt.js CHANGED
@@ -23,13 +23,39 @@ exports.SessionManager = exports.JWTManager = void 0;
23
23
  const crypto_1 = __importDefault(require("crypto"));
24
24
  class JWTManager {
25
25
  constructor(secret) {
26
- if (!secret && !process.env.HWEB_AUTH_SECRET) {
27
- throw new Error('JWT secret is required. Set HWEB_AUTH_SECRET environment variable or provide secret parameter.');
26
+ if (!secret && !process.env.VATTS_AUTH_SECRET) {
27
+ throw new Error('JWT secret is required. Set VATTS_AUTH_SECRET environment variable or provide secret parameter.');
28
28
  }
29
- this.secret = secret || process.env.HWEB_AUTH_SECRET;
29
+ this.secret = secret || process.env.VATTS_AUTH_SECRET;
30
+ // SECURITY: Enforce minimum secret length
30
31
  if (this.secret.length < 32) {
31
32
  throw new Error('JWT secret must be at least 32 characters long for security.');
32
33
  }
34
+ // SECURITY: Warn about weak/common secrets in development
35
+ const weakSecrets = [
36
+ 'your-secret-key',
37
+ 'vatts-test-secret-key-change-in-production',
38
+ 'secret',
39
+ 'changeme',
40
+ 'password',
41
+ '12345678',
42
+ 'test-secret',
43
+ 'development-secret'
44
+ ];
45
+ if (weakSecrets.some(weak => this.secret.toLowerCase().includes(weak))) {
46
+ console.warn('\x1b[33m%s\x1b[0m', '⚠️ SECURITY WARNING: You are using a weak/common JWT secret!');
47
+ console.warn('\x1b[33m%s\x1b[0m', ' This is a CRITICAL security risk in production.');
48
+ console.warn('\x1b[33m%s\x1b[0m', ' Generate a strong secret: node -e "console.log(require(\'crypto\').randomBytes(64).toString(\'base64\'))"');
49
+ // SECURITY: Refuse to start in production with weak secret
50
+ if (process.env.NODE_ENV === 'production') {
51
+ throw new Error('PRODUCTION: Weak JWT secret detected. Application refused to start for security reasons.');
52
+ }
53
+ }
54
+ // SECURITY: Check for sufficient entropy (basic check)
55
+ const uniqueChars = new Set(this.secret).size;
56
+ if (uniqueChars < 16) {
57
+ console.warn('\x1b[33m%s\x1b[0m', '⚠️ WARNING: JWT secret has low entropy (few unique characters). Consider using a more random secret.');
58
+ }
33
59
  }
34
60
  /**
35
61
  * Cria um JWT token com validação de algoritmo
@@ -75,13 +101,14 @@ class JWTManager {
75
101
  // Validate algorithm in payload matches header
76
102
  if (decodedPayload.alg !== 'HS256')
77
103
  return null;
78
- // Verifica expiração com margem de erro de 30 segundos
104
+ // SECURITY: Verifica expiração com margem de erro de 5 segundos (clock skew)
105
+ // Reduzido de 30s para minimizar janela de replay attacks
79
106
  const now = Math.floor(Date.now() / 1000);
80
- if (decodedPayload.exp && decodedPayload.exp < (now - 30)) {
107
+ if (decodedPayload.exp && decodedPayload.exp < (now - 5)) {
81
108
  return null;
82
109
  }
83
- // Validate issued at time (not too far in future)
84
- if (decodedPayload.iat && decodedPayload.iat > (now + 300)) {
110
+ // SECURITY: Validate issued at time (not too far in future - 60s tolerance)
111
+ if (decodedPayload.iat && decodedPayload.iat > (now + 60)) {
85
112
  return null;
86
113
  }
87
114
  return decodedPayload;
@@ -96,11 +123,21 @@ class JWTManager {
96
123
  }
97
124
  const sanitized = {};
98
125
  for (const [key, value] of Object.entries(payload)) {
99
- // Skip dangerous properties
126
+ // SECURITY: Skip dangerous properties that could lead to prototype pollution
100
127
  if (key.startsWith('__') || key === 'constructor' || key === 'prototype') {
101
128
  continue;
102
129
  }
103
- sanitized[key] = value;
130
+ // SECURITY: Recursively sanitize nested objects to prevent deep prototype pollution
131
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
132
+ sanitized[key] = this.sanitizePayload(value);
133
+ }
134
+ else if (Array.isArray(value)) {
135
+ // Sanitize arrays recursively
136
+ sanitized[key] = value.map(item => (item && typeof item === 'object') ? this.sanitizePayload(item) : item);
137
+ }
138
+ else {
139
+ sanitized[key] = value;
140
+ }
104
141
  }
105
142
  return sanitized;
106
143
  }
@@ -121,6 +158,11 @@ class JWTManager {
121
158
  .replace(/=/g, '');
122
159
  }
123
160
  base64UrlDecode(str) {
161
+ // SECURITY: Prevent DoS attacks with extremely large strings
162
+ // JWT tokens are typically < 4KB, we allow up to 16KB to be safe
163
+ if (str.length > 16384) {
164
+ throw new Error('Token too large');
165
+ }
124
166
  str += '='.repeat(4 - str.length % 4);
125
167
  return Buffer.from(str.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString();
126
168
  }
@@ -54,7 +54,7 @@ export declare class CredentialsProvider implements AuthProviderClass {
54
54
  */
55
55
  validateCredentials(credentials: Record<string, string>): boolean;
56
56
  /**
57
- * Validação simples de email
57
+ * Validação robusta de email (RFC 5322 simplificado)
58
58
  */
59
59
  private isValidEmail;
60
60
  }
@@ -87,11 +87,32 @@ class CredentialsProvider {
87
87
  return true;
88
88
  }
89
89
  /**
90
- * Validação simples de email
90
+ * Validação robusta de email (RFC 5322 simplificado)
91
91
  */
92
92
  isValidEmail(email) {
93
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
94
- return emailRegex.test(email);
93
+ // SECURITY: Validate email length to prevent DoS
94
+ if (!email || email.length > 320) { // RFC 5321: max 320 chars
95
+ return false;
96
+ }
97
+ // SECURITY: More robust email validation regex
98
+ // Prevents common bypasses like multiple @, script tags, etc.
99
+ const emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
100
+ if (!emailRegex.test(email)) {
101
+ return false;
102
+ }
103
+ // SECURITY: Validate parts separately
104
+ const parts = email.split('@');
105
+ if (parts.length !== 2)
106
+ return false;
107
+ const [local, domain] = parts;
108
+ if (local.length > 64 || domain.length > 255) { // RFC 5321 limits
109
+ return false;
110
+ }
111
+ // SECURITY: Prevent consecutive dots
112
+ if (email.includes('..')) {
113
+ return false;
114
+ }
115
+ return true;
95
116
  }
96
117
  }
97
118
  exports.CredentialsProvider = CredentialsProvider;
@@ -0,0 +1,63 @@
1
+ import type { AuthProviderClass, AuthRoute, User } from '../types';
2
+ export interface GithubConfig {
3
+ id?: string;
4
+ name?: string;
5
+ clientId: string;
6
+ clientSecret: string;
7
+ callbackUrl?: string;
8
+ successUrl?: string;
9
+ scope?: string[];
10
+ }
11
+ /**
12
+ * Provider para autenticação com GitHub OAuth2
13
+ *
14
+ * Este provider permite autenticação usando GitHub.
15
+ * Automaticamente gerencia o fluxo OAuth completo e rotas necessárias.
16
+ *
17
+ * Exemplo de uso:
18
+ * ```typescript
19
+ * new GithubProvider({
20
+ * clientId: process.env.GITHUB_CLIENT_ID!,
21
+ * clientSecret: process.env.GITHUB_CLIENT_SECRET!,
22
+ * callbackUrl: "http://localhost:3000/api/auth/callback/github"
23
+ * })
24
+ * ```
25
+ *
26
+ * Fluxo de autenticação:
27
+ * 1. GET /api/auth/signin/github - Gera URL e redireciona para GitHub
28
+ * 2. GitHub redireciona para /api/auth/callback/github com código
29
+ * 3. Provider troca código por token e busca dados do usuário
30
+ * 4. Retorna objeto User com dados do GitHub
31
+ */
32
+ export declare class GithubProvider implements AuthProviderClass {
33
+ readonly id: string;
34
+ readonly name: string;
35
+ readonly type: string;
36
+ private config;
37
+ private readonly defaultScope;
38
+ constructor(config: GithubConfig);
39
+ /**
40
+ * Método para gerar URL OAuth (usado pelo handleSignIn)
41
+ */
42
+ handleOauth(credentials?: Record<string, string>): string;
43
+ /**
44
+ * Método principal - redireciona para OAuth ou processa o callback
45
+ */
46
+ handleSignIn(credentials: Record<string, string>): Promise<User | string | null>;
47
+ /**
48
+ * Processa o callback do OAuth (troca o código pelo usuário)
49
+ */
50
+ private processOAuthCallback;
51
+ /**
52
+ * Rotas adicionais específicas do GitHub OAuth
53
+ */
54
+ additionalRoutes: AuthRoute[];
55
+ /**
56
+ * Gera a URL de autorização do GitHub
57
+ */
58
+ getAuthorizationUrl(): string;
59
+ /**
60
+ * Retorna a configuração pública do provider
61
+ */
62
+ getConfig(): any;
63
+ }
@@ -0,0 +1,218 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GithubProvider = void 0;
4
+ const vatts_1 = require("vatts");
5
+ /**
6
+ * Provider para autenticação com GitHub OAuth2
7
+ *
8
+ * Este provider permite autenticação usando GitHub.
9
+ * Automaticamente gerencia o fluxo OAuth completo e rotas necessárias.
10
+ *
11
+ * Exemplo de uso:
12
+ * ```typescript
13
+ * new GithubProvider({
14
+ * clientId: process.env.GITHUB_CLIENT_ID!,
15
+ * clientSecret: process.env.GITHUB_CLIENT_SECRET!,
16
+ * callbackUrl: "http://localhost:3000/api/auth/callback/github"
17
+ * })
18
+ * ```
19
+ *
20
+ * Fluxo de autenticação:
21
+ * 1. GET /api/auth/signin/github - Gera URL e redireciona para GitHub
22
+ * 2. GitHub redireciona para /api/auth/callback/github com código
23
+ * 3. Provider troca código por token e busca dados do usuário
24
+ * 4. Retorna objeto User com dados do GitHub
25
+ */
26
+ class GithubProvider {
27
+ constructor(config) {
28
+ this.type = 'github';
29
+ this.defaultScope = [
30
+ 'read:user',
31
+ 'user:email'
32
+ ];
33
+ /**
34
+ * Rotas adicionais específicas do GitHub OAuth
35
+ */
36
+ this.additionalRoutes = [
37
+ // Rota de callback do GitHub
38
+ {
39
+ method: 'GET',
40
+ path: '/api/auth/callback/github',
41
+ handler: async (req, params) => {
42
+ const url = new URL(req.url || '', 'http://localhost');
43
+ const code = url.searchParams.get('code');
44
+ if (!code) {
45
+ return vatts_1.VattsResponse.json({ error: 'Authorization code not provided' }, { status: 400 });
46
+ }
47
+ try {
48
+ // Delega o 'code' para o endpoint de signin principal
49
+ const authResponse = await fetch(`${req.headers.origin || 'http://localhost:3000'}/api/auth/signin`, {
50
+ method: 'POST',
51
+ headers: {
52
+ 'Content-Type': 'application/json',
53
+ },
54
+ body: JSON.stringify({
55
+ provider: this.id,
56
+ code,
57
+ })
58
+ });
59
+ if (authResponse.ok) {
60
+ // Propaga o cookie de sessão e redireciona para a URL de sucesso
61
+ const setCookieHeader = authResponse.headers.get('set-cookie');
62
+ if (this.config.successUrl) {
63
+ return vatts_1.VattsResponse
64
+ .redirect(this.config.successUrl)
65
+ .header('Set-Cookie', setCookieHeader || '');
66
+ }
67
+ return vatts_1.VattsResponse.json({ success: true })
68
+ .header('Set-Cookie', setCookieHeader || '');
69
+ }
70
+ else {
71
+ const errorText = await authResponse.text();
72
+ console.error(`[${this.id} Provider] Session creation failed during callback. Status: ${authResponse.status}, Body: ${errorText}`);
73
+ return vatts_1.VattsResponse.json({ error: 'Session creation failed' }, { status: 500 });
74
+ }
75
+ }
76
+ catch (error) {
77
+ console.error(`[${this.id} Provider] Callback handler fetch error:`, error);
78
+ return vatts_1.VattsResponse.json({ error: 'Internal server error' }, { status: 500 });
79
+ }
80
+ }
81
+ }
82
+ ];
83
+ this.config = config;
84
+ this.id = config.id || 'github';
85
+ this.name = config.name || 'GitHub';
86
+ }
87
+ /**
88
+ * Método para gerar URL OAuth (usado pelo handleSignIn)
89
+ */
90
+ handleOauth(credentials = {}) {
91
+ return this.getAuthorizationUrl();
92
+ }
93
+ /**
94
+ * Método principal - redireciona para OAuth ou processa o callback
95
+ */
96
+ async handleSignIn(credentials) {
97
+ // Se tem código, é o callback - processa a autenticação
98
+ if (credentials.code) {
99
+ return await this.processOAuthCallback(credentials);
100
+ }
101
+ // Se não tem código, é o início do OAuth - retorna a URL
102
+ return this.handleOauth(credentials);
103
+ }
104
+ /**
105
+ * Processa o callback do OAuth (troca o código pelo usuário)
106
+ */
107
+ async processOAuthCallback(credentials) {
108
+ try {
109
+ const { code } = credentials;
110
+ if (!code) {
111
+ throw new Error('Authorization code not provided');
112
+ }
113
+ // Troca o código por um access token
114
+ // Nota: O GitHub requer o header Accept: application/json para retornar JSON
115
+ const tokenResponse = await fetch('https://github.com/login/oauth/access_token', {
116
+ method: 'POST',
117
+ headers: {
118
+ 'Content-Type': 'application/json',
119
+ 'Accept': 'application/json'
120
+ },
121
+ body: JSON.stringify({
122
+ client_id: this.config.clientId,
123
+ client_secret: this.config.clientSecret,
124
+ code,
125
+ redirect_uri: this.config.callbackUrl || undefined,
126
+ }),
127
+ });
128
+ if (!tokenResponse.ok) {
129
+ const error = await tokenResponse.text();
130
+ throw new Error(`Failed to exchange code for token: ${error}`);
131
+ }
132
+ const tokens = await tokenResponse.json();
133
+ if (tokens.error) {
134
+ throw new Error(`GitHub Token Error: ${tokens.error_description || tokens.error}`);
135
+ }
136
+ // Busca os dados do usuário com o access token
137
+ const userResponse = await fetch('https://api.github.com/user', {
138
+ headers: {
139
+ 'Authorization': `Bearer ${tokens.access_token}`,
140
+ 'Accept': 'application/vnd.github.v3+json',
141
+ },
142
+ });
143
+ if (!userResponse.ok) {
144
+ throw new Error('Failed to fetch user data');
145
+ }
146
+ const githubUser = await userResponse.json();
147
+ // Lógica específica do GitHub: O email pode ser privado e não vir no objeto user principal
148
+ let email = githubUser.email;
149
+ if (!email) {
150
+ try {
151
+ const emailsResponse = await fetch('https://api.github.com/user/emails', {
152
+ headers: {
153
+ 'Authorization': `Bearer ${tokens.access_token}`,
154
+ 'Accept': 'application/vnd.github.v3+json',
155
+ },
156
+ });
157
+ if (emailsResponse.ok) {
158
+ const emails = await emailsResponse.json();
159
+ // Tenta pegar o email primário e verificado, ou o primeiro disponível
160
+ const primaryEmail = emails.find((e) => e.primary && e.verified) ||
161
+ emails.find((e) => e.verified) ||
162
+ emails[0];
163
+ if (primaryEmail) {
164
+ email = primaryEmail.email;
165
+ }
166
+ }
167
+ }
168
+ catch (emailError) {
169
+ console.warn(`[${this.id} Provider] Could not fetch private emails`, emailError);
170
+ }
171
+ }
172
+ // Retorna o objeto User padronizado
173
+ return {
174
+ id: String(githubUser.id), // GitHub retorna ID numérico
175
+ name: githubUser.name || githubUser.login, // Fallback para o username se não tiver nome configurado
176
+ email: email,
177
+ image: githubUser.avatar_url || null,
178
+ provider: this.id,
179
+ providerId: String(githubUser.id),
180
+ accessToken: tokens.access_token,
181
+ // GitHub geralmente não retorna refresh tokens em Apps OAuth padrão (web flow)
182
+ // a menos que especificamente configurado, mas mantemos o campo se vier
183
+ refreshToken: tokens.refresh_token || undefined
184
+ };
185
+ }
186
+ catch (error) {
187
+ console.error(`[${this.id} Provider] Error during OAuth callback:`, error);
188
+ return null;
189
+ }
190
+ }
191
+ /**
192
+ * Gera a URL de autorização do GitHub
193
+ */
194
+ getAuthorizationUrl() {
195
+ const params = new URLSearchParams({
196
+ client_id: this.config.clientId,
197
+ redirect_uri: this.config.callbackUrl || '',
198
+ scope: (this.config.scope || this.defaultScope).join(' '),
199
+ // GitHub não usa 'response_type=code' explicitamente na URL padrão, mas aceita.
200
+ // O padrão é web application flow.
201
+ });
202
+ return `https://github.com/login/oauth/authorize?${params.toString()}`;
203
+ }
204
+ /**
205
+ * Retorna a configuração pública do provider
206
+ */
207
+ getConfig() {
208
+ return {
209
+ id: this.id,
210
+ name: this.name,
211
+ type: this.type,
212
+ clientId: this.config.clientId, // Público
213
+ scope: this.config.scope || this.defaultScope,
214
+ callbackUrl: this.config.callbackUrl
215
+ };
216
+ }
217
+ }
218
+ exports.GithubProvider = GithubProvider;
@@ -1,3 +1,4 @@
1
1
  export { CredentialsProvider } from './providers/credentials';
2
2
  export { DiscordProvider } from './providers/discord';
3
3
  export { GoogleProvider } from './providers/google';
4
+ export { GithubProvider } from "./providers/github";
package/dist/providers.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GoogleProvider = exports.DiscordProvider = exports.CredentialsProvider = void 0;
3
+ exports.GithubProvider = exports.GoogleProvider = exports.DiscordProvider = exports.CredentialsProvider = void 0;
4
4
  /*
5
5
  * This file is part of the Vatts.js Project.
6
6
  * Copyright (c) 2026 itsmuzin
@@ -24,3 +24,5 @@ var discord_1 = require("./providers/discord");
24
24
  Object.defineProperty(exports, "DiscordProvider", { enumerable: true, get: function () { return discord_1.DiscordProvider; } });
25
25
  var google_1 = require("./providers/google");
26
26
  Object.defineProperty(exports, "GoogleProvider", { enumerable: true, get: function () { return google_1.GoogleProvider; } });
27
+ var github_1 = require("./providers/github");
28
+ Object.defineProperty(exports, "GithubProvider", { enumerable: true, get: function () { return github_1.GithubProvider; } });
package/dist/react.js CHANGED
@@ -50,7 +50,7 @@ function SessionProvider({ children, basePath = '/api/auth', refetchInterval = 0
50
50
  }
51
51
  }
52
52
  catch (error) {
53
- console.error('[hweb-auth] Error fetching session:', error);
53
+ console.error('[vatts-auth] Error fetching session:', error);
54
54
  setSession(null);
55
55
  setStatus('unauthenticated');
56
56
  return null;
@@ -106,7 +106,7 @@ function SessionProvider({ children, basePath = '/api/auth', refetchInterval = 0
106
106
  }
107
107
  }
108
108
  catch (error) {
109
- console.error('[hweb-auth] Error on signIn:', error);
109
+ console.error('[vatts-auth] Error on signIn:', error);
110
110
  return {
111
111
  error: 'Network error',
112
112
  status: 500,
@@ -133,7 +133,7 @@ function SessionProvider({ children, basePath = '/api/auth', refetchInterval = 0
133
133
  }
134
134
  }
135
135
  catch (error) {
136
- console.error('[hweb-auth] Error on signOut:', error);
136
+ console.error('[vatts-auth] Error on signOut:', error);
137
137
  }
138
138
  }, [basePath]);
139
139
  // Update session
package/dist/routes.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { VattsRequest } from 'vatts';
2
2
  import type { AuthConfig } from './types';
3
- import { HWebAuth } from './core';
3
+ import { VattsAuth } from './core';
4
4
  /**
5
5
  * Cria o handler catch-all para /api/auth/[...value]
6
6
  */
@@ -12,5 +12,5 @@ export declare function createAuthRoutes(config: AuthConfig): {
12
12
  POST(req: VattsRequest, params: {
13
13
  [key: string]: string;
14
14
  }): Promise<any>;
15
- auth: HWebAuth;
15
+ auth: VattsAuth;
16
16
  };
package/dist/routes.js CHANGED
@@ -23,7 +23,7 @@ const core_1 = require("./core");
23
23
  * Cria o handler catch-all para /api/auth/[...value]
24
24
  */
25
25
  function createAuthRoutes(config) {
26
- const auth = new core_1.HWebAuth(config);
26
+ const auth = new core_1.VattsAuth(config);
27
27
  /**
28
28
  * Handler principal que gerencia todas as rotas de auth
29
29
  * Uso: /api/auth/[...value].ts
@@ -102,9 +102,10 @@ async function handleSession(req, auth) {
102
102
  * Handler para GET /api/auth/csrf
103
103
  */
104
104
  async function handleCsrf(req) {
105
- // Token CSRF simples para proteção
106
- const csrfToken = Math.random().toString(36).substring(2, 15) +
107
- Math.random().toString(36).substring(2, 15);
105
+ // SECURITY: Usa crypto.randomBytes para token criptograficamente seguro
106
+ // 32 bytes = 256 bits de entropia, codificado em base64url (URL-safe)
107
+ const crypto = await import('crypto');
108
+ const csrfToken = crypto.randomBytes(32).toString('base64url');
108
109
  return vatts_1.VattsResponse.json({ csrfToken });
109
110
  }
110
111
  /**
@@ -140,7 +141,7 @@ async function handleSignIn(req, auth) {
140
141
  });
141
142
  }
142
143
  catch (error) {
143
- console.error('[hweb-auth] Error on handleSignIn:', error);
144
+ console.error('[vatts-auth] Error on handleSignIn:', error);
144
145
  return vatts_1.VattsResponse.json({ error: 'Authentication failed' }, { status: 500 });
145
146
  }
146
147
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vatts/auth",
3
- "version": "1.0.2-alpha.1",
3
+ "version": "1.0.2-alpha.3",
4
4
  "description": "Authentication package for Vatts.js framework",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -42,7 +42,7 @@
42
42
  "peerDependencies": {
43
43
  "react": "^19.2.0",
44
44
  "react-dom": "^19.2.0",
45
- "vatts": "^1.0.2-alpha.1"
45
+ "vatts": "^1.0.2-alpha.3"
46
46
  },
47
47
  "peerDependenciesMeta": {
48
48
  "react-dom": {