@hightjs/auth 0.4.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/LICENSE +13 -0
- package/dist/client.d.ts +24 -0
- package/dist/client.js +146 -0
- package/dist/components.d.ts +29 -0
- package/dist/components.js +100 -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 +48 -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 +48 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright 2025 itsmuzin
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { SignInOptions, SignInResult, Session } from './types';
|
|
2
|
+
export declare function setBasePath(path: string): void;
|
|
3
|
+
/**
|
|
4
|
+
* Função para obter a sessão atual (similar ao NextAuth getSession)
|
|
5
|
+
*/
|
|
6
|
+
export declare function getSession(): Promise<Session | null>;
|
|
7
|
+
/**
|
|
8
|
+
* Função para obter token CSRF
|
|
9
|
+
*/
|
|
10
|
+
export declare function getCsrfToken(): Promise<string | null>;
|
|
11
|
+
/**
|
|
12
|
+
* Função para obter providers disponíveis
|
|
13
|
+
*/
|
|
14
|
+
export declare function getProviders(): Promise<any[] | null>;
|
|
15
|
+
/**
|
|
16
|
+
* Função para fazer login (similar ao NextAuth signIn)
|
|
17
|
+
*/
|
|
18
|
+
export declare function signIn(provider?: string, options?: SignInOptions): Promise<SignInResult | undefined>;
|
|
19
|
+
/**
|
|
20
|
+
* Função para fazer logout (similar ao NextAuth signOut)
|
|
21
|
+
*/
|
|
22
|
+
export declare function signOut(options?: {
|
|
23
|
+
callbackUrl?: string;
|
|
24
|
+
}): Promise<void>;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.setBasePath = setBasePath;
|
|
4
|
+
exports.getSession = getSession;
|
|
5
|
+
exports.getCsrfToken = getCsrfToken;
|
|
6
|
+
exports.getProviders = getProviders;
|
|
7
|
+
exports.signIn = signIn;
|
|
8
|
+
exports.signOut = signOut;
|
|
9
|
+
// Configuração global do client
|
|
10
|
+
let basePath = '/api/auth';
|
|
11
|
+
function setBasePath(path) {
|
|
12
|
+
basePath = path;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Função para obter a sessão atual (similar ao NextAuth getSession)
|
|
16
|
+
*/
|
|
17
|
+
async function getSession() {
|
|
18
|
+
try {
|
|
19
|
+
const response = await fetch(`${basePath}/session`, {
|
|
20
|
+
credentials: 'include'
|
|
21
|
+
});
|
|
22
|
+
if (!response.ok) {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
const data = await response.json();
|
|
26
|
+
return data.session || null;
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
console.error('[hweb-auth] Error fetching session:', error);
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Função para obter token CSRF
|
|
35
|
+
*/
|
|
36
|
+
async function getCsrfToken() {
|
|
37
|
+
try {
|
|
38
|
+
const response = await fetch(`${basePath}/csrf`, {
|
|
39
|
+
credentials: 'include'
|
|
40
|
+
});
|
|
41
|
+
if (!response.ok) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
const data = await response.json();
|
|
45
|
+
return data.csrfToken || null;
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
console.error('[hweb-auth] Error fetching CSRF token:', error);
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Função para obter providers disponíveis
|
|
54
|
+
*/
|
|
55
|
+
async function getProviders() {
|
|
56
|
+
try {
|
|
57
|
+
const response = await fetch(`${basePath}/providers`, {
|
|
58
|
+
credentials: 'include'
|
|
59
|
+
});
|
|
60
|
+
if (!response.ok) {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
const data = await response.json();
|
|
64
|
+
return data.providers || [];
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
console.error('[hweb-auth] Error searching for providers:', error);
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Função para fazer login (similar ao NextAuth signIn)
|
|
73
|
+
*/
|
|
74
|
+
async function signIn(provider = 'credentials', options = {}) {
|
|
75
|
+
try {
|
|
76
|
+
const { redirect = true, callbackUrl, ...credentials } = options;
|
|
77
|
+
const response = await fetch(`${basePath}/signin`, {
|
|
78
|
+
method: 'POST',
|
|
79
|
+
headers: {
|
|
80
|
+
'Content-Type': 'application/json',
|
|
81
|
+
},
|
|
82
|
+
credentials: 'include',
|
|
83
|
+
body: JSON.stringify({
|
|
84
|
+
provider,
|
|
85
|
+
...credentials
|
|
86
|
+
})
|
|
87
|
+
});
|
|
88
|
+
const data = await response.json();
|
|
89
|
+
if (response.ok && data.success) {
|
|
90
|
+
// Se é OAuth, redireciona para URL fornecida
|
|
91
|
+
if (data.type === 'oauth' && data.redirectUrl) {
|
|
92
|
+
if (redirect && typeof window !== 'undefined') {
|
|
93
|
+
window.location.href = data.redirectUrl;
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
ok: true,
|
|
97
|
+
status: 200,
|
|
98
|
+
url: data.redirectUrl
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
// Se é sessão (credentials), redireciona para callbackUrl
|
|
102
|
+
if (data.type === 'session') {
|
|
103
|
+
if (redirect && typeof window !== 'undefined') {
|
|
104
|
+
window.location.href = callbackUrl || '/';
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
ok: true,
|
|
108
|
+
status: 200,
|
|
109
|
+
url: callbackUrl || '/'
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
return {
|
|
115
|
+
error: data.error || 'Authentication failed',
|
|
116
|
+
status: response.status,
|
|
117
|
+
ok: false
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
console.error('[hweb-auth] Error on signIn:', error);
|
|
123
|
+
return {
|
|
124
|
+
error: 'Network error',
|
|
125
|
+
status: 500,
|
|
126
|
+
ok: false
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Função para fazer logout (similar ao NextAuth signOut)
|
|
132
|
+
*/
|
|
133
|
+
async function signOut(options = {}) {
|
|
134
|
+
try {
|
|
135
|
+
await fetch(`${basePath}/signout`, {
|
|
136
|
+
method: 'POST',
|
|
137
|
+
credentials: 'include'
|
|
138
|
+
});
|
|
139
|
+
if (typeof window !== 'undefined') {
|
|
140
|
+
window.location.href = options.callbackUrl || '/';
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
console.error('[hweb-auth] Error on signOut:', error);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import React, { ReactNode } from 'react';
|
|
2
|
+
interface ProtectedRouteProps {
|
|
3
|
+
children: ReactNode;
|
|
4
|
+
fallback?: ReactNode;
|
|
5
|
+
redirectTo?: string;
|
|
6
|
+
requireAuth?: boolean;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Componente para proteger rotas que requerem autenticação
|
|
10
|
+
*/
|
|
11
|
+
export declare function ProtectedRoute({ children, fallback, redirectTo, requireAuth }: ProtectedRouteProps): string | number | bigint | true | Iterable<React.ReactNode> | Promise<string | number | bigint | boolean | React.ReactPortal | React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | null | undefined> | import("react/jsx-runtime").JSX.Element | null;
|
|
12
|
+
interface GuardProps {
|
|
13
|
+
children: ReactNode;
|
|
14
|
+
fallback?: ReactNode;
|
|
15
|
+
redirectTo?: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Guard simples que só renderiza children se estiver autenticado
|
|
19
|
+
*/
|
|
20
|
+
export declare function AuthGuard({ children, fallback, redirectTo }: GuardProps): string | number | bigint | true | Iterable<React.ReactNode> | Promise<string | number | bigint | boolean | React.ReactPortal | React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | null | undefined> | import("react/jsx-runtime").JSX.Element | null;
|
|
21
|
+
/**
|
|
22
|
+
* Componente para mostrar conteúdo apenas para usuários não autenticados
|
|
23
|
+
*/
|
|
24
|
+
export declare function GuestOnly({ children, fallback, redirectTo }: GuardProps): string | number | bigint | true | Iterable<React.ReactNode> | Promise<string | number | bigint | boolean | React.ReactPortal | React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | null | undefined> | import("react/jsx-runtime").JSX.Element;
|
|
25
|
+
/**
|
|
26
|
+
* Hook para redirecionar baseado no status de autenticação
|
|
27
|
+
*/
|
|
28
|
+
export declare function useAuthRedirect(authenticatedRedirect?: string, unauthenticatedRedirect?: string): void;
|
|
29
|
+
export {};
|
|
@@ -0,0 +1,100 @@
|
|
|
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.ProtectedRoute = ProtectedRoute;
|
|
7
|
+
exports.AuthGuard = AuthGuard;
|
|
8
|
+
exports.GuestOnly = GuestOnly;
|
|
9
|
+
exports.useAuthRedirect = useAuthRedirect;
|
|
10
|
+
const jsx_runtime_1 = require("react/jsx-runtime");
|
|
11
|
+
/*
|
|
12
|
+
* This file is part of the HightJS Project.
|
|
13
|
+
* Copyright (c) 2025 itsmuzin
|
|
14
|
+
*
|
|
15
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
16
|
+
* you may not use this file except in compliance with the License.
|
|
17
|
+
* You may obtain a copy of the License at
|
|
18
|
+
*
|
|
19
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
20
|
+
*
|
|
21
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
22
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
23
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
24
|
+
* See the License for the specific language governing permissions and
|
|
25
|
+
* limitations under the License.
|
|
26
|
+
*/
|
|
27
|
+
const react_1 = __importDefault(require("react"));
|
|
28
|
+
const react_2 = require("./react");
|
|
29
|
+
const react_3 = require("hightjs/react");
|
|
30
|
+
/**
|
|
31
|
+
* Componente para proteger rotas que requerem autenticação
|
|
32
|
+
*/
|
|
33
|
+
function ProtectedRoute({ children, fallback, redirectTo = '/auth/signin', requireAuth = true }) {
|
|
34
|
+
const { isAuthenticated, isLoading } = (0, react_2.useAuth)();
|
|
35
|
+
// Ainda carregando
|
|
36
|
+
if (isLoading) {
|
|
37
|
+
return fallback || (0, jsx_runtime_1.jsx)("div", { children: "Loading..." });
|
|
38
|
+
}
|
|
39
|
+
// Requer auth mas não está autenticado
|
|
40
|
+
if (requireAuth && !isAuthenticated) {
|
|
41
|
+
if (typeof window !== 'undefined' && redirectTo) {
|
|
42
|
+
window.location.href = redirectTo;
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
return fallback || (0, jsx_runtime_1.jsx)("div", { children: "Unauthorized" });
|
|
46
|
+
}
|
|
47
|
+
// Não requer auth mas está autenticado (ex: página de login)
|
|
48
|
+
if (!requireAuth && isAuthenticated && redirectTo) {
|
|
49
|
+
if (typeof window !== 'undefined') {
|
|
50
|
+
window.location.href = redirectTo;
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: children });
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Guard simples que só renderiza children se estiver autenticado
|
|
58
|
+
*/
|
|
59
|
+
function AuthGuard({ children, fallback, redirectTo }) {
|
|
60
|
+
const { isAuthenticated, isLoading } = (0, react_2.useAuth)();
|
|
61
|
+
if (redirectTo && !isLoading && !isAuthenticated) {
|
|
62
|
+
react_3.router.push(redirectTo);
|
|
63
|
+
}
|
|
64
|
+
if (isLoading) {
|
|
65
|
+
return fallback || (0, jsx_runtime_1.jsx)("div", {});
|
|
66
|
+
}
|
|
67
|
+
if (!isAuthenticated) {
|
|
68
|
+
return fallback || null;
|
|
69
|
+
}
|
|
70
|
+
return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: children });
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Componente para mostrar conteúdo apenas para usuários não autenticados
|
|
74
|
+
*/
|
|
75
|
+
function GuestOnly({ children, fallback, redirectTo }) {
|
|
76
|
+
const { isAuthenticated, isLoading } = (0, react_2.useAuth)();
|
|
77
|
+
if (redirectTo && !isLoading && isAuthenticated) {
|
|
78
|
+
react_3.router.push(redirectTo);
|
|
79
|
+
}
|
|
80
|
+
if (isLoading || isAuthenticated) {
|
|
81
|
+
return fallback || (0, jsx_runtime_1.jsx)("div", {});
|
|
82
|
+
}
|
|
83
|
+
return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: children });
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Hook para redirecionar baseado no status de autenticação
|
|
87
|
+
*/
|
|
88
|
+
function useAuthRedirect(authenticatedRedirect, unauthenticatedRedirect) {
|
|
89
|
+
const { isAuthenticated, isLoading } = (0, react_2.useAuth)();
|
|
90
|
+
react_1.default.useEffect(() => {
|
|
91
|
+
if (isLoading)
|
|
92
|
+
return;
|
|
93
|
+
if (isAuthenticated && authenticatedRedirect) {
|
|
94
|
+
window.location.href = authenticatedRedirect;
|
|
95
|
+
}
|
|
96
|
+
else if (!isAuthenticated && unauthenticatedRedirect) {
|
|
97
|
+
window.location.href = unauthenticatedRedirect;
|
|
98
|
+
}
|
|
99
|
+
}, [isAuthenticated, isLoading, authenticatedRedirect, unauthenticatedRedirect]);
|
|
100
|
+
}
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { HightJSRequest, HightJSResponse } from 'hightjs';
|
|
2
|
+
import type { AuthConfig, AuthProviderClass, Session } from './types';
|
|
3
|
+
export declare class HWebAuth {
|
|
4
|
+
private config;
|
|
5
|
+
private sessionManager;
|
|
6
|
+
constructor(config: AuthConfig);
|
|
7
|
+
/**
|
|
8
|
+
* Middleware para adicionar autenticação às rotas
|
|
9
|
+
*/
|
|
10
|
+
private middleware;
|
|
11
|
+
/**
|
|
12
|
+
* Autentica um usuário usando um provider específico
|
|
13
|
+
*/
|
|
14
|
+
signIn(providerId: string, credentials: Record<string, string>): Promise<{
|
|
15
|
+
session: Session;
|
|
16
|
+
token: string;
|
|
17
|
+
} | {
|
|
18
|
+
redirectUrl: string;
|
|
19
|
+
} | null>;
|
|
20
|
+
/**
|
|
21
|
+
* Faz logout do usuário
|
|
22
|
+
*/
|
|
23
|
+
signOut(req: HightJSRequest): Promise<HightJSResponse>;
|
|
24
|
+
/**
|
|
25
|
+
* Obtém a sessão atual
|
|
26
|
+
*/
|
|
27
|
+
getSession(req: HightJSRequest): Promise<Session | null>;
|
|
28
|
+
/**
|
|
29
|
+
* Verifica se o usuário está autenticado
|
|
30
|
+
*/
|
|
31
|
+
isAuthenticated(req: HightJSRequest): Promise<boolean>;
|
|
32
|
+
/**
|
|
33
|
+
* Retorna todos os providers disponíveis (dados públicos)
|
|
34
|
+
*/
|
|
35
|
+
getProviders(): any[];
|
|
36
|
+
/**
|
|
37
|
+
* Busca um provider específico
|
|
38
|
+
*/
|
|
39
|
+
getProvider(id: string): AuthProviderClass | null;
|
|
40
|
+
/**
|
|
41
|
+
* Retorna todas as rotas adicionais dos providers
|
|
42
|
+
*/
|
|
43
|
+
getAllAdditionalRoutes(): Array<{
|
|
44
|
+
provider: string;
|
|
45
|
+
route: any;
|
|
46
|
+
}>;
|
|
47
|
+
/**
|
|
48
|
+
* Cria resposta com cookie de autenticação - Secure implementation
|
|
49
|
+
*/
|
|
50
|
+
createAuthResponse(token: string, data: any): HightJSResponse;
|
|
51
|
+
/**
|
|
52
|
+
* Extrai token da requisição (cookie ou header)
|
|
53
|
+
*/
|
|
54
|
+
private getTokenFromRequest;
|
|
55
|
+
}
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
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 hightjs_1 = require("hightjs");
|
|
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 hightjs_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 hightjs_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/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
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/jwt.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
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
|
+
}
|