@hightjs/auth 0.4.0
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/LICENSE +13 -0
- package/dist/client.d.ts +24 -0
- package/dist/client.js +146 -0
- package/dist/components.d.ts +29 -0
- package/dist/components.js +100 -0
- package/dist/core.d.ts +55 -0
- package/dist/core.js +189 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +45 -0
- package/dist/jwt.d.ts +41 -0
- package/dist/jwt.js +185 -0
- package/dist/providers/credentials.d.ts +60 -0
- package/dist/providers/credentials.js +97 -0
- package/dist/providers/discord.d.ts +63 -0
- package/dist/providers/discord.js +190 -0
- package/dist/providers/google.d.ts +63 -0
- package/dist/providers/google.js +186 -0
- package/dist/providers/index.d.ts +2 -0
- package/dist/providers/index.js +35 -0
- package/dist/providers.d.ts +3 -0
- package/dist/providers.js +26 -0
- package/dist/react/index.d.ts +6 -0
- package/dist/react/index.js +48 -0
- package/dist/react.d.ts +22 -0
- package/dist/react.js +199 -0
- package/dist/routes.d.ts +16 -0
- package/dist/routes.js +152 -0
- package/dist/types.d.ts +76 -0
- package/dist/types.js +18 -0
- package/package.json +48 -0
package/dist/jwt.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.SessionManager = exports.JWTManager = void 0;
|
|
7
|
+
/*
|
|
8
|
+
* This file is part of the HightJS Project.
|
|
9
|
+
* Copyright (c) 2025 itsmuzin
|
|
10
|
+
*
|
|
11
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
12
|
+
* you may not use this file except in compliance with the License.
|
|
13
|
+
* You may obtain a copy of the License at
|
|
14
|
+
*
|
|
15
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
16
|
+
*
|
|
17
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
18
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
19
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
20
|
+
* See the License for the specific language governing permissions and
|
|
21
|
+
* limitations under the License.
|
|
22
|
+
*/
|
|
23
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
24
|
+
class JWTManager {
|
|
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.');
|
|
28
|
+
}
|
|
29
|
+
this.secret = secret || process.env.HWEB_AUTH_SECRET;
|
|
30
|
+
if (this.secret.length < 32) {
|
|
31
|
+
throw new Error('JWT secret must be at least 32 characters long for security.');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Cria um JWT token com validação de algoritmo
|
|
36
|
+
*/
|
|
37
|
+
sign(payload, expiresIn = 86400) {
|
|
38
|
+
const header = { alg: 'HS256', typ: 'JWT' };
|
|
39
|
+
const now = Math.floor(Date.now() / 1000);
|
|
40
|
+
// Sanitize payload to prevent injection
|
|
41
|
+
const sanitizedPayload = this.sanitizePayload(payload);
|
|
42
|
+
const tokenPayload = {
|
|
43
|
+
...sanitizedPayload,
|
|
44
|
+
iat: now,
|
|
45
|
+
exp: now + expiresIn,
|
|
46
|
+
alg: 'HS256' // Prevent algorithm confusion attacks
|
|
47
|
+
};
|
|
48
|
+
const encodedHeader = this.base64UrlEncode(JSON.stringify(header));
|
|
49
|
+
const encodedPayload = this.base64UrlEncode(JSON.stringify(tokenPayload));
|
|
50
|
+
const signature = this.createSignature(encodedHeader + '.' + encodedPayload);
|
|
51
|
+
return `${encodedHeader}.${encodedPayload}.${signature}`;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Verifica e decodifica um JWT token com validação rigorosa
|
|
55
|
+
*/
|
|
56
|
+
verify(token) {
|
|
57
|
+
try {
|
|
58
|
+
if (!token || typeof token !== 'string')
|
|
59
|
+
return null;
|
|
60
|
+
const parts = token.split('.');
|
|
61
|
+
if (parts.length !== 3)
|
|
62
|
+
return null;
|
|
63
|
+
const [headerEncoded, payloadEncoded, signature] = parts;
|
|
64
|
+
// Decode and validate header
|
|
65
|
+
const header = JSON.parse(this.base64UrlDecode(headerEncoded));
|
|
66
|
+
if (header.alg !== 'HS256' || header.typ !== 'JWT') {
|
|
67
|
+
return null; // Prevent algorithm confusion attacks
|
|
68
|
+
}
|
|
69
|
+
// Verifica a assinatura usando constant-time comparison
|
|
70
|
+
const expectedSignature = this.createSignature(headerEncoded + '.' + payloadEncoded);
|
|
71
|
+
if (!this.constantTimeEqual(signature, expectedSignature))
|
|
72
|
+
return null;
|
|
73
|
+
// Decodifica o payload
|
|
74
|
+
const decodedPayload = JSON.parse(this.base64UrlDecode(payloadEncoded));
|
|
75
|
+
// Validate algorithm in payload matches header
|
|
76
|
+
if (decodedPayload.alg !== 'HS256')
|
|
77
|
+
return null;
|
|
78
|
+
// Verifica expiração com margem de erro de 30 segundos
|
|
79
|
+
const now = Math.floor(Date.now() / 1000);
|
|
80
|
+
if (decodedPayload.exp && decodedPayload.exp < (now - 30)) {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
// Validate issued at time (not too far in future)
|
|
84
|
+
if (decodedPayload.iat && decodedPayload.iat > (now + 300)) {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
return decodedPayload;
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
sanitizePayload(payload) {
|
|
94
|
+
if (typeof payload !== 'object' || payload === null) {
|
|
95
|
+
return {};
|
|
96
|
+
}
|
|
97
|
+
const sanitized = {};
|
|
98
|
+
for (const [key, value] of Object.entries(payload)) {
|
|
99
|
+
// Skip dangerous properties
|
|
100
|
+
if (key.startsWith('__') || key === 'constructor' || key === 'prototype') {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
sanitized[key] = value;
|
|
104
|
+
}
|
|
105
|
+
return sanitized;
|
|
106
|
+
}
|
|
107
|
+
constantTimeEqual(a, b) {
|
|
108
|
+
if (a.length !== b.length)
|
|
109
|
+
return false;
|
|
110
|
+
let result = 0;
|
|
111
|
+
for (let i = 0; i < a.length; i++) {
|
|
112
|
+
result |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
113
|
+
}
|
|
114
|
+
return result === 0;
|
|
115
|
+
}
|
|
116
|
+
base64UrlEncode(str) {
|
|
117
|
+
return Buffer.from(str)
|
|
118
|
+
.toString('base64')
|
|
119
|
+
.replace(/\+/g, '-')
|
|
120
|
+
.replace(/\//g, '_')
|
|
121
|
+
.replace(/=/g, '');
|
|
122
|
+
}
|
|
123
|
+
base64UrlDecode(str) {
|
|
124
|
+
str += '='.repeat(4 - str.length % 4);
|
|
125
|
+
return Buffer.from(str.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString();
|
|
126
|
+
}
|
|
127
|
+
createSignature(data) {
|
|
128
|
+
return crypto_1.default
|
|
129
|
+
.createHmac('sha256', this.secret)
|
|
130
|
+
.update(data)
|
|
131
|
+
.digest('base64')
|
|
132
|
+
.replace(/\+/g, '-')
|
|
133
|
+
.replace(/\//g, '_')
|
|
134
|
+
.replace(/=/g, '');
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
exports.JWTManager = JWTManager;
|
|
138
|
+
class SessionManager {
|
|
139
|
+
constructor(secret, maxAge = 86400) {
|
|
140
|
+
this.jwtManager = new JWTManager(secret);
|
|
141
|
+
this.maxAge = maxAge;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Cria uma nova sessão
|
|
145
|
+
*/
|
|
146
|
+
createSession(user) {
|
|
147
|
+
const expires = new Date(Date.now() + this.maxAge * 1000).toISOString();
|
|
148
|
+
const session = {
|
|
149
|
+
user,
|
|
150
|
+
expires
|
|
151
|
+
};
|
|
152
|
+
const token = this.jwtManager.sign({
|
|
153
|
+
...user
|
|
154
|
+
}, this.maxAge);
|
|
155
|
+
return { session, token };
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Verifica uma sessão a partir do token
|
|
159
|
+
*/
|
|
160
|
+
verifySession(token) {
|
|
161
|
+
try {
|
|
162
|
+
const payload = this.jwtManager.verify(token);
|
|
163
|
+
if (!payload)
|
|
164
|
+
return null;
|
|
165
|
+
const session = {
|
|
166
|
+
user: payload,
|
|
167
|
+
expires: new Date(payload.exp * 1000).toISOString()
|
|
168
|
+
};
|
|
169
|
+
return session;
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Atualiza uma sessão existente
|
|
177
|
+
*/
|
|
178
|
+
updateSession(token) {
|
|
179
|
+
const currentSession = this.verifySession(token);
|
|
180
|
+
if (!currentSession)
|
|
181
|
+
return null;
|
|
182
|
+
return this.createSession(currentSession.user);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
exports.SessionManager = SessionManager;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { AuthProviderClass, User } from '../types';
|
|
2
|
+
export interface CredentialsConfig {
|
|
3
|
+
id?: string;
|
|
4
|
+
name?: string;
|
|
5
|
+
credentials: Record<string, {
|
|
6
|
+
label: string;
|
|
7
|
+
type: string;
|
|
8
|
+
placeholder?: string;
|
|
9
|
+
}>;
|
|
10
|
+
authorize: (credentials: Record<string, string>) => Promise<User | null> | User | null;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Provider para autenticação com credenciais (email/senha)
|
|
14
|
+
*
|
|
15
|
+
* Este provider permite autenticação usando email/senha ou qualquer outro
|
|
16
|
+
* sistema de credenciais customizado. Você define a função authorize
|
|
17
|
+
* que será chamada para validar as credenciais.
|
|
18
|
+
*
|
|
19
|
+
* Exemplo de uso:
|
|
20
|
+
* ```typescript
|
|
21
|
+
* new CredentialsProvider({
|
|
22
|
+
* name: "Credentials",
|
|
23
|
+
* credentials: {
|
|
24
|
+
* email: { label: "Email", type: "email" },
|
|
25
|
+
* password: { label: "Password", type: "password" }
|
|
26
|
+
* },
|
|
27
|
+
* async authorize(credentials) {
|
|
28
|
+
* // Aqui você faz a validação com seu banco de dados
|
|
29
|
+
* const user = await validateUser(credentials.email, credentials.password);
|
|
30
|
+
* if (user) {
|
|
31
|
+
* return { id: user.id, name: user.name, email: user.email };
|
|
32
|
+
* }
|
|
33
|
+
* return null;
|
|
34
|
+
* }
|
|
35
|
+
* })
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export declare class CredentialsProvider implements AuthProviderClass {
|
|
39
|
+
readonly id: string;
|
|
40
|
+
readonly name: string;
|
|
41
|
+
readonly type: string;
|
|
42
|
+
private config;
|
|
43
|
+
constructor(config: CredentialsConfig);
|
|
44
|
+
/**
|
|
45
|
+
* Método principal para autenticar usuário com credenciais
|
|
46
|
+
*/
|
|
47
|
+
handleSignIn(credentials: Record<string, string>): Promise<User | null>;
|
|
48
|
+
/**
|
|
49
|
+
* Retorna configuração pública do provider
|
|
50
|
+
*/
|
|
51
|
+
getConfig(): any;
|
|
52
|
+
/**
|
|
53
|
+
* Valida se as credenciais fornecidas são válidas
|
|
54
|
+
*/
|
|
55
|
+
validateCredentials(credentials: Record<string, string>): boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Validação simples de email
|
|
58
|
+
*/
|
|
59
|
+
private isValidEmail;
|
|
60
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CredentialsProvider = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Provider para autenticação com credenciais (email/senha)
|
|
6
|
+
*
|
|
7
|
+
* Este provider permite autenticação usando email/senha ou qualquer outro
|
|
8
|
+
* sistema de credenciais customizado. Você define a função authorize
|
|
9
|
+
* que será chamada para validar as credenciais.
|
|
10
|
+
*
|
|
11
|
+
* Exemplo de uso:
|
|
12
|
+
* ```typescript
|
|
13
|
+
* new CredentialsProvider({
|
|
14
|
+
* name: "Credentials",
|
|
15
|
+
* credentials: {
|
|
16
|
+
* email: { label: "Email", type: "email" },
|
|
17
|
+
* password: { label: "Password", type: "password" }
|
|
18
|
+
* },
|
|
19
|
+
* async authorize(credentials) {
|
|
20
|
+
* // Aqui você faz a validação com seu banco de dados
|
|
21
|
+
* const user = await validateUser(credentials.email, credentials.password);
|
|
22
|
+
* if (user) {
|
|
23
|
+
* return { id: user.id, name: user.name, email: user.email };
|
|
24
|
+
* }
|
|
25
|
+
* return null;
|
|
26
|
+
* }
|
|
27
|
+
* })
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
class CredentialsProvider {
|
|
31
|
+
constructor(config) {
|
|
32
|
+
this.type = 'credentials';
|
|
33
|
+
this.config = config;
|
|
34
|
+
this.id = config.id || 'credentials';
|
|
35
|
+
this.name = config.name || 'Credentials';
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Método principal para autenticar usuário com credenciais
|
|
39
|
+
*/
|
|
40
|
+
async handleSignIn(credentials) {
|
|
41
|
+
try {
|
|
42
|
+
if (!this.config.authorize) {
|
|
43
|
+
throw new Error('Authorize function not provided');
|
|
44
|
+
}
|
|
45
|
+
const user = await this.config.authorize(credentials);
|
|
46
|
+
if (!user) {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
// Adiciona informações do provider ao usuário
|
|
50
|
+
return {
|
|
51
|
+
...user,
|
|
52
|
+
provider: this.id,
|
|
53
|
+
providerId: user.id || user.email || 'unknown'
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
console.error(`[${this.id} Provider] Error during sign in:`, error);
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Retorna configuração pública do provider
|
|
63
|
+
*/
|
|
64
|
+
getConfig() {
|
|
65
|
+
return {
|
|
66
|
+
id: this.id,
|
|
67
|
+
name: this.name,
|
|
68
|
+
type: this.type,
|
|
69
|
+
credentials: this.config.credentials
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Valida se as credenciais fornecidas são válidas
|
|
74
|
+
*/
|
|
75
|
+
validateCredentials(credentials) {
|
|
76
|
+
for (const [key, field] of Object.entries(this.config.credentials)) {
|
|
77
|
+
if (!credentials[key]) {
|
|
78
|
+
console.warn(`[${this.id} Provider] Missing required credential: ${key}`);
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
// Validações básicas por tipo
|
|
82
|
+
if (field.type === 'email' && !this.isValidEmail(credentials[key])) {
|
|
83
|
+
console.warn(`[${this.id} Provider] Invalid email format: ${credentials[key]}`);
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Validação simples de email
|
|
91
|
+
*/
|
|
92
|
+
isValidEmail(email) {
|
|
93
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
94
|
+
return emailRegex.test(email);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
exports.CredentialsProvider = CredentialsProvider;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { AuthProviderClass, AuthRoute, User } from '../types';
|
|
2
|
+
export interface DiscordConfig {
|
|
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 Discord OAuth2
|
|
13
|
+
*
|
|
14
|
+
* Este provider permite autenticação usando Discord OAuth2.
|
|
15
|
+
* Automaticamente gerencia o fluxo OAuth completo e rotas necessárias.
|
|
16
|
+
*
|
|
17
|
+
* Exemplo de uso:
|
|
18
|
+
* ```typescript
|
|
19
|
+
* new DiscordProvider({
|
|
20
|
+
* clientId: process.env.DISCORD_CLIENT_ID!,
|
|
21
|
+
* clientSecret: process.env.DISCORD_CLIENT_SECRET!,
|
|
22
|
+
* callbackUrl: "http://localhost:3000/api/auth/callback/discord"
|
|
23
|
+
* })
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* Fluxo de autenticação:
|
|
27
|
+
* 1. GET /api/auth/signin/discord - Gera URL e redireciona para Discord
|
|
28
|
+
* 2. Discord redireciona para /api/auth/callback/discord 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 Discord
|
|
31
|
+
*/
|
|
32
|
+
export declare class DiscordProvider implements AuthProviderClass {
|
|
33
|
+
readonly id: string;
|
|
34
|
+
readonly name: string;
|
|
35
|
+
readonly type: string;
|
|
36
|
+
private config;
|
|
37
|
+
private readonly defaultScope;
|
|
38
|
+
constructor(config: DiscordConfig);
|
|
39
|
+
/**
|
|
40
|
+
* Método para gerar URL OAuth (usado pelo handleSignIn)
|
|
41
|
+
*/
|
|
42
|
+
handleOauth(credentials?: Record<string, string>): string;
|
|
43
|
+
/**
|
|
44
|
+
* Método principal - agora redireciona para OAuth ou processa callback
|
|
45
|
+
*/
|
|
46
|
+
handleSignIn(credentials: Record<string, string>): Promise<User | string | null>;
|
|
47
|
+
/**
|
|
48
|
+
* Processa o callback OAuth (código → usuário)
|
|
49
|
+
*/
|
|
50
|
+
private processOAuthCallback;
|
|
51
|
+
/**
|
|
52
|
+
* Rotas adicionais específicas do Discord OAuth
|
|
53
|
+
*/
|
|
54
|
+
additionalRoutes: AuthRoute[];
|
|
55
|
+
/**
|
|
56
|
+
* Gera URL de autorização do Discord
|
|
57
|
+
*/
|
|
58
|
+
getAuthorizationUrl(): string;
|
|
59
|
+
/**
|
|
60
|
+
* Retorna configuração pública do provider
|
|
61
|
+
*/
|
|
62
|
+
getConfig(): any;
|
|
63
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DiscordProvider = void 0;
|
|
4
|
+
const hightjs_1 = require("hightjs");
|
|
5
|
+
/**
|
|
6
|
+
* Provider para autenticação com Discord OAuth2
|
|
7
|
+
*
|
|
8
|
+
* Este provider permite autenticação usando Discord OAuth2.
|
|
9
|
+
* Automaticamente gerencia o fluxo OAuth completo e rotas necessárias.
|
|
10
|
+
*
|
|
11
|
+
* Exemplo de uso:
|
|
12
|
+
* ```typescript
|
|
13
|
+
* new DiscordProvider({
|
|
14
|
+
* clientId: process.env.DISCORD_CLIENT_ID!,
|
|
15
|
+
* clientSecret: process.env.DISCORD_CLIENT_SECRET!,
|
|
16
|
+
* callbackUrl: "http://localhost:3000/api/auth/callback/discord"
|
|
17
|
+
* })
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* Fluxo de autenticação:
|
|
21
|
+
* 1. GET /api/auth/signin/discord - Gera URL e redireciona para Discord
|
|
22
|
+
* 2. Discord redireciona para /api/auth/callback/discord 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 Discord
|
|
25
|
+
*/
|
|
26
|
+
class DiscordProvider {
|
|
27
|
+
constructor(config) {
|
|
28
|
+
this.type = 'discord';
|
|
29
|
+
this.defaultScope = ['identify', 'email'];
|
|
30
|
+
/**
|
|
31
|
+
* Rotas adicionais específicas do Discord OAuth
|
|
32
|
+
*/
|
|
33
|
+
this.additionalRoutes = [
|
|
34
|
+
// Rota de callback do Discord
|
|
35
|
+
{
|
|
36
|
+
method: 'GET',
|
|
37
|
+
path: '/api/auth/callback/discord',
|
|
38
|
+
handler: async (req, params) => {
|
|
39
|
+
const url = new URL(req.url || '', 'http://localhost');
|
|
40
|
+
const code = url.searchParams.get('code');
|
|
41
|
+
if (!code) {
|
|
42
|
+
return hightjs_1.HightJSResponse.json({ error: 'Authorization code not provided' }, { status: 400 });
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
// CORREÇÃO: O fluxo correto é delegar o 'code' para o endpoint de signin
|
|
46
|
+
// principal, que processará o código uma única vez. A implementação anterior
|
|
47
|
+
// usava o código duas vezes, causando o erro 'invalid_grant'.
|
|
48
|
+
const authResponse = await fetch(`${req.headers.origin || 'http://localhost:3000'}/api/auth/signin`, {
|
|
49
|
+
method: 'POST',
|
|
50
|
+
headers: {
|
|
51
|
+
'Content-Type': 'application/json',
|
|
52
|
+
},
|
|
53
|
+
body: JSON.stringify({
|
|
54
|
+
provider: this.id,
|
|
55
|
+
code,
|
|
56
|
+
})
|
|
57
|
+
});
|
|
58
|
+
if (authResponse.ok) {
|
|
59
|
+
// Propaga o cookie de sessão retornado pelo endpoint de signin
|
|
60
|
+
// e redireciona o usuário para a página de sucesso.
|
|
61
|
+
const setCookieHeader = authResponse.headers.get('set-cookie');
|
|
62
|
+
if (this.config.successUrl) {
|
|
63
|
+
return hightjs_1.HightJSResponse
|
|
64
|
+
.redirect(this.config.successUrl)
|
|
65
|
+
.header('Set-Cookie', setCookieHeader || '');
|
|
66
|
+
}
|
|
67
|
+
return hightjs_1.HightJSResponse.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 hightjs_1.HightJSResponse.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 hightjs_1.HightJSResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
];
|
|
83
|
+
this.config = config;
|
|
84
|
+
this.id = config.id || 'discord';
|
|
85
|
+
this.name = config.name || 'Discord';
|
|
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 - agora redireciona para OAuth ou processa callback
|
|
95
|
+
*/
|
|
96
|
+
async handleSignIn(credentials) {
|
|
97
|
+
// Se tem código, é callback - processa autenticação
|
|
98
|
+
if (credentials.code) {
|
|
99
|
+
return await this.processOAuthCallback(credentials);
|
|
100
|
+
}
|
|
101
|
+
// Se não tem código, é início do OAuth - retorna URL
|
|
102
|
+
return this.handleOauth(credentials);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Processa o callback OAuth (código → 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 access token
|
|
114
|
+
const tokenResponse = await fetch('https://discord.com/api/oauth2/token', {
|
|
115
|
+
method: 'POST',
|
|
116
|
+
headers: {
|
|
117
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
118
|
+
},
|
|
119
|
+
body: new URLSearchParams({
|
|
120
|
+
client_id: this.config.clientId,
|
|
121
|
+
client_secret: this.config.clientSecret,
|
|
122
|
+
grant_type: 'authorization_code',
|
|
123
|
+
code,
|
|
124
|
+
redirect_uri: this.config.callbackUrl || '',
|
|
125
|
+
}),
|
|
126
|
+
});
|
|
127
|
+
if (!tokenResponse.ok) {
|
|
128
|
+
const error = await tokenResponse.text();
|
|
129
|
+
// O erro original "Invalid \"code\" in request." acontece aqui.
|
|
130
|
+
throw new Error(`Failed to exchange code for token: ${error}`);
|
|
131
|
+
}
|
|
132
|
+
const tokens = await tokenResponse.json();
|
|
133
|
+
// Busca dados do usuário
|
|
134
|
+
const userResponse = await fetch('https://discord.com/api/users/@me', {
|
|
135
|
+
headers: {
|
|
136
|
+
'Authorization': `Bearer ${tokens.access_token}`,
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
if (!userResponse.ok) {
|
|
140
|
+
throw new Error('Failed to fetch user data');
|
|
141
|
+
}
|
|
142
|
+
const discordUser = await userResponse.json();
|
|
143
|
+
// Retorna objeto User padronizado
|
|
144
|
+
return {
|
|
145
|
+
id: discordUser.id,
|
|
146
|
+
name: discordUser.global_name || discordUser.username,
|
|
147
|
+
email: discordUser.email,
|
|
148
|
+
image: discordUser.avatar
|
|
149
|
+
? `https://cdn.discordapp.com/avatars/${discordUser.id}/${discordUser.avatar}.png`
|
|
150
|
+
: null,
|
|
151
|
+
username: discordUser.username,
|
|
152
|
+
discriminator: discordUser.discriminator,
|
|
153
|
+
provider: this.id,
|
|
154
|
+
providerId: discordUser.id,
|
|
155
|
+
accessToken: tokens.access_token,
|
|
156
|
+
refreshToken: tokens.refresh_token
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
console.error(`[${this.id} Provider] Error during OAuth callback:`, error);
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Gera URL de autorização do Discord
|
|
166
|
+
*/
|
|
167
|
+
getAuthorizationUrl() {
|
|
168
|
+
const params = new URLSearchParams({
|
|
169
|
+
client_id: this.config.clientId,
|
|
170
|
+
redirect_uri: this.config.callbackUrl || '',
|
|
171
|
+
response_type: 'code',
|
|
172
|
+
scope: (this.config.scope || this.defaultScope).join(' ')
|
|
173
|
+
});
|
|
174
|
+
return `https://discord.com/api/oauth2/authorize?${params.toString()}`;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Retorna configuração pública do provider
|
|
178
|
+
*/
|
|
179
|
+
getConfig() {
|
|
180
|
+
return {
|
|
181
|
+
id: this.id,
|
|
182
|
+
name: this.name,
|
|
183
|
+
type: this.type,
|
|
184
|
+
clientId: this.config.clientId, // Público
|
|
185
|
+
scope: this.config.scope || this.defaultScope,
|
|
186
|
+
callbackUrl: this.config.callbackUrl
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
exports.DiscordProvider = DiscordProvider;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { AuthProviderClass, AuthRoute, User } from '../types';
|
|
2
|
+
export interface GoogleConfig {
|
|
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 Google OAuth2
|
|
13
|
+
*
|
|
14
|
+
* Este provider permite autenticação usando Google OAuth2.
|
|
15
|
+
* Automaticamente gerencia o fluxo OAuth completo e rotas necessárias.
|
|
16
|
+
*
|
|
17
|
+
* Exemplo de uso:
|
|
18
|
+
* ```typescript
|
|
19
|
+
* new GoogleProvider({
|
|
20
|
+
* clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
21
|
+
* clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
22
|
+
* callbackUrl: "http://localhost:3000/api/auth/callback/google"
|
|
23
|
+
* })
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* Fluxo de autenticação:
|
|
27
|
+
* 1. GET /api/auth/signin/google - Gera URL e redireciona para Google
|
|
28
|
+
* 2. Google redireciona para /api/auth/callback/google 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 Google
|
|
31
|
+
*/
|
|
32
|
+
export declare class GoogleProvider implements AuthProviderClass {
|
|
33
|
+
readonly id: string;
|
|
34
|
+
readonly name: string;
|
|
35
|
+
readonly type: string;
|
|
36
|
+
private config;
|
|
37
|
+
private readonly defaultScope;
|
|
38
|
+
constructor(config: GoogleConfig);
|
|
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 Google OAuth
|
|
53
|
+
*/
|
|
54
|
+
additionalRoutes: AuthRoute[];
|
|
55
|
+
/**
|
|
56
|
+
* Gera a URL de autorização do Google
|
|
57
|
+
*/
|
|
58
|
+
getAuthorizationUrl(): string;
|
|
59
|
+
/**
|
|
60
|
+
* Retorna a configuração pública do provider
|
|
61
|
+
*/
|
|
62
|
+
getConfig(): any;
|
|
63
|
+
}
|