hightjs 0.1.1 → 0.2.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/dist/api/http.js +5 -3
- package/dist/auth/client.d.ts +11 -1
- package/dist/auth/client.js +78 -0
- package/dist/auth/core.d.ts +21 -4
- package/dist/auth/core.js +66 -17
- package/dist/auth/example.d.ts +40 -0
- package/dist/auth/example.js +104 -0
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +2 -1
- package/dist/auth/providers/credentials.d.ts +68 -0
- package/dist/auth/providers/credentials.js +132 -0
- package/dist/auth/providers/discord.d.ts +67 -0
- package/dist/auth/providers/discord.js +198 -0
- package/dist/auth/providers/index.d.ts +2 -0
- package/dist/auth/providers/index.js +19 -0
- package/dist/auth/providers.d.ts +2 -5
- package/dist/auth/providers.js +6 -12
- package/dist/auth/react.js +20 -13
- package/dist/auth/routes.d.ts +2 -2
- package/dist/auth/routes.js +45 -13
- package/dist/auth/types.d.ts +36 -21
- package/dist/router.js +9 -1
- package/package.json +1 -1
- package/src/api/http.ts +6 -2
- package/src/auth/client.ts +84 -3
- package/src/auth/core.ts +75 -19
- package/src/auth/example.ts +115 -0
- package/src/auth/index.ts +2 -1
- package/src/auth/providers/credentials.ts +158 -0
- package/src/auth/providers/discord.ts +231 -0
- package/src/auth/providers/index.ts +4 -0
- package/src/auth/providers.ts +3 -12
- package/src/auth/react.tsx +21 -13
- package/src/auth/routes.ts +51 -18
- package/src/auth/types.ts +49 -26
- package/src/router.ts +9 -1
|
@@ -0,0 +1,67 @@
|
|
|
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
|
+
* Método opcional para logout
|
|
53
|
+
*/
|
|
54
|
+
handleSignOut?(): Promise<void>;
|
|
55
|
+
/**
|
|
56
|
+
* Rotas adicionais específicas do Discord OAuth
|
|
57
|
+
*/
|
|
58
|
+
additionalRoutes: AuthRoute[];
|
|
59
|
+
/**
|
|
60
|
+
* Gera URL de autorização do Discord
|
|
61
|
+
*/
|
|
62
|
+
getAuthorizationUrl(): string;
|
|
63
|
+
/**
|
|
64
|
+
* Retorna configuração pública do provider
|
|
65
|
+
*/
|
|
66
|
+
getConfig(): any;
|
|
67
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DiscordProvider = void 0;
|
|
4
|
+
const http_1 = require("../../api/http");
|
|
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 http_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 http_1.HightJSResponse
|
|
64
|
+
.redirect(this.config.successUrl)
|
|
65
|
+
.header('Set-Cookie', setCookieHeader || '');
|
|
66
|
+
}
|
|
67
|
+
return http_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 http_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 http_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
|
+
* Método opcional para logout
|
|
166
|
+
*/
|
|
167
|
+
async handleSignOut() {
|
|
168
|
+
// Discord OAuth não precisa de logout especial
|
|
169
|
+
// O token será invalidado pelo tempo de vida
|
|
170
|
+
console.log(`[${this.id} Provider] User signed out`);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Gera URL de autorização do Discord
|
|
174
|
+
*/
|
|
175
|
+
getAuthorizationUrl() {
|
|
176
|
+
const params = new URLSearchParams({
|
|
177
|
+
client_id: this.config.clientId,
|
|
178
|
+
redirect_uri: this.config.callbackUrl || '',
|
|
179
|
+
response_type: 'code',
|
|
180
|
+
scope: (this.config.scope || this.defaultScope).join(' ')
|
|
181
|
+
});
|
|
182
|
+
return `https://discord.com/api/oauth2/authorize?${params.toString()}`;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Retorna configuração pública do provider
|
|
186
|
+
*/
|
|
187
|
+
getConfig() {
|
|
188
|
+
return {
|
|
189
|
+
id: this.id,
|
|
190
|
+
name: this.name,
|
|
191
|
+
type: this.type,
|
|
192
|
+
clientId: this.config.clientId, // Público
|
|
193
|
+
scope: this.config.scope || this.defaultScope,
|
|
194
|
+
callbackUrl: this.config.callbackUrl
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
exports.DiscordProvider = DiscordProvider;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
// Exportações dos providers
|
|
18
|
+
__exportStar(require("./credentials"), exports);
|
|
19
|
+
__exportStar(require("./discord"), exports);
|
package/dist/auth/providers.d.ts
CHANGED
|
@@ -1,5 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* Provider para autenticação com credenciais (email/senha)
|
|
4
|
-
*/
|
|
5
|
-
export declare function CredentialsProvider(config: CredentialsConfig): AuthProvider;
|
|
1
|
+
export { CredentialsProvider } from './providers/credentials';
|
|
2
|
+
export { DiscordProvider } from './providers/discord';
|
package/dist/auth/providers.js
CHANGED
|
@@ -1,14 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.CredentialsProvider =
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
id: config.id || 'credentials',
|
|
10
|
-
name: config.name || 'Credentials',
|
|
11
|
-
type: 'credentials',
|
|
12
|
-
authorize: config.authorize
|
|
13
|
-
};
|
|
14
|
-
}
|
|
3
|
+
exports.DiscordProvider = exports.CredentialsProvider = void 0;
|
|
4
|
+
// Exportações dos providers
|
|
5
|
+
var credentials_1 = require("./providers/credentials");
|
|
6
|
+
Object.defineProperty(exports, "CredentialsProvider", { enumerable: true, get: function () { return credentials_1.CredentialsProvider; } });
|
|
7
|
+
var discord_1 = require("./providers/discord");
|
|
8
|
+
Object.defineProperty(exports, "DiscordProvider", { enumerable: true, get: function () { return discord_1.DiscordProvider; } });
|
package/dist/auth/react.js
CHANGED
|
@@ -5,7 +5,7 @@ exports.useSession = useSession;
|
|
|
5
5
|
exports.useAuth = useAuth;
|
|
6
6
|
const jsx_runtime_1 = require("react/jsx-runtime");
|
|
7
7
|
const react_1 = require("react");
|
|
8
|
-
const
|
|
8
|
+
const clientRouter_1 = require("../client/clientRouter");
|
|
9
9
|
const SessionContext = (0, react_1.createContext)(undefined);
|
|
10
10
|
function SessionProvider({ children, basePath = '/api/auth', refetchInterval = 0, refetchOnWindowFocus = true }) {
|
|
11
11
|
const [session, setSession] = (0, react_1.useState)(null);
|
|
@@ -57,21 +57,28 @@ function SessionProvider({ children, basePath = '/api/auth', refetchInterval = 0
|
|
|
57
57
|
});
|
|
58
58
|
const data = await response.json();
|
|
59
59
|
if (response.ok && data.success) {
|
|
60
|
-
//
|
|
61
|
-
if (
|
|
62
|
-
|
|
63
|
-
|
|
60
|
+
// Se é OAuth, redireciona para URL fornecida
|
|
61
|
+
if (data.type === 'oauth' && data.redirectUrl) {
|
|
62
|
+
if (redirect && typeof window !== 'undefined') {
|
|
63
|
+
window.location.href = data.redirectUrl;
|
|
64
64
|
}
|
|
65
|
-
|
|
65
|
+
return {
|
|
66
|
+
ok: true,
|
|
67
|
+
status: 200,
|
|
68
|
+
url: data.redirectUrl
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
// Se é sessão (credentials), redireciona para callbackUrl
|
|
72
|
+
if (data.type === 'session') {
|
|
73
|
+
if (redirect && typeof window !== 'undefined') {
|
|
66
74
|
window.location.href = callbackUrl || '/';
|
|
67
75
|
}
|
|
76
|
+
return {
|
|
77
|
+
ok: true,
|
|
78
|
+
status: 200,
|
|
79
|
+
url: callbackUrl || '/'
|
|
80
|
+
};
|
|
68
81
|
}
|
|
69
|
-
await fetchSession();
|
|
70
|
-
return {
|
|
71
|
-
ok: true,
|
|
72
|
-
status: 200,
|
|
73
|
-
url: callbackUrl || '/'
|
|
74
|
-
};
|
|
75
82
|
}
|
|
76
83
|
else {
|
|
77
84
|
return {
|
|
@@ -101,7 +108,7 @@ function SessionProvider({ children, basePath = '/api/auth', refetchInterval = 0
|
|
|
101
108
|
setStatus('unauthenticated');
|
|
102
109
|
if (typeof window !== 'undefined') {
|
|
103
110
|
try {
|
|
104
|
-
|
|
111
|
+
clientRouter_1.router.push(options.callbackUrl || '/');
|
|
105
112
|
}
|
|
106
113
|
catch (e) {
|
|
107
114
|
window.location.href = options.callbackUrl || '/';
|
package/dist/auth/routes.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { HightJSRequest
|
|
1
|
+
import { HightJSRequest } from '../api/http';
|
|
2
2
|
import type { AuthConfig } from './types';
|
|
3
3
|
import { HWebAuth } from './core';
|
|
4
4
|
/**
|
|
@@ -8,7 +8,7 @@ export declare function createAuthRoutes(config: AuthConfig): {
|
|
|
8
8
|
pattern: string;
|
|
9
9
|
GET(req: HightJSRequest, params: {
|
|
10
10
|
[key: string]: string;
|
|
11
|
-
}): Promise<
|
|
11
|
+
}): Promise<any>;
|
|
12
12
|
POST(req: HightJSRequest, params: {
|
|
13
13
|
[key: string]: string;
|
|
14
14
|
}): Promise<any>;
|
package/dist/auth/routes.js
CHANGED
|
@@ -13,17 +13,31 @@ function createAuthRoutes(config) {
|
|
|
13
13
|
* Uso: /api/auth/[...value].ts
|
|
14
14
|
*/
|
|
15
15
|
return {
|
|
16
|
-
pattern: '/api/auth/[value]',
|
|
16
|
+
pattern: '/api/auth/[...value]',
|
|
17
17
|
async GET(req, params) {
|
|
18
18
|
const path = params["value"];
|
|
19
19
|
const route = Array.isArray(path) ? path.join('/') : path || '';
|
|
20
|
+
// Verifica rotas adicionais dos providers primeiro
|
|
21
|
+
const additionalRoutes = auth.getAllAdditionalRoutes();
|
|
22
|
+
for (const { provider, route: additionalRoute } of additionalRoutes) {
|
|
23
|
+
if (additionalRoute.method === 'GET' && additionalRoute.path.includes(route)) {
|
|
24
|
+
try {
|
|
25
|
+
return await additionalRoute.handler(req, params);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
console.error(`[${provider} Provider] Error in additional route:`, error);
|
|
29
|
+
return http_1.HightJSResponse.json({ error: 'Provider route error' }, { status: 500 });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
// Rotas padrão do sistema
|
|
20
34
|
switch (route) {
|
|
21
35
|
case 'session':
|
|
22
36
|
return await handleSession(req, auth);
|
|
23
37
|
case 'csrf':
|
|
24
38
|
return await handleCsrf(req);
|
|
25
39
|
case 'providers':
|
|
26
|
-
return await handleProviders(
|
|
40
|
+
return await handleProviders(auth);
|
|
27
41
|
default:
|
|
28
42
|
return http_1.HightJSResponse.json({ error: 'Route not found' }, { status: 404 });
|
|
29
43
|
}
|
|
@@ -31,6 +45,20 @@ function createAuthRoutes(config) {
|
|
|
31
45
|
async POST(req, params) {
|
|
32
46
|
const path = params["value"];
|
|
33
47
|
const route = Array.isArray(path) ? path.join('/') : path || '';
|
|
48
|
+
// Verifica rotas adicionais dos providers primeiro
|
|
49
|
+
const additionalRoutes = auth.getAllAdditionalRoutes();
|
|
50
|
+
for (const { provider, route: additionalRoute } of additionalRoutes) {
|
|
51
|
+
if (additionalRoute.method === 'POST' && additionalRoute.path.includes(route)) {
|
|
52
|
+
try {
|
|
53
|
+
return await additionalRoute.handler(req, params);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
console.error(`[${provider} Provider] Error in additional route:`, error);
|
|
57
|
+
return http_1.HightJSResponse.json({ error: 'Provider route error' }, { status: 500 });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
// Rotas padrão do sistema
|
|
34
62
|
switch (route) {
|
|
35
63
|
case 'signin':
|
|
36
64
|
return await handleSignIn(req, auth);
|
|
@@ -66,14 +94,8 @@ async function handleCsrf(req) {
|
|
|
66
94
|
/**
|
|
67
95
|
* Handler para GET /api/auth/providers
|
|
68
96
|
*/
|
|
69
|
-
async function handleProviders(
|
|
70
|
-
const providers =
|
|
71
|
-
.filter(p => p.type === 'credentials') // Apenas credentials
|
|
72
|
-
.map(p => ({
|
|
73
|
-
id: p.id,
|
|
74
|
-
name: p.name,
|
|
75
|
-
type: p.type
|
|
76
|
-
}));
|
|
97
|
+
async function handleProviders(auth) {
|
|
98
|
+
const providers = auth.getProviders();
|
|
77
99
|
return http_1.HightJSResponse.json({ providers });
|
|
78
100
|
}
|
|
79
101
|
/**
|
|
@@ -82,17 +104,27 @@ async function handleProviders(config) {
|
|
|
82
104
|
async function handleSignIn(req, auth) {
|
|
83
105
|
try {
|
|
84
106
|
const { provider = 'credentials', ...credentials } = await req.json();
|
|
85
|
-
// Apenas credentials agora
|
|
86
107
|
const result = await auth.signIn(provider, credentials);
|
|
87
108
|
if (!result) {
|
|
88
109
|
return http_1.HightJSResponse.json({ error: 'Invalid credentials' }, { status: 401 });
|
|
89
110
|
}
|
|
111
|
+
// Se tem redirectUrl, é OAuth - retorna URL para redirecionamento
|
|
112
|
+
if ('redirectUrl' in result) {
|
|
113
|
+
return http_1.HightJSResponse.json({
|
|
114
|
+
success: true,
|
|
115
|
+
redirectUrl: result.redirectUrl,
|
|
116
|
+
type: 'oauth'
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
// Se tem session, é credentials - retorna sessão
|
|
90
120
|
return auth.createAuthResponse(result.token, {
|
|
91
121
|
success: true,
|
|
92
|
-
user: result.session.user
|
|
122
|
+
user: result.session.user,
|
|
123
|
+
type: 'session'
|
|
93
124
|
});
|
|
94
125
|
}
|
|
95
126
|
catch (error) {
|
|
127
|
+
console.error('[hweb-auth] Erro no handleSignIn:', error);
|
|
96
128
|
return http_1.HightJSResponse.json({ error: 'Authentication failed' }, { status: 500 });
|
|
97
129
|
}
|
|
98
130
|
}
|
|
@@ -100,5 +132,5 @@ async function handleSignIn(req, auth) {
|
|
|
100
132
|
* Handler para POST /api/auth/signout
|
|
101
133
|
*/
|
|
102
134
|
async function handleSignOut(req, auth) {
|
|
103
|
-
return auth.signOut();
|
|
135
|
+
return await auth.signOut(req);
|
|
104
136
|
}
|
package/dist/auth/types.d.ts
CHANGED
|
@@ -4,8 +4,43 @@ export interface Session {
|
|
|
4
4
|
expires: string;
|
|
5
5
|
accessToken?: string;
|
|
6
6
|
}
|
|
7
|
+
export interface SignInOptions {
|
|
8
|
+
redirect?: boolean;
|
|
9
|
+
callbackUrl?: string;
|
|
10
|
+
[key: string]: any;
|
|
11
|
+
}
|
|
12
|
+
export interface SignInResult {
|
|
13
|
+
error?: string;
|
|
14
|
+
status?: number;
|
|
15
|
+
ok?: boolean;
|
|
16
|
+
url?: string;
|
|
17
|
+
}
|
|
18
|
+
export interface SessionContextType {
|
|
19
|
+
data: Session | null;
|
|
20
|
+
status: 'loading' | 'authenticated' | 'unauthenticated';
|
|
21
|
+
signIn: (provider?: string, options?: SignInOptions) => Promise<SignInResult | undefined>;
|
|
22
|
+
signOut: (options?: {
|
|
23
|
+
callbackUrl?: string;
|
|
24
|
+
}) => Promise<void>;
|
|
25
|
+
update: () => Promise<Session | null>;
|
|
26
|
+
}
|
|
27
|
+
export interface AuthRoute {
|
|
28
|
+
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
29
|
+
path: string;
|
|
30
|
+
handler: (req: any, params: any) => Promise<any>;
|
|
31
|
+
}
|
|
32
|
+
export interface AuthProviderClass {
|
|
33
|
+
id: string;
|
|
34
|
+
name: string;
|
|
35
|
+
type: string;
|
|
36
|
+
handleOauth?(credentials: Record<string, string>): Promise<string> | string;
|
|
37
|
+
handleSignIn(credentials: Record<string, string>): Promise<User | string | null>;
|
|
38
|
+
handleSignOut?(): Promise<void>;
|
|
39
|
+
additionalRoutes?: AuthRoute[];
|
|
40
|
+
getConfig?(): any;
|
|
41
|
+
}
|
|
7
42
|
export interface AuthConfig {
|
|
8
|
-
providers:
|
|
43
|
+
providers: AuthProviderClass[];
|
|
9
44
|
pages?: {
|
|
10
45
|
signIn?: string;
|
|
11
46
|
signOut?: string;
|
|
@@ -30,26 +65,6 @@ export interface AuthProvider {
|
|
|
30
65
|
type: 'credentials';
|
|
31
66
|
authorize?: (credentials: Record<string, string>) => Promise<User | null> | User | null;
|
|
32
67
|
}
|
|
33
|
-
export interface SignInOptions {
|
|
34
|
-
redirect?: boolean;
|
|
35
|
-
callbackUrl?: string;
|
|
36
|
-
[key: string]: any;
|
|
37
|
-
}
|
|
38
|
-
export interface SignInResult {
|
|
39
|
-
error?: string;
|
|
40
|
-
status?: number;
|
|
41
|
-
ok?: boolean;
|
|
42
|
-
url?: string;
|
|
43
|
-
}
|
|
44
|
-
export interface SessionContextType {
|
|
45
|
-
data: Session | null;
|
|
46
|
-
status: 'loading' | 'authenticated' | 'unauthenticated';
|
|
47
|
-
signIn: (provider?: string, options?: SignInOptions) => Promise<SignInResult | undefined>;
|
|
48
|
-
signOut: (options?: {
|
|
49
|
-
callbackUrl?: string;
|
|
50
|
-
}) => Promise<void>;
|
|
51
|
-
update: () => Promise<Session | null>;
|
|
52
|
-
}
|
|
53
68
|
export interface CredentialsConfig {
|
|
54
69
|
id?: string;
|
|
55
70
|
name?: string;
|
package/dist/router.js
CHANGED
|
@@ -309,7 +309,15 @@ function findMatchingBackendRoute(pathname, method) {
|
|
|
309
309
|
// Verifica se a rota tem um handler para o método HTTP atual
|
|
310
310
|
if (!route.pattern || !route[method.toUpperCase()])
|
|
311
311
|
continue;
|
|
312
|
-
const regexPattern = route.pattern
|
|
312
|
+
const regexPattern = route.pattern
|
|
313
|
+
// [[...param]] → opcional catch-all
|
|
314
|
+
.replace(/\[\[\.\.\.(\w+)\]\]/g, '(?<$1>.+)?')
|
|
315
|
+
// [...param] → obrigatório catch-all
|
|
316
|
+
.replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)')
|
|
317
|
+
// [[param]] → segmento opcional
|
|
318
|
+
.replace(/\[\[(\w+)\]\]/g, '(?<$1>[^/]+)?')
|
|
319
|
+
// [param] → segmento obrigatório
|
|
320
|
+
.replace(/\[(\w+)\]/g, '(?<$1>[^/]+)');
|
|
313
321
|
const regex = new RegExp(`^${regexPattern}/?$`);
|
|
314
322
|
const match = pathname.match(regex);
|
|
315
323
|
if (match) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hightjs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "HightJS is a high-level framework for building web applications with ease and speed. It provides a robust set of tools and features to streamline development and enhance productivity.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
package/src/api/http.ts
CHANGED
|
@@ -407,12 +407,16 @@ export class HightJSResponse {
|
|
|
407
407
|
}
|
|
408
408
|
});
|
|
409
409
|
|
|
410
|
+
// Handle redirects specifically
|
|
411
|
+
if (this._headers['Location']) {
|
|
412
|
+
res.redirect(this._headers['Location']);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
|
|
410
416
|
// Envia o corpo se foi definido
|
|
411
417
|
if (this._sent && this._body !== null) {
|
|
412
418
|
if (this._headers['Content-Type']?.includes('application/json')) {
|
|
413
419
|
res.json(JSON.parse(this._body));
|
|
414
|
-
} else if (this._headers['Location']) {
|
|
415
|
-
res.redirect(this._headers['Location']);
|
|
416
420
|
} else {
|
|
417
421
|
res.send(this._body);
|
|
418
422
|
}
|