@hightjs/auth 0.5.0 → 0.5.2

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 CHANGED
@@ -25,16 +25,6 @@ A complete authentication solution built specifically for HightJS framework:
25
25
  - **🚀 Zero Config** - Works out of the box
26
26
  - **🔒 Production Ready** - HTTP-only cookies, CSRF protection, and more
27
27
 
28
- ---
29
-
30
- ## 📦 Installation
31
-
32
- ```bash
33
- npm install hightjs @hightjs/auth
34
- ```
35
-
36
- ---
37
-
38
28
  ## 📚 Documentation
39
29
 
40
30
  For complete documentation, installation guides, and tutorials, visit:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hightjs/auth",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
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.5.0"
41
+ "hightjs": "0.5.2"
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';