@vatts/auth 1.0.2-alpha.2 → 1.0.2-alpha.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/dist/providers/github.d.ts +63 -0
- package/dist/providers/github.js +218 -0
- package/dist/providers.d.ts +1 -0
- package/dist/providers.js +3 -1
- package/package.json +2 -2
|
@@ -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;
|
package/dist/providers.d.ts
CHANGED
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vatts/auth",
|
|
3
|
-
"version": "1.0.2-alpha.
|
|
3
|
+
"version": "1.0.2-alpha.4",
|
|
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.
|
|
45
|
+
"vatts": "^1.0.2-alpha.4"
|
|
46
46
|
},
|
|
47
47
|
"peerDependenciesMeta": {
|
|
48
48
|
"react-dom": {
|