@nytejs/auth 1.0.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/LICENSE +13 -0
- package/README.md +48 -0
- package/dist/client.d.ts +24 -0
- package/dist/client.js +146 -0
- package/dist/components.d.ts +19 -0
- package/dist/components.js +73 -0
- package/dist/core.d.ts +55 -0
- package/dist/core.js +189 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +45 -0
- package/dist/jwt.d.ts +41 -0
- package/dist/jwt.js +185 -0
- package/dist/providers/credentials.d.ts +60 -0
- package/dist/providers/credentials.js +97 -0
- package/dist/providers/discord.d.ts +63 -0
- package/dist/providers/discord.js +190 -0
- package/dist/providers/google.d.ts +63 -0
- package/dist/providers/google.js +186 -0
- package/dist/providers/index.d.ts +2 -0
- package/dist/providers/index.js +35 -0
- package/dist/providers.d.ts +3 -0
- package/dist/providers.js +26 -0
- package/dist/react/index.d.ts +6 -0
- package/dist/react/index.js +47 -0
- package/dist/react.d.ts +22 -0
- package/dist/react.js +199 -0
- package/dist/routes.d.ts +16 -0
- package/dist/routes.js +152 -0
- package/dist/types.d.ts +76 -0
- package/dist/types.js +18 -0
- package/package.json +51 -0
- package/src/client.ts +171 -0
- package/src/components.tsx +84 -0
- package/src/core.ts +215 -0
- package/src/index.ts +25 -0
- package/src/jwt.ts +210 -0
- package/src/providers/credentials.ts +138 -0
- package/src/providers/discord.ts +239 -0
- package/src/providers/google.ts +234 -0
- package/src/providers/index.ts +20 -0
- package/src/providers.ts +20 -0
- package/src/react/index.ts +25 -0
- package/src/react.tsx +234 -0
- package/src/routes.ts +182 -0
- package/src/types.ts +108 -0
package/src/core.ts
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* This file is part of the Nyte.js Project.
|
|
3
|
+
* Copyright (c) 2026 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 { NyteRequest, NyteResponse } from 'nyte';
|
|
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: NyteRequest): 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: NyteRequest): Promise<NyteResponse> {
|
|
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 NyteResponse
|
|
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: NyteRequest): 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: NyteRequest): 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): NyteResponse {
|
|
183
|
+
return NyteResponse
|
|
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: NyteRequest): 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/index.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* This file is part of the Nyte.js Project.
|
|
3
|
+
* Copyright (c) 2026 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/jwt.ts
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* This file is part of the Nyte.js Project.
|
|
3
|
+
* Copyright (c) 2026 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
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* This file is part of the Nyte.js Project.
|
|
3
|
+
* Copyright (c) 2026 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
|
+
|
|
19
|
+
export interface CredentialsConfig {
|
|
20
|
+
id?: string;
|
|
21
|
+
name?: string;
|
|
22
|
+
credentials: Record<string, {
|
|
23
|
+
label: string;
|
|
24
|
+
type: string;
|
|
25
|
+
placeholder?: string;
|
|
26
|
+
}>;
|
|
27
|
+
authorize: (credentials: Record<string, string>) => Promise<User | null> | User | null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Provider para autenticação com credenciais (email/senha)
|
|
32
|
+
*
|
|
33
|
+
* Este provider permite autenticação usando email/senha ou qualquer outro
|
|
34
|
+
* sistema de credenciais customizado. Você define a função authorize
|
|
35
|
+
* que será chamada para validar as credenciais.
|
|
36
|
+
*
|
|
37
|
+
* Exemplo de uso:
|
|
38
|
+
* ```typescript
|
|
39
|
+
* new CredentialsProvider({
|
|
40
|
+
* name: "Credentials",
|
|
41
|
+
* credentials: {
|
|
42
|
+
* email: { label: "Email", type: "email" },
|
|
43
|
+
* password: { label: "Password", type: "password" }
|
|
44
|
+
* },
|
|
45
|
+
* async authorize(credentials) {
|
|
46
|
+
* // Aqui você faz a validação com seu banco de dados
|
|
47
|
+
* const user = await validateUser(credentials.email, credentials.password);
|
|
48
|
+
* if (user) {
|
|
49
|
+
* return { id: user.id, name: user.name, email: user.email };
|
|
50
|
+
* }
|
|
51
|
+
* return null;
|
|
52
|
+
* }
|
|
53
|
+
* })
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export class CredentialsProvider implements AuthProviderClass {
|
|
57
|
+
public readonly id: string;
|
|
58
|
+
public readonly name: string;
|
|
59
|
+
public readonly type: string = 'credentials';
|
|
60
|
+
|
|
61
|
+
private config: CredentialsConfig;
|
|
62
|
+
|
|
63
|
+
constructor(config: CredentialsConfig) {
|
|
64
|
+
this.config = config;
|
|
65
|
+
this.id = config.id || 'credentials';
|
|
66
|
+
this.name = config.name || 'Credentials';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Método principal para autenticar usuário com credenciais
|
|
71
|
+
*/
|
|
72
|
+
async handleSignIn(credentials: Record<string, string>): Promise<User | null> {
|
|
73
|
+
try {
|
|
74
|
+
if (!this.config.authorize) {
|
|
75
|
+
throw new Error('Authorize function not provided');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const user = await this.config.authorize(credentials);
|
|
79
|
+
|
|
80
|
+
if (!user) {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Adiciona informações do provider ao usuário
|
|
85
|
+
return {
|
|
86
|
+
...user,
|
|
87
|
+
provider: this.id,
|
|
88
|
+
providerId: user.id || user.email || 'unknown'
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
} catch (error) {
|
|
92
|
+
console.error(`[${this.id} Provider] Error during sign in:`, error);
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Retorna configuração pública do provider
|
|
101
|
+
*/
|
|
102
|
+
getConfig(): any {
|
|
103
|
+
return {
|
|
104
|
+
id: this.id,
|
|
105
|
+
name: this.name,
|
|
106
|
+
type: this.type,
|
|
107
|
+
credentials: this.config.credentials
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Valida se as credenciais fornecidas são válidas
|
|
113
|
+
*/
|
|
114
|
+
validateCredentials(credentials: Record<string, string>): boolean {
|
|
115
|
+
for (const [key, field] of Object.entries(this.config.credentials)) {
|
|
116
|
+
if (!credentials[key]) {
|
|
117
|
+
console.warn(`[${this.id} Provider] Missing required credential: ${key}`);
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Validações básicas por tipo
|
|
122
|
+
if (field.type === 'email' && !this.isValidEmail(credentials[key])) {
|
|
123
|
+
console.warn(`[${this.id} Provider] Invalid email format: ${credentials[key]}`);
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Validação simples de email
|
|
133
|
+
*/
|
|
134
|
+
private isValidEmail(email: string): boolean {
|
|
135
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
136
|
+
return emailRegex.test(email);
|
|
137
|
+
}
|
|
138
|
+
}
|