hightjs 0.3.5 → 0.5.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/README.md +48 -116
- package/dist/bin/hightjs.js +51 -23
- package/dist/builder.js +198 -8
- 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 +77 -9
- 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 +84 -4
- package/dist/index.js +72 -61
- 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 -30
- 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/auth.ts +0 -42
- package/example/src/web/backend/routes/auth.ts +0 -3
- package/example/src/web/backend/routes/version.ts +0 -13
- package/example/src/web/globals.css +0 -5
- package/example/src/web/layout.tsx +0 -100
- package/example/src/web/routes/index.tsx +0 -153
- package/example/src/web/routes/login.tsx +0 -175
- package/example/tailwind.config.js +0 -12
- package/example/tsconfig.json +0 -15
- package/src/adapters/express.ts +0 -87
- package/src/adapters/factory.ts +0 -112
- package/src/adapters/fastify.ts +0 -104
- package/src/adapters/native.ts +0 -234
- package/src/api/console.ts +0 -305
- package/src/api/http.ts +0 -535
- 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/src/bin/hightjs.js +0 -222
- package/src/builder.js +0 -411
- package/src/client/DefaultNotFound.tsx +0 -84
- package/src/client/clientRouter.ts +0 -153
- package/src/client/entry.client.tsx +0 -444
- package/src/client.ts +0 -24
- package/src/components/Link.tsx +0 -38
- package/src/helpers.ts +0 -542
- package/src/hotReload.ts +0 -489
- package/src/index.ts +0 -546
- package/src/renderer.tsx +0 -263
- package/src/router.ts +0 -730
- package/src/types/framework.ts +0 -58
- package/src/types.ts +0 -207
- package/tsconfig.json +0 -17
|
@@ -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
|
-
}
|
|
@@ -1,234 +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 GoogleConfig {
|
|
21
|
-
id?: string;
|
|
22
|
-
name?: string;
|
|
23
|
-
clientId: string;
|
|
24
|
-
clientSecret: string;
|
|
25
|
-
callbackUrl?: string;
|
|
26
|
-
successUrl?: string;
|
|
27
|
-
// Escopos OAuth do Google, padrão: ['openid', 'email', 'profile']
|
|
28
|
-
scope?: string[];
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Provider para autenticação com Google OAuth2
|
|
33
|
-
*
|
|
34
|
-
* Este provider permite autenticação usando Google OAuth2.
|
|
35
|
-
* Automaticamente gerencia o fluxo OAuth completo e rotas necessárias.
|
|
36
|
-
*
|
|
37
|
-
* Exemplo de uso:
|
|
38
|
-
* ```typescript
|
|
39
|
-
* new GoogleProvider({
|
|
40
|
-
* clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
41
|
-
* clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
42
|
-
* callbackUrl: "http://localhost:3000/api/auth/callback/google"
|
|
43
|
-
* })
|
|
44
|
-
* ```
|
|
45
|
-
*
|
|
46
|
-
* Fluxo de autenticação:
|
|
47
|
-
* 1. GET /api/auth/signin/google - Gera URL e redireciona para Google
|
|
48
|
-
* 2. Google redireciona para /api/auth/callback/google 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 Google
|
|
51
|
-
*/
|
|
52
|
-
export class GoogleProvider implements AuthProviderClass {
|
|
53
|
-
public readonly id: string;
|
|
54
|
-
public readonly name: string;
|
|
55
|
-
public readonly type: string = 'google';
|
|
56
|
-
|
|
57
|
-
private config: GoogleConfig;
|
|
58
|
-
private readonly defaultScope = [
|
|
59
|
-
'openid',
|
|
60
|
-
'https://www.googleapis.com/auth/userinfo.email',
|
|
61
|
-
'https://www.googleapis.com/auth/userinfo.profile'
|
|
62
|
-
];
|
|
63
|
-
|
|
64
|
-
constructor(config: GoogleConfig) {
|
|
65
|
-
this.config = config;
|
|
66
|
-
this.id = config.id || 'google';
|
|
67
|
-
this.name = config.name || 'Google';
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* Método para gerar URL OAuth (usado pelo handleSignIn)
|
|
72
|
-
*/
|
|
73
|
-
handleOauth(credentials: Record<string, string> = {}): string {
|
|
74
|
-
return this.getAuthorizationUrl();
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* Método principal - redireciona para OAuth ou processa o callback
|
|
79
|
-
*/
|
|
80
|
-
async handleSignIn(credentials: Record<string, string>): Promise<User | string | null> {
|
|
81
|
-
// Se tem código, é o callback - processa a autenticação
|
|
82
|
-
if (credentials.code) {
|
|
83
|
-
return await this.processOAuthCallback(credentials);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// Se não tem código, é o início do OAuth - retorna a URL
|
|
87
|
-
return this.handleOauth(credentials);
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Processa o callback do OAuth (troca o código pelo usuário)
|
|
92
|
-
*/
|
|
93
|
-
private async processOAuthCallback(credentials: Record<string, string>): Promise<User | null> {
|
|
94
|
-
try {
|
|
95
|
-
const { code } = credentials;
|
|
96
|
-
if (!code) {
|
|
97
|
-
throw new Error('Authorization code not provided');
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
// Troca o código por um access token
|
|
101
|
-
const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {
|
|
102
|
-
method: 'POST',
|
|
103
|
-
headers: {
|
|
104
|
-
'Content-Type': 'application/x-www-form-urlencoded',
|
|
105
|
-
},
|
|
106
|
-
body: new URLSearchParams({
|
|
107
|
-
client_id: this.config.clientId,
|
|
108
|
-
client_secret: this.config.clientSecret,
|
|
109
|
-
grant_type: 'authorization_code',
|
|
110
|
-
code,
|
|
111
|
-
redirect_uri: this.config.callbackUrl || '',
|
|
112
|
-
}),
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
if (!tokenResponse.ok) {
|
|
116
|
-
const error = await tokenResponse.text();
|
|
117
|
-
throw new Error(`Failed to exchange code for token: ${error}`);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
const tokens = await tokenResponse.json();
|
|
121
|
-
|
|
122
|
-
// Busca os dados do usuário com o access token
|
|
123
|
-
const userResponse = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
|
|
124
|
-
headers: {
|
|
125
|
-
'Authorization': `Bearer ${tokens.access_token}`,
|
|
126
|
-
},
|
|
127
|
-
});
|
|
128
|
-
|
|
129
|
-
if (!userResponse.ok) {
|
|
130
|
-
throw new Error('Failed to fetch user data');
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
const googleUser = await userResponse.json();
|
|
134
|
-
|
|
135
|
-
// Retorna o objeto User padronizado
|
|
136
|
-
return {
|
|
137
|
-
id: googleUser.id,
|
|
138
|
-
name: googleUser.name,
|
|
139
|
-
email: googleUser.email,
|
|
140
|
-
image: googleUser.picture || null,
|
|
141
|
-
provider: this.id,
|
|
142
|
-
providerId: googleUser.id,
|
|
143
|
-
accessToken: tokens.access_token,
|
|
144
|
-
refreshToken: tokens.refresh_token
|
|
145
|
-
};
|
|
146
|
-
|
|
147
|
-
} catch (error) {
|
|
148
|
-
console.error(`[${this.id} Provider] Error during OAuth callback:`, error);
|
|
149
|
-
return null;
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/**
|
|
154
|
-
* Rotas adicionais específicas do Google OAuth
|
|
155
|
-
*/
|
|
156
|
-
public additionalRoutes: AuthRoute[] = [
|
|
157
|
-
// Rota de callback do Google
|
|
158
|
-
{
|
|
159
|
-
method: 'GET',
|
|
160
|
-
path: '/api/auth/callback/google',
|
|
161
|
-
handler: async (req: HightJSRequest, params: any) => {
|
|
162
|
-
const url = new URL(req.url || '', 'http://localhost');
|
|
163
|
-
const code = url.searchParams.get('code');
|
|
164
|
-
|
|
165
|
-
if (!code) {
|
|
166
|
-
return HightJSResponse.json({ error: 'Authorization code not provided' }, { status: 400 });
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
try {
|
|
170
|
-
// Delega o 'code' para o endpoint de signin principal
|
|
171
|
-
const authResponse = await fetch(`${req.headers.origin || 'http://localhost:3000'}/api/auth/signin`, {
|
|
172
|
-
method: 'POST',
|
|
173
|
-
headers: {
|
|
174
|
-
'Content-Type': 'application/json',
|
|
175
|
-
},
|
|
176
|
-
body: JSON.stringify({
|
|
177
|
-
provider: this.id,
|
|
178
|
-
code,
|
|
179
|
-
})
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
if (authResponse.ok) {
|
|
183
|
-
// Propaga o cookie de sessão e redireciona para a URL de sucesso
|
|
184
|
-
const setCookieHeader = authResponse.headers.get('set-cookie');
|
|
185
|
-
|
|
186
|
-
if(this.config.successUrl) {
|
|
187
|
-
return HightJSResponse
|
|
188
|
-
.redirect(this.config.successUrl)
|
|
189
|
-
.header('Set-Cookie', setCookieHeader || '');
|
|
190
|
-
}
|
|
191
|
-
return HightJSResponse.json({ success: true })
|
|
192
|
-
.header('Set-Cookie', setCookieHeader || '');
|
|
193
|
-
} else {
|
|
194
|
-
const errorText = await authResponse.text();
|
|
195
|
-
console.error(`[${this.id} Provider] Session creation failed during callback. Status: ${authResponse.status}, Body: ${errorText}`);
|
|
196
|
-
return HightJSResponse.json({ error: 'Session creation failed' }, { status: 500 });
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
} catch (error) {
|
|
200
|
-
console.error(`[${this.id} Provider] Callback handler fetch error:`, error);
|
|
201
|
-
return HightJSResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
];
|
|
206
|
-
|
|
207
|
-
/**
|
|
208
|
-
* Gera a URL de autorização do Google
|
|
209
|
-
*/
|
|
210
|
-
getAuthorizationUrl(): string {
|
|
211
|
-
const params = new URLSearchParams({
|
|
212
|
-
client_id: this.config.clientId,
|
|
213
|
-
redirect_uri: this.config.callbackUrl || '',
|
|
214
|
-
response_type: 'code',
|
|
215
|
-
scope: (this.config.scope || this.defaultScope).join(' ')
|
|
216
|
-
});
|
|
217
|
-
|
|
218
|
-
return `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
/**
|
|
222
|
-
* Retorna a configuração pública do provider
|
|
223
|
-
*/
|
|
224
|
-
getConfig(): any {
|
|
225
|
-
return {
|
|
226
|
-
id: this.id,
|
|
227
|
-
name: this.name,
|
|
228
|
-
type: this.type,
|
|
229
|
-
clientId: this.config.clientId, // Público
|
|
230
|
-
scope: this.config.scope || this.defaultScope,
|
|
231
|
-
callbackUrl: this.config.callbackUrl
|
|
232
|
-
};
|
|
233
|
-
}
|
|
234
|
-
}
|
|
@@ -1,20 +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
|
-
// Exportações dos providers
|
|
18
|
-
export * from './credentials';
|
|
19
|
-
export * from './discord';
|
|
20
|
-
|
package/src/auth/providers.ts
DELETED
|
@@ -1,20 +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
|
-
// Exportações dos providers
|
|
18
|
-
export { CredentialsProvider } from './providers/credentials';
|
|
19
|
-
export { DiscordProvider } from './providers/discord';
|
|
20
|
-
export { GoogleProvider } from './providers/google';
|
package/src/auth/react/index.ts
DELETED
|
@@ -1,25 +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
|
-
// Exportações do frontend
|
|
18
|
-
export * from '../react';
|
|
19
|
-
export * from '../client';
|
|
20
|
-
export * from '../components';
|
|
21
|
-
|
|
22
|
-
// Re-exports das funções mais usadas para conveniência
|
|
23
|
-
export { getSession } from '../client';
|
|
24
|
-
export { useSession, useAuth, SessionProvider } from '../react';
|
|
25
|
-
export { ProtectedRoute, AuthGuard, GuestOnly } from '../components';
|