@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/src/routes.ts ADDED
@@ -0,0 +1,182 @@
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 } from './types';
19
+ import { HWebAuth } from './core';
20
+
21
+ /**
22
+ * Cria o handler catch-all para /api/auth/[...value]
23
+ */
24
+ export function createAuthRoutes(config: AuthConfig) {
25
+ const auth = new HWebAuth(config);
26
+
27
+ /**
28
+ * Handler principal que gerencia todas as rotas de auth
29
+ * Uso: /api/auth/[...value].ts
30
+ */
31
+ return {
32
+ pattern: '/api/auth/[...value]',
33
+
34
+ async GET(req: HightJSRequest, params: { [key: string]: string }) {
35
+
36
+ const path = params["value"];
37
+ const route = Array.isArray(path) ? path.join('/') : path || '';
38
+
39
+ // Verifica rotas adicionais dos providers primeiro
40
+ const additionalRoutes = auth.getAllAdditionalRoutes();
41
+ for (const { provider, route: additionalRoute } of additionalRoutes) {
42
+
43
+ if (additionalRoute.method === 'GET' && additionalRoute.path.includes(route)) {
44
+ try {
45
+ return await additionalRoute.handler(req, params);
46
+ } catch (error) {
47
+ console.error(`[${provider} Provider] Error in additional route:`, error);
48
+ return HightJSResponse.json({ error: 'Provider route error' }, { status: 500 });
49
+ }
50
+ }
51
+ }
52
+
53
+ // Rotas padrão do sistema
54
+ switch (route) {
55
+ case 'session':
56
+ return await handleSession(req, auth);
57
+
58
+ case 'csrf':
59
+ return await handleCsrf(req);
60
+
61
+ case 'providers':
62
+ return await handleProviders(auth);
63
+
64
+ default:
65
+ return HightJSResponse.json({ error: 'Route not found' }, { status: 404 });
66
+ }
67
+ },
68
+
69
+ async POST(req: HightJSRequest, params: { [key: string]: string }) {
70
+ const path = params["value"];
71
+ const route = Array.isArray(path) ? path.join('/') : path || '';
72
+
73
+ // Verifica rotas adicionais dos providers primeiro
74
+ const additionalRoutes = auth.getAllAdditionalRoutes();
75
+ for (const { provider, route: additionalRoute } of additionalRoutes) {
76
+ if (additionalRoute.method === 'POST' && additionalRoute.path.includes(route)) {
77
+ try {
78
+ return await additionalRoute.handler(req, params);
79
+ } catch (error) {
80
+ console.error(`[${provider} Provider] Error in additional route:`, error);
81
+ return HightJSResponse.json({ error: 'Provider route error' }, { status: 500 });
82
+ }
83
+ }
84
+ }
85
+
86
+ // Rotas padrão do sistema
87
+ switch (route) {
88
+ case 'signin':
89
+ return await handleSignIn(req, auth);
90
+
91
+ case 'signout':
92
+ return await handleSignOut(req, auth);
93
+
94
+ default:
95
+ return HightJSResponse.json({ error: 'Route not found' }, { status: 404 });
96
+ }
97
+ },
98
+
99
+ // Instância do auth para uso manual
100
+ auth
101
+ };
102
+ }
103
+
104
+ /**
105
+ * Handler para GET /api/auth/session
106
+ */
107
+ async function handleSession(req: HightJSRequest, auth: HWebAuth) {
108
+ const session = await auth.getSession(req);
109
+
110
+ if (!session) {
111
+ return HightJSResponse.json({ session: null });
112
+ }
113
+
114
+ return HightJSResponse.json({ session });
115
+ }
116
+
117
+ /**
118
+ * Handler para GET /api/auth/csrf
119
+ */
120
+ async function handleCsrf(req: HightJSRequest) {
121
+ // Token CSRF simples para proteção
122
+ const csrfToken = Math.random().toString(36).substring(2, 15) +
123
+ Math.random().toString(36).substring(2, 15);
124
+
125
+ return HightJSResponse.json({ csrfToken });
126
+ }
127
+
128
+ /**
129
+ * Handler para GET /api/auth/providers
130
+ */
131
+ async function handleProviders(auth: HWebAuth) {
132
+ const providers = auth.getProviders();
133
+
134
+ return HightJSResponse.json({ providers });
135
+ }
136
+
137
+ /**
138
+ * Handler para POST /api/auth/signin
139
+ */
140
+ async function handleSignIn(req: HightJSRequest, auth: HWebAuth) {
141
+ try {
142
+ const { provider = 'credentials', ...credentials } = await req.json();
143
+
144
+ const result = await auth.signIn(provider, credentials);
145
+
146
+ if (!result) {
147
+ return HightJSResponse.json(
148
+ { error: 'Invalid credentials' },
149
+ { status: 401 }
150
+ );
151
+ }
152
+
153
+ // Se tem redirectUrl, é OAuth - retorna URL para redirecionamento
154
+ if ('redirectUrl' in result) {
155
+ return HightJSResponse.json({
156
+ success: true,
157
+ redirectUrl: result.redirectUrl,
158
+ type: 'oauth'
159
+ });
160
+ }
161
+
162
+ // Se tem session, é credentials - retorna sessão
163
+ return auth.createAuthResponse(result.token, {
164
+ success: true,
165
+ user: result.session.user,
166
+ type: 'session'
167
+ });
168
+ } catch (error) {
169
+ console.error('[hweb-auth] Error on handleSignIn:', error);
170
+ return HightJSResponse.json(
171
+ { error: 'Authentication failed' },
172
+ { status: 500 }
173
+ );
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Handler para POST /api/auth/signout
179
+ */
180
+ async function handleSignOut(req: HightJSRequest, auth: HWebAuth) {
181
+ return await auth.signOut(req);
182
+ }
package/src/types.ts ADDED
@@ -0,0 +1,108 @@
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
+
18
+ // Tipos para o sistema de autenticação
19
+ export type User = Record<string, any>;
20
+
21
+ export interface Session {
22
+ user: User;
23
+ expires: string;
24
+ accessToken?: string;
25
+ }
26
+
27
+ // Client-side types
28
+ export interface SignInOptions {
29
+ redirect?: boolean;
30
+ callbackUrl?: string;
31
+ [key: string]: any;
32
+ }
33
+
34
+ export interface SignInResult {
35
+ error?: string;
36
+ status?: number;
37
+ ok?: boolean;
38
+ url?: string;
39
+ }
40
+
41
+ export interface SessionContextType {
42
+ data: Session | null;
43
+ status: 'loading' | 'authenticated' | 'unauthenticated';
44
+ signIn: (provider?: string, options?: SignInOptions) => Promise<SignInResult | undefined>;
45
+ signOut: (options?: { callbackUrl?: string }) => Promise<void>;
46
+ update: () => Promise<Session | null>;
47
+ }
48
+
49
+ export interface AuthRoute {
50
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
51
+ path: string;
52
+ handler: (req: any, params: any) => Promise<any>;
53
+ }
54
+
55
+ export interface AuthProviderClass {
56
+ id: string;
57
+ name: string;
58
+ type: string;
59
+
60
+ // Para providers OAuth - retorna URL de redirecionamento
61
+ handleOauth?(credentials: Record<string, string>): Promise<string> | string;
62
+
63
+ // Métodos principais
64
+ handleSignIn(credentials: Record<string, string>): Promise<User | string | null>;
65
+ handleSignOut?(): Promise<void>;
66
+
67
+ // Rotas adicionais que o provider pode ter
68
+ additionalRoutes?: AuthRoute[];
69
+
70
+ // Configurações específicas do provider
71
+ getConfig?(): any;
72
+ }
73
+
74
+ export interface AuthConfig {
75
+ providers: AuthProviderClass[];
76
+ pages?: {
77
+ signIn?: string;
78
+ signOut?: string;
79
+ error?: string;
80
+ };
81
+ callbacks?: {
82
+ signIn?: (user: User, account: any, profile: any) => boolean | Promise<boolean>;
83
+ session?: ({session, user, provider}: {session: Session, user: User, provider: string}) => Session | Promise<Session>;
84
+ jwt?: (token: any, user: User, account: any, profile: any) => any | Promise<any>;
85
+ };
86
+ session?: {
87
+ strategy?: 'jwt' | 'database';
88
+ maxAge?: number;
89
+ updateAge?: number;
90
+ };
91
+ secret?: string;
92
+ debug?: boolean;
93
+ secureCookies?: boolean;
94
+ }
95
+
96
+
97
+
98
+ // Provider para credenciais
99
+ export interface CredentialsConfig {
100
+ id?: string;
101
+ name?: string;
102
+ credentials: Record<string, {
103
+ label: string;
104
+ type: string;
105
+ placeholder?: string;
106
+ }>;
107
+ authorize: (credentials: Record<string, string>) => Promise<User | null> | User | null;
108
+ }