hightjs 0.4.0 → 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.
Files changed (125) hide show
  1. package/README.md +48 -116
  2. package/dist/bin/hightjs.js +51 -23
  3. package/dist/builder.js +139 -4
  4. package/dist/client/DefaultNotFound.d.ts +1 -1
  5. package/dist/client/DefaultNotFound.js +72 -46
  6. package/dist/client/client.d.ts +3 -0
  7. package/dist/{client.js → client/client.js} +4 -4
  8. package/dist/client/entry.client.js +39 -29
  9. package/dist/global/global.d.ts +117 -0
  10. package/dist/{auth/types.js → global/global.js} +0 -1
  11. package/dist/helpers.js +80 -2
  12. package/dist/hotReload.js +2 -2
  13. package/dist/index.js +16 -16
  14. package/dist/loaders.d.ts +1 -0
  15. package/dist/loaders.js +46 -0
  16. package/dist/renderer.js +158 -4
  17. package/dist/types.d.ts +44 -0
  18. package/package.json +36 -31
  19. package/.idea/HightJS.iml +0 -9
  20. package/.idea/copilot.data.migration.agent.xml +0 -6
  21. package/.idea/copilot.data.migration.ask.xml +0 -6
  22. package/.idea/copilot.data.migration.ask2agent.xml +0 -6
  23. package/.idea/copilot.data.migration.edit.xml +0 -6
  24. package/.idea/copilotDiffState.xml +0 -67
  25. package/.idea/inspectionProfiles/Project_Default.xml +0 -13
  26. package/.idea/libraries/test_package.xml +0 -9
  27. package/.idea/libraries/ts_commonjs_default_export.xml +0 -9
  28. package/.idea/misc.xml +0 -7
  29. package/.idea/modules.xml +0 -8
  30. package/.idea/vcs.xml +0 -6
  31. package/dist/auth/client.d.ts +0 -24
  32. package/dist/auth/client.js +0 -146
  33. package/dist/auth/components.d.ts +0 -29
  34. package/dist/auth/components.js +0 -100
  35. package/dist/auth/core.d.ts +0 -55
  36. package/dist/auth/core.js +0 -189
  37. package/dist/auth/index.d.ts +0 -7
  38. package/dist/auth/index.js +0 -45
  39. package/dist/auth/jwt.d.ts +0 -41
  40. package/dist/auth/jwt.js +0 -185
  41. package/dist/auth/providers/credentials.d.ts +0 -60
  42. package/dist/auth/providers/credentials.js +0 -97
  43. package/dist/auth/providers/discord.d.ts +0 -63
  44. package/dist/auth/providers/discord.js +0 -190
  45. package/dist/auth/providers/google.d.ts +0 -63
  46. package/dist/auth/providers/google.js +0 -186
  47. package/dist/auth/providers/index.d.ts +0 -2
  48. package/dist/auth/providers/index.js +0 -35
  49. package/dist/auth/providers.d.ts +0 -3
  50. package/dist/auth/providers.js +0 -26
  51. package/dist/auth/react/index.d.ts +0 -6
  52. package/dist/auth/react/index.js +0 -48
  53. package/dist/auth/react.d.ts +0 -22
  54. package/dist/auth/react.js +0 -199
  55. package/dist/auth/routes.d.ts +0 -16
  56. package/dist/auth/routes.js +0 -152
  57. package/dist/auth/types.d.ts +0 -76
  58. package/dist/client.d.ts +0 -3
  59. package/docs/README.md +0 -58
  60. package/docs/arquivos-especiais.md +0 -10
  61. package/docs/autenticacao.md +0 -212
  62. package/docs/checklist.md +0 -9
  63. package/docs/cli.md +0 -72
  64. package/docs/config.md +0 -216
  65. package/docs/estrutura.md +0 -20
  66. package/docs/faq.md +0 -10
  67. package/docs/hot-reload.md +0 -5
  68. package/docs/integracoes.md +0 -240
  69. package/docs/middlewares.md +0 -73
  70. package/docs/rotas-backend.md +0 -45
  71. package/docs/rotas-frontend.md +0 -66
  72. package/docs/seguranca.md +0 -8
  73. package/docs/websocket.md +0 -45
  74. package/example/certs/cert.pem +0 -20
  75. package/example/certs/key.pem +0 -27
  76. package/example/hightjs.config.ts +0 -87
  77. package/example/package-lock.json +0 -1174
  78. package/example/package.json +0 -26
  79. package/example/postcss.config.js +0 -8
  80. package/example/src/backend/auth.ts +0 -42
  81. package/example/src/backend/routes/auth.ts +0 -3
  82. package/example/src/backend/routes/version.ts +0 -13
  83. package/example/src/web/components/Home.tsx +0 -140
  84. package/example/src/web/components/LoginPage.tsx +0 -149
  85. package/example/src/web/globals.css +0 -5
  86. package/example/src/web/layout.tsx +0 -100
  87. package/example/src/web/routes/index.tsx +0 -13
  88. package/example/src/web/routes/login.tsx +0 -30
  89. package/example/tailwind.config.js +0 -12
  90. package/example/tsconfig.json +0 -15
  91. package/src/adapters/express.ts +0 -87
  92. package/src/adapters/factory.ts +0 -112
  93. package/src/adapters/fastify.ts +0 -104
  94. package/src/adapters/native.ts +0 -234
  95. package/src/api/console.ts +0 -305
  96. package/src/api/http.ts +0 -535
  97. package/src/auth/client.ts +0 -171
  98. package/src/auth/components.tsx +0 -125
  99. package/src/auth/core.ts +0 -215
  100. package/src/auth/index.ts +0 -25
  101. package/src/auth/jwt.ts +0 -210
  102. package/src/auth/providers/credentials.ts +0 -139
  103. package/src/auth/providers/discord.ts +0 -239
  104. package/src/auth/providers/google.ts +0 -234
  105. package/src/auth/providers/index.ts +0 -20
  106. package/src/auth/providers.ts +0 -20
  107. package/src/auth/react/index.ts +0 -25
  108. package/src/auth/react.tsx +0 -234
  109. package/src/auth/routes.ts +0 -183
  110. package/src/auth/types.ts +0 -108
  111. package/src/bin/hightjs.js +0 -222
  112. package/src/builder.js +0 -472
  113. package/src/client/DefaultNotFound.tsx +0 -84
  114. package/src/client/clientRouter.ts +0 -153
  115. package/src/client/entry.client.tsx +0 -511
  116. package/src/client.ts +0 -24
  117. package/src/components/Link.tsx +0 -38
  118. package/src/helpers.ts +0 -542
  119. package/src/hotReload.ts +0 -569
  120. package/src/index.ts +0 -555
  121. package/src/renderer.tsx +0 -263
  122. package/src/router.ts +0 -730
  123. package/src/types/framework.ts +0 -58
  124. package/src/types.ts +0 -207
  125. package/tsconfig.json +0 -17
