@hightjs/auth 0.4.0

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/dist/routes.js ADDED
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createAuthRoutes = createAuthRoutes;
4
+ /*
5
+ * This file is part of the HightJS Project.
6
+ * Copyright (c) 2025 itsmuzin
7
+ *
8
+ * Licensed under the Apache License, Version 2.0 (the "License");
9
+ * you may not use this file except in compliance with the License.
10
+ * You may obtain a copy of the License at
11
+ *
12
+ * http://www.apache.org/licenses/LICENSE-2.0
13
+ *
14
+ * Unless required by applicable law or agreed to in writing, software
15
+ * distributed under the License is distributed on an "AS IS" BASIS,
16
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ * See the License for the specific language governing permissions and
18
+ * limitations under the License.
19
+ */
20
+ const hightjs_1 = require("hightjs");
21
+ const core_1 = require("./core");
22
+ /**
23
+ * Cria o handler catch-all para /api/auth/[...value]
24
+ */
25
+ function createAuthRoutes(config) {
26
+ const auth = new core_1.HWebAuth(config);
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
+ async GET(req, params) {
34
+ const path = params["value"];
35
+ const route = Array.isArray(path) ? path.join('/') : path || '';
36
+ // Verifica rotas adicionais dos providers primeiro
37
+ const additionalRoutes = auth.getAllAdditionalRoutes();
38
+ for (const { provider, route: additionalRoute } of additionalRoutes) {
39
+ if (additionalRoute.method === 'GET' && additionalRoute.path.includes(route)) {
40
+ try {
41
+ return await additionalRoute.handler(req, params);
42
+ }
43
+ catch (error) {
44
+ console.error(`[${provider} Provider] Error in additional route:`, error);
45
+ return hightjs_1.HightJSResponse.json({ error: 'Provider route error' }, { status: 500 });
46
+ }
47
+ }
48
+ }
49
+ // Rotas padrão do sistema
50
+ switch (route) {
51
+ case 'session':
52
+ return await handleSession(req, auth);
53
+ case 'csrf':
54
+ return await handleCsrf(req);
55
+ case 'providers':
56
+ return await handleProviders(auth);
57
+ default:
58
+ return hightjs_1.HightJSResponse.json({ error: 'Route not found' }, { status: 404 });
59
+ }
60
+ },
61
+ async POST(req, params) {
62
+ const path = params["value"];
63
+ const route = Array.isArray(path) ? path.join('/') : path || '';
64
+ // Verifica rotas adicionais dos providers primeiro
65
+ const additionalRoutes = auth.getAllAdditionalRoutes();
66
+ for (const { provider, route: additionalRoute } of additionalRoutes) {
67
+ if (additionalRoute.method === 'POST' && additionalRoute.path.includes(route)) {
68
+ try {
69
+ return await additionalRoute.handler(req, params);
70
+ }
71
+ catch (error) {
72
+ console.error(`[${provider} Provider] Error in additional route:`, error);
73
+ return hightjs_1.HightJSResponse.json({ error: 'Provider route error' }, { status: 500 });
74
+ }
75
+ }
76
+ }
77
+ // Rotas padrão do sistema
78
+ switch (route) {
79
+ case 'signin':
80
+ return await handleSignIn(req, auth);
81
+ case 'signout':
82
+ return await handleSignOut(req, auth);
83
+ default:
84
+ return hightjs_1.HightJSResponse.json({ error: 'Route not found' }, { status: 404 });
85
+ }
86
+ },
87
+ // Instância do auth para uso manual
88
+ auth
89
+ };
90
+ }
91
+ /**
92
+ * Handler para GET /api/auth/session
93
+ */
94
+ async function handleSession(req, auth) {
95
+ const session = await auth.getSession(req);
96
+ if (!session) {
97
+ return hightjs_1.HightJSResponse.json({ session: null });
98
+ }
99
+ return hightjs_1.HightJSResponse.json({ session });
100
+ }
101
+ /**
102
+ * Handler para GET /api/auth/csrf
103
+ */
104
+ async function handleCsrf(req) {
105
+ // Token CSRF simples para proteção
106
+ const csrfToken = Math.random().toString(36).substring(2, 15) +
107
+ Math.random().toString(36).substring(2, 15);
108
+ return hightjs_1.HightJSResponse.json({ csrfToken });
109
+ }
110
+ /**
111
+ * Handler para GET /api/auth/providers
112
+ */
113
+ async function handleProviders(auth) {
114
+ const providers = auth.getProviders();
115
+ return hightjs_1.HightJSResponse.json({ providers });
116
+ }
117
+ /**
118
+ * Handler para POST /api/auth/signin
119
+ */
120
+ async function handleSignIn(req, auth) {
121
+ try {
122
+ const { provider = 'credentials', ...credentials } = await req.json();
123
+ const result = await auth.signIn(provider, credentials);
124
+ if (!result) {
125
+ return hightjs_1.HightJSResponse.json({ error: 'Invalid credentials' }, { status: 401 });
126
+ }
127
+ // Se tem redirectUrl, é OAuth - retorna URL para redirecionamento
128
+ if ('redirectUrl' in result) {
129
+ return hightjs_1.HightJSResponse.json({
130
+ success: true,
131
+ redirectUrl: result.redirectUrl,
132
+ type: 'oauth'
133
+ });
134
+ }
135
+ // Se tem session, é credentials - retorna sessão
136
+ return auth.createAuthResponse(result.token, {
137
+ success: true,
138
+ user: result.session.user,
139
+ type: 'session'
140
+ });
141
+ }
142
+ catch (error) {
143
+ console.error('[hweb-auth] Error on handleSignIn:', error);
144
+ return hightjs_1.HightJSResponse.json({ error: 'Authentication failed' }, { status: 500 });
145
+ }
146
+ }
147
+ /**
148
+ * Handler para POST /api/auth/signout
149
+ */
150
+ async function handleSignOut(req, auth) {
151
+ return await auth.signOut(req);
152
+ }
@@ -0,0 +1,76 @@
1
+ export type User = Record<string, any>;
2
+ export interface Session {
3
+ user: User;
4
+ expires: string;
5
+ accessToken?: string;
6
+ }
7
+ export interface SignInOptions {
8
+ redirect?: boolean;
9
+ callbackUrl?: string;
10
+ [key: string]: any;
11
+ }
12
+ export interface SignInResult {
13
+ error?: string;
14
+ status?: number;
15
+ ok?: boolean;
16
+ url?: string;
17
+ }
18
+ export interface SessionContextType {
19
+ data: Session | null;
20
+ status: 'loading' | 'authenticated' | 'unauthenticated';
21
+ signIn: (provider?: string, options?: SignInOptions) => Promise<SignInResult | undefined>;
22
+ signOut: (options?: {
23
+ callbackUrl?: string;
24
+ }) => Promise<void>;
25
+ update: () => Promise<Session | null>;
26
+ }
27
+ export interface AuthRoute {
28
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
29
+ path: string;
30
+ handler: (req: any, params: any) => Promise<any>;
31
+ }
32
+ export interface AuthProviderClass {
33
+ id: string;
34
+ name: string;
35
+ type: string;
36
+ handleOauth?(credentials: Record<string, string>): Promise<string> | string;
37
+ handleSignIn(credentials: Record<string, string>): Promise<User | string | null>;
38
+ handleSignOut?(): Promise<void>;
39
+ additionalRoutes?: AuthRoute[];
40
+ getConfig?(): any;
41
+ }
42
+ export interface AuthConfig {
43
+ providers: AuthProviderClass[];
44
+ pages?: {
45
+ signIn?: string;
46
+ signOut?: string;
47
+ error?: string;
48
+ };
49
+ callbacks?: {
50
+ signIn?: (user: User, account: any, profile: any) => boolean | Promise<boolean>;
51
+ session?: ({ session, user, provider }: {
52
+ session: Session;
53
+ user: User;
54
+ provider: string;
55
+ }) => Session | Promise<Session>;
56
+ jwt?: (token: any, user: User, account: any, profile: any) => any | Promise<any>;
57
+ };
58
+ session?: {
59
+ strategy?: 'jwt' | 'database';
60
+ maxAge?: number;
61
+ updateAge?: number;
62
+ };
63
+ secret?: string;
64
+ debug?: boolean;
65
+ secureCookies?: boolean;
66
+ }
67
+ export interface CredentialsConfig {
68
+ id?: string;
69
+ name?: string;
70
+ credentials: Record<string, {
71
+ label: string;
72
+ type: string;
73
+ placeholder?: string;
74
+ }>;
75
+ authorize: (credentials: Record<string, string>) => Promise<User | null> | User | null;
76
+ }
package/dist/types.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ /*
3
+ * This file is part of the HightJS Project.
4
+ * Copyright (c) 2025 itsmuzin
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@hightjs/auth",
3
+ "version": "0.4.0",
4
+ "description": "Authentication package for HightJS framework",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "private": false,
8
+ "author": "itsmuzin",
9
+ "license": "Apache-2.0",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.js"
15
+ },
16
+ "./react": {
17
+ "types": "./dist/react/index.d.ts",
18
+ "import": "./dist/react/index.js",
19
+ "require": "./dist/react/index.js"
20
+ }
21
+ },
22
+ "keywords": [
23
+ "hightjs",
24
+ "auth",
25
+ "authentication",
26
+ "framework"
27
+ ],
28
+ "files": [
29
+ "dist",
30
+ "README.md"
31
+ ],
32
+ "devDependencies": {
33
+ "@types/node": "^20.11.24",
34
+ "rimraf": "^5.0.0",
35
+ "typescript": "^5.9.3"
36
+ },
37
+ "dependencies": {
38
+ "@types/react": "^19.2.2",
39
+ "react": "^19.2.0",
40
+ "hightjs": "0.4.0"
41
+ },
42
+ "scripts": {
43
+ "build": "tsc",
44
+ "build:watch": "tsc --watch",
45
+ "clean": "rimraf dist",
46
+ "test": "echo \"Error: no test specified\" && exit 1"
47
+ }
48
+ }