@hightjs/auth 0.4.0 → 0.5.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/README.md +55 -0
- package/dist/components.d.ts +0 -10
- package/dist/components.js +0 -27
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.js +1 -2
- package/package.json +4 -3
- 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/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
<picture>
|
|
3
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://repository-images.githubusercontent.com/1069175740/e5c59d3a-e1fd-446c-a89f-785ed08f6a16">
|
|
4
|
+
<img alt="HightJS logo" src="https://repository-images.githubusercontent.com/1069175740/e5c59d3a-e1fd-446c-a89f-785ed08f6a16" height="128">
|
|
5
|
+
</picture>
|
|
6
|
+
<h1>@hightjs/auth</h1>
|
|
7
|
+
|
|
8
|
+
[](https://www.npmjs.com/package/@hightjs/auth)
|
|
9
|
+
[](../../LICENSE)
|
|
10
|
+
|
|
11
|
+
</div>
|
|
12
|
+
|
|
13
|
+
> Official authentication package for **[HightJS](https://www.npmjs.com/package/hightjs)** - Powerful, secure, and flexible authentication system with JWT, OAuth providers, and session management.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## ✨ Why @hightjs/auth?
|
|
18
|
+
|
|
19
|
+
A complete authentication solution built specifically for HightJS framework:
|
|
20
|
+
|
|
21
|
+
- **🔐 Secure by Default** - Industry-standard JWT implementation
|
|
22
|
+
- **🎯 Multiple Providers** - OAuth, credentials, and custom providers
|
|
23
|
+
- **⚛️ React Ready** - Built-in hooks and components
|
|
24
|
+
- **🛡️ Type-Safe** - Full TypeScript support
|
|
25
|
+
- **🚀 Zero Config** - Works out of the box
|
|
26
|
+
- **🔒 Production Ready** - HTTP-only cookies, CSRF protection, and more
|
|
27
|
+
|
|
28
|
+
## 📚 Documentation
|
|
29
|
+
|
|
30
|
+
For complete documentation, installation guides, and tutorials, visit:
|
|
31
|
+
|
|
32
|
+
**[https://docs.hgo.me](https://docs.hgo.me)**
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## 💬 Need Help?
|
|
37
|
+
|
|
38
|
+
If you have questions or need support, feel free to reach out:
|
|
39
|
+
|
|
40
|
+
[](https://discord.com/users/1264710048786026588)
|
|
41
|
+
[](mailto:murillofrazaocunha@gmail.com)
|
|
42
|
+
[](https://instagram.com/itsmuh_)
|
|
43
|
+
[](https://github.com/murillo-frazao-cunha)
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## 🪪 License
|
|
48
|
+
|
|
49
|
+
Copyright 2025 itsmuzin
|
|
50
|
+
|
|
51
|
+
This project is licensed under the [Apache License 2.0](../../LICENSE).
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
|
package/dist/components.d.ts
CHANGED
|
@@ -1,14 +1,4 @@
|
|
|
1
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
2
|
interface GuardProps {
|
|
13
3
|
children: ReactNode;
|
|
14
4
|
fallback?: ReactNode;
|
package/dist/components.js
CHANGED
|
@@ -3,7 +3,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.ProtectedRoute = ProtectedRoute;
|
|
7
6
|
exports.AuthGuard = AuthGuard;
|
|
8
7
|
exports.GuestOnly = GuestOnly;
|
|
9
8
|
exports.useAuthRedirect = useAuthRedirect;
|
|
@@ -27,32 +26,6 @@ const jsx_runtime_1 = require("react/jsx-runtime");
|
|
|
27
26
|
const react_1 = __importDefault(require("react"));
|
|
28
27
|
const react_2 = require("./react");
|
|
29
28
|
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
29
|
/**
|
|
57
30
|
* Guard simples que só renderiza children se estiver autenticado
|
|
58
31
|
*/
|
package/dist/react/index.d.ts
CHANGED
|
@@ -3,4 +3,4 @@ export * from '../client';
|
|
|
3
3
|
export * from '../components';
|
|
4
4
|
export { getSession } from '../client';
|
|
5
5
|
export { useSession, useAuth, SessionProvider } from '../react';
|
|
6
|
-
export {
|
|
6
|
+
export { AuthGuard, GuestOnly } from '../components';
|
package/dist/react/index.js
CHANGED
|
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.GuestOnly = exports.AuthGuard = exports.
|
|
17
|
+
exports.GuestOnly = exports.AuthGuard = exports.SessionProvider = exports.useAuth = exports.useSession = exports.getSession = void 0;
|
|
18
18
|
/*
|
|
19
19
|
* This file is part of the HightJS Project.
|
|
20
20
|
* Copyright (c) 2025 itsmuzin
|
|
@@ -43,6 +43,5 @@ Object.defineProperty(exports, "useSession", { enumerable: true, get: function (
|
|
|
43
43
|
Object.defineProperty(exports, "useAuth", { enumerable: true, get: function () { return react_1.useAuth; } });
|
|
44
44
|
Object.defineProperty(exports, "SessionProvider", { enumerable: true, get: function () { return react_1.SessionProvider; } });
|
|
45
45
|
var components_1 = require("../components");
|
|
46
|
-
Object.defineProperty(exports, "ProtectedRoute", { enumerable: true, get: function () { return components_1.ProtectedRoute; } });
|
|
47
46
|
Object.defineProperty(exports, "AuthGuard", { enumerable: true, get: function () { return components_1.AuthGuard; } });
|
|
48
47
|
Object.defineProperty(exports, "GuestOnly", { enumerable: true, get: function () { return components_1.GuestOnly; } });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hightjs/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "Authentication package for HightJS framework",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -27,7 +27,8 @@
|
|
|
27
27
|
],
|
|
28
28
|
"files": [
|
|
29
29
|
"dist",
|
|
30
|
-
"README.md"
|
|
30
|
+
"README.md",
|
|
31
|
+
"src"
|
|
31
32
|
],
|
|
32
33
|
"devDependencies": {
|
|
33
34
|
"@types/node": "^20.11.24",
|
|
@@ -37,7 +38,7 @@
|
|
|
37
38
|
"dependencies": {
|
|
38
39
|
"@types/react": "^19.2.2",
|
|
39
40
|
"react": "^19.2.0",
|
|
40
|
-
"hightjs": "0.
|
|
41
|
+
"hightjs": "0.5.1"
|
|
41
42
|
},
|
|
42
43
|
"scripts": {
|
|
43
44
|
"build": "tsc",
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
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 type { SignInOptions, SignInResult, Session } from './types';
|
|
18
|
+
// Configuração global do client
|
|
19
|
+
let basePath = '/api/auth';
|
|
20
|
+
|
|
21
|
+
export function setBasePath(path: string) {
|
|
22
|
+
basePath = path;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Função para obter a sessão atual (similar ao NextAuth getSession)
|
|
27
|
+
*/
|
|
28
|
+
export async function getSession(): Promise<Session | null> {
|
|
29
|
+
try {
|
|
30
|
+
const response = await fetch(`${basePath}/session`, {
|
|
31
|
+
credentials: 'include'
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
if (!response.ok) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const data = await response.json();
|
|
39
|
+
return data.session || null;
|
|
40
|
+
} catch (error) {
|
|
41
|
+
console.error('[hweb-auth] Error fetching session:', error);
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Função para obter token CSRF
|
|
48
|
+
*/
|
|
49
|
+
export async function getCsrfToken(): Promise<string | null> {
|
|
50
|
+
try {
|
|
51
|
+
const response = await fetch(`${basePath}/csrf`, {
|
|
52
|
+
credentials: 'include'
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
if (!response.ok) {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const data = await response.json();
|
|
60
|
+
return data.csrfToken || null;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
console.error('[hweb-auth] Error fetching CSRF token:', error);
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Função para obter providers disponíveis
|
|
69
|
+
*/
|
|
70
|
+
export async function getProviders(): Promise<any[] | null> {
|
|
71
|
+
try {
|
|
72
|
+
const response = await fetch(`${basePath}/providers`, {
|
|
73
|
+
credentials: 'include'
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
if (!response.ok) {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const data = await response.json();
|
|
81
|
+
return data.providers || [];
|
|
82
|
+
} catch (error) {
|
|
83
|
+
console.error('[hweb-auth] Error searching for providers:', error);
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Função para fazer login (similar ao NextAuth signIn)
|
|
90
|
+
*/
|
|
91
|
+
export async function signIn(
|
|
92
|
+
provider: string = 'credentials',
|
|
93
|
+
options: SignInOptions = {}
|
|
94
|
+
): Promise<SignInResult | undefined> {
|
|
95
|
+
try {
|
|
96
|
+
const { redirect = true, callbackUrl, ...credentials } = options;
|
|
97
|
+
|
|
98
|
+
const response = await fetch(`${basePath}/signin`, {
|
|
99
|
+
method: 'POST',
|
|
100
|
+
headers: {
|
|
101
|
+
'Content-Type': 'application/json',
|
|
102
|
+
},
|
|
103
|
+
credentials: 'include',
|
|
104
|
+
body: JSON.stringify({
|
|
105
|
+
provider,
|
|
106
|
+
...credentials
|
|
107
|
+
})
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
const data = await response.json();
|
|
111
|
+
|
|
112
|
+
if (response.ok && data.success) {
|
|
113
|
+
// Se é OAuth, redireciona para URL fornecida
|
|
114
|
+
if (data.type === 'oauth' && data.redirectUrl) {
|
|
115
|
+
if (redirect && typeof window !== 'undefined') {
|
|
116
|
+
window.location.href = data.redirectUrl;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
ok: true,
|
|
121
|
+
status: 200,
|
|
122
|
+
url: data.redirectUrl
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Se é sessão (credentials), redireciona para callbackUrl
|
|
127
|
+
if (data.type === 'session') {
|
|
128
|
+
if (redirect && typeof window !== 'undefined') {
|
|
129
|
+
window.location.href = callbackUrl || '/';
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
ok: true,
|
|
134
|
+
status: 200,
|
|
135
|
+
url: callbackUrl || '/'
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
} else {
|
|
139
|
+
return {
|
|
140
|
+
error: data.error || 'Authentication failed',
|
|
141
|
+
status: response.status,
|
|
142
|
+
ok: false
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
} catch (error) {
|
|
146
|
+
console.error('[hweb-auth] Error on signIn:', error);
|
|
147
|
+
return {
|
|
148
|
+
error: 'Network error',
|
|
149
|
+
status: 500,
|
|
150
|
+
ok: false
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Função para fazer logout (similar ao NextAuth signOut)
|
|
157
|
+
*/
|
|
158
|
+
export async function signOut(options: { callbackUrl?: string } = {}): Promise<void> {
|
|
159
|
+
try {
|
|
160
|
+
await fetch(`${basePath}/signout`, {
|
|
161
|
+
method: 'POST',
|
|
162
|
+
credentials: 'include'
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
if (typeof window !== 'undefined') {
|
|
166
|
+
window.location.href = options.callbackUrl || '/';
|
|
167
|
+
}
|
|
168
|
+
} catch (error) {
|
|
169
|
+
console.error('[hweb-auth] Error on signOut:', error);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
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 'hightjs/react';
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
interface GuardProps {
|
|
23
|
+
children: ReactNode;
|
|
24
|
+
fallback?: ReactNode;
|
|
25
|
+
redirectTo?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Guard simples que só renderiza children se estiver autenticado
|
|
30
|
+
*/
|
|
31
|
+
export function AuthGuard({ children, fallback, redirectTo }: GuardProps) {
|
|
32
|
+
const { isAuthenticated, isLoading } = useAuth();
|
|
33
|
+
|
|
34
|
+
if(redirectTo && !isLoading && !isAuthenticated) {
|
|
35
|
+
router.push(redirectTo);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (isLoading) {
|
|
39
|
+
return fallback || <div></div>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (!isAuthenticated) {
|
|
43
|
+
return fallback || null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return <>{children}</>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Componente para mostrar conteúdo apenas para usuários não autenticados
|
|
51
|
+
*/
|
|
52
|
+
export function GuestOnly({ children, fallback, redirectTo }: GuardProps) {
|
|
53
|
+
const { isAuthenticated, isLoading } = useAuth();
|
|
54
|
+
|
|
55
|
+
if(redirectTo && !isLoading && isAuthenticated) {
|
|
56
|
+
router.push(redirectTo);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (isLoading || isAuthenticated) {
|
|
60
|
+
return fallback || <div></div>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return <>{children}</>;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Hook para redirecionar baseado no status de autenticação
|
|
68
|
+
*/
|
|
69
|
+
export function useAuthRedirect(
|
|
70
|
+
authenticatedRedirect?: string,
|
|
71
|
+
unauthenticatedRedirect?: string
|
|
72
|
+
) {
|
|
73
|
+
const { isAuthenticated, isLoading } = useAuth();
|
|
74
|
+
|
|
75
|
+
React.useEffect(() => {
|
|
76
|
+
if (isLoading) return;
|
|
77
|
+
|
|
78
|
+
if (isAuthenticated && authenticatedRedirect) {
|
|
79
|
+
window.location.href = authenticatedRedirect;
|
|
80
|
+
} else if (!isAuthenticated && unauthenticatedRedirect) {
|
|
81
|
+
window.location.href = unauthenticatedRedirect;
|
|
82
|
+
}
|
|
83
|
+
}, [isAuthenticated, isLoading, authenticatedRedirect, unauthenticatedRedirect]);
|
|
84
|
+
}
|
package/src/core.ts
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
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 'hightjs';
|
|
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/index.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
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';
|