mbkauthe 2.4.0 → 3.0.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/docs/api.md CHANGED
@@ -11,6 +11,10 @@ This document provides comprehensive API documentation for MBKAuthe authenticati
11
11
  - [Authentication](#authentication)
12
12
  - [Session Management](#session-management)
13
13
  - [API Endpoints](#api-endpoints)
14
+ - [Public Endpoints](#public-endpoints)
15
+ - [Protected Endpoints](#protected-endpoints)
16
+ - [OAuth Endpoints](#oauth-endpoints)
17
+ - [Information Endpoints](#information-endpoints)
14
18
  - [Middleware Reference](#middleware-reference)
15
19
  - [Code Examples](#code-examples)
16
20
 
@@ -326,6 +330,35 @@ Displays MBKAuthe version information and configuration.
326
330
 
327
331
  ---
328
332
 
333
+ #### `GET /mbkauthe/ErrorCode`
334
+
335
+ Displays comprehensive error code documentation with descriptions and user messages.
336
+
337
+ **Response:** HTML page showing:
338
+ - All error codes organized by category
339
+ - Error code ranges (Authentication, 2FA, Session, Authorization, etc.)
340
+ - User-friendly messages and hints for each error
341
+ - Dynamically generated from `lib/utils/errors.js`
342
+
343
+ **Categories:**
344
+ - **600-699**: Authentication Errors
345
+ - **700-799**: Two-Factor Authentication Errors
346
+ - **800-899**: Session Management Errors
347
+ - **900-999**: Authorization Errors
348
+ - **1000-1099**: Input Validation Errors
349
+ - **1100-1199**: Rate Limiting Errors
350
+ - **1200-1299**: Server Errors
351
+ - **1300-1399**: OAuth Errors
352
+
353
+ **Note:** This page is automatically synchronized with the error definitions in the codebase. Adding new errors only requires updating `lib/utils/errors.js` and the category code array.
354
+
355
+ **Usage:**
356
+ ```
357
+ GET /mbkauthe/ErrorCode
358
+ ```
359
+
360
+ ---
361
+
329
362
  #### `GET /mbkauthe/main.js`
330
363
 
331
364
  Serves the client-side JavaScript file containing helper functions for authentication operations.
@@ -364,6 +397,35 @@ Serves the client-side JavaScript file containing helper functions for authentic
364
397
  - Forces page reload
365
398
 
366
399
 
400
+ ---
401
+
402
+ #### `GET /mbkauthe/ErrorCode`
403
+
404
+ Displays comprehensive error code documentation with descriptions and user messages.
405
+
406
+ **Response:** HTML page showing:
407
+ - All error codes organized by category
408
+ - Error code ranges (Authentication, 2FA, Session, Authorization, etc.)
409
+ - User-friendly messages and hints for each error
410
+ - Dynamically generated from `lib/utils/errors.js`
411
+
412
+ **Categories:**
413
+ - **600-699**: Authentication Errors
414
+ - **700-799**: Two-Factor Authentication Errors
415
+ - **800-899**: Session Management Errors
416
+ - **900-999**: Authorization Errors
417
+ - **1000-1099**: Input Validation Errors
418
+ - **1100-1199**: Rate Limiting Errors
419
+ - **1200-1299**: Server Errors
420
+ - **1300-1399**: OAuth Errors
421
+
422
+ **Note:** This page is automatically synchronized with the error definitions in the codebase. Adding new errors only requires updating `lib/utils/errors.js` and the category code array.
423
+
424
+ **Usage:**
425
+ ```
426
+ GET /mbkauthe/ErrorCode
427
+ ```
428
+
367
429
  ---
368
430
 
369
431
  #### `GET /icon.svg`
@@ -448,6 +510,79 @@ GET /mbkauthe/test
448
510
 
449
511
  ---
450
512
 
513
+ ### OAuth Endpoints
514
+
515
+ #### `GET /mbkauthe/api/github/login`
516
+
517
+ Initiates the GitHub OAuth authentication flow.
518
+
519
+ **Rate Limit:** 10 requests per 5 minutes
520
+
521
+ **Query Parameters:**
522
+ - `redirect` (optional) - Relative URL to redirect after successful authentication (must start with `/` to prevent open redirect attacks)
523
+
524
+ **Response:** Redirects to GitHub OAuth authorization page
525
+
526
+ **Prerequisites:**
527
+ - `GITHUB_LOGIN_ENABLED=true` in environment
528
+ - Valid `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` configured
529
+ - User's GitHub account must be linked to an MBKAuth account in `user_github` table
530
+
531
+ **Example:**
532
+ ```
533
+ GET /mbkauthe/api/github/login?redirect=/dashboard
534
+ ```
535
+
536
+ **Workflow:**
537
+ 1. User clicks "Login with GitHub"
538
+ 2. Redirects to GitHub for authorization
539
+ 3. GitHub redirects back to callback URL
540
+ 4. System verifies GitHub account is linked
541
+ 5. If 2FA enabled, prompts for 2FA
542
+ 6. Creates session and redirects to specified URL
543
+
544
+ ---
545
+
546
+ #### `GET /mbkauthe/api/github/login/callback`
547
+
548
+ Handles the OAuth callback from GitHub after user authorization.
549
+
550
+ **Rate Limit:** Inherited from OAuth rate limiter (10 requests per 5 minutes)
551
+
552
+ **Query Parameters:**
553
+ - `code` - Authorization code from GitHub (automatically provided)
554
+ - `state` - State parameter for CSRF protection (automatically provided)
555
+
556
+ **Response:**
557
+ - Redirects to 2FA page if 2FA is enabled for the user
558
+ - Redirects to `loginRedirectURL` or stored redirect URL if 2FA is not required
559
+ - Renders error page if authentication fails
560
+
561
+ **Error Handling:**
562
+ - **GitHub Not Linked**: Returns error if GitHub account is not in `user_github` table
563
+ - **Account Inactive**: Returns error if user account is deactivated
564
+ - **Not Authorized**: Returns error if user is not allowed to access the application
565
+ - **GitHub Auth Error**: Returns error for any OAuth-related failures
566
+
567
+ **Success Flow:**
568
+ ```
569
+ GitHub → /api/github/login/callback
570
+ → (If 2FA enabled) → /mbkauthe/2fa
571
+ → (If no 2FA) → loginRedirectURL or stored redirect
572
+ ```
573
+
574
+ **Database Query:**
575
+ ```sql
576
+ SELECT ug.*, u."UserName", u."Role", u."Active", u."AllowedApps", u."id"
577
+ FROM user_github ug
578
+ JOIN "Users" u ON ug.user_name = u."UserName"
579
+ WHERE ug.github_id = $1
580
+ ```
581
+
582
+ **Note:** This endpoint is automatically called by GitHub and should not be accessed directly by users.
583
+
584
+ ---
585
+
451
586
  ## Middleware Reference
452
587
 
453
588
  ### `validateSession`
@@ -931,10 +1066,13 @@ app.use((req, res) => {
931
1066
  | `/mbkauthe/api/login` | 8 requests | 1 minute |
932
1067
  | `/mbkauthe/api/logout` | 10 requests | 1 minute |
933
1068
  | `/mbkauthe/api/verify-2fa` | 5 requests | 1 minute |
1069
+ | `/mbkauthe/api/github/login` | 10 requests | 5 minutes |
1070
+ | `/mbkauthe/api/github/login/callback` | 10 requests | 5 minutes |
934
1071
  | `/mbkauthe/login` | 8 requests | 1 minute |
935
1072
  | `/mbkauthe/info` | 8 requests | 1 minute |
1073
+ | `/mbkauthe/test` | 8 requests | 1 minute |
936
1074
 
937
- Rate limits are applied per IP address.
1075
+ Rate limits are applied per IP address. Logged-in users are exempt from some rate limits (e.g., login page rate limit).
938
1076
 
939
1077
  ---
940
1078
 
package/docs/db.md CHANGED
@@ -138,13 +138,14 @@ The GitHub login feature is now fully integrated into your mbkauthe system and r
138
138
 
139
139
  - `id` (INTEGER, auto-increment, primary key): Unique identifier for each user.
140
140
  - `UserName` (TEXT): The username of the user.
141
- - `Password` (TEXT): The hashed password of the user.
141
+ - `Password` (TEXT): The raw password of the user (used when EncPass=false).
142
+ - `PasswordEnc` (TEXT): The encrypted/hashed password of the user (used when EncPass=true).
142
143
  - `Role` (ENUM): The role of the user. Possible values: `SuperAdmin`, `NormalUser`, `Guest`.
143
144
  - `Active` (BOOLEAN): Indicates whether the user account is active.
144
145
  - `HaveMailAccount` (BOOLEAN)(optional): Indicates if the user has a linked mail account.
145
146
  - `SessionId` (TEXT): The session ID associated with the user.
146
147
  - `GuestRole` (JSONB): Stores additional guest-specific role information in binary JSON format.
147
- - `AllowedApps`(JSONB):
148
+ - `AllowedApps`(JSONB): Array of applications the user is authorized to access.
148
149
 
149
150
  - **Schema:**
150
151
  ```sql
@@ -153,7 +154,8 @@ CREATE TYPE role AS ENUM ('SuperAdmin', 'NormalUser', 'Guest');
153
154
  CREATE TABLE "Users" (
154
155
  id INTEGER PRIMARY KEY AUTOINCREMENT,
155
156
  "UserName" VARCHAR(50) NOT NULL UNIQUE,
156
- "Password" VARCHAR(61) NOT NULL, -- For bcrypt hash
157
+ "Password" VARCHAR(61), -- For raw passwords (when EncPass=false)
158
+ "PasswordEnc" VARCHAR(128), -- For encrypted passwords (when EncPass=true)
157
159
  "Role" role DEFAULT 'NormalUser' NOT NULL,
158
160
  "Active" BOOLEAN DEFAULT FALSE,
159
161
  "HaveMailAccount" BOOLEAN DEFAULT FALSE,
@@ -173,6 +175,12 @@ CREATE INDEX IF NOT EXISTS idx_users_last_login ON "Users" (last_login);
173
175
  CREATE INDEX IF NOT EXISTS idx_users_id_sessionid_active_role ON "Users" ("id", LOWER("SessionId"), "Active", "Role");
174
176
  ```
175
177
 
178
+ **Password Storage Notes:**
179
+ - When `EncPass=false` (default): The system uses the `Password` column to store and validate raw passwords
180
+ - When `EncPass=true` (recommended for production): The system uses the `PasswordEnc` column to store hashed passwords using PBKDF2 with the username as salt
181
+ - Only one password column should be populated based on your EncPass configuration
182
+ - The PasswordEnc field stores 128-character hex strings when using PBKDF2 hashing
183
+
176
184
  ### Session Table
177
185
 
178
186
  - **Columns:**
@@ -255,6 +263,7 @@ CREATE INDEX IF NOT EXISTS idx_trusted_devices_expires ON "TrustedDevices"("Expi
255
263
 
256
264
  To add new users to the `Users` table, use the following SQL queries:
257
265
 
266
+ **For Raw Password Storage (EncPass=false):**
258
267
  ```sql
259
268
  INSERT INTO "Users" ("UserName", "Password", "Role", "Active", "HaveMailAccount", "SessionId", "GuestRole")
260
269
  VALUES ('support', '12345678', 'SuperAdmin', true, false, NULL, '{"allowPages": [""], "NotallowPages": [""]}'::jsonb);
@@ -263,8 +272,29 @@ To add new users to the `Users` table, use the following SQL queries:
263
272
  VALUES ('test', '12345678', 'NormalUser', true, false, NULL, '{"allowPages": [""], "NotallowPages": [""]}'::jsonb);
264
273
  ```
265
274
 
275
+ **For Encrypted Password Storage (EncPass=true):**
276
+ ```sql
277
+ -- Note: You'll need to hash the password using the hashPassword function
278
+ -- Example with pre-hashed password (PBKDF2 with username as salt)
279
+ INSERT INTO "Users" ("UserName", "PasswordEnc", "Role", "Active", "HaveMailAccount", "SessionId", "GuestRole")
280
+ VALUES ('support', 'your_hashed_password_here', 'SuperAdmin', true, false, NULL, '{"allowPages": [""], "NotallowPages": [""]}'::jsonb);
281
+
282
+ INSERT INTO "Users" ("UserName", "PasswordEnc", "Role", "Active", "HaveMailAccount", "SessionId", "GuestRole")
283
+ VALUES ('test', 'your_hashed_password_here', 'NormalUser', true, false, NULL, '{"allowPages": [""], "NotallowPages": [""]}'::jsonb);
284
+ ```
285
+
286
+ **Configuration Notes:**
266
287
  - Replace `support` and `test` with the desired usernames.
267
- - Replace `12345678` with the actual passwords.
288
+ - For raw passwords: Replace `12345678` with the actual plain text passwords.
289
+ - For encrypted passwords: Use the hashPassword function to generate the hash before inserting.
268
290
  - Adjust the `Role` values as needed (`SuperAdmin`, `NormalUser`, or `Guest`).
269
291
  - Modify the `Active` and `HaveMailAccount` values as required.
270
- - Update the `GuestRole` JSON object if specific permissions are required(this functionality is under construction).
292
+ - Update the `GuestRole` JSON object if specific permissions are required (this functionality is under construction).
293
+
294
+ **Generating Encrypted Passwords:**
295
+ If you're using `EncPass=true`, you can generate encrypted passwords using the hashPassword function:
296
+ ```javascript
297
+ import { hashPassword } from 'mbkauthe';
298
+ const encryptedPassword = hashPassword('12345678', 'support');
299
+ console.log(encryptedPassword); // Use this value for PasswordEnc column
300
+ ```
package/docs/env.md CHANGED
@@ -29,6 +29,7 @@ Main_SECRET_TOKEN=your-secure-token-number
29
29
  SESSION_SECRET_KEY=your-secure-random-key-here
30
30
  IS_DEPLOYED=false
31
31
  DOMAIN=localhost
32
+ EncPass=false
32
33
  ```
33
34
 
34
35
  #### Main_SECRET_TOKEN
@@ -80,6 +81,35 @@ DOMAIN=localhost
80
81
  IS_DEPLOYED=false
81
82
  ```
82
83
 
84
+ #### EncPass
85
+ **Description:** Controls whether passwords are stored and validated in encrypted format.
86
+
87
+ **Values:**
88
+ - `true` - Use encrypted password validation
89
+ - Passwords are hashed using PBKDF2 with the username as salt
90
+ - Compares against `PasswordEnc` column in Users table
91
+ - `false` - Use raw password validation (default)
92
+ - Passwords are stored and compared in plain text
93
+ - Compares against `Password` column in Users table
94
+
95
+ **Default:** `false`
96
+
97
+ **Security Note:** Setting `EncPass=true` is recommended for production environments as it provides better security by storing hashed passwords instead of plain text.
98
+
99
+ **Examples:**
100
+ ```env
101
+ # Production (recommended)
102
+ EncPass=true
103
+
104
+ # Development
105
+ EncPass=false
106
+ ```
107
+
108
+ **Database Implications:**
109
+ - When `EncPass=true`: The system uses the `PasswordEnc` column
110
+ - When `EncPass=false`: The system uses the `Password` column
111
+ - Ensure your database schema includes the appropriate column based on your configuration
112
+
83
113
  ---
84
114
 
85
115
  ## 🗄️ Database Configuration
@@ -278,6 +308,7 @@ Main_SECRET_TOKEN=dev-token-123
278
308
  SESSION_SECRET_KEY=dev-secret-key-change-in-production
279
309
  IS_DEPLOYED=false
280
310
  DOMAIN=localhost
311
+ EncPass=false
281
312
  LOGIN_DB=postgresql://admin:password@localhost:5432/mbkauth_dev
282
313
  MBKAUTH_TWO_FA_ENABLE=false
283
314
  COOKIE_EXPIRE_TIME=7
@@ -296,6 +327,7 @@ Main_SECRET_TOKEN=your-secure-production-token
296
327
  SESSION_SECRET_KEY=your-super-secure-production-key-here
297
328
  IS_DEPLOYED=true
298
329
  DOMAIN=yourdomain.com
330
+ EncPass=true
299
331
  LOGIN_DB=postgresql://dbuser:securepass@prod-db.example.com:5432/mbkauth_prod
300
332
  MBKAUTH_TWO_FA_ENABLE=true
301
333
  COOKIE_EXPIRE_TIME=2