mbkauthe 5.0.0 → 5.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 CHANGED
@@ -6,172 +6,158 @@
6
6
  [![Publish](https://github.com/MIbnEKhalid/mbkauthe/actions/workflows/publish.yml/badge.svg?branch=main)](https://github.com/MIbnEKhalid/mbkauthe/actions/workflows/publish.yml)
7
7
  [![Downloads](https://img.shields.io/npm/dm/mbkauthe.svg)](https://www.npmjs.com/package/mbkauthe)
8
8
 
9
-
10
9
  <p align="center">
11
10
  <img height="64px" src="./public/logo.png" alt="MBKAuthe" />
12
11
  </p>
13
12
 
14
- **MBKAuthe** is an open source package focused on login, authentication, and validating sessions for your desired apps in Node.js with Express and PostgreSQL. It provides secure login, session validation, 2FA, role/app access checks, OAuth (GitHub & Google), multi-session support, and related authentication flows.
15
-
16
- > **Note:** MBKAuthe is intentionally limited to authentication and session validation. The full user/permission/dashboard management system is a separate product called **MBKCore**, developed by MBKTech and not currently open source. Access to MBKCore is currently available only to the MBKTech team, and we may refine it and consider open sourcing it in the future.
13
+ **MBKAuthe** is an open source authentication package for Node.js, Express, and PostgreSQL. It handles login, session validation, role/app access checks, optional TOTP 2FA, OAuth login, API token authentication, and multi-session management.
17
14
 
18
- ## Todo
19
- - Currently, for every request to a protected page, a database query is made to retrieve authentication information (allowed apps, username, session ID, role, etc.). We should implement a caching mechanism to reduce this overhead, but also find a way to allow administrators to log users out and update permissions in near real-time.
15
+ > **Note:** MBKAuthe is intentionally focused on authentication and session validation. The broader user, permission, and dashboard management system is a separate MBKTech product named **MBKCore**(closed source for now).
20
16
 
21
- ## ✨ Key Features
17
+ ## Features
22
18
 
23
- - Compatible With Serverless Function (Vercel)
24
- - Secure password authentication (PBKDF2)
25
- - PostgreSQL session management
26
- - Multi-session support (configurable concurrent sessions per user)
27
- - Optional TOTP-based 2FA with trusted devices
28
- - Social login (GitHub App & Google OAuth)
29
- - Role-based access: SuperAdmin, NormalUser, Guest, member
30
- - CSRF protection & rate limiting
31
- - Easy Express.js integration
32
- - Customizable Handlebars templates
33
- - Session fixation prevention
34
- - Dynamic profile picture routing with session caching
35
- - Modern responsive UI with desktop two-column layout
36
- - Dev-only DB Query Monitor with callsite, timing, and request context
19
+ - Express middleware for session validation and role checks
20
+ - PostgreSQL-backed user, session, 2FA, trusted-device, and API-token storage
21
+ - Secure password authentication with PBKDF2
22
+ - Optional TOTP 2FA with trusted devices
23
+ - GitHub App and Google OAuth login flows
24
+ - API token authentication with read-only/write scopes
25
+ - Configurable multi-session support per user
26
+ - CSRF protection, rate limiting, secure cookies, and session fixation prevention
27
+ - Customizable Handlebars views
28
+ - Vercel/serverless-friendly deployment support
29
+ - Dev-only DB Query Monitor with callsite, timing, request context, and pool stats
37
30
 
38
- ## 📦 Installation
31
+ ## Installation
39
32
 
40
33
  ```bash
41
34
  npm install mbkauthe
42
35
  ```
43
36
 
44
- ## 🚀 Quick Start
37
+ ## Quick Start
45
38
 
46
- **1. Configure Environment**
39
+ 1. Copy the environment template.
47
40
 
48
- ```bash
41
+ ```powershell
49
42
  Copy-Item .env.example .env
50
43
  ```
51
- See [docs/env.md](docs/env.md).
52
44
 
53
- **2. Set Up Database**
54
- 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).
45
+ 2. Configure environment values.
55
46
 
56
- **3. Integrate with Express**
57
-
58
- ```javascript
59
- import express from 'express';
60
- import mbkauthe, { sessVal, roleChk } from 'mbkauthe';
61
- import dotenv from 'dotenv';
62
- dotenv.config();
47
+ See the [configuration guide](docs/guides/configuration.md) for `mbkautheVar`, `mbkauthShared`, OAuth settings, session settings, and deployment flags.
63
48
 
64
- const app = express();
65
- app.use(mbkauthe);
49
+ 3. Create database tables.
66
50
 
67
- app.get('/dashboard', sessVal, (req, res) => res.send(`Welcome ${req.session.user.username}!`));
68
- app.get('/admin', sessVal, roleChk(['SuperAdmin']), (req, res) => res.send('Admin Panel'));
69
-
70
- app.listen(3000);
71
- ```
72
-
73
- ## 🧪 Testing
51
+ Run [docs/schema/db.sql](docs/schema/db.sql) against PostgreSQL, or use the package script:
74
52
 
75
53
  ```bash
76
- npm test
77
- npm run test:watch
78
- npm run dev
54
+ npm run create-tables
79
55
  ```
80
56
 
81
- ## 🔧 Core API
57
+ The schema includes a default SuperAdmin user (`support` / `12345678`). Change that password immediately. See the [database guide](docs/guides/database.md).
82
58
 
83
- - **Session Validation:** `validateSession`
84
- - **Role Check:** `checkRolePermission(['Role'])`/`roleChk(['Role'])`
85
- - **Combined:** `validateSessionAndRole(['SuperAdmin', 'NormalUser'])`/`sessRole(['SuperAdmin', 'NormalUser'])`
86
- - **API Token Auth:** `authenticate(process.env.API_TOKEN)`
59
+ 4. Mount MBKAuthe in Express.
87
60
 
88
- ## 🧾 JSON Responses (HTML vs JSON)
89
-
90
- Most browser page routes render HTML on auth errors, while API/AJAX-style requests receive JSON error responses.
91
-
92
- MBKAuthe treats a request as **JSON** (and returns JSON errors) when any of the following apply:
93
-
94
- - URL/path starts with `/mbkauthe/api/` or `/api/`
95
- - `X-Requested-With: XMLHttpRequest`
96
- - `Accept` indicates JSON (e.g., `application/json`) and does not explicitly prefer `text/html`
97
- - `User-Agent` looks like a non-browser client (e.g., `curl`, `wget`, `Postman`)
98
- - `User-Agent: json` (explicitly forces JSON responses)
61
+ ```javascript
62
+ import express from "express";
63
+ import dotenv from "dotenv";
64
+ import mbkauthe, { sessVal, roleChk } from "mbkauthe";
99
65
 
100
- **Example (force JSON errors):**
101
- ```bash
102
- curl -i -H "User-Agent: json" http://localhost:3000/mbkauthe/test
103
- ```
66
+ dotenv.config();
104
67
 
105
- ## 🧰 Diagnostics (dev only)
68
+ const app = express();
106
69
 
107
- These are only mounted when `process.env.env === "dev"`:
70
+ app.use(mbkauthe);
108
71
 
109
- - **DB Query Monitor (HTML):** `/mbkauthe/db`
110
- - **DB Query Monitor (JSON):** `/mbkauthe/db.json`
111
- - **SuperAdmin check:** `/mbkauthe/validate-superadmin`
72
+ app.get("/dashboard", sessVal, (req, res) => {
73
+ res.send(`Welcome ${req.session.user.username}!`);
74
+ });
112
75
 
113
- ## 🔐 Security
76
+ app.get("/admin", sessVal, roleChk("SuperAdmin"), (req, res) => {
77
+ res.send("Admin Panel");
78
+ });
114
79
 
115
- - Rate limiting, CSRF protection, secure cookies
116
- - Password hashing (PBKDF2, 100k iterations)
117
- - PostgreSQL-backed sessions with automatic cleanup
118
- - OAuth with state validation and secure callbacks
80
+ app.listen(3000);
81
+ ```
119
82
 
120
- ## 📱 Two-Factor Authentication
83
+ ## Common Exports
121
84
 
122
- Enable via `MBKAUTH_TWO_FA_ENABLE=true`. Trusted devices can skip 2FA for a set duration.
85
+ - `sessVal` / `validateSession` - require a valid session or API token.
86
+ - `roleChk` / `checkRolePermission` - require a role after session validation.
87
+ - `sessRole` / `validateSessionAndRole` - combine session and role checks.
88
+ - `strictValidateSession` - require cookie session authentication only.
89
+ - `strictValidateSessionAndRole` - strict cookie session plus role check.
90
+ - `authenticate(token)` - protect server-to-server routes with a static bearer token.
91
+ - `dblogin` - access the configured PostgreSQL pool.
123
92
 
124
- ## 🔄 Social Login Integration
93
+ See the [API reference](docs/reference/api.md) for endpoints, middleware, examples, security notes, and rate limits.
125
94
 
126
- **GitHub App / Google OAuth:** Configure credentials via `.env` or `mbkautheVar`. Users must link accounts before login.
95
+ ## JSON Error Responses
127
96
 
128
- ## 🎨 Customization
97
+ Browser page routes usually render HTML errors, while API/AJAX-style requests receive JSON. MBKAuthe treats a request as JSON when any of these are true:
129
98
 
130
- - **Redirect URL:** `mbkautheVar={"loginRedirectURL":"/dashboard"}`
131
- - **Custom Views:** `views/loginmbkauthe.handlebars`, `2fa.handlebars`, `Error/dError.handlebars`
132
- - **Database Access:** `import { dblogin } from 'mbkauthe'; const result = await dblogin.query('SELECT * FROM "Users"');`
99
+ - The path starts with `/mbkauthe/api/` or `/api/`
100
+ - `X-Requested-With: XMLHttpRequest`
101
+ - `Accept` prefers JSON and does not explicitly prefer `text/html`
102
+ - `User-Agent` looks like a non-browser client such as `curl`, `wget`, or `Postman`
103
+ - `User-Agent: json`
133
104
 
134
- ## 📄 API Reference
105
+ ```bash
106
+ curl -i -H "User-Agent: json" http://localhost:3000/mbkauthe/test
107
+ ```
135
108
 
136
- - Full endpoint list and details: [docs/api.md](docs/api.md)
109
+ ## Development
137
110
 
138
- ## 🧰 Diagnostics (dev only)
111
+ ```bash
112
+ npm test
113
+ npm run test:watch
114
+ npm run dev
115
+ ```
139
116
 
140
- - **DB Query Monitor (HTML):** `/mbkauthe/db`
141
- - **DB Query Monitor (JSON):** `/mbkauthe/db.json`
142
- - **SuperAdmin check:** `/mbkauthe/debug/validate-superadmin`
117
+ Development-only diagnostics are mounted when `process.env.env === "dev"`:
143
118
 
144
- These routes are only mounted when `process.env.env === "dev"`. They expose query timing, status/error, pool stats, request context, and callsite data for troubleshooting.
119
+ - `/mbkauthe/db` - DB Query Monitor UI
120
+ - `/mbkauthe/db.json` - DB Query Monitor JSON
121
+ - `/mbkauthe/db/reset` - reset diagnostic query logs
122
+ - `/mbkauthe/validate-superadmin` - SuperAdmin validation check
145
123
 
146
- ## 🚢 Deployment
124
+ ## Documentation
147
125
 
148
- Checklist for production:
149
- - `IS_DEPLOYED=true`
150
- - Strong secrets for SESSION_SECRET_KEY & Main_SECRET_TOKEN
151
- - HTTPS enabled
152
- - Correct DOMAIN & COOKIE_EXPIRE_TIME
153
- - Use environment variables for all secrets
126
+ - [Documentation index](docs/README.md)
127
+ - [Configuration guide](docs/guides/configuration.md)
128
+ - [Database guide](docs/guides/database.md)
129
+ - [API reference](docs/reference/api.md)
130
+ - [Authentication and sessions](docs/reference/api/authentication.md)
131
+ - [Endpoints](docs/reference/api/endpoints.md)
132
+ - [Middleware](docs/reference/api/middleware.md)
133
+ - [Code examples](docs/reference/api/examples.md)
134
+ - [Operational reference](docs/reference/api/operations.md)
135
+ - [Error codes](docs/reference/error-codes.md)
136
+ - [Documentation style guide](docs/STYLE.md)
154
137
 
155
- **Vercel:** Supports shared OAuth credentials via `mbkauthShared`.
138
+ ## Deployment Checklist
156
139
 
157
- ## 📚 Documentation
140
+ - Set `IS_DEPLOYED=true`
141
+ - Use strong `SESSION_SECRET_KEY` and `Main_SECRET_TOKEN` values
142
+ - Enable HTTPS
143
+ - Set the correct `DOMAIN`
144
+ - Set an appropriate `COOKIE_EXPIRE_TIME`
145
+ - Store secrets in environment variables
146
+ - Configure OAuth credentials only when the matching provider is enabled
158
147
 
159
- - [API Reference](docs/api.md)
160
- - [Database Schema](docs/db.md)
161
- - [Environment Config](docs/env.md)
162
- - [Error Codes](docs/error-messages.md)
148
+ Vercel deployments can use shared OAuth credentials through `mbkauthShared`.
163
149
 
164
- ## 📝 License
150
+ ## License
165
151
 
166
- GPL v2.0 see [LICENSE](LICENSE)
152
+ GPL v2.0 - see [LICENSE](LICENSE).
167
153
 
168
- ## 👨‍💻 Author
154
+ ## Author
169
155
 
170
156
  **Muhammad Bin Khalid**
171
- 📧 [support@mbktech.org](mailto:support@mbktech.org) | [chmuhammadbinkhalid28@gmail.com](mailto:chmuhammadbinkhalid28@gmail.com)
172
- 🔗 [GitHub @MIbnEKhalid](https://github.com/MIbnEKhalid)
157
+ [support@mbktech.org](mailto:support@mbktech.org) | [chmuhammadbinkhalid28@gmail.com](mailto:chmuhammadbinkhalid28@gmail.com)
158
+ [GitHub @MIbnEKhalid](https://github.com/MIbnEKhalid)
173
159
 
174
- ## 🔗 Links
160
+ ## Links
175
161
 
176
162
  - [npm](https://www.npmjs.com/package/mbkauthe)
177
163
  - [GitHub](https://github.com/MIbnEKhalid/mbkauthe)
@@ -179,4 +165,4 @@ GPL v2.0 — see [LICENSE](LICENSE)
179
165
 
180
166
  ---
181
167
 
182
- Made with ❤️ by [MBKTech.org](https://mbktech.org)
168
+ Made with love by [MBKTech.org](https://mbktech.org).
package/docs/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # MBKAuthe Documentation
2
+
3
+ This directory is organized by how the documentation is used:
4
+
5
+ - **Guides** - setup and operational walkthroughs.
6
+ - **Reference** - detailed API and error-code documentation.
7
+ - **Schema** - executable database SQL.
8
+ - **Diagrams** - Mermaid source files and rendered images.
9
+
10
+ ## Start here
11
+
12
+ - [Project README](../README.md)
13
+ - [Configuration guide](guides/configuration.md)
14
+ - [Database guide](guides/database.md)
15
+ - [API reference](reference/api.md)
16
+ - [Error codes](reference/error-codes.md)
17
+ - [Documentation style guide](STYLE.md)
18
+
19
+ ## Source layout
20
+
21
+ - `guides/` - task-oriented setup and operations docs.
22
+ - `reference/` - detailed facts, route lists, middleware details, and error-code documentation.
23
+ - `reference/api/` - split API reference sections included from the API index.
24
+ - `schema/` - executable SQL and schema assets.
25
+ - `diagrams/` - Mermaid source files.
26
+ - `images/` - rendered diagram outputs and documentation images.
27
+
28
+ ## Assets
29
+
30
+ - [Database schema SQL](schema/db.sql)
31
+ - [Authentication flow Mermaid source](diagrams/auth-flows.mmd)
32
+ - [Authentication process Mermaid source](diagrams/auth-processes.mmd)
33
+ - [Rendered diagram images](images/)
package/docs/STYLE.md ADDED
@@ -0,0 +1,40 @@
1
+ # Documentation Style Guide
2
+
3
+ [Back to docs index](README.md) | [Back to project README](../README.md)
4
+
5
+ Use this guide when adding or changing documentation source.
6
+
7
+ ## File Placement
8
+
9
+ - Put setup walkthroughs and operational how-to content in `guides/`.
10
+ - Put endpoint, middleware, type, and error-code details in `reference/`.
11
+ - Put long API sections under `reference/api/` and link them from `reference/api.md`.
12
+ - Put executable database SQL in `schema/`.
13
+ - Put Mermaid source in `diagrams/` and rendered outputs in `images/`.
14
+
15
+ ## Markdown Structure
16
+
17
+ - Use one `#` title per file.
18
+ - Keep files focused on one job; split a file when it becomes hard to scan or review.
19
+ - Add a small navigation line under the title for files below `docs/`.
20
+ - Prefer descriptive links such as `[Configuration guide](guides/configuration.md)` over raw paths in prose.
21
+ - Keep table-of-contents blocks short; rely on smaller files instead of very deep TOCs.
22
+
23
+ ## Code Blocks
24
+
25
+ - Always include a language tag when the language is known: `javascript`, `json`, `bash`, `sql`, `env`, or `typescript`.
26
+ - Keep examples copy-pasteable where possible.
27
+ - Use placeholders for secrets and tokens; never include real credentials.
28
+ - Keep endpoint examples close to the endpoint they describe.
29
+
30
+ ## Cross-Links
31
+
32
+ - Links from `docs/README.md` are relative to `docs/`.
33
+ - Links from `docs/reference/api/*.md` need one extra `..` segment to reach the docs index.
34
+ - After moving docs, run a Markdown link check before committing.
35
+
36
+ ## Generated Assets
37
+
38
+ - Mermaid source is authoritative.
39
+ - Rendered images in `images/` should be regenerated when the matching `.mmd` file changes.
40
+ - Keep package scripts aligned with the source paths in `diagrams/`.
@@ -0,0 +1,120 @@
1
+ sequenceDiagram
2
+ autonumber
3
+
4
+ participant R as Protected Route
5
+ participant VS as validateSession
6
+ participant JT as isJsonRequest
7
+ participant VT as validateTokenAuthentication
8
+ participant CS as validateCookieSession
9
+ participant DB as AuthRepository / DB
10
+ participant RES as Response
11
+
12
+ R->>VS: validateSession(req, res, next, strictTokenValidation?)
13
+
14
+ alt Authorization header exists
15
+ alt strictTokenValidation is true
16
+ VS-->>RES: 401 INVALID_AUTH_TOKEN
17
+ Note over VS,RES: Token auth is rejected for strict cookie-only middleware.
18
+ else token auth allowed
19
+ VS->>VT: validateTokenAuthentication(req)
20
+
21
+ alt Header is not "Bearer <token>"
22
+ VT-->>VS: null
23
+ VS-->>RES: 401 INVALID_AUTH_TOKEN
24
+ else Token does not start with mbk_ or is too long
25
+ VT-->>VS: { error: "INVALID_TOKEN" }
26
+ VS-->>RES: 401 INVALID_AUTH_TOKEN
27
+ else Token format is accepted
28
+ VT->>VT: hashApiToken(token)
29
+ VT->>DB: getApiTokenByHash(tokenHash)
30
+
31
+ alt API token row not found
32
+ DB-->>VT: null
33
+ VT-->>VS: { error: "INVALID_TOKEN" }
34
+ VS-->>RES: 401 INVALID_AUTH_TOKEN
35
+ else API token expired
36
+ DB-->>VT: row with ExpiresAt <= now
37
+ VT-->>VS: { error: "TOKEN_EXPIRED" }
38
+ VS-->>RES: 401 API_TOKEN_EXPIRED
39
+ else API token found
40
+ DB-->>VT: token row joined to user
41
+ VT->>VT: Resolve token scope and allowedApps
42
+ VT->>DB: updateApiTokenLastUsed(row.id) async
43
+ VT-->>VS: tokenUser
44
+
45
+ alt tokenUser.active is false
46
+ VS-->>RES: 401 ACCOUNT_INACTIVE
47
+ else Non-SuperAdmin has no allowed apps
48
+ VS-->>RES: 401 APP_NOT_AUTHORIZED
49
+ else Token allowedApps has wildcard but user apps do not include APP_NAME
50
+ VS-->>RES: 401 APP_NOT_AUTHORIZED
51
+ else Token allowedApps does not include APP_NAME
52
+ VS-->>RES: 401 APP_NOT_AUTHORIZED
53
+ else App access allowed
54
+ VS->>VS: attachApiTokenUser(req, res, tokenUser)
55
+ Note over VS: Sets req.auth, req.user, req.userRole,<br/>and request-local req.session.user.
56
+
57
+ alt tokenScope does not allow req.method
58
+ VS-->>RES: 403 TOKEN_SCOPE_INSUFFICIENT
59
+ else token scope allows method
60
+ VS-->>R: next()
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
66
+ else No Authorization header
67
+ VS->>JT: isJsonRequest(req)
68
+ JT-->>VS: prefersJson
69
+ VS->>CS: validateCookieSession(req, res, next, prefersJson)
70
+
71
+ alt req.session.user is missing
72
+ alt prefersJson
73
+ CS-->>RES: 401 SESSION_NOT_FOUND
74
+ else browser/page request
75
+ CS-->>RES: 302 /mbkauthe/login?redirect=...&reason=logged_out
76
+ end
77
+ else req.session.user exists
78
+ CS->>CS: Read req.session.user.sessionId
79
+
80
+ alt sessionId missing or not UUID
81
+ CS->>CS: destroy session and clear cookies
82
+ alt prefersJson
83
+ CS-->>RES: 401 SESSION_EXPIRED
84
+ else browser/page request
85
+ CS-->>RES: Render "Session Expired" error page
86
+ end
87
+ else sessionId is UUID
88
+ CS->>DB: getSessionAuthData(sessionId)
89
+
90
+ alt DB session row not found
91
+ CS->>CS: destroy session and clear cookies
92
+ alt prefersJson
93
+ CS-->>RES: 401 SESSION_INVALID
94
+ else browser/page request
95
+ CS-->>RES: Render "Session Expired" error page
96
+ end
97
+ else DB session row found
98
+ DB-->>CS: session row joined to user
99
+
100
+ alt session expired
101
+ CS->>CS: destroy session and clear cookies
102
+ CS-->>RES: 401 SESSION_EXPIRED or rendered error page
103
+ else user account inactive
104
+ CS->>CS: destroy session and clear cookies
105
+ CS-->>RES: 401 ACCOUNT_INACTIVE or rendered support page
106
+ else user not allowed for APP_NAME
107
+ CS->>CS: destroy session and clear cookies
108
+ CS-->>RES: 401 APP_NOT_AUTHORIZED or rendered unauthorized page
109
+ else session valid and app access allowed
110
+ CS->>CS: req.userRole = sessionRow.Role
111
+ CS-->>R: next()
112
+ end
113
+ end
114
+ end
115
+ end
116
+ end
117
+
118
+ opt Token or session validation throws
119
+ VS-->>RES: 500 INTERNAL_SERVER_ERROR
120
+ end
@@ -0,0 +1,122 @@
1
+ ```mermaid
2
+ sequenceDiagram
3
+ autonumber
4
+
5
+ participant R as Protected Route
6
+ participant VS as validateSession
7
+ participant JT as isJsonRequest
8
+ participant VT as validateTokenAuthentication
9
+ participant CS as validateCookieSession
10
+ participant DB as AuthRepository / DB
11
+ participant RES as Response
12
+
13
+ R->>VS: validateSession(req, res, next, strictTokenValidation?)
14
+
15
+ alt Authorization header exists
16
+ alt strictTokenValidation is true
17
+ VS-->>RES: 401 INVALID_AUTH_TOKEN
18
+ Note over VS,RES: Token auth is rejected for strict cookie-only middleware.
19
+ else token auth allowed
20
+ VS->>VT: validateTokenAuthentication(req)
21
+
22
+ alt Header is not "Bearer <token>"
23
+ VT-->>VS: null
24
+ VS-->>RES: 401 INVALID_AUTH_TOKEN
25
+ else Token does not start with mbk_ or is too long
26
+ VT-->>VS: { error: "INVALID_TOKEN" }
27
+ VS-->>RES: 401 INVALID_AUTH_TOKEN
28
+ else Token format is accepted
29
+ VT->>VT: hashApiToken(token)
30
+ VT->>DB: getApiTokenByHash(tokenHash)
31
+
32
+ alt API token row not found
33
+ DB-->>VT: null
34
+ VT-->>VS: { error: "INVALID_TOKEN" }
35
+ VS-->>RES: 401 INVALID_AUTH_TOKEN
36
+ else API token expired
37
+ DB-->>VT: row with ExpiresAt <= now
38
+ VT-->>VS: { error: "TOKEN_EXPIRED" }
39
+ VS-->>RES: 401 API_TOKEN_EXPIRED
40
+ else API token found
41
+ DB-->>VT: token row joined to user
42
+ VT->>VT: Resolve token scope and allowedApps
43
+ VT->>DB: updateApiTokenLastUsed(row.id) async
44
+ VT-->>VS: tokenUser
45
+
46
+ alt tokenUser.active is false
47
+ VS-->>RES: 401 ACCOUNT_INACTIVE
48
+ else Non-SuperAdmin has no allowed apps
49
+ VS-->>RES: 401 APP_NOT_AUTHORIZED
50
+ else Token allowedApps has wildcard but user apps do not include APP_NAME
51
+ VS-->>RES: 401 APP_NOT_AUTHORIZED
52
+ else Token allowedApps does not include APP_NAME
53
+ VS-->>RES: 401 APP_NOT_AUTHORIZED
54
+ else App access allowed
55
+ VS->>VS: attachApiTokenUser(req, res, tokenUser)
56
+ Note over VS: Sets req.auth, req.user, req.userRole,<br/>and request-local req.session.user.
57
+
58
+ alt tokenScope does not allow req.method
59
+ VS-->>RES: 403 TOKEN_SCOPE_INSUFFICIENT
60
+ else token scope allows method
61
+ VS-->>R: next()
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
67
+ else No Authorization header
68
+ VS->>JT: isJsonRequest(req)
69
+ JT-->>VS: prefersJson
70
+ VS->>CS: validateCookieSession(req, res, next, prefersJson)
71
+
72
+ alt req.session.user is missing
73
+ alt prefersJson
74
+ CS-->>RES: 401 SESSION_NOT_FOUND
75
+ else browser/page request
76
+ CS-->>RES: 302 /mbkauthe/login?redirect=...&reason=logged_out
77
+ end
78
+ else req.session.user exists
79
+ CS->>CS: Read req.session.user.sessionId
80
+
81
+ alt sessionId missing or not UUID
82
+ CS->>CS: destroy session and clear cookies
83
+ alt prefersJson
84
+ CS-->>RES: 401 SESSION_EXPIRED
85
+ else browser/page request
86
+ CS-->>RES: Render "Session Expired" error page
87
+ end
88
+ else sessionId is UUID
89
+ CS->>DB: getSessionAuthData(sessionId)
90
+
91
+ alt DB session row not found
92
+ CS->>CS: destroy session and clear cookies
93
+ alt prefersJson
94
+ CS-->>RES: 401 SESSION_INVALID
95
+ else browser/page request
96
+ CS-->>RES: Render "Session Expired" error page
97
+ end
98
+ else DB session row found
99
+ DB-->>CS: session row joined to user
100
+
101
+ alt session expired
102
+ CS->>CS: destroy session and clear cookies
103
+ CS-->>RES: 401 SESSION_EXPIRED or rendered error page
104
+ else user account inactive
105
+ CS->>CS: destroy session and clear cookies
106
+ CS-->>RES: 401 ACCOUNT_INACTIVE or rendered support page
107
+ else user not allowed for APP_NAME
108
+ CS->>CS: destroy session and clear cookies
109
+ CS-->>RES: 401 APP_NOT_AUTHORIZED or rendered unauthorized page
110
+ else session valid and app access allowed
111
+ CS->>CS: req.userRole = sessionRow.Role
112
+ CS-->>R: next()
113
+ end
114
+ end
115
+ end
116
+ end
117
+ end
118
+
119
+ opt Token or session validation throws
120
+ VS-->>RES: 500 INTERNAL_SERVER_ERROR
121
+ end
122
+ ```
@@ -1,6 +1,7 @@
1
1
  # Environment Configuration Guide
2
2
 
3
- [ Back to README](README.md)
3
+ [Back to docs index](../README.md) | [Back to project README](../../README.md)
4
+
4
5
  This document describes the environment variables MBKAuth expects and keeps brief usage notes for each parameter. Validation and defaults are implemented in `lib/config/index.js` (it parses `mbkautheVar`, applies optional `mbkauthShared` fallbacks, normalizes values, and throws on validation failures).
5
6
 
6
7
  ## How configuration is provided
@@ -1,6 +1,8 @@
1
1
  # Database Schema
2
2
 
3
- **Executable DDL lives only in [`docs/db.sql`](db.sql).** This file explains what that script creates and how the app uses it. Run the script against Postgres when bootstrapping or aligning a database (for example `psql $DATABASE_URL -f docs/db.sql`). The app can also apply it via `lib/createTable.js`, which reads `docs/db.sql`.
3
+ [Back to docs index](../README.md) | [Back to project README](../../README.md)
4
+
5
+ **Executable DDL lives only in [`docs/schema/db.sql`](../schema/db.sql).** This file explains what that script creates and how the app uses it. Run the script against Postgres when bootstrapping or aligning a database (for example `psql $DATABASE_URL -f docs/schema/db.sql`). The app can also apply it via `lib/createTable.js`, which reads `docs/schema/db.sql`.
4
6
 
5
7
  ---
6
8