mbkauthe 2.5.0 → 3.1.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
 
@@ -51,14 +55,65 @@ When a user logs in, MBKAuthe creates a session and sets the following cookies:
51
55
 
52
56
  ### Public Endpoints
53
57
 
58
+ #### `GET /login`
59
+
60
+ Redirect route that forwards to the main login page.
61
+
62
+ **Rate Limit:** No rate limiting applied
63
+
64
+ **Query Parameters:**
65
+ - All query parameters are preserved and forwarded
66
+
67
+ **Response:** 302 redirect to `/mbkauthe/login`
68
+
69
+ **Example:**
70
+ ```
71
+ GET /login?redirect=/dashboard
72
+ → Redirects to: /mbkauthe/login?redirect=/dashboard
73
+ ```
74
+
75
+ ---
76
+
77
+ #### `GET /signin`
78
+
79
+ Alias redirect route that forwards to the main login page.
80
+
81
+ **Rate Limit:** No rate limiting applied
82
+
83
+ **Query Parameters:**
84
+ - All query parameters are preserved and forwarded
85
+
86
+ **Response:** 302 redirect to `/mbkauthe/login`
87
+
88
+ **Example:**
89
+ ```
90
+ GET /signin
91
+ → Redirects to: /mbkauthe/login
92
+ ```
93
+
94
+ ---
95
+
54
96
  #### `GET /mbkauthe/login`
55
97
 
56
- Renders the login page.
98
+ Renders the main login page.
99
+
100
+ **Rate Limit:** 8 requests per minute (exempt for logged-in users)
101
+
102
+ **CSRF Protection:** Required (token included in form)
57
103
 
58
104
  **Query Parameters:**
59
105
  - `redirect` (optional) - URL to redirect after successful login
60
106
 
61
- **Response:** HTML page
107
+ **Response:** HTML page with login form
108
+
109
+ **Template Variables:**
110
+ - `githubLoginEnabled` - Whether GitHub OAuth is enabled
111
+ - `customURL` - Redirect URL after login
112
+ - `userLoggedIn` - Whether user is already authenticated
113
+ - `username` - Current username if logged in
114
+ - `version` - MBKAuthe version
115
+ - `appName` - Application name
116
+ - `csrfToken` - CSRF protection token
62
117
 
63
118
  **Example:**
64
119
  ```
@@ -271,13 +326,17 @@ fetch('/mbkauthe/api/logout', {
271
326
 
272
327
  Terminates all active sessions across all users (admin only).
273
328
 
274
- **Authentication:** API token required
329
+ **Authentication:** API token required (via `authenticate` middleware)
330
+
331
+ **Rate Limit:** No explicit rate limiting applied
275
332
 
276
333
  **Headers:**
277
334
  ```
278
- Authorization: your-api-token
335
+ Authorization: your-main-secret-token
279
336
  ```
280
337
 
338
+ **Request Body:** None required
339
+
281
340
  **Success Response (200 OK):**
282
341
  ```json