@@ -1,125 +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 React, { ReactNode } from 'react';
18
- import { useAuth } from './react';
19
- import { router } from '../client/clientRouter';
20
- interface ProtectedRouteProps {
21
- children: ReactNode;
22
- fallback?: ReactNode;
23
- redirectTo?: string;
24
- requireAuth?: boolean;
25
- }
26
-
27
- /**
28
- * Componente para proteger rotas que requerem autenticação
29
- */
30
- export function ProtectedRoute({
31
- children,
32
- fallback,
33
- redirectTo = '/auth/signin',
34
- requireAuth = true
35
- }: ProtectedRouteProps) {
36
- const { isAuthenticated, isLoading } = useAuth();
37
-
38
- // Ainda carregando
39
- if (isLoading) {
40
- return fallback || <div>Loading...</div>;
41
- }
42
-
43
- // Requer auth mas não está autenticado
44
- if (requireAuth && !isAuthenticated) {
45
- if (typeof window !== 'undefined' && redirectTo) {
46
- window.location.href = redirectTo;
47
- return null;
48
- }
49
- return fallback || <div>Unauthorized</div>;
50
- }
51
-
52
- // Não requer auth mas está autenticado (ex: página de login)
53
- if (!requireAuth && isAuthenticated && redirectTo) {
54
- if (typeof window !== 'undefined') {
55
- window.location.href = redirectTo;
56
- return null;
57
- }
58
- }
59
-
60
- return <>{children}</>;
61
- }
62
-
63
- interface GuardProps {
64
- children: ReactNode;
65
- fallback?: ReactNode;
66
- redirectTo?: string;
67
- }
68
-
69
- /**
70
- * Guard simples que só renderiza children se estiver autenticado
71
- */
72
- export function AuthGuard({ children, fallback, redirectTo }: GuardProps) {
73
- const { isAuthenticated, isLoading } = useAuth();
74
-
75
- if(redirectTo && !isLoading && !isAuthenticated) {
76
- router.push(redirectTo);
77
- }
78
-
79
- if (isLoading) {
80
- return fallback || <div></div>;
81
- }
82
-
83
- if (!isAuthenticated) {
84
- return fallback || null;
85
- }
86
-
87
- return <>{children}</>;
88
- }
89
-
90
- /**
91
- * Componente para mostrar conteúdo apenas para usuários não autenticados
92
- */
93
- export function GuestOnly({ children, fallback, redirectTo }: GuardProps) {
94
- const { isAuthenticated, isLoading } = useAuth();
95
-
96
- if(redirectTo && !isLoading && isAuthenticated) {
97
- router.push(redirectTo);
98
- }
99
-
100
- if (isLoading || isAuthenticated) {
101
- return fallback || <div></div>;
102
- }
103
-
104
- return <>{children}</>;
105
- }
106
-
107
- /**
108
- * Hook para redirecionar baseado no status de autenticação
109
- */
110
- export function useAuthRedirect(
111
- authenticatedRedirect?: string,
112
- unauthenticatedRedirect?: string
113
- ) {
114
- const { isAuthenticated, isLoading } = useAuth();
115
-
116
- React.useEffect(() => {
117
- if (isLoading) return;
118
-
119
- if (isAuthenticated && authenticatedRedirect) {
120
- window.location.href = authenticatedRedirect;
121
- } else if (!isAuthenticated && unauthenticatedRedirect) {
122
- window.location.href = unauthenticatedRedirect;
123
- }
124
- }, [isAuthenticated, isLoading, authenticatedRedirect, unauthenticatedRedirect]);
125
- }
package/src/auth/core.ts DELETED
@@ -1,215 +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 { HightJSRequest, HightJSResponse } from '../api/http';
18
- import type { AuthConfig, AuthProviderClass, User, Session } from './types';
19
- import { SessionManager } from './jwt';
20
-
21
- export class HWebAuth {
22
- private config: AuthConfig;
23
- private sessionManager: SessionManager;
24
-
25
- constructor(config: AuthConfig) {
26
- this.config = {
27
- session: { strategy: 'jwt', maxAge: 86400, ...config.session },
28
- pages: { signIn: '/auth/signin', signOut: '/auth/signout', ...config.pages },
29
- ...config
30
- };
31
-
32
- this.sessionManager = new SessionManager(
33
- config.secret,
34
- this.config.session?.maxAge || 86400
35
- );
36
- }
37
-
38
- /**
39
- * Middleware para adicionar autenticação às rotas
40
- */
41
- private async middleware(req: HightJSRequest): Promise<{ session: Session | null; user: User | null }> {
42
- const token = this.getTokenFromRequest(req);
43
-
44
- if (!token) {
45
- return { session: null, user: null };
46
- }
47
-
48
- const session = this.sessionManager.verifySession(token);
49
- return {
50
- session,
51
- user: session?.user || null
52
- };
53
- }
54
-
55
- /**
56
- * Autentica um usuário usando um provider específico
57
- */
58
- async signIn(providerId: string, credentials: Record<string, string>): Promise<{ session: Session; token: string } | { redirectUrl: string } | null> {
59
- const provider = this.config.providers.find(p => p.id === providerId);
60
- if (!provider) {
61
- console.error(`[hweb-auth] Provider not found: ${providerId}`);
62
- return null;
63
- }
64
-
65
- try {
66
- // Usa o método handleSignIn do provider
67
- const result = await provider.handleSignIn(credentials);
68
-
69
- if (!result) return null;
70
-
71
- // Se resultado é string, é URL de redirecionamento OAuth
72
- if (typeof result === 'string') {
73
- return { redirectUrl: result };
74
- }
75
-
76
- // Se resultado é User, cria sessão
77
- const user = result as User;
78
-
79
- // Callback de signIn se definido
80
- if (this.config.callbacks?.signIn) {
81
- const allowed = await this.config.callbacks.signIn(user, { provider: providerId }, {});
82
- if (!allowed) return null;
83
- }
84
-
85
- const sessionResult = this.sessionManager.createSession(user);
86
-
87
- // Callback de sessão se definido
88
- if (this.config.callbacks?.session) {
89
- sessionResult.session = await this.config.callbacks.session({session: sessionResult.session, user, provider: providerId});
90
- }
91
-
92
- return sessionResult;
93
- } catch (error) {
94
- console.error(`[hweb-auth] Error signing in with provider ${providerId}:`, error);
95
- return null;
96
- }
97
- }
98
-
99
- /**
100
- * Faz logout do usuário
101
- */
102
- async signOut(req: HightJSRequest): Promise<HightJSResponse> {
103
- // Busca a sessão atual para saber qual provider usar
104
- const { session } = await this.middleware(req);
105
-
106
- if (session?.user?.provider) {
107
- const provider = this.config.providers.find(p => p.id === session.user.provider);
108
- if (provider && provider.handleSignOut) {
109
- try {
110
- await provider.handleSignOut();
111
- } catch (error) {
112
- console.error(`[hweb-auth] Signout error on provider ${provider.id}:`, error);
113
- }
114
- }
115
- }
116
-
117
- return HightJSResponse
118
- .json({ success: true })
119
- .clearCookie('hweb-auth-token', {
120
- path: '/',
121
- httpOnly: true,
122
- secure: this.config.secureCookies || false,
123
- sameSite: 'strict'
124
- });
125
- }
126
-
127
- /**
128
- * Obtém a sessão atual
129
- */
130
- async getSession(req: HightJSRequest): Promise<Session | null> {
131
- const { session } = await this.middleware(req);
132
- return session;
133
- }
134
-
135
- /**
136
- * Verifica se o usuário está autenticado
137
- */
138
- async isAuthenticated(req: HightJSRequest): Promise<boolean> {
139
- const session = await this.getSession(req);
140
- return session !== null;
141
- }
142
-
143
- /**
144
- * Retorna todos os providers disponíveis (dados públicos)
145
- */
146
- getProviders(): any[] {
147
- return this.config.providers.map(provider => ({
148
- id: provider.id,
149
- name: provider.name,
150
- type: provider.type,
151
- config: provider.getConfig ? provider.getConfig() : {}
152
- }));
153
- }
154
-
155
- /**
156
- * Busca um provider específico
157
- */
158
- getProvider(id: string): AuthProviderClass | null {
159
- return this.config.providers.find(p => p.id === id) || null;
160
- }
161
-
162
- /**
163
- * Retorna todas as rotas adicionais dos providers
164
- */
165
- getAllAdditionalRoutes(): Array<{ provider: string; route: any }> {
166
- const routes: Array<{ provider: string; route: any }> = [];
167
-
168
- for (const provider of this.config.providers) {
169
- if (provider.additionalRoutes) {
170
- for (const route of provider.additionalRoutes) {
171
- routes.push({ provider: provider.id, route });
172
- }
173
- }
174
- }
175
-
176
- return routes;
177
- }
178
-
179
- /**
180
- * Cria resposta com cookie de autenticação - Secure implementation
181
- */
182
- createAuthResponse(token: string, data: any): HightJSResponse {
183
- return HightJSResponse
184
- .json(data)
185
- .cookie('hweb-auth-token', token, {
186
- httpOnly: true,
187
- secure: this.config.secureCookies || false, // Always secure, even in development
188
- sameSite: 'strict', // Prevent CSRF attacks
189
- maxAge: (this.config.session?.maxAge || 86400) * 1000,
190
- path: '/',
191
- domain: undefined // Let browser set automatically for security
192
- })
193
- .header('X-Content-Type-Options', 'nosniff')
194
- .header('X-Frame-Options', 'DENY')
195
- .header('X-XSS-Protection', '1; mode=block')
196
- .header('Referrer-Policy', 'strict-origin-when-cross-origin');
197
- }
198
-
199
- /**
200
- * Extrai token da requisição (cookie ou header)
201
- */
202
- private getTokenFromRequest(req: HightJSRequest): string | null {
203
- // Primeiro tenta pegar do cookie
204
- const cookieToken = req.cookie('hweb-auth-token');
205
- if (cookieToken) return cookieToken;
206
-
207
- // Depois tenta do header Authorization
208
- const authHeader = req.header('authorization');
209
- if (authHeader && typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {
210
- return authHeader.substring(7);
211
- }
212
-
213
- return null;
214
- }
215
- }
package/src/auth/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 principais do sistema de autenticação
18
- export * from './types';
19
- export * from './providers';
20
- export * from './core';
21
- export * from './routes';
22
- export * from './jwt';
23
-
24
- export { CredentialsProvider, DiscordProvider, GoogleProvider } from './providers';
25
- export { createAuthRoutes } from './routes';
package/src/auth/jwt.ts DELETED
@@ -1,210 +0,0 @@
1
- /*
2
- * This file is part of the HightJS Project.
3
- * Copyright (c) 2025 itsmuzin
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- import crypto from 'crypto';
18
- import type { User, Session } from './types';
19
-
20
- export class JWTManager {
21
- private secret: string;
22
-
23
- constructor(secret?: string) {
24
- if (!secret && !process.env.HWEB_AUTH_SECRET) {
25
- throw new Error('JWT secret is required. Set HWEB_AUTH_SECRET environment variable or provide secret parameter.');
26
- }
27
-
28
- this.secret = secret || process.env.HWEB_AUTH_SECRET!;
29
-
30
- if (this.secret.length < 32) {
31
- throw new Error('JWT secret must be at least 32 characters long for security.');
32
- }
33
- }
34
-
35
- /**
36
- * Cria um JWT token com validação de algoritmo
37
- */
38
- sign(payload: any, expiresIn: number = 86400): string {
39
- const header = { alg: 'HS256', typ: 'JWT' };
40
- const now = Math.floor(Date.now() / 1000);
41
-
42
- // Sanitize payload to prevent injection
43
- const sanitizedPayload = this.sanitizePayload(payload);
44
-
45
- const tokenPayload = {
46
- ...sanitizedPayload,
47
- iat: now,
48
- exp: now + expiresIn,
49
- alg: 'HS256' // Prevent algorithm confusion attacks
50
- };
51
-
52
- const encodedHeader = this.base64UrlEncode(JSON.stringify(header));
53
- const encodedPayload = this.base64UrlEncode(JSON.stringify(tokenPayload));
54
-
55
- const signature = this.createSignature(encodedHeader + '.' + encodedPayload);
56
-
57
- return `${encodedHeader}.${encodedPayload}.${signature}`;
58
- }
59
-
60
- /**
61
- * Verifica e decodifica um JWT token com validação rigorosa
62
- */
63
- verify(token: string): any | null {
64
- try {
65
- if (!token || typeof token !== 'string') return null;
66
-
67
- const parts = token.split('.');
68
- if (parts.length !== 3) return null;
69
-
70
- const [headerEncoded, payloadEncoded, signature] = parts;
71
-
72
- // Decode and validate header
73
- const header = JSON.parse(this.base64UrlDecode(headerEncoded));
74
- if (header.alg !== 'HS256' || header.typ !== 'JWT') {
75
- return null; // Prevent algorithm confusion attacks
76
- }
77
-
78
- // Verifica a assinatura usando constant-time comparison
79
- const expectedSignature = this.createSignature(headerEncoded + '.' + payloadEncoded);
80
- if (!this.constantTimeEqual(signature, expectedSignature)) return null;
81
-
82
- // Decodifica o payload
83
- const decodedPayload = JSON.parse(this.base64UrlDecode(payloadEncoded));
84
-
85
- // Validate algorithm in payload matches header
86
- if (decodedPayload.alg !== 'HS256') return null;
87
-
88
- // Verifica expiração com margem de erro de 30 segundos
89
- const now = Math.floor(Date.now() / 1000);
90
- if (decodedPayload.exp && decodedPayload.exp < (now - 30)) {
91
- return null;
92
- }
93
-
94
- // Validate issued at time (not too far in future)
95
- if (decodedPayload.iat && decodedPayload.iat > (now + 300)) {
96
- return null;
97
- }
98
-
99
- return decodedPayload;
100
- } catch (error) {
101
- return null;
102
- }
103
- }
104
-
105
- private sanitizePayload(payload: any): any {
106
- if (typeof payload !== 'object' || payload === null) {
107
- return {};
108
- }
109
-
110
- const sanitized: any = {};
111
- for (const [key, value] of Object.entries(payload)) {
112
- // Skip dangerous properties
113
- if (key.startsWith('__') || key === 'constructor' || key === 'prototype') {
114
- continue;
115
- }
116
- sanitized[key] = value;
117
- }
118
- return sanitized;
119
- }
120
-
121
- private constantTimeEqual(a: string, b: string): boolean {
122
- if (a.length !== b.length) return false;
123
-
124
- let result = 0;
125
- for (let i = 0; i < a.length; i++) {
126
- result |= a.charCodeAt(i) ^ b.charCodeAt(i);
127
- }
128
- return result === 0;
129
- }
130
-
131
- private base64UrlEncode(str: string): string {
132
- return Buffer.from(str)
133
- .toString('base64')
134
- .replace(/\+/g, '-')
135
- .replace(/\//g, '_')
136
- .replace(/=/g, '');
137
- }
138
-
139
- private base64UrlDecode(str: string): string {
140
- str += '='.repeat(4 - str.length % 4);
141
- return Buffer.from(str.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString();
142
- }
143
-
144
- private createSignature(data: string): string {
145
- return crypto
146
- .createHmac('sha256', this.secret)
147
- .update(data)
148
- .digest('base64')
149
- .replace(/\+/g, '-')
150
- .replace(/\//g, '_')
151
- .replace(/=/g, '');
152
- }
153
- }
154
-
155
- export class SessionManager {
156
- private jwtManager: JWTManager;
157
- private maxAge: number;
158
-
159
- constructor(secret?: string, maxAge: number = 86400) {
160
- this.jwtManager = new JWTManager(secret);
161
- this.maxAge = maxAge;
162
- }
163
-
164
- /**
165
- * Cria uma nova sessão
166
- */
167
- createSession(user: User): { session: Session; token: string } {
168
- const expires = new Date(Date.now() + this.maxAge * 1000).toISOString();
169
-
170
- const session: Session = {
171
- user,
172
- expires
173
- };
174
-
175
- const token = this.jwtManager.sign({
176
- ...user
177
- }, this.maxAge);
178
-
179
- return { session, token };
180
- }
181
-
182
- /**
183
- * Verifica uma sessão a partir do token
184
- */
185
- verifySession(token: string): Session | null {
186
- try {
187
- const payload = this.jwtManager.verify(token);
188
- if (!payload) return null;
189
-
190
- const session: Session = {
191
- user: payload,
192
- expires: new Date(payload.exp * 1000).toISOString()
193
- };
194
-
195
- return session;
196
- } catch (error) {
197
- return null;
198
- }
199
- }
200
-
201
- /**
202
- * Atualiza uma sessão existente
203
- */
204
- updateSession(token: string): { session: Session; token: string } | null {
205
- const currentSession = this.verifySession(token);
206
- if (!currentSession) return null;
207
-
208
- return this.createSession(currentSession.user);
209
- }
210
- }