mbkauthe 3.5.0 → 4.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.
- package/README.md +54 -304
- package/docs/api.md +2 -2
- package/docs/db.md +26 -20
- package/docs/db.sql +116 -0
- package/docs/env.md +10 -0
- package/index.d.ts +3 -3
- package/index.js +4 -1
- package/lib/config/cookies.js +6 -0
- package/lib/config/index.js +20 -4
- package/lib/config/security.js +1 -1
- package/lib/middleware/auth.js +64 -30
- package/lib/middleware/index.js +37 -28
- package/lib/routes/auth.js +59 -36
- package/lib/routes/misc.js +22 -9
- package/package.json +1 -1
- package/views/Error/dError.handlebars +175 -88
- package/views/loginmbkauthe.handlebars +0 -2
package/README.md
CHANGED
|
@@ -1,35 +1,28 @@
|
|
|
1
|
-
# MBKAuthe - Authentication System
|
|
1
|
+
# MBKAuthe - Node.js Authentication System
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/mbkauthe)
|
|
4
4
|
[](LICENSE)
|
|
5
5
|
[](https://nodejs.org/)
|
|
6
|
-
[](https://github.com/MIbnEKhalid/mbkauthe/actions/workflows/codeql.yml)
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
<p align="center">
|
|
11
|
-
<img height="64px" src="./public/icon.svg" alt="MBK Chat Platform" />
|
|
12
|
-
</p>
|
|
6
|
+
[](https://github.com/MIbnEKhalid/mbkauthe/actions/workflows/publish.yml)
|
|
13
7
|
|
|
14
8
|
<p align="center">
|
|
15
|
-
<img src="
|
|
16
|
-
<img height="48px" src="https://handlebarsjs.com/handlebars-icon.svg" alt="Handlebars" />
|
|
9
|
+
<img height="64px" src="./public/icon.svg" alt="MBKAuthe" />
|
|
17
10
|
</p>
|
|
18
11
|
|
|
19
|
-
**MBKAuthe** is a production-ready authentication system for Node.js
|
|
12
|
+
**MBKAuthe** is a production-ready authentication system for Node.js with Express and PostgreSQL. Features include secure login, 2FA, role-based access, OAuth (GitHub & Google), multi-session support, and multi-app user management.
|
|
20
13
|
|
|
21
14
|
## ✨ Key Features
|
|
22
15
|
|
|
23
|
-
-
|
|
24
|
-
-
|
|
25
|
-
-
|
|
26
|
-
-
|
|
27
|
-
-
|
|
28
|
-
-
|
|
29
|
-
-
|
|
30
|
-
-
|
|
31
|
-
-
|
|
32
|
-
-
|
|
16
|
+
- Secure password authentication (PBKDF2)
|
|
17
|
+
- PostgreSQL session management
|
|
18
|
+
- Multi-session support (configurable concurrent sessions per user)
|
|
19
|
+
- Optional TOTP-based 2FA with trusted devices
|
|
20
|
+
- OAuth login (GitHub & Google)
|
|
21
|
+
- Role-based access: SuperAdmin, NormalUser, Guest
|
|
22
|
+
- CSRF protection & rate limiting
|
|
23
|
+
- Easy Express.js integration
|
|
24
|
+
- Customizable Handlebars templates
|
|
25
|
+
- Session fixation prevention
|
|
33
26
|
|
|
34
27
|
## 📦 Installation
|
|
35
28
|
|
|
@@ -39,49 +32,15 @@ npm install mbkauthe
|
|
|
39
32
|
|
|
40
33
|
## 🚀 Quick Start
|
|
41
34
|
|
|
42
|
-
**1. Configure Environment
|
|
35
|
+
**1. Configure Environment**
|
|
43
36
|
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
SESSION_SECRET_KEY=your-secret-key
|
|
47
|
-
MAIN_SECRET_TOKEN=api-token
|
|
48
|
-
IS_DEPLOYED=false
|
|
49
|
-
DOMAIN=localhost
|
|
50
|
-
LOGIN_DB=postgresql://user:pass@localhost:5432/db
|
|
51
|
-
|
|
52
|
-
# Optional Features
|
|
53
|
-
MBKAUTH_TWO_FA_ENABLE=false
|
|
54
|
-
COOKIE_EXPIRE_TIME=2
|
|
55
|
-
|
|
56
|
-
# OAuth Configuration (Optional)
|
|
57
|
-
GITHUB_LOGIN_ENABLED=false
|
|
58
|
-
GITHUB_CLIENT_ID=
|
|
59
|
-
GITHUB_CLIENT_SECRET=
|
|
60
|
-
|
|
61
|
-
GOOGLE_LOGIN_ENABLED=false
|
|
62
|
-
GOOGLE_CLIENT_ID=
|
|
63
|
-
GOOGLE_CLIENT_SECRET=
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
**2. Set Up Database**
|
|
67
|
-
|
|
68
|
-
```sql
|
|
69
|
-
CREATE TYPE role AS ENUM ('SuperAdmin', 'NormalUser', 'Guest');
|
|
70
|
-
|
|
71
|
-
CREATE TABLE "Users" (
|
|
72
|
-
id SERIAL PRIMARY KEY,
|
|
73
|
-
"UserName" VARCHAR(50) NOT NULL UNIQUE,
|
|
74
|
-
"Password" VARCHAR(61) NOT NULL,
|
|
75
|
-
"Role" role DEFAULT 'NormalUser',
|
|
76
|
-
"Active" BOOLEAN DEFAULT FALSE,
|
|
77
|
-
"AllowedApps" JSONB DEFAULT '["mbkauthe"]',
|
|
78
|
-
"SessionId" VARCHAR(213),
|
|
79
|
-
created_at TIMESTAMP DEFAULT NOW(),
|
|
80
|
-
updated_at TIMESTAMP DEFAULT NOW()
|
|
81
|
-
);
|
|
37
|
+
```bash
|
|
38
|
+
Copy-Item .env.example .env
|
|
82
39
|
```
|
|
40
|
+
See [docs/env.md](docs/env.md).
|
|
83
41
|
|
|
84
|
-
|
|
42
|
+
**2. Set Up Database**
|
|
43
|
+
Run [docs/db.sql](docs/db.sql) to create tables and a default SuperAdmin (`support` / `12345678`). Change the password immediately. See [docs/db.md](docs/db.md).
|
|
85
44
|
|
|
86
45
|
**3. Integrate with Express**
|
|
87
46
|
|
|
@@ -89,295 +48,86 @@ See [docs/db.md](docs/db.md) for complete schemas.
|
|
|
89
48
|
import express from 'express';
|
|
90
49
|
import mbkauthe, { validateSession, checkRolePermission } from 'mbkauthe';
|
|
91
50
|
import dotenv from 'dotenv';
|
|
92
|
-
|
|
93
51
|
dotenv.config();
|
|
94
52
|
|
|
95
|
-
// App-specific configuration (as JSON string)
|
|
96
|
-
process.env.mbkautheVar = JSON.stringify({
|
|
97
|
-
APP_NAME: process.env.APP_NAME,
|
|
98
|
-
SESSION_SECRET_KEY: process.env.SESSION_SECRET_KEY,
|
|
99
|
-
Main_SECRET_TOKEN: process.env.MAIN_SECRET_TOKEN,
|
|
100
|
-
IS_DEPLOYED: process.env.IS_DEPLOYED,
|
|
101
|
-
DOMAIN: process.env.DOMAIN,
|
|
102
|
-
LOGIN_DB: process.env.LOGIN_DB,
|
|
103
|
-
loginRedirectURL: '/dashboard'
|
|
104
|
-
});
|
|
105
|
-
|
|
106
|
-
// Optional shared configuration (useful for shared OAuth credentials across multiple projects)
|
|
107
|
-
process.env.mbkauthShared = JSON.stringify({
|
|
108
|
-
GITHUB_CLIENT_ID: process.env.GITHUB_CLIENT_ID,
|
|
109
|
-
GITHUB_CLIENT_SECRET: process.env.GITHUB_CLIENT_SECRET,
|
|
110
|
-
GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
|
|
111
|
-
GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET
|
|
112
|
-
});
|
|
113
|
-
|
|
114
|
-
// MBKAuth prioritizes values in mbkautheVar, then mbkauthShared, then built-in defaults.
|
|
115
|
-
|
|
116
53
|
const app = express();
|
|
117
|
-
|
|
118
|
-
// Mount authentication routes
|
|
119
54
|
app.use(mbkauthe);
|
|
120
55
|
|
|
121
|
-
|
|
122
|
-
app.get('/
|
|
123
|
-
res.send(`Welcome ${req.session.user.username}!`);
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
app.get('/admin', validateSession, checkRolePermission(['SuperAdmin']), (req, res) => {
|
|
127
|
-
res.send('Admin Panel');
|
|
128
|
-
});
|
|
56
|
+
app.get('/dashboard', validateSession, (req, res) => res.send(`Welcome ${req.session.user.username}!`));
|
|
57
|
+
app.get('/admin', validateSession, checkRolePermission(['SuperAdmin']), (req, res) => res.send('Admin Panel'));
|
|
129
58
|
|
|
130
59
|
app.listen(3000);
|
|
131
60
|
```
|
|
132
61
|
|
|
133
|
-
|
|
134
|
-
## 🧪 Testing & Git Hooks
|
|
135
|
-
|
|
136
|
-
MBKAuthe includes comprehensive test coverage for all authentication features. **A pre-commit hook is provided to ensure code quality:**
|
|
137
|
-
|
|
138
|
-
### Pre-commit Hook (Automatic Test Runner)
|
|
139
|
-
|
|
140
|
-
- Located at `scripts/pre-commit` and `scripts/pre-commit` (Node.js, cross-platform)
|
|
141
|
-
- Starts the dev server, runs all tests, and blocks commits if any test fails
|
|
142
|
-
- The dev server is automatically stopped after tests complete
|
|
143
|
-
- Ensures you never commit code that breaks tests
|
|
144
|
-
|
|
145
|
-
### Git Hook Setup
|
|
146
|
-
|
|
147
|
-
Hooks are auto-configured every time you run `npm run dev`, `npm test`, or `npm run test:watch` (see `scripts/setup-hooks.js`).
|
|
148
|
-
|
|
149
|
-
If you ever need to manually set up hooks:
|
|
150
|
-
|
|
151
|
-
```bash
|
|
152
|
-
node scripts/setup-hooks.js
|
|
153
|
-
```
|
|
154
|
-
|
|
155
|
-
### Running Tests
|
|
62
|
+
## 🧪 Testing
|
|
156
63
|
|
|
157
64
|
```bash
|
|
158
|
-
# Run all tests (auto-configures hooks)
|
|
159
65
|
npm test
|
|
160
|
-
|
|
161
|
-
# Run tests in watch mode (auto-configures hooks)
|
|
162
66
|
npm run test:watch
|
|
163
|
-
|
|
164
|
-
# Run with development flags (auto-configures hooks)
|
|
165
67
|
npm run dev
|
|
166
68
|
```
|
|
167
69
|
|
|
168
|
-
**Test Coverage:**
|
|
169
|
-
- ✅ Authentication flows (login, 2FA, logout)
|
|
170
|
-
- ✅ OAuth integration (GitHub)
|
|
171
|
-
- ✅ Session management and security
|
|
172
|
-
- ✅ Role-based access control
|
|
173
|
-
- ✅ API endpoints and error handling
|
|
174
|
-
- ✅ CSRF protection and rate limiting
|
|
175
|
-
- ✅ Static asset serving
|
|
176
|
-
|
|
177
|
-
## 📂 Architecture (v3.0)
|
|
178
|
-
|
|
179
|
-
```
|
|
180
|
-
lib/
|
|
181
|
-
├── config/ # Configuration & security
|
|
182
|
-
├── database/ # PostgreSQL pool
|
|
183
|
-
├── utils/ # Errors & response helpers
|
|
184
|
-
├── middleware/ # Auth & session middleware
|
|
185
|
-
└── routes/ # Auth, OAuth, misc routes
|
|
186
|
-
```
|
|
187
|
-
|
|
188
|
-
**Key Improvements in v3.0:**
|
|
189
|
-
- Modular structure with clear separation of concerns
|
|
190
|
-
- Organized config, database, utils, middleware, and routes
|
|
191
|
-
- Better maintainability and scalability
|
|
192
|
-
|
|
193
70
|
## 🔧 Core API
|
|
194
71
|
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
app.get('/protected', validateSession, handler);
|
|
200
|
-
|
|
201
|
-
// Role checking
|
|
202
|
-
app.get('/admin', validateSession, checkRolePermission(['SuperAdmin']), handler);
|
|
72
|
+
- **Session Validation:** `validateSession`
|
|
73
|
+
- **Role Check:** `checkRolePermission(['Role'])`
|
|
74
|
+
- **Combined:** `validateSessionAndRole(['SuperAdmin', 'NormalUser'])`
|
|
75
|
+
- **API Token Auth:** `authenticate(process.env.API_TOKEN)`
|
|
203
76
|
|
|
204
|
-
|
|
205
|
-
import { validateSessionAndRole } from 'mbkauthe';
|
|
206
|
-
app.get('/mod', validateSessionAndRole(['SuperAdmin', 'NormalUser']), handler);
|
|
207
|
-
|
|
208
|
-
// API token auth
|
|
209
|
-
import { authenticate } from 'mbkauthe';
|
|
210
|
-
app.post('/api/data', authenticate(process.env.API_TOKEN), handler);
|
|
211
|
-
```
|
|
77
|
+
## 🔐 Security
|
|
212
78
|
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
-
|
|
217
|
-
- `GET /mbkauthe/login` - Login page (8/min rate limit)
|
|
218
|
-
- `POST /mbkauthe/api/login` - Login endpoint (8/min rate limit)
|
|
219
|
-
- `POST /mbkauthe/api/logout` - Logout endpoint (10/min rate limit)
|
|
220
|
-
- `GET /mbkauthe/2fa` - 2FA verification page (if enabled)
|
|
221
|
-
- `POST /mbkauthe/api/verify-2fa` - 2FA verification API (5/min rate limit)
|
|
222
|
-
|
|
223
|
-
**OAuth Routes:**
|
|
224
|
-
- `GET /mbkauthe/api/github/login` - GitHub OAuth initiation (10/5min rate limit)
|
|
225
|
-
- `GET /mbkauthe/api/github/login/callback` - GitHub OAuth callback
|
|
226
|
-
- `GET /mbkauthe/api/google/login` - Google OAuth initiation (10/5min rate limit)
|
|
227
|
-
- `GET /mbkauthe/api/google/login/callback` - Google OAuth callback
|
|
228
|
-
|
|
229
|
-
**Information & Utility Routes:**
|
|
230
|
-
- `GET /mbkauthe/info`, `/mbkauthe/i` - Version & config info (8/min rate limit)
|
|
231
|
-
- `GET /mbkauthe/ErrorCode` - Error code documentation
|
|
232
|
-
- `GET /mbkauthe/test` - Test authentication status (8/min rate limit)
|
|
233
|
-
|
|
234
|
-
**Static Asset Routes:**
|
|
235
|
-
- `GET /mbkauthe/main.js` - Client-side JavaScript utilities
|
|
236
|
-
- `GET /mbkauthe/bg.webp` - Background image for auth pages
|
|
237
|
-
- `GET /icon.svg` - Application SVG icon (root level)
|
|
238
|
-
- `GET /favicon.ico`, `/icon.ico` - Application favicon
|
|
239
|
-
|
|
240
|
-
**Admin API Routes:**
|
|
241
|
-
- `POST /mbkauthe/api/terminateAllSessions` - Terminate all sessions (admin only)
|
|
242
|
-
|
|
243
|
-
## 🔐 Security Features
|
|
244
|
-
|
|
245
|
-
- **Rate Limiting**: Login (8/min), Logout (10/min), 2FA (5/min), OAuth (10/5min), Admin (3/5min)
|
|
246
|
-
- **CSRF Protection**: All state-changing routes protected with token validation
|
|
247
|
-
- **Secure Cookies**: httpOnly, sameSite, secure in production
|
|
248
|
-
- **Password Hashing**: PBKDF2 with 100k iterations
|
|
249
|
-
- **Session Security**: PostgreSQL-backed, automatic cleanup, session fixation prevention
|
|
250
|
-
- **OAuth Security**: State validation, token expiry handling, secure callback validation
|
|
79
|
+
- Rate limiting, CSRF protection, secure cookies
|
|
80
|
+
- Password hashing (PBKDF2, 100k iterations)
|
|
81
|
+
- PostgreSQL-backed sessions with automatic cleanup
|
|
82
|
+
- OAuth with state validation and secure callbacks
|
|
251
83
|
|
|
252
84
|
## 📱 Two-Factor Authentication
|
|
253
85
|
|
|
254
|
-
Enable
|
|
255
|
-
|
|
256
|
-
```sql
|
|
257
|
-
CREATE TABLE "TwoFA" (
|
|
258
|
-
"UserName" VARCHAR(50) PRIMARY KEY REFERENCES "Users"("UserName"),
|
|
259
|
-
"TwoFAStatus" BOOLEAN NOT NULL,
|
|
260
|
-
"TwoFASecret" TEXT
|
|
261
|
-
);
|
|
262
|
-
```
|
|
263
|
-
|
|
264
|
-
Users can mark devices as trusted to skip 2FA for configurable duration.
|
|
86
|
+
Enable via `MBKAUTH_TWO_FA_ENABLE=true`. Trusted devices can skip 2FA for a set duration.
|
|
265
87
|
|
|
266
88
|
## 🔄 OAuth Integration
|
|
267
89
|
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
**Setup:**
|
|
271
|
-
|
|
272
|
-
1. Create GitHub OAuth App with callback: `https://yourdomain.com/mbkauthe/api/github/login/callback`
|
|
273
|
-
2. Configure environment:
|
|
274
|
-
```env
|
|
275
|
-
GITHUB_LOGIN_ENABLED=true
|
|
276
|
-
GITHUB_CLIENT_ID=your_client_id
|
|
277
|
-
GITHUB_CLIENT_SECRET=your_client_secret
|
|
278
|
-
```
|
|
279
|
-
3. Create table:
|
|
280
|
-
```sql
|
|
281
|
-
CREATE TABLE user_github (
|
|
282
|
-
id SERIAL PRIMARY KEY,
|
|
283
|
-
user_name VARCHAR(50) REFERENCES "Users"("UserName"),
|
|
284
|
-
github_id VARCHAR(255) UNIQUE,
|
|
285
|
-
github_username VARCHAR(255),
|
|
286
|
-
access_token VARCHAR(255),
|
|
287
|
-
created_at TIMESTAMP DEFAULT NOW()
|
|
288
|
-
);
|
|
289
|
-
```
|
|
290
|
-
|
|
291
|
-
### Google OAuth
|
|
292
|
-
|
|
293
|
-
**Setup:**
|
|
294
|
-
|
|
295
|
-
1. Create Google OAuth 2.0 Client in [Google Cloud Console](https://console.cloud.google.com/)
|
|
296
|
-
2. Add authorized redirect URI: `https://yourdomain.com/mbkauthe/api/google/login/callback`
|
|
297
|
-
3. Configure environment:
|
|
298
|
-
```env
|
|
299
|
-
GOOGLE_LOGIN_ENABLED=true
|
|
300
|
-
GOOGLE_CLIENT_ID=your_client_id
|
|
301
|
-
GOOGLE_CLIENT_SECRET=your_client_secret
|
|
302
|
-
```
|
|
303
|
-
4. Create table:
|
|
304
|
-
```sql
|
|
305
|
-
CREATE TABLE user_google (
|
|
306
|
-
id SERIAL PRIMARY KEY,
|
|
307
|
-
user_name VARCHAR(50) REFERENCES "Users"("UserName"),
|
|
308
|
-
google_id VARCHAR(255) UNIQUE,
|
|
309
|
-
google_email VARCHAR(255),
|
|
310
|
-
access_token VARCHAR(255),
|
|
311
|
-
created_at TIMESTAMP DEFAULT NOW()
|
|
312
|
-
);
|
|
313
|
-
```
|
|
314
|
-
|
|
315
|
-
**Note:** Users must link their OAuth accounts before they can use OAuth login.
|
|
90
|
+
**GitHub / Google OAuth:** Configure apps and credentials via `.env` or `mbkautheVar`. Users must link accounts before login.
|
|
316
91
|
|
|
317
92
|
## 🎨 Customization
|
|
318
93
|
|
|
319
|
-
**Redirect URL:**
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
// ...
|
|
323
|
-
loginRedirectURL: '/dashboard'
|
|
324
|
-
});
|
|
325
|
-
```
|
|
326
|
-
|
|
327
|
-
**Custom Views:** Create in `views/` directory:
|
|
328
|
-
- `loginmbkauthe.handlebars` - Login page
|
|
329
|
-
- `2fa.handlebars` - 2FA page
|
|
330
|
-
- `Error/dError.handlebars` - Error page
|
|
331
|
-
|
|
332
|
-
**Database Access:**
|
|
333
|
-
```javascript
|
|
334
|
-
import { dblogin } from 'mbkauthe';
|
|
335
|
-
const result = await dblogin.query('SELECT * FROM "Users"');
|
|
336
|
-
```
|
|
94
|
+
- **Redirect URL:** `mbkautheVar={"loginRedirectURL":"/dashboard"}`
|
|
95
|
+
- **Custom Views:** `views/loginmbkauthe.handlebars`, `2fa.handlebars`, `Error/dError.handlebars`
|
|
96
|
+
- **Database Access:** `import { dblogin } from 'mbkauthe'; const result = await dblogin.query('SELECT * FROM "Users"');`
|
|
337
97
|
|
|
338
98
|
## 🚢 Deployment
|
|
339
99
|
|
|
340
|
-
|
|
341
|
-
-
|
|
342
|
-
-
|
|
343
|
-
-
|
|
344
|
-
-
|
|
345
|
-
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
**Vercel:**
|
|
349
|
-
|
|
350
|
-
Tip: On Vercel you can set `mbkauthShared` at the project or team level to share common OAuth credentials across multiple deployments. MBKAuth will use values from `mbkautheVar` first and fall back to `mbkauthShared`.
|
|
351
|
-
```json
|
|
352
|
-
{
|
|
353
|
-
"version": 2,
|
|
354
|
-
"builds": [{ "src": "index.js", "use": "@vercel/node" }],
|
|
355
|
-
"routes": [{ "src": "/(.*)", "dest": "/index.js" }]
|
|
356
|
-
}
|
|
357
|
-
```
|
|
100
|
+
Checklist for production:
|
|
101
|
+
- `IS_DEPLOYED=true`
|
|
102
|
+
- Strong secrets for SESSION_SECRET_KEY & Main_SECRET_TOKEN
|
|
103
|
+
- HTTPS enabled
|
|
104
|
+
- Correct DOMAIN & COOKIE_EXPIRE_TIME
|
|
105
|
+
- Use environment variables for all secrets
|
|
106
|
+
|
|
107
|
+
**Vercel:** Supports shared OAuth credentials via `mbkauthShared`.
|
|
358
108
|
|
|
359
109
|
## 📚 Documentation
|
|
360
110
|
|
|
361
|
-
- [API
|
|
362
|
-
- [Database
|
|
363
|
-
- [Environment Config](docs/env.md)
|
|
364
|
-
- [Error
|
|
111
|
+
- [API Reference](docs/api.md)
|
|
112
|
+
- [Database Schema](docs/db.md)
|
|
113
|
+
- [Environment Config](docs/env.md)
|
|
114
|
+
- [Error Codes](docs/error-messages.md)
|
|
365
115
|
|
|
366
116
|
## 📝 License
|
|
367
117
|
|
|
368
|
-
|
|
118
|
+
GPL v2.0 — see [LICENSE](LICENSE)
|
|
369
119
|
|
|
370
120
|
## 👨💻 Author
|
|
371
121
|
|
|
372
122
|
**Muhammad Bin Khalid**
|
|
373
123
|
📧 [support@mbktech.org](mailto:support@mbktech.org) | [chmuhammadbinkhalid28@gmail.com](mailto:chmuhammadbinkhalid28@gmail.com)
|
|
374
|
-
🔗 [@MIbnEKhalid](https://github.com/MIbnEKhalid)
|
|
124
|
+
🔗 [GitHub @MIbnEKhalid](https://github.com/MIbnEKhalid)
|
|
375
125
|
|
|
376
126
|
## 🔗 Links
|
|
377
127
|
|
|
378
|
-
- [npm
|
|
379
|
-
- [GitHub
|
|
380
|
-
- [
|
|
128
|
+
- [npm](https://www.npmjs.com/package/mbkauthe)
|
|
129
|
+
- [GitHub](https://github.com/MIbnEKhalid/mbkauthe)
|
|
130
|
+
- [Support](https://github.com/MIbnEKhalid/mbkauthe/issues)
|
|
381
131
|
|
|
382
132
|
---
|
|
383
133
|
|
package/docs/api.md
CHANGED
|
@@ -38,7 +38,7 @@ When a user logs in, MBKAuthe creates a session and sets the following cookies:
|
|
|
38
38
|
| Cookie Name | Description | HttpOnly | Secure | SameSite |
|
|
39
39
|
|------------|-------------|----------|--------|----------|
|
|
40
40
|
| `mbkauthe.sid` | Session identifier | ✓ | Auto* | lax |
|
|
41
|
-
| `sessionId` |
|
|
41
|
+
| `sessionId` | Opaque session token (backed by `Sessions` table) | ✓ | Auto* | lax |
|
|
42
42
|
| `username` | Username | ✗ | Auto* | lax |
|
|
43
43
|
|
|
44
44
|
\* `secure` flag is automatically set to `true` in production when `IS_DEPLOYED=true`
|
|
@@ -46,7 +46,7 @@ When a user logs in, MBKAuthe creates a session and sets the following cookies:
|
|
|
46
46
|
### Session Lifetime
|
|
47
47
|
|
|
48
48
|
- Default: 2 days (configurable via `COOKIE_EXPIRE_TIME`)
|
|
49
|
-
-
|
|
49
|
+
- Application sessions are stored in the `Sessions` table in PostgreSQL
|
|
50
50
|
- Sessions persist across subdomains in production
|
|
51
51
|
|
|
52
52
|
---
|
package/docs/db.md
CHANGED
|
@@ -170,11 +170,6 @@ GITHUB_CLIENT_SECRET=your_github_client_secret
|
|
|
170
170
|
|
|
171
171
|
The GitHub login feature is now fully integrated into your mbkauthe system and ready to use!
|
|
172
172
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
173
|
## Database structure
|
|
179
174
|
|
|
180
175
|
[<- Back](README.md)
|
|
@@ -198,7 +193,7 @@ The GitHub login feature is now fully integrated into your mbkauthe system and r
|
|
|
198
193
|
- `Role` (ENUM): The role of the user. Possible values: `SuperAdmin`, `NormalUser`, `Guest`.
|
|
199
194
|
- `Active` (BOOLEAN): Indicates whether the user account is active.
|
|
200
195
|
- `HaveMailAccount` (BOOLEAN)(optional): Indicates if the user has a linked mail account.
|
|
201
|
-
-
|
|
196
|
+
- (SessionId removed) The application now stores multiple concurrent sessions in the `Sessions` table.
|
|
202
197
|
- `GuestRole` (JSONB): Stores additional guest-specific role information in binary JSON format.
|
|
203
198
|
- `AllowedApps`(JSONB): Array of applications the user is authorized to access.
|
|
204
199
|
|
|
@@ -215,19 +210,32 @@ CREATE TABLE "Users" (
|
|
|
215
210
|
"Active" BOOLEAN DEFAULT FALSE,
|
|
216
211
|
"HaveMailAccount" BOOLEAN DEFAULT FALSE,
|
|
217
212
|
"AllowedApps" JSONB DEFAULT '["mbkauthe", "portal"]',
|
|
218
|
-
"SessionId" VARCHAR(213),
|
|
219
213
|
"created_at" TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
|
220
214
|
"updated_at" TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
|
221
215
|
"last_login" TIMESTAMP WITH TIME ZONE
|
|
222
216
|
);
|
|
223
217
|
|
|
224
218
|
-- Add indexes for performance optimization
|
|
225
|
-
CREATE INDEX IF NOT EXISTS idx_users_sessionid ON "Users" (LOWER("SessionId"));
|
|
226
219
|
CREATE INDEX IF NOT EXISTS idx_users_username ON "Users" ("UserName");
|
|
227
220
|
CREATE INDEX IF NOT EXISTS idx_users_active ON "Users" ("Active");
|
|
228
221
|
CREATE INDEX IF NOT EXISTS idx_users_role ON "Users" ("Role");
|
|
229
222
|
CREATE INDEX IF NOT EXISTS idx_users_last_login ON "Users" (last_login);
|
|
230
|
-
|
|
223
|
+
|
|
224
|
+
-- Application Sessions table (stores multiple concurrent sessions per user)
|
|
225
|
+
-- Note: this is separate from the express-session store table named "session"
|
|
226
|
+
CREATE TABLE "Sessions" (
|
|
227
|
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- requires pgcrypto or uuid-ossp
|
|
228
|
+
"UserName" VARCHAR(50) NOT NULL REFERENCES "Users"("UserName") ON DELETE CASCADE,
|
|
229
|
+
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
|
230
|
+
expires_at TIMESTAMP WITH TIME ZONE,
|
|
231
|
+
meta JSONB
|
|
232
|
+
);
|
|
233
|
+
|
|
234
|
+
-- Indexes optimized by username instead of numeric user id
|
|
235
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_username ON "Sessions" ("UserName");
|
|
236
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_user_created ON "Sessions" ("UserName", created_at);
|
|
237
|
+
|
|
238
|
+
**Multi-session behavior:** MBKAuthe supports multiple concurrent application sessions per user. The maximum number of concurrent sessions is controlled by `mbkautheVar.MAX_SESSIONS_PER_USER` (default: 5). When a new session would exceed that limit, the system prunes the oldest session(s) for that user (ordered by `created_at`) to keep the count within the configured maximum.
|
|
231
239
|
```
|
|
232
240
|
|
|
233
241
|
**Password Storage Notes:**
|
|
@@ -250,12 +258,10 @@ CREATE TABLE "session" (
|
|
|
250
258
|
sid VARCHAR(33) PRIMARY KEY NOT NULL,
|
|
251
259
|
sess JSONB NOT NULL,
|
|
252
260
|
expire TimeStamp WITH TIME ZONE Not Null,
|
|
253
|
-
last_activity TimeStamp WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
|
254
261
|
);
|
|
255
262
|
|
|
256
263
|
-- Add indexes for performance optimization
|
|
257
264
|
CREATE INDEX IF NOT EXISTS idx_session_expire ON "session" ("expire");
|
|
258
|
-
CREATE INDEX IF NOT EXISTS idx_session_last_activity ON "session" (last_activity);
|
|
259
265
|
CREATE INDEX IF NOT EXISTS idx_session_user_id ON "session" ((sess->'user'->>'id'));
|
|
260
266
|
```
|
|
261
267
|
|
|
@@ -286,7 +292,7 @@ CREATE INDEX IF NOT EXISTS idx_twofa_username_status ON "TwoFA" ("UserName", "Tw
|
|
|
286
292
|
|
|
287
293
|
- `id` (INTEGER, auto-increment, primary key): Unique identifier for each trusted device.
|
|
288
294
|
- `UserName` (VARCHAR): The username of the device owner (foreign key to Users).
|
|
289
|
-
- `DeviceToken` (VARCHAR):
|
|
295
|
+
- `DeviceToken` (VARCHAR): **HMAC-SHA256 hash** of the device token (raw token is only sent to the client in an httpOnly cookie and **not** stored in plaintext).
|
|
290
296
|
- `DeviceName` (VARCHAR): Optional friendly name for the device.
|
|
291
297
|
- `UserAgent` (TEXT): Browser/client user agent string.
|
|
292
298
|
- `IpAddress` (VARCHAR): IP address when device was trusted.
|
|
@@ -320,22 +326,22 @@ To add new users to the `Users` table, use the following SQL queries:
|
|
|
320
326
|
|
|
321
327
|
**For Raw Password Storage (EncPass=false):**
|
|
322
328
|
```sql
|
|
323
|
-
INSERT INTO "Users" ("UserName", "Password", "Role", "Active", "HaveMailAccount", "
|
|
324
|
-
VALUES ('support', '12345678', 'SuperAdmin', true, false,
|
|
329
|
+
INSERT INTO "Users" ("UserName", "Password", "Role", "Active", "HaveMailAccount", "GuestRole")
|
|
330
|
+
VALUES ('support', '12345678', 'SuperAdmin', true, false, '{"allowPages": [""], "NotallowPages": [""]}'::jsonb);
|
|
325
331
|
|
|
326
|
-
INSERT INTO "Users" ("UserName", "Password", "Role", "Active", "HaveMailAccount", "
|
|
327
|
-
VALUES ('test', '12345678', 'NormalUser', true, false,
|
|
332
|
+
INSERT INTO "Users" ("UserName", "Password", "Role", "Active", "HaveMailAccount", "GuestRole")
|
|
333
|
+
VALUES ('test', '12345678', 'NormalUser', true, false, '{"allowPages": [""], "NotallowPages": [""]}'::jsonb);
|
|
328
334
|
```
|
|
329
335
|
|
|
330
336
|
**For Encrypted Password Storage (EncPass=true):**
|
|
331
337
|
```sql
|
|
332
338
|
-- Note: You'll need to hash the password using the hashPassword function
|
|
333
339
|
-- Example with pre-hashed password (PBKDF2 with username as salt)
|
|
334
|
-
INSERT INTO "Users" ("UserName", "PasswordEnc", "Role", "Active", "HaveMailAccount", "
|
|
335
|
-
VALUES ('support', 'your_hashed_password_here', 'SuperAdmin', true, false,
|
|
340
|
+
INSERT INTO "Users" ("UserName", "PasswordEnc", "Role", "Active", "HaveMailAccount", "GuestRole")
|
|
341
|
+
VALUES ('support', 'your_hashed_password_here', 'SuperAdmin', true, false, '{"allowPages": [""], "NotallowPages": [""]}'::jsonb);
|
|
336
342
|
|
|
337
|
-
INSERT INTO "Users" ("UserName", "PasswordEnc", "Role", "Active", "HaveMailAccount", "
|
|
338
|
-
VALUES ('test', 'your_hashed_password_here', 'NormalUser', true, false,
|
|
343
|
+
INSERT INTO "Users" ("UserName", "PasswordEnc", "Role", "Active", "HaveMailAccount", "GuestRole")
|
|
344
|
+
VALUES ('test', 'your_hashed_password_here', 'NormalUser', true, false, '{"allowPages": [""], "NotallowPages": [""]}'::jsonb);
|
|
339
345
|
```
|
|
340
346
|
|
|
341
347
|
**Configuration Notes:**
|