283
342
  {
@@ -294,16 +353,28 @@ Authorization: your-api-token
294
353
  | 500 | Failed to terminate sessions |
295
354
  | 500 | Internal Server Error |
296
355
 
356
+ **Implementation Details:**
357
+ - Clears all user session IDs in the database (`Users` table)
358
+ - Deletes all session records from the `session` table
359
+ - Destroys the current request session
360
+ - Clears session cookies
361
+ - Runs database operations in parallel for better performance
362
+
297
363
  **Example Request:**
298
364
  ```javascript
299
365
  fetch('/mbkauthe/api/terminateAllSessions', {
300
366
  method: 'POST',
301
367
  headers: {
302
- 'Authorization': 'your-secret-token',
368
+ 'Authorization': process.env.MAIN_SECRET_TOKEN,
369
+ 'Content-Type': 'application/json'
303
370
  }
304
371
  })
305
372
  .then(response => response.json())
306
- .then(data => console.log(data));
373
+ .then(data => {
374
+ if (data.success) {
375
+ console.log('All sessions terminated successfully');
376
+ }
377
+ });
307
378
  ```
308
379
 
309
380
  ---
@@ -326,10 +397,43 @@ Displays MBKAuthe version information and configuration.
326
397
 
327
398
  ---
328
399
 
400
+ #### `GET /mbkauthe/ErrorCode`
401
+
402
+ Displays comprehensive error code documentation with descriptions and user messages.
403
+
404
+ **Response:** HTML page showing:
405
+ - All error codes organized by category
406
+ - Error code ranges (Authentication, 2FA, Session, Authorization, etc.)
407
+ - User-friendly messages and hints for each error
408
+ - Dynamically generated from `lib/utils/errors.js`
409
+
410
+ **Categories:**
411
+ - **600-699**: Authentication Errors
412
+ - **700-799**: Two-Factor Authentication Errors
413
+ - **800-899**: Session Management Errors
414
+ - **900-999**: Authorization Errors
415
+ - **1000-1099**: Input Validation Errors
416
+ - **1100-1199**: Rate Limiting Errors
417
+ - **1200-1299**: Server Errors
418
+ - **1300-1399**: OAuth Errors
419
+
420
+ **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.
421
+
422
+ **Usage:**
423
+ ```
424
+ GET /mbkauthe/ErrorCode
425
+ ```
426
+
427
+ ---
428
+
329
429
  #### `GET /mbkauthe/main.js`
330
430
 
331
431
  Serves the client-side JavaScript file containing helper functions for authentication operations.
332
432
 
433
+ **Rate Limit:** No rate limiting applied
434
+
435
+ **Cache:** Cached for 1 year (max-age=31536000)
436
+
333
437
  **Purpose:** Provides frontend JavaScript utilities including:
334
438
  - `logout()` - Logout function with confirmation dialog and cache clearing
335
439
  - `logoutuser()` - Alias for logout function
@@ -363,17 +467,20 @@ Serves the client-side JavaScript file containing helper functions for authentic
363
467
  - Clears cookies
364
468
  - Forces page reload
365
469
 
366
-
367
470
  ---
368
471
 
369
472
  #### `GET /icon.svg`
370
473
 
371
- Serves the application's SVG icon file.
474
+ Serves the application's SVG icon file from the root level.
475
+
476
+ **Rate Limit:** No rate limiting applied
372
477
 
373
478
  **Response:** SVG image file (Content-Type: image/svg+xml)
374
479
 
375
480
  **Cache:** Cached for 1 year (max-age=31536000)
376
481
 
482
+ **Note:** This route is mounted at the root level (not under `/mbkauthe`)
483
+
377
484
  **Usage:**
378
485
  ```html
379
486
  <img src="/icon.svg" alt="App Icon">
@@ -448,6 +555,79 @@ GET /mbkauthe/test
448
555
 
449
556
  ---
450
557
 
558
+ ### OAuth Endpoints
559
+
560
+ #### `GET /mbkauthe/api/github/login`
561
+
562
+ Initiates the GitHub OAuth authentication flow.
563
+
564
+ **Rate Limit:** 10 requests per 5 minutes
565
+
566
+ **Query Parameters:**
567
+ - `redirect` (optional) - Relative URL to redirect after successful authentication (must start with `/` to prevent open redirect attacks)
568
+
569
+ **Response:** Redirects to GitHub OAuth authorization page
570
+
571
+ **Prerequisites:**
572
+ - `GITHUB_LOGIN_ENABLED=true` in environment
573
+ - Valid `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` configured
574
+ - User's GitHub account must be linked to an MBKAuth account in `user_github` table
575
+
576
+ **Example:**
577
+ ```
578
+ GET /mbkauthe/api/github/login?redirect=/dashboard
579
+ ```
580
+
581
+ **Workflow:**
582
+ 1. User clicks "Login with GitHub"
583
+ 2. Redirects to GitHub for authorization
584
+ 3. GitHub redirects back to callback URL
585
+ 4. System verifies GitHub account is linked
586
+ 5. If 2FA enabled, prompts for 2FA
587
+ 6. Creates session and redirects to specified URL
588
+
589
+ ---
590
+
591
+ #### `GET /mbkauthe/api/github/login/callback`
592
+
593
+ Handles the OAuth callback from GitHub after user authorization.
594
+
595
+ **Rate Limit:** Inherited from OAuth rate limiter (10 requests per 5 minutes)
596
+
597
+ **Query Parameters:**
598
+ - `code` - Authorization code from GitHub (automatically provided)
599
+ - `state` - State parameter for CSRF protection (automatically provided)
600
+
601
+ **Response:**
602
+ - Redirects to 2FA page if 2FA is enabled for the user
603
+ - Redirects to `loginRedirectURL` or stored redirect URL if 2FA is not required
604
+ - Renders error page if authentication fails
605
+
606
+ **Error Handling:**
607
+ - **GitHub Not Linked**: Returns error if GitHub account is not in `user_github` table
608
+ - **Account Inactive**: Returns error if user account is deactivated
609
+ - **Not Authorized**: Returns error if user is not allowed to access the application
610
+ - **GitHub Auth Error**: Returns error for any OAuth-related failures
611
+
612
+ **Success Flow:**
613
+ ```
614
+ GitHub → /api/github/login/callback
615
+ → (If 2FA enabled) → /mbkauthe/2fa
616
+ → (If no 2FA) → loginRedirectURL or stored redirect
617
+ ```
618
+
619
+ **Database Query:**
620
+ ```sql
621
+ SELECT ug.*, u."UserName", u."Role", u."Active", u."AllowedApps", u."id"
622
+ FROM user_github ug
623
+ JOIN "Users" u ON ug.user_name = u."UserName"
624
+ WHERE ug.github_id = $1
625
+ ```
626
+
627
+ **Note:** This endpoint is automatically called by GitHub and should not be accessed directly by users.
628
+
629
+ ---
630
+
451
631
  ## Middleware Reference
452
632
 
453
633
  ### `validateSession`
@@ -575,64 +755,6 @@ Authorization: your-secret-token
575
755
 
576
756
  ---
577
757
 
578
- ### `authapi(requiredRole)`
579
-
580
- Advanced API authentication with role-based access control.
581
-
582
- **Parameters:**
583
- - `requiredRole` (array, optional) - Array of allowed roles
584
-
585
- **Usage:**
586
- ```javascript
587
- import { authapi } from 'mbkauthe';
588
-
589
- // Any authenticated API user
590
- app.get('/api/data', authapi(), (req, res) => {
591
- console.log(req.user); // { username, UserName, role, Role }
592
- res.json({ data: 'API data' });
593
- });
594
-
595
- // Only SuperAdmin via API
596
- app.post('/api/admin/action', authapi(['SuperAdmin']), (req, res) => {
597
- res.json({ success: true });
598
- });
599
- ```
600
-
601
- **Headers Required:**
602
- ```
603
- Authorization: user-api-key-64-char-hex
604
- ```
605
-
606
- **Behavior:**
607
- - Validates API key from `Authorization` header
608
- - Looks up user associated with API key
609
- - Checks if user account is active
610
- - Verifies user role if `requiredRole` is specified
611
- - Blocks demo users from accessing endpoints
612
- - Populates `req.user` with user information
613
- - Returns 401 if unauthorized, 403 if insufficient permissions
614
-
615
- **req.user Object:**
616
- ```javascript
617
- req.user = {
618
- username: "john.doe",
619
- UserName: "john.doe",
620
- role: "NormalUser",
621
- Role: "NormalUser"
622
- }
623
- ```
624
-
625
- **Database Requirement:**
626
- Requires `UserAuthApiKey` table:
627
- ```sql
628
- CREATE TABLE "UserAuthApiKey" (
629
- username VARCHAR(50) PRIMARY KEY REFERENCES "Users"("UserName"),
630
- "key" VARCHAR(64) UNIQUE NOT NULL
631
- );
632
- ```
633
-
634
- ---
635
-
636
758
  ## Error Codes
637
759
 
638
760
  ### HTTP Status Codes
@@ -741,7 +863,7 @@ app.get('/moderator',
741
863
  ### API Authentication
742
864
 
743
865
  ```javascript
744
- import { authenticate, authapi } from 'mbkauthe';
866
+ import { authenticate } from 'mbkauthe';
745
867
 
746
868
  // Simple token authentication
747
869
  app.post('/api/webhook',
@@ -752,24 +874,27 @@ app.post('/api/webhook',
752
874
  }
753
875
  );
754
876
 
755
- // API key with user validation
756
- app.get('/api/user/profile', authapi(), async (req, res) => {
757
- const { username } = req.user;
758
-
759
- // Fetch user profile
760
- const profile = await getUserProfile(username);
761
-
762
- res.json({ success: true, profile });
763
- });
764
-
765
- // API key with role requirement
766
- app.delete('/api/admin/users/:id',
767
- authapi(['SuperAdmin']),
877
+ // Admin API with token authentication
878
+ app.post('/api/admin/terminate-sessions',
879
+ authenticate(process.env.MAIN_SECRET_TOKEN),
768
880
  async (req, res) => {
769
- await deleteUser(req.params.id);
881
+ // Terminate all sessions
770
882
  res.json({ success: true });
771
883
  }
772
884
  );
885
+
886
+ // Protected API endpoint (requires session)
887
+ app.get('/api/user/profile',
888
+ validateSession,
889
+ async (req, res) => {
890
+ const { username } = req.session.user;
891
+
892
+ // Fetch user profile
893
+ const profile = await getUserProfile(username);
894
+
895
+ res.json({ success: true, profile });
896
+ }
897
+ );
773
898
  ```
774
899
 
775
900
  ---
@@ -931,10 +1056,13 @@ app.use((req, res) => {
931
1056
  | `/mbkauthe/api/login` | 8 requests | 1 minute |
932
1057
  | `/mbkauthe/api/logout` | 10 requests | 1 minute |
933
1058
  | `/mbkauthe/api/verify-2fa` | 5 requests | 1 minute |
1059
+ | `/mbkauthe/api/github/login` | 10 requests | 5 minutes |
1060
+ | `/mbkauthe/api/github/login/callback` | 10 requests | 5 minutes |
934
1061
  | `/mbkauthe/login` | 8 requests | 1 minute |
935
1062
  | `/mbkauthe/info` | 8 requests | 1 minute |
1063
+ | `/mbkauthe/test` | 8 requests | 1 minute |
936
1064
 
937
- Rate limits are applied per IP address.
1065
+ Rate limits are applied per IP address. Logged-in users are exempt from some rate limits (e.g., login page rate limit).
938
1066
 
939
1067
  ---
940
1068
 
package/docs/db.md CHANGED
@@ -294,7 +294,7 @@ To add new users to the `Users` table, use the following SQL queries:
294
294
  **Generating Encrypted Passwords:**
295
295
  If you're using `EncPass=true`, you can generate encrypted passwords using the hashPassword function:
296
296
  ```javascript
297
- import { hashPassword } from './lib/config.js';
297
+ import { hashPassword } from 'mbkauthe';
298
298
  const encryptedPassword = hashPassword('12345678', 'support');
299
299
  console.log(encryptedPassword); // Use this value for PasswordEnc column
300
300
  ```