@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
@@ -0,0 +1,239 @@
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 type {AuthProviderClass, AuthRoute, User} from '../types';
18
+ import {NyteRequest, NyteResponse} from 'nyte';
19
+
20
+ export interface DiscordConfig {
21
+ id?: string;
22
+ name?: string;
23
+ clientId: string;
24
+ clientSecret: string;
25
+ callbackUrl?: string;
26
+ successUrl?: string;
27
+ // Escopos OAuth, padrão: ['identify', 'email']
28
+ scope?: string[];
29
+ }
30
+
31
+ /**
32
+ * Provider para autenticação com Discord OAuth2
33
+ *
34
+ * Este provider permite autenticação usando Discord OAuth2.
35
+ * Automaticamente gerencia o fluxo OAuth completo e rotas necessárias.
36
+ *
37
+ * Exemplo de uso:
38
+ * ```typescript
39
+ * new DiscordProvider({
40
+ * clientId: process.env.DISCORD_CLIENT_ID!,
41
+ * clientSecret: process.env.DISCORD_CLIENT_SECRET!,
42
+ * callbackUrl: "http://localhost:3000/api/auth/callback/discord"
43
+ * })
44
+ * ```
45
+ *
46
+ * Fluxo de autenticação:
47
+ * 1. GET /api/auth/signin/discord - Gera URL e redireciona para Discord
48
+ * 2. Discord redireciona para /api/auth/callback/discord com código
49
+ * 3. Provider troca código por token e busca dados do usuário
50
+ * 4. Retorna objeto User com dados do Discord
51
+ */
52
+ export class DiscordProvider implements AuthProviderClass {
53
+ public readonly id: string;
54
+ public readonly name: string;
55
+ public readonly type: string = 'discord';
56
+
57
+ private config: DiscordConfig;
58
+ private readonly defaultScope = ['identify', 'email'];
59
+
60
+ constructor(config: DiscordConfig) {
61
+ this.config = config;
62
+ this.id = config.id || 'discord';
63
+ this.name = config.name || 'Discord';
64
+ }
65
+
66
+ /**
67
+ * Método para gerar URL OAuth (usado pelo handleSignIn)
68
+ */
69
+ handleOauth(credentials: Record<string, string> = {}): string {
70
+ return this.getAuthorizationUrl();
71
+ }
72
+
73
+ /**
74
+ * Método principal - agora redireciona para OAuth ou processa callback
75
+ */
76
+ async handleSignIn(credentials: Record<string, string>): Promise<User | string | null> {
77
+ // Se tem código, é callback - processa autenticação
78
+ if (credentials.code) {
79
+ return await this.processOAuthCallback(credentials);
80
+ }
81
+
82
+ // Se não tem código, é início do OAuth - retorna URL
83
+ return this.handleOauth(credentials);
84
+ }
85
+
86
+ /**
87
+ * Processa o callback OAuth (código → usuário)
88
+ */
89
+ private async processOAuthCallback(credentials: Record<string, string>): Promise<User | null> {
90
+ try {
91
+ const { code } = credentials;
92
+ if (!code) {
93
+ throw new Error('Authorization code not provided');
94
+ }
95
+
96
+
97
+ // Troca o código por access token
98
+ const tokenResponse = await fetch('https://discord.com/api/oauth2/token', {
99
+ method: 'POST',
100
+ headers: {
101
+ 'Content-Type': 'application/x-www-form-urlencoded',
102
+ },
103
+ body: new URLSearchParams({
104
+ client_id: this.config.clientId,
105
+ client_secret: this.config.clientSecret,
106
+ grant_type: 'authorization_code',
107
+ code,
108
+ redirect_uri: this.config.callbackUrl || '',
109
+ }),
110
+ });
111
+
112
+ if (!tokenResponse.ok) {
113
+ const error = await tokenResponse.text();
114
+ // O erro original "Invalid \"code\" in request." acontece aqui.
115
+ throw new Error(`Failed to exchange code for token: ${error}`);
116
+ }
117
+
118
+ const tokens = await tokenResponse.json();
119
+
120
+ // Busca dados do usuário
121
+ const userResponse = await fetch('https://discord.com/api/users/@me', {
122
+ headers: {
123
+ 'Authorization': `Bearer ${tokens.access_token}`,
124
+ },
125
+ });
126
+
127
+ if (!userResponse.ok) {
128
+ throw new Error('Failed to fetch user data');
129
+ }
130
+
131
+ const discordUser = await userResponse.json();
132
+
133
+ // Retorna objeto User padronizado
134
+ return {
135
+ id: discordUser.id,
136
+ name: discordUser.global_name || discordUser.username,
137
+ email: discordUser.email,
138
+ image: discordUser.avatar
139
+ ? `https://cdn.discordapp.com/avatars/${discordUser.id}/${discordUser.avatar}.png`
140
+ : null,
141
+ username: discordUser.username,
142
+ discriminator: discordUser.discriminator,
143
+ provider: this.id,
144
+ providerId: discordUser.id,
145
+ accessToken: tokens.access_token,
146
+ refreshToken: tokens.refresh_token
147
+ };
148
+
149
+ } catch (error) {
150
+ console.error(`[${this.id} Provider] Error during OAuth callback:`, error);
151
+ return null;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Rotas adicionais específicas do Discord OAuth
157
+ */
158
+ public additionalRoutes: AuthRoute[] = [
159
+ // Rota de callback do Discord
160
+ {
161
+ method: 'GET',
162
+ path: '/api/auth/callback/discord',
163
+ handler: async (req: NyteRequest, params: any) => {
164
+ const url = new URL(req.url || '', 'http://localhost');
165
+ const code = url.searchParams.get('code');
166
+
167
+ if (!code) {
168
+ return NyteResponse.json({ error: 'Authorization code not provided' }, { status: 400 });
169
+ }
170
+
171
+ try {
172
+ // CORREÇÃO: O fluxo correto é delegar o 'code' para o endpoint de signin
173
+ // principal, que processará o código uma única vez. A implementação anterior
174
+ // usava o código duas vezes, causando o erro 'invalid_grant'.
175
+ const authResponse = await fetch(`${req.headers.origin || 'http://localhost:3000'}/api/auth/signin`, {
176
+ method: 'POST',
177
+ headers: {
178
+ 'Content-Type': 'application/json',
179
+ },
180
+ body: JSON.stringify({
181
+ provider: this.id,
182
+ code,
183
+ })
184
+ });
185
+
186
+ if (authResponse.ok) {
187
+ // Propaga o cookie de sessão retornado pelo endpoint de signin
188
+ // e redireciona o usuário para a página de sucesso.
189
+ const setCookieHeader = authResponse.headers.get('set-cookie');
190
+
191
+ if(this.config.successUrl) {
192
+ return NyteResponse
193
+ .redirect(this.config.successUrl)
194
+ .header('Set-Cookie', setCookieHeader || '');
195
+ }
196
+ return NyteResponse.json({ success: true })
197
+ .header('Set-Cookie', setCookieHeader || '');
198
+ } else {
199
+ const errorText = await authResponse.text();
200
+ console.error(`[${this.id} Provider] Session creation failed during callback. Status: ${authResponse.status}, Body: ${errorText}`);
201
+ return NyteResponse.json({ error: 'Session creation failed' }, { status: 500 });
202
+ }
203
+
204
+ } catch (error) {
205
+ console.error(`[${this.id} Provider] Callback handler fetch error:`, error);
206
+ return NyteResponse.json({ error: 'Internal server error' }, { status: 500 });
207
+ }
208
+ }
209
+ }
210
+ ];
211
+
212
+ /**
213
+ * Gera URL de autorização do Discord
214
+ */
215
+ getAuthorizationUrl(): string {
216
+ const params = new URLSearchParams({
217
+ client_id: this.config.clientId,
218
+ redirect_uri: this.config.callbackUrl || '',
219
+ response_type: 'code',
220
+ scope: (this.config.scope || this.defaultScope).join(' ')
221
+ });
222
+
223
+ return `https://discord.com/api/oauth2/authorize?${params.toString()}`;
224
+ }
225
+
226
+ /**
227
+ * Retorna configuração pública do provider
228
+ */
229
+ getConfig(): any {
230
+ return {
231
+ id: this.id,
232
+ name: this.name,
233
+ type: this.type,
234
+ clientId: this.config.clientId, // Público
235
+ scope: this.config.scope || this.defaultScope,
236
+ callbackUrl: this.config.callbackUrl
237
+ };
238
+ }
239
+ }
@@ -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 type {AuthProviderClass, AuthRoute, User} from '../types';
18
+ import {NyteRequest, NyteResponse} from 'nyte';
19
+
20
+ export interface GoogleConfig {
21
+ id?: string;
22
+ name?: string;
23
+ clientId: string;
24
+ clientSecret: string;
25
+ callbackUrl?: string;
26
+ successUrl?: string;
27
+ // Escopos OAuth do Google, padrão: ['openid', 'email', 'profile']
28
+ scope?: string[];
29
+ }
30
+
31
+ /**
32
+ * Provider para autenticação com Google OAuth2
33
+ *
34
+ * Este provider permite autenticação usando Google OAuth2.
35
+ * Automaticamente gerencia o fluxo OAuth completo e rotas necessárias.
36
+ *
37
+ * Exemplo de uso:
38
+ * ```typescript
39
+ * new GoogleProvider({
40
+ * clientId: process.env.GOOGLE_CLIENT_ID!,
41
+ * clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
42
+ * callbackUrl: "http://localhost:3000/api/auth/callback/google"
43
+ * })
44
+ * ```
45
+ *
46
+ * Fluxo de autenticação:
47
+ * 1. GET /api/auth/signin/google - Gera URL e redireciona para Google
48
+ * 2. Google redireciona para /api/auth/callback/google com código
49
+ * 3. Provider troca código por token e busca dados do usuário
50
+ * 4. Retorna objeto User com dados do Google
51
+ */
52
+ export class GoogleProvider implements AuthProviderClass {
53
+ public readonly id: string;
54
+ public readonly name: string;
55
+ public readonly type: string = 'google';
56
+
57
+ private config: GoogleConfig;
58
+ private readonly defaultScope = [
59
+ 'openid',
60
+ 'https://www.googleapis.com/auth/userinfo.email',
61
+ 'https://www.googleapis.com/auth/userinfo.profile'
62
+ ];
63
+
64
+ constructor(config: GoogleConfig) {
65
+ this.config = config;
66
+ this.id = config.id || 'google';
67
+ this.name = config.name || 'Google';
68
+ }
69
+
70
+ /**
71
+ * Método para gerar URL OAuth (usado pelo handleSignIn)
72
+ */
73
+ handleOauth(credentials: Record<string, string> = {}): string {
74
+ return this.getAuthorizationUrl();
75
+ }
76
+
77
+ /**
78
+ * Método principal - redireciona para OAuth ou processa o callback
79
+ */
80
+ async handleSignIn(credentials: Record<string, string>): Promise<User | string | null> {
81
+ // Se tem código, é o callback - processa a autenticação
82
+ if (credentials.code) {
83
+ return await this.processOAuthCallback(credentials);
84
+ }
85
+
86
+ // Se não tem código, é o início do OAuth - retorna a URL
87
+ return this.handleOauth(credentials);
88
+ }
89
+
90
+ /**
91
+ * Processa o callback do OAuth (troca o código pelo usuário)
92
+ */
93
+ private async processOAuthCallback(credentials: Record<string, string>): Promise<User | null> {
94
+ try {
95
+ const { code } = credentials;
96
+ if (!code) {
97
+ throw new Error('Authorization code not provided');
98
+ }
99
+
100
+ // Troca o código por um access token
101
+ const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {
102
+ method: 'POST',
103
+ headers: {
104
+ 'Content-Type': 'application/x-www-form-urlencoded',
105
+ },
106
+ body: new URLSearchParams({
107
+ client_id: this.config.clientId,
108
+ client_secret: this.config.clientSecret,
109
+ grant_type: 'authorization_code',
110
+ code,
111
+ redirect_uri: this.config.callbackUrl || '',
112
+ }),
113
+ });
114
+
115
+ if (!tokenResponse.ok) {
116
+ const error = await tokenResponse.text();
117
+ throw new Error(`Failed to exchange code for token: ${error}`);
118
+ }
119
+
120
+ const tokens = await tokenResponse.json();
121
+
122
+ // Busca os dados do usuário com o access token
123
+ const userResponse = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
124
+ headers: {
125
+ 'Authorization': `Bearer ${tokens.access_token}`,
126
+ },
127
+ });
128
+
129
+ if (!userResponse.ok) {
130
+ throw new Error('Failed to fetch user data');
131
+ }
132
+
133
+ const googleUser = await userResponse.json();
134
+
135
+ // Retorna o objeto User padronizado
136
+ return {
137
+ id: googleUser.id,
138
+ name: googleUser.name,
139
+ email: googleUser.email,
140
+ image: googleUser.picture || null,
141
+ provider: this.id,
142
+ providerId: googleUser.id,
143
+ accessToken: tokens.access_token,
144
+ refreshToken: tokens.refresh_token
145
+ };
146
+
147
+ } catch (error) {
148
+ console.error(`[${this.id} Provider] Error during OAuth callback:`, error);
149
+ return null;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Rotas adicionais específicas do Google OAuth
155
+ */
156
+ public additionalRoutes: AuthRoute[] = [
157
+ // Rota de callback do Google
158
+ {
159
+ method: 'GET',
160
+ path: '/api/auth/callback/google',
161
+ handler: async (req: NyteRequest, params: any) => {
162
+ const url = new URL(req.url || '', 'http://localhost');
163
+ const code = url.searchParams.get('code');
164
+
165
+ if (!code) {
166
+ return NyteResponse.json({ error: 'Authorization code not provided' }, { status: 400 });
167
+ }
168
+
169
+ try {
170
+ // Delega o 'code' para o endpoint de signin principal
171
+ const authResponse = await fetch(`${req.headers.origin || 'http://localhost:3000'}/api/auth/signin`, {
172
+ method: 'POST',
173
+ headers: {
174
+ 'Content-Type': 'application/json',
175
+ },
176
+ body: JSON.stringify({
177
+ provider: this.id,
178
+ code,
179
+ })
180
+ });
181
+
182
+ if (authResponse.ok) {
183
+ // Propaga o cookie de sessão e redireciona para a URL de sucesso
184
+ const setCookieHeader = authResponse.headers.get('set-cookie');
185
+
186
+ if(this.config.successUrl) {
187
+ return NyteResponse
188
+ .redirect(this.config.successUrl)
189
+ .header('Set-Cookie', setCookieHeader || '');
190
+ }
191
+ return NyteResponse.json({ success: true })
192
+ .header('Set-Cookie', setCookieHeader || '');
193
+ } else {
194
+ const errorText = await authResponse.text();
195
+ console.error(`[${this.id} Provider] Session creation failed during callback. Status: ${authResponse.status}, Body: ${errorText}`);
196
+ return NyteResponse.json({ error: 'Session creation failed' }, { status: 500 });
197
+ }
198
+
199
+ } catch (error) {
200
+ console.error(`[${this.id} Provider] Callback handler fetch error:`, error);
201
+ return NyteResponse.json({ error: 'Internal server error' }, { status: 500 });
202
+ }
203
+ }
204
+ }
205
+ ];
206
+
207
+ /**
208
+ * Gera a URL de autorização do Google
209
+ */
210
+ getAuthorizationUrl(): string {
211
+ const params = new URLSearchParams({
212
+ client_id: this.config.clientId,
213
+ redirect_uri: this.config.callbackUrl || '',
214
+ response_type: 'code',
215
+ scope: (this.config.scope || this.defaultScope).join(' ')
216
+ });
217
+
218
+ return `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
219
+ }
220
+
221
+ /**
222
+ * Retorna a configuração pública do provider
223
+ */
224
+ getConfig(): any {
225
+ return {
226
+ id: this.id,
227
+ name: this.name,
228
+ type: this.type,
229
+ clientId: this.config.clientId, // Público
230
+ scope: this.config.scope || this.defaultScope,
231
+ callbackUrl: this.config.callbackUrl
232
+ };
233
+ }
234
+ }
@@ -0,0 +1,20 @@
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
+ // Exportações dos providers
18
+ export * from './credentials';
19
+ export * from './discord';
20
+
@@ -0,0 +1,20 @@
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
+ // Exportações dos providers
18
+ export { CredentialsProvider } from './providers/credentials';
19
+ export { DiscordProvider } from './providers/discord';
20
+ export { GoogleProvider } from './providers/google';
@@ -0,0 +1,25 @@
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
+ // Exportações do frontend
18
+ export * from '../react';
19
+ export * from '../client';
20
+ export * from '../components';
21
+
22
+ // Re-exports das funções mais usadas para conveniência
23
+ export { getSession } from '../client';
24
+ export { useSession, useAuth, SessionProvider } from '../react';
25
+ export { AuthGuard, GuestOnly } from '../components';