@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.
Files changed (45) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +48 -0
  3. package/dist/client.d.ts +24 -0
  4. package/dist/client.js +146 -0
  5. package/dist/components.d.ts +19 -0
  6. package/dist/components.js +73 -0
  7. package/dist/core.d.ts +55 -0
  8. package/dist/core.js +189 -0
  9. package/dist/index.d.ts +7 -0
  10. package/dist/index.js +45 -0
  11. package/dist/jwt.d.ts +41 -0
  12. package/dist/jwt.js +185 -0
  13. package/dist/providers/credentials.d.ts +60 -0
  14. package/dist/providers/credentials.js +97 -0
  15. package/dist/providers/discord.d.ts +63 -0
  16. package/dist/providers/discord.js +190 -0
  17. package/dist/providers/google.d.ts +63 -0
  18. package/dist/providers/google.js +186 -0
  19. package/dist/providers/index.d.ts +2 -0
  20. package/dist/providers/index.js +35 -0
  21. package/dist/providers.d.ts +3 -0
  22. package/dist/providers.js +26 -0
  23. package/dist/react/index.d.ts +6 -0
  24. package/dist/react/index.js +47 -0
  25. package/dist/react.d.ts +22 -0
  26. package/dist/react.js +199 -0
  27. package/dist/routes.d.ts +16 -0
  28. package/dist/routes.js +152 -0
  29. package/dist/types.d.ts +76 -0
  30. package/dist/types.js +18 -0
  31. package/package.json +51 -0
  32. package/src/client.ts +171 -0
  33. package/src/components.tsx +84 -0
  34. package/src/core.ts +215 -0
  35. package/src/index.ts +25 -0
  36. package/src/jwt.ts +210 -0
  37. package/src/providers/credentials.ts +138 -0
  38. package/src/providers/discord.ts +239 -0
  39. package/src/providers/google.ts +234 -0
  40. package/src/providers/index.ts +20 -0
  41. package/src/providers.ts +20 -0
  42. package/src/react/index.ts +25 -0
  43. package/src/react.tsx +234 -0
  44. package/src/routes.ts +182 -0
  45. package/src/types.ts +108 -0
