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