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
package/dist/auth/core.js
DELETED
|
@@ -1,189 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.HWebAuth = void 0;
|
|
4
|
-
/*
|
|
5
|
-
* This file is part of the HightJS Project.
|
|
6
|
-
* Copyright (c) 2025 itsmuzin
|
|
7
|
-
*
|
|
8
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
9
|
-
* you may not use this file except in compliance with the License.
|
|
10
|
-
* You may obtain a copy of the License at
|
|
11
|
-
*
|
|
12
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
13
|
-
*
|
|
14
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
15
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
16
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
17
|
-
* See the License for the specific language governing permissions and
|
|
18
|
-
* limitations under the License.
|
|
19
|
-
*/
|
|
20
|
-
const http_1 = require("../api/http");
|
|
21
|
-
const jwt_1 = require("./jwt");
|
|
22
|
-
class HWebAuth {
|
|
23
|
-
constructor(config) {
|
|
24
|
-
this.config = {
|
|
25
|
-
session: { strategy: 'jwt', maxAge: 86400, ...config.session },
|
|
26
|
-
pages: { signIn: '/auth/signin', signOut: '/auth/signout', ...config.pages },
|
|
27
|
-
...config
|
|
28
|
-
};
|
|
29
|
-
this.sessionManager = new jwt_1.SessionManager(config.secret, this.config.session?.maxAge || 86400);
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Middleware para adicionar autenticação às rotas
|
|
33
|
-
*/
|
|
34
|
-
async middleware(req) {
|
|
35
|
-
const token = this.getTokenFromRequest(req);
|
|
36
|
-
if (!token) {
|
|
37
|
-
return { session: null, user: null };
|
|
38
|
-
}
|
|
39
|
-
const session = this.sessionManager.verifySession(token);
|
|
40
|
-
return {
|
|
41
|
-
session,
|
|
42
|
-
user: session?.user || null
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Autentica um usuário usando um provider específico
|
|
47
|
-
*/
|
|
48
|
-
async signIn(providerId, credentials) {
|
|
49
|
-
const provider = this.config.providers.find(p => p.id === providerId);
|
|
50
|
-
if (!provider) {
|
|
51
|
-
console.error(`[hweb-auth] Provider not found: ${providerId}`);
|
|
52
|
-
return null;
|
|
53
|
-
}
|
|
54
|
-
try {
|
|
55
|
-
// Usa o método handleSignIn do provider
|
|
56
|
-
const result = await provider.handleSignIn(credentials);
|
|
57
|
-
if (!result)
|
|
58
|
-
return null;
|
|
59
|
-
// Se resultado é string, é URL de redirecionamento OAuth
|
|
60
|
-
if (typeof result === 'string') {
|
|
61
|
-
return { redirectUrl: result };
|
|
62
|
-
}
|
|
63
|
-
// Se resultado é User, cria sessão
|
|
64
|
-
const user = result;
|
|
65
|
-
// Callback de signIn se definido
|
|
66
|
-
if (this.config.callbacks?.signIn) {
|
|
67
|
-
const allowed = await this.config.callbacks.signIn(user, { provider: providerId }, {});
|
|
68
|
-
if (!allowed)
|
|
69
|
-
return null;
|
|
70
|
-
}
|
|
71
|
-
const sessionResult = this.sessionManager.createSession(user);
|
|
72
|
-
// Callback de sessão se definido
|
|
73
|
-
if (this.config.callbacks?.session) {
|
|
74
|
-
sessionResult.session = await this.config.callbacks.session({ session: sessionResult.session, user, provider: providerId });
|
|
75
|
-
}
|
|
76
|
-
return sessionResult;
|
|
77
|
-
}
|
|
78
|
-
catch (error) {
|
|
79
|
-
console.error(`[hweb-auth] Error signing in with provider ${providerId}:`, error);
|
|
80
|
-
return null;
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* Faz logout do usuário
|
|
85
|
-
*/
|
|
86
|
-
async signOut(req) {
|
|
87
|
-
// Busca a sessão atual para saber qual provider usar
|
|
88
|
-
const { session } = await this.middleware(req);
|
|
89
|
-
if (session?.user?.provider) {
|
|
90
|
-
const provider = this.config.providers.find(p => p.id === session.user.provider);
|
|
91
|
-
if (provider && provider.handleSignOut) {
|
|
92
|
-
try {
|
|
93
|
-
await provider.handleSignOut();
|
|
94
|
-
}
|
|
95
|
-
catch (error) {
|
|
96
|
-
console.error(`[hweb-auth] Signout error on provider ${provider.id}:`, error);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
return http_1.HightJSResponse
|
|
101
|
-
.json({ success: true })
|
|
102
|
-
.clearCookie('hweb-auth-token', {
|
|
103
|
-
path: '/',
|
|
104
|
-
httpOnly: true,
|
|
105
|
-
secure: this.config.secureCookies || false,
|
|
106
|
-
sameSite: 'strict'
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* Obtém a sessão atual
|
|
111
|
-
*/
|
|
112
|
-
async getSession(req) {
|
|
113
|
-
const { session } = await this.middleware(req);
|
|
114
|
-
return session;
|
|
115
|
-
}
|
|
116
|
-
/**
|
|
117
|
-
* Verifica se o usuário está autenticado
|
|
118
|
-
*/
|
|
119
|
-
async isAuthenticated(req) {
|
|
120
|
-
const session = await this.getSession(req);
|
|
121
|
-
return session !== null;
|
|
122
|
-
}
|
|
123
|
-
/**
|
|
124
|
-
* Retorna todos os providers disponíveis (dados públicos)
|
|
125
|
-
*/
|
|
126
|
-
getProviders() {
|
|
127
|
-
return this.config.providers.map(provider => ({
|
|
128
|
-
id: provider.id,
|
|
129
|
-
name: provider.name,
|
|
130
|
-
type: provider.type,
|
|
131
|
-
config: provider.getConfig ? provider.getConfig() : {}
|
|
132
|
-
}));
|
|
133
|
-
}
|
|
134
|
-
/**
|
|
135
|
-
* Busca um provider específico
|
|
136
|
-
*/
|
|
137
|
-
getProvider(id) {
|
|
138
|
-
return this.config.providers.find(p => p.id === id) || null;
|
|
139
|
-
}
|
|
140
|
-
/**
|
|
141
|
-
* Retorna todas as rotas adicionais dos providers
|
|
142
|
-
*/
|
|
143
|
-
getAllAdditionalRoutes() {
|
|
144
|
-
const routes = [];
|
|
145
|
-
for (const provider of this.config.providers) {
|
|
146
|
-
if (provider.additionalRoutes) {
|
|
147
|
-
for (const route of provider.additionalRoutes) {
|
|
148
|
-
routes.push({ provider: provider.id, route });
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
return routes;
|
|
153
|
-
}
|
|
154
|
-
/**
|
|
155
|
-
* Cria resposta com cookie de autenticação - Secure implementation
|
|
156
|
-
*/
|
|
157
|
-
createAuthResponse(token, data) {
|
|
158
|
-
return http_1.HightJSResponse
|
|
159
|
-
.json(data)
|
|
160
|
-
.cookie('hweb-auth-token', token, {
|
|
161
|
-
httpOnly: true,
|
|
162
|
-
secure: this.config.secureCookies || false, // Always secure, even in development
|
|
163
|
-
sameSite: 'strict', // Prevent CSRF attacks
|
|
164
|
-
maxAge: (this.config.session?.maxAge || 86400) * 1000,
|
|
165
|
-
path: '/',
|
|
166
|
-
domain: undefined // Let browser set automatically for security
|
|
167
|
-
})
|
|
168
|
-
.header('X-Content-Type-Options', 'nosniff')
|
|
169
|
-
.header('X-Frame-Options', 'DENY')
|
|
170
|
-
.header('X-XSS-Protection', '1; mode=block')
|
|
171
|
-
.header('Referrer-Policy', 'strict-origin-when-cross-origin');
|
|
172
|
-
}
|
|
173
|
-
/**
|
|
174
|
-
* Extrai token da requisição (cookie ou header)
|
|
175
|
-
*/
|
|
176
|
-
getTokenFromRequest(req) {
|
|
177
|
-
// Primeiro tenta pegar do cookie
|
|
178
|
-
const cookieToken = req.cookie('hweb-auth-token');
|
|
179
|
-
if (cookieToken)
|
|
180
|
-
return cookieToken;
|
|
181
|
-
// Depois tenta do header Authorization
|
|
182
|
-
const authHeader = req.header('authorization');
|
|
183
|
-
if (authHeader && typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {
|
|
184
|
-
return authHeader.substring(7);
|
|
185
|
-
}
|
|
186
|
-
return null;
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
exports.HWebAuth = HWebAuth;
|
package/dist/auth/index.d.ts
DELETED
package/dist/auth/index.js
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
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
|
-
exports.createAuthRoutes = exports.GoogleProvider = exports.DiscordProvider = exports.CredentialsProvider = void 0;
|
|
18
|
-
/*
|
|
19
|
-
* This file is part of the HightJS Project.
|
|
20
|
-
* Copyright (c) 2025 itsmuzin
|
|
21
|
-
*
|
|
22
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
23
|
-
* you may not use this file except in compliance with the License.
|
|
24
|
-
* You may obtain a copy of the License at
|
|
25
|
-
*
|
|
26
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
27
|
-
*
|
|
28
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
29
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
30
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
31
|
-
* See the License for the specific language governing permissions and
|
|
32
|
-
* limitations under the License.
|
|
33
|
-
*/
|
|
34
|
-
// Exportações principais do sistema de autenticação
|
|
35
|
-
__exportStar(require("./types"), exports);
|
|
36
|
-
__exportStar(require("./providers"), exports);
|
|
37
|
-
__exportStar(require("./core"), exports);
|
|
38
|
-
__exportStar(require("./routes"), exports);
|
|
39
|
-
__exportStar(require("./jwt"), exports);
|
|
40
|
-
var providers_1 = require("./providers");
|
|
41
|
-
Object.defineProperty(exports, "CredentialsProvider", { enumerable: true, get: function () { return providers_1.CredentialsProvider; } });
|
|
42
|
-
Object.defineProperty(exports, "DiscordProvider", { enumerable: true, get: function () { return providers_1.DiscordProvider; } });
|
|
43
|
-
Object.defineProperty(exports, "GoogleProvider", { enumerable: true, get: function () { return providers_1.GoogleProvider; } });
|
|
44
|
-
var routes_1 = require("./routes");
|
|
45
|
-
Object.defineProperty(exports, "createAuthRoutes", { enumerable: true, get: function () { return routes_1.createAuthRoutes; } });
|
package/dist/auth/jwt.d.ts
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import type { User, Session } from './types';
|
|
2
|
-
export declare class JWTManager {
|
|
3
|
-
private secret;
|
|
4
|
-
constructor(secret?: string);
|
|
5
|
-
/**
|
|
6
|
-
* Cria um JWT token com validação de algoritmo
|
|
7
|
-
*/
|
|
8
|
-
sign(payload: any, expiresIn?: number): string;
|
|
9
|
-
/**
|
|
10
|
-
* Verifica e decodifica um JWT token com validação rigorosa
|
|
11
|
-
*/
|
|
12
|
-
verify(token: string): any | null;
|
|
13
|
-
private sanitizePayload;
|
|
14
|
-
private constantTimeEqual;
|
|
15
|
-
private base64UrlEncode;
|
|
16
|
-
private base64UrlDecode;
|
|
17
|
-
private createSignature;
|
|
18
|
-
}
|
|
19
|
-
export declare class SessionManager {
|
|
20
|
-
private jwtManager;
|
|
21
|
-
private maxAge;
|
|
22
|
-
constructor(secret?: string, maxAge?: number);
|
|
23
|
-
/**
|
|
24
|
-
* Cria uma nova sessão
|
|
25
|
-
*/
|
|
26
|
-
createSession(user: User): {
|
|
27
|
-
session: Session;
|
|
28
|
-
token: string;
|
|
29
|
-
};
|
|
30
|
-
/**
|
|
31
|
-
* Verifica uma sessão a partir do token
|
|
32
|
-
*/
|
|
33
|
-
verifySession(token: string): Session | null;
|
|
34
|
-
/**
|
|
35
|
-
* Atualiza uma sessão existente
|
|
36
|
-
*/
|
|
37
|
-
updateSession(token: string): {
|
|
38
|
-
session: Session;
|
|
39
|
-
token: string;
|
|
40
|
-
} | null;
|
|
41
|
-
}
|
package/dist/auth/jwt.js
DELETED
|
@@ -1,185 +0,0 @@
|
|
|
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;
|
|
@@ -1,60 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,97 +0,0 @@
|
|
|
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;
|
|
@@ -1,63 +0,0 @@
|
|
|
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
|
-
}
|