package/src/react.tsx ADDED
@@ -0,0 +1,234 @@
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 React, { createContext, useContext, useEffect, useState, useCallback, ReactNode } from 'react';
18
+ import type { Session, SessionContextType, SignInOptions, SignInResult, User } from './types';
19
+ import { router } from "nyte/react";
20
+
21
+ const SessionContext = createContext<SessionContextType | undefined>(undefined);
22
+
23
+ interface SessionProviderProps {
24
+ children: ReactNode;
25
+ basePath?: string;
26
+ refetchInterval?: number;
27
+ refetchOnWindowFocus?: boolean;
28
+ }
29
+
30
+ export function SessionProvider({
31
+ children,
32
+ basePath = '/api/auth',
33
+ refetchInterval = 0,
34
+ refetchOnWindowFocus = true
35
+ }: SessionProviderProps) {
36
+ const [session, setSession] = useState<Session | null>(null);
37
+ const [status, setStatus] = useState<'loading' | 'authenticated' | 'unauthenticated'>('loading');
38
+
39
+ // Fetch da sessão atual
40
+ const fetchSession = useCallback(async (): Promise<Session | null> => {
41
+ try {
42
+ const response = await fetch(`${basePath}/session`, {
43
+ credentials: 'include'
44
+ });
45
+
46
+ if (!response.ok) {
47
+ setStatus('unauthenticated');
48
+ return null;
49
+ }
50
+
51
+ const data = await response.json();
52
+ const sessionData = data.session;
53
+
54
+ if (sessionData) {
55
+ setSession(sessionData);
56
+ setStatus('authenticated');
57
+ return sessionData;
58
+ } else {
59
+ setSession(null);
60
+ setStatus('unauthenticated');
61
+ return null;
62
+ }
63
+ } catch (error) {
64
+ console.error('[hweb-auth] Error fetching session:', error);
65
+ setSession(null);
66
+ setStatus('unauthenticated');
67
+ return null;
68
+ }
69
+ }, [basePath]);
70
+
71
+ // SignIn function
72
+ const signIn = useCallback(async (
73
+ provider: string = 'credentials',
74
+ options: SignInOptions = {}
75
+ ): Promise<SignInResult | undefined> => {
76
+ try {
77
+ const { redirect = true, callbackUrl, ...credentials } = options;
78
+
79
+ const response = await fetch(`${basePath}/signin`, {
80
+ method: 'POST',
81
+ headers: {
82
+ 'Content-Type': 'application/json',
83
+ },
84
+ credentials: 'include',
85
+ body: JSON.stringify({
86
+ provider,
87
+ ...credentials
88
+ })
89
+ });
90
+
91
+ const data = await response.json();
92
+
93
+ if (response.ok && data.success) {
94
+ await fetchSession();
95
+ // Se é OAuth, redireciona para URL fornecida
96
+ if (data.type === 'oauth' && data.redirectUrl) {
97
+ if (redirect && typeof window !== 'undefined') {
98
+ window.location.href = data.redirectUrl;
99
+ }
100
+
101
+ return {
102
+ ok: true,
103
+ status: 200,
104
+ url: data.redirectUrl
105
+ };
106
+ }
107
+
108
+ // Se é sessão (credentials), redireciona para callbackUrl
109
+ if (data.type === 'session') {
110
+ if (redirect && typeof window !== 'undefined') {
111
+ window.location.href = callbackUrl || '/';
112
+ }
113
+
114
+ return {
115
+ ok: true,
116
+ status: 200,
117
+ url: callbackUrl || '/'
118
+ };
119
+ }
120
+ } else {
121
+ return {
122
+ error: data.error || 'Authentication failed',
123
+ status: response.status,
124
+ ok: false
125
+ };
126
+ }
127
+ } catch (error) {
128
+ console.error('[hweb-auth] Error on signIn:', error);
129
+ return {
130
+ error: 'Network error',
131
+ status: 500,
132
+ ok: false
133
+ };
134
+ }
135
+ }, [basePath, fetchSession]);
136
+
137
+ // SignOut function
138
+ const signOut = useCallback(async (options: { callbackUrl?: string } = {}): Promise<void> => {
139
+ try {
140
+ await fetch(`${basePath}/signout`, {
141
+ method: 'POST',
142
+ credentials: 'include'
143
+ });
144
+
145
+ setSession(null);
146
+ setStatus('unauthenticated');
147
+
148
+ if (typeof window !== 'undefined') {
149
+ try {
150
+ router.push(options.callbackUrl || '/');
151
+ } catch (e) {
152
+ window.location.href = options.callbackUrl || '/';
153
+ }
154
+ }
155
+ } catch (error) {
156
+ console.error('[hweb-auth] Error on signOut:', error);
157
+ }
158
+ }, [basePath]);
159
+
160
+ // Update session
161
+ const update = useCallback(async (): Promise<Session | null> => {
162
+ return await fetchSession();
163
+ }, [fetchSession]);
164
+
165
+ // Initial session fetch
166
+ useEffect(() => {
167
+ fetchSession();
168
+ }, [fetchSession]);
169
+
170
+ // Refetch interval
171
+ useEffect(() => {
172
+ if (refetchInterval > 0) {
173
+ const interval = setInterval(() => {
174
+ if (status === 'authenticated') {
175
+ fetchSession();
176
+ }
177
+ }, refetchInterval * 1000);
178
+
179
+ return () => clearInterval(interval);
180
+ }
181
+ }, [refetchInterval, status, fetchSession]);
182
+
183
+ // Refetch on window focus
184
+ useEffect(() => {
185
+ if (refetchOnWindowFocus) {
186
+ const handleFocus = () => {
187
+ if (status === 'authenticated') {
188
+ fetchSession();
189
+ }
190
+ };
191
+
192
+ window.addEventListener('focus', handleFocus);
193
+ return () => window.removeEventListener('focus', handleFocus);
194
+ }
195
+ }, [refetchOnWindowFocus, status, fetchSession]);
196
+
197
+ const value: SessionContextType = {
198
+ data: session,
199
+ status,
200
+ signIn,
201
+ signOut,
202
+ update
203
+ };
204
+
205
+ return (
206
+ <SessionContext.Provider value={value}>
207
+ {children}
208
+ </SessionContext.Provider>
209
+ );
210
+ }
211
+
212
+ /**
213
+ * Hook para acessar a sessão atual
214
+ */
215
+ export function useSession(): SessionContextType {
216
+ const context = useContext(SessionContext);
217
+ if (context === undefined) {
218
+ throw new Error('useSession must be used inside a SessionProvider');
219
+ }
220
+ return context;
221
+ }
222
+
223
+ /**
224
+ * Hook para verificar se o usuário está autenticado
225
+ */
226
+ export function useAuth(): { user: User | null; isAuthenticated: boolean; isLoading: boolean } {
227
+ const { data: session, status } = useSession();
228
+
229
+ return {
230
+ user: session?.user || null,
231
+ isAuthenticated: status === 'authenticated',
232
+ isLoading: status === 'loading'
233
+ };
234
+ }
package/src/routes.ts ADDED
@@ -0,0 +1,182 @@
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 } 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: NyteRequest, 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 NyteResponse.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 NyteResponse.json({ error: 'Route not found' }, { status: 404 });
66
+ }
67
+ },
68
+
69
+ async POST(req: NyteRequest, 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 NyteResponse.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 NyteResponse.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: NyteRequest, auth: HWebAuth) {
108
+ const session = await auth.getSession(req);
109
+
110
+ if (!session) {
111
+ return NyteResponse.json({ session: null });
112
+ }
113
+
114
+ return NyteResponse.json({ session });
115
+ }
116
+
117
+ /**
118
+ * Handler para GET /api/auth/csrf
119
+ */
120
+ async function handleCsrf(req: NyteRequest) {
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 NyteResponse.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 NyteResponse.json({ providers });
135
+ }
136
+
137
+ /**
138
+ * Handler para POST /api/auth/signin
139
+ */
140
+ async function handleSignIn(req: NyteRequest, 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 NyteResponse.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 NyteResponse.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 NyteResponse.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: NyteRequest, 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 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
+
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
+ }