webspresso 0.0.83 → 0.0.85
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 +84 -3
- package/bin/commands/orm-map.js +1 -1
- package/core/auth/index.js +10 -42
- package/core/auth/jwt.js +235 -0
- package/core/auth/manager.js +193 -0
- package/core/auth/middleware.js +66 -4
- package/index.d.ts +22 -0
- package/package.json +3 -3
- package/plugins/admin-panel/api.js +73 -0
- package/plugins/admin-panel/app.js +31 -13
- package/plugins/admin-panel/core/admin-module.js +75 -3
- package/plugins/admin-panel/core/registry.js +68 -0
- package/plugins/admin-panel/index.js +23 -4
- package/plugins/admin-panel/modules/custom-pages.js +40 -1
- package/plugins/admin-panel/modules/menu.js +23 -11
- package/plugins/admin-panel/modules/profile.js +192 -0
- package/plugins/content/client/inline-edit.js +33 -1
- package/plugins/cors.js +171 -0
- package/plugins/csrf/index.js +8 -1
- package/plugins/index.js +2 -0
- package/src/server.js +4 -2
- package/templates/skills/webspresso-usage/REFERENCE-framework.md +16 -8
package/README.md
CHANGED
|
@@ -846,18 +846,19 @@ if (adminApi) {
|
|
|
846
846
|
}
|
|
847
847
|
```
|
|
848
848
|
|
|
849
|
-
**registerModule config:**
|
|
850
849
|
| Field | Description |
|
|
851
850
|
|-------|-------------|
|
|
852
851
|
| `id` | Unique module identifier (required) |
|
|
853
|
-
| `pages` | Custom admin pages (`id`, `title`, `path`, `icon`, `description`, `componentFile`, `component`, `layout`) |
|
|
852
|
+
| `pages` | Custom admin pages (`id`, `title`, `path`, `icon`, `description`, `url`, `iframeUrl`, `html`, `htmlFile`, `componentFile`, `component`, `layout`) |
|
|
854
853
|
| `pagesDir` | Path to directory containing page folders/configs for automatic discovery |
|
|
855
854
|
| `menu` | Sidebar menu items (`id`, `label`, `path`, `icon`, `order`) |
|
|
856
855
|
| `menuGroups` | Collapsible menu groups (`id`, `label`, `order`) |
|
|
857
856
|
| `api` | API routes (`prefix`, `routes`: `method`, `path`, `handler`, `auth`) |
|
|
858
857
|
| `widgets` | Dashboard widgets (`id`, `title`, `dataLoader`) |
|
|
858
|
+
| `scripts` | External script URLs, script objects, or inline scripts injected into SSR Admin Panel (`registerScript`) |
|
|
859
|
+
| `styles` | External stylesheet URLs or inline CSS injected into SSR Admin Panel (`registerStyle`) |
|
|
859
860
|
|
|
860
|
-
Pages support `componentFile`
|
|
861
|
+
Pages support JavaScript client components (`componentFile`, `pagesDir`, `component`) as well as **custom HTML & external URL pages** (`url` or `iframeUrl` for external web apps, and `html` or `htmlFile` for local HTML files like EUIX Engine apps). By default (`layout: true`), custom page views are automatically wrapped in the Admin Layout with Breadcrumbs. Set `layout: false` for full-screen / custom canvas pages.
|
|
861
862
|
|
|
862
863
|
**Example component file (`admin/reports.js`):**
|
|
863
864
|
|
|
@@ -1315,6 +1316,86 @@ createApp({
|
|
|
1315
1316
|
});
|
|
1316
1317
|
```
|
|
1317
1318
|
|
|
1319
|
+
### Authentication & JWT Support (`quickAuth`)
|
|
1320
|
+
|
|
1321
|
+
Webspresso provides a zero-dependency **Dual Authentication** system (`webspresso/core/auth`):
|
|
1322
|
+
- **Session + Cookie**: Stateful auth for browser SSR routes and Admin Panel (`/`, `/_admin`).
|
|
1323
|
+
- **JWT + Refresh Token**: Stateless HS256 auth for REST APIs, Mobile Apps, and SPAs (`/api/*`).
|
|
1324
|
+
|
|
1325
|
+
```javascript
|
|
1326
|
+
// createApp setup with quickAuth
|
|
1327
|
+
const { quickAuth } = require('webspresso/core/auth');
|
|
1328
|
+
|
|
1329
|
+
const auth = quickAuth({
|
|
1330
|
+
db,
|
|
1331
|
+
userModel: 'User',
|
|
1332
|
+
jwt: {
|
|
1333
|
+
expiresIn: '15m', // Access token duration (default: 24h)
|
|
1334
|
+
refreshExpiresIn: '30d', // Refresh token duration (default: 30d)
|
|
1335
|
+
},
|
|
1336
|
+
});
|
|
1337
|
+
|
|
1338
|
+
createApp({
|
|
1339
|
+
pagesDir: './pages',
|
|
1340
|
+
db,
|
|
1341
|
+
auth,
|
|
1342
|
+
});
|
|
1343
|
+
```
|
|
1344
|
+
|
|
1345
|
+
**File-Based API Route Examples (`pages/api/*`):**
|
|
1346
|
+
|
|
1347
|
+
```javascript
|
|
1348
|
+
// 1. pages/api/auth/login.post.js (Login & Token Generation)
|
|
1349
|
+
module.exports = {
|
|
1350
|
+
schema: ({ z }) => ({
|
|
1351
|
+
body: z.object({
|
|
1352
|
+
email: z.string().email(),
|
|
1353
|
+
password: z.string().min(1),
|
|
1354
|
+
}),
|
|
1355
|
+
}),
|
|
1356
|
+
async handler(req, res) {
|
|
1357
|
+
const { email, password } = req.input.body;
|
|
1358
|
+
const user = await req.auth.attempt(email, password);
|
|
1359
|
+
if (!user) return res.status(401).json({ error: 'Invalid credentials' });
|
|
1360
|
+
|
|
1361
|
+
const accessToken = req.auth.generateUserToken(user);
|
|
1362
|
+
const refreshToken = req.auth.generateRefreshToken(user);
|
|
1363
|
+
|
|
1364
|
+
return res.json({ accessToken, refreshToken, user: { id: user.id, email: user.email } });
|
|
1365
|
+
},
|
|
1366
|
+
};
|
|
1367
|
+
```
|
|
1368
|
+
|
|
1369
|
+
```javascript
|
|
1370
|
+
// 2. pages/api/auth/refresh.post.js (Token Rotation Endpoint)
|
|
1371
|
+
module.exports = {
|
|
1372
|
+
schema: ({ z }) => ({
|
|
1373
|
+
body: z.object({
|
|
1374
|
+
refreshToken: z.string(),
|
|
1375
|
+
}),
|
|
1376
|
+
}),
|
|
1377
|
+
async handler(req, res) {
|
|
1378
|
+
const { refreshToken } = req.input.body;
|
|
1379
|
+
try {
|
|
1380
|
+
const result = await req.auth.refreshAccessToken(refreshToken, { rotate: true });
|
|
1381
|
+
return res.json({ accessToken: result.accessToken, refreshToken: result.refreshToken });
|
|
1382
|
+
} catch (err) {
|
|
1383
|
+
return res.status(401).json({ error: err.message });
|
|
1384
|
+
}
|
|
1385
|
+
},
|
|
1386
|
+
};
|
|
1387
|
+
```
|
|
1388
|
+
|
|
1389
|
+
```javascript
|
|
1390
|
+
// 3. pages/api/profile.get.js (Protected REST API Route)
|
|
1391
|
+
module.exports = {
|
|
1392
|
+
middleware: ['jwt'],
|
|
1393
|
+
async handler(req, res) {
|
|
1394
|
+
return res.json({ user: req.user, token: req.token });
|
|
1395
|
+
},
|
|
1396
|
+
};
|
|
1397
|
+
```
|
|
1398
|
+
|
|
1318
1399
|
**With Schema Validation (same object shape):**
|
|
1319
1400
|
|
|
1320
1401
|
```javascript
|
package/bin/commands/orm-map.js
CHANGED
|
@@ -54,7 +54,7 @@ function openFile(filePath, cwd) {
|
|
|
54
54
|
if (process.platform === 'darwin') {
|
|
55
55
|
execFileSync('open', [fp], { stdio: 'ignore' });
|
|
56
56
|
} else if (process.platform === 'win32') {
|
|
57
|
-
execFileSync('
|
|
57
|
+
execFileSync('explorer.exe', [fp.replace(/\//g, '\\')], { stdio: 'ignore' });
|
|
58
58
|
} else {
|
|
59
59
|
execFileSync('xdg-open', [fp], { stdio: 'ignore' });
|
|
60
60
|
}
|
package/core/auth/index.js
CHANGED
|
@@ -8,6 +8,7 @@ const { AuthManager, AuthenticationError, DEFAULT_CONFIG } = require('./manager'
|
|
|
8
8
|
const { PolicyManager, AuthorizationError } = require('./policy');
|
|
9
9
|
const { createAuthMiddleware, setupAuthMiddleware } = require('./middleware');
|
|
10
10
|
const { hash, verify, needsRehash, generateToken, hashToken } = require('./hash');
|
|
11
|
+
const { signJwt, verifyJwt, decodeJwt } = require('./jwt');
|
|
11
12
|
const {
|
|
12
13
|
TOKEN_TYPES,
|
|
13
14
|
createAuthTokensTable,
|
|
@@ -23,50 +24,9 @@ const {
|
|
|
23
24
|
* @param {Object} [config.rememberTokens] - Remember token adapter
|
|
24
25
|
* @param {Object} [config.session] - Session configuration
|
|
25
26
|
* @param {Object} [config.rememberMe] - Remember me configuration
|
|
27
|
+
* @param {Object|boolean} [config.jwt] - JWT configuration
|
|
26
28
|
* @param {Object} [config.routes] - Route configuration
|
|
27
29
|
* @returns {AuthManager}
|
|
28
|
-
*
|
|
29
|
-
* @example
|
|
30
|
-
* const auth = createAuth({
|
|
31
|
-
* findUserById: async (id) => {
|
|
32
|
-
* return await UserRepo.findById(id);
|
|
33
|
-
* },
|
|
34
|
-
*
|
|
35
|
-
* findUserByCredentials: async (email, password) => {
|
|
36
|
-
* const user = await UserRepo.findOne({ email });
|
|
37
|
-
* if (user && await verify(password, user.password)) {
|
|
38
|
-
* return user;
|
|
39
|
-
* }
|
|
40
|
-
* return null;
|
|
41
|
-
* },
|
|
42
|
-
*
|
|
43
|
-
* // Optional: Remember me tokens
|
|
44
|
-
* rememberTokens: {
|
|
45
|
-
* create: async (userId, token, expiresAt) => {
|
|
46
|
-
* await db.knex('remember_tokens').insert({
|
|
47
|
-
* user_id: userId,
|
|
48
|
-
* token,
|
|
49
|
-
* expires_at: expiresAt,
|
|
50
|
-
* });
|
|
51
|
-
* },
|
|
52
|
-
* find: async (token) => {
|
|
53
|
-
* return await db.knex('remember_tokens').where({ token }).first();
|
|
54
|
-
* },
|
|
55
|
-
* delete: async (token) => {
|
|
56
|
-
* await db.knex('remember_tokens').where({ token }).delete();
|
|
57
|
-
* },
|
|
58
|
-
* deleteAllForUser: async (userId) => {
|
|
59
|
-
* await db.knex('remember_tokens').where({ user_id: userId }).delete();
|
|
60
|
-
* },
|
|
61
|
-
* },
|
|
62
|
-
*
|
|
63
|
-
* session: {
|
|
64
|
-
* secret: process.env.SESSION_SECRET,
|
|
65
|
-
* cookie: {
|
|
66
|
-
* maxAge: 24 * 60 * 60 * 1000, // 1 day
|
|
67
|
-
* },
|
|
68
|
-
* },
|
|
69
|
-
* });
|
|
70
30
|
*/
|
|
71
31
|
function createAuth(config) {
|
|
72
32
|
return new AuthManager(config);
|
|
@@ -82,6 +42,7 @@ function createAuth(config) {
|
|
|
82
42
|
* @param {Object} [options.session] - Session config
|
|
83
43
|
* @param {boolean} [options.rememberMe=true] - Enable remember me
|
|
84
44
|
* @param {boolean} [options.authTokens=false] - Enable auth_tokens adapter (password reset / email verify)
|
|
45
|
+
* @param {Object|boolean} [options.jwt=false] - Enable JWT support or JWT config
|
|
85
46
|
* @param {string} [options.verifiedField='email_verified_at'] - Verified timestamp column
|
|
86
47
|
* @returns {AuthManager}
|
|
87
48
|
*/
|
|
@@ -94,6 +55,7 @@ function quickAuth(options) {
|
|
|
94
55
|
session = {},
|
|
95
56
|
rememberMe = true,
|
|
96
57
|
authTokens: enableAuthTokens = false,
|
|
58
|
+
jwt = false,
|
|
97
59
|
verifiedField = 'email_verified_at',
|
|
98
60
|
} = options;
|
|
99
61
|
|
|
@@ -127,6 +89,7 @@ function quickAuth(options) {
|
|
|
127
89
|
identifierField,
|
|
128
90
|
passwordField,
|
|
129
91
|
verifiedField,
|
|
92
|
+
jwt,
|
|
130
93
|
|
|
131
94
|
session: {
|
|
132
95
|
secret: process.env.SESSION_SECRET || session.secret,
|
|
@@ -218,6 +181,11 @@ module.exports = {
|
|
|
218
181
|
needsRehash,
|
|
219
182
|
generateToken,
|
|
220
183
|
hashToken,
|
|
184
|
+
|
|
185
|
+
// JWT utilities
|
|
186
|
+
signJwt,
|
|
187
|
+
verifyJwt,
|
|
188
|
+
decodeJwt,
|
|
221
189
|
|
|
222
190
|
// Migration helpers
|
|
223
191
|
createRememberTokensTable,
|
package/core/auth/jwt.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Webspresso Auth - Zero-dependency JWT implementation
|
|
3
|
+
* Uses Node.js native crypto module for HS256 HMAC-SHA256 signatures
|
|
4
|
+
* @module core/auth/jwt
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const crypto = require('crypto');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Base64URL encode string or Buffer
|
|
11
|
+
* @param {string|Buffer} input
|
|
12
|
+
* @returns {string}
|
|
13
|
+
*/
|
|
14
|
+
function base64UrlEncode(input) {
|
|
15
|
+
const buf = Buffer.isBuffer(input) ? input : Buffer.from(input, 'utf8');
|
|
16
|
+
return buf
|
|
17
|
+
.toString('base64')
|
|
18
|
+
.replace(/=/g, '')
|
|
19
|
+
.replace(/\+/g, '-')
|
|
20
|
+
.replace(/\//g, '_');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Base64URL decode string
|
|
25
|
+
* @param {string} input
|
|
26
|
+
* @returns {string}
|
|
27
|
+
*/
|
|
28
|
+
function base64UrlDecode(input) {
|
|
29
|
+
let base64 = input.replace(/-/g, '+').replace(/_/g, '/');
|
|
30
|
+
while (base64.length % 4 !== 0) {
|
|
31
|
+
base64 += '=';
|
|
32
|
+
}
|
|
33
|
+
return Buffer.from(base64, 'base64').toString('utf8');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Parse duration string (e.g. '1h', '7d', '15m', '3600') into seconds
|
|
38
|
+
* @param {string|number} duration
|
|
39
|
+
* @returns {number} Seconds
|
|
40
|
+
*/
|
|
41
|
+
function parseDuration(duration) {
|
|
42
|
+
if (typeof duration === 'number') {
|
|
43
|
+
return duration;
|
|
44
|
+
}
|
|
45
|
+
if (typeof duration !== 'string') {
|
|
46
|
+
return 3600; // Default 1 hour
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const match = duration.trim().match(/^(\d+)\s*([smhd])?$/i);
|
|
50
|
+
if (!match) {
|
|
51
|
+
const parsed = parseInt(duration, 10);
|
|
52
|
+
return isNaN(parsed) ? 3600 : parsed;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const value = parseInt(match[1], 10);
|
|
56
|
+
const unit = (match[2] || 's').toLowerCase();
|
|
57
|
+
|
|
58
|
+
switch (unit) {
|
|
59
|
+
case 's': return value;
|
|
60
|
+
case 'm': return value * 60;
|
|
61
|
+
case 'h': return value * 3600;
|
|
62
|
+
case 'd': return value * 86400;
|
|
63
|
+
default: return value;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Sign payload to create HS256 JWT string
|
|
69
|
+
* @param {Object} payload - Payload object
|
|
70
|
+
* @param {string} secret - Secret key for signing
|
|
71
|
+
* @param {Object} [options] - Signing options
|
|
72
|
+
* @param {string|number} [options.expiresIn='24h'] - Expiration time (seconds or '1h', '7d', etc.)
|
|
73
|
+
* @param {string} [options.algorithm='HS256'] - Signature algorithm (HS256 supported)
|
|
74
|
+
* @param {string} [options.issuer] - Token issuer (iss)
|
|
75
|
+
* @param {string} [options.subject] - Token subject (sub)
|
|
76
|
+
* @param {string} [options.audience] - Token audience (aud)
|
|
77
|
+
* @returns {string} JWT string
|
|
78
|
+
*/
|
|
79
|
+
function signJwt(payload, secret, options = {}) {
|
|
80
|
+
if (!secret) {
|
|
81
|
+
throw new Error('Secret is required to sign JWT');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const algorithm = options.algorithm || 'HS256';
|
|
85
|
+
if (algorithm !== 'HS256') {
|
|
86
|
+
throw new Error(`Unsupported algorithm '${algorithm}'. Only HS256 is supported.`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const header = {
|
|
90
|
+
alg: algorithm,
|
|
91
|
+
typ: 'JWT',
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const nowSec = Math.floor(Date.now() / 1000);
|
|
95
|
+
const claims = {
|
|
96
|
+
iat: nowSec,
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
if (options.expiresIn !== false) {
|
|
100
|
+
const ttlSec = parseDuration(options.expiresIn ?? '24h');
|
|
101
|
+
claims.exp = nowSec + ttlSec;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (options.issuer) claims.iss = options.issuer;
|
|
105
|
+
if (options.subject) claims.sub = options.subject;
|
|
106
|
+
if (options.audience) claims.aud = options.audience;
|
|
107
|
+
|
|
108
|
+
const fullPayload = {
|
|
109
|
+
...claims,
|
|
110
|
+
...payload,
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const encodedHeader = base64UrlEncode(JSON.stringify(header));
|
|
114
|
+
const encodedPayload = base64UrlEncode(JSON.stringify(fullPayload));
|
|
115
|
+
|
|
116
|
+
const signingInput = `${encodedHeader}.${encodedPayload}`;
|
|
117
|
+
const signature = crypto
|
|
118
|
+
.createHmac('sha256', secret)
|
|
119
|
+
.update(signingInput)
|
|
120
|
+
.digest();
|
|
121
|
+
|
|
122
|
+
const encodedSignature = base64UrlEncode(signature);
|
|
123
|
+
|
|
124
|
+
return `${signingInput}.${encodedSignature}`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Verify and decode HS256 JWT string
|
|
129
|
+
* @param {string} token - JWT string
|
|
130
|
+
* @param {string} secret - Secret key
|
|
131
|
+
* @param {Object} [options] - Verification options
|
|
132
|
+
* @param {boolean} [options.ignoreExpiration=false] - Ignore token expiration
|
|
133
|
+
* @param {string} [options.issuer] - Expected issuer
|
|
134
|
+
* @param {string} [options.audience] - Expected audience
|
|
135
|
+
* @returns {Object} Decoded payload
|
|
136
|
+
* @throws {Error} If token is invalid or expired
|
|
137
|
+
*/
|
|
138
|
+
function verifyJwt(token, secret, options = {}) {
|
|
139
|
+
if (!secret) {
|
|
140
|
+
throw new Error('Secret is required to verify JWT');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (!token || typeof token !== 'string') {
|
|
144
|
+
throw new Error('JWT token must be a non-empty string');
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const parts = token.split('.');
|
|
148
|
+
if (parts.length !== 3) {
|
|
149
|
+
throw new Error('Invalid JWT format');
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const [encodedHeader, encodedPayload, encodedSignature] = parts;
|
|
153
|
+
|
|
154
|
+
let header;
|
|
155
|
+
let payload;
|
|
156
|
+
|
|
157
|
+
try {
|
|
158
|
+
header = JSON.parse(base64UrlDecode(encodedHeader));
|
|
159
|
+
} catch (e) {
|
|
160
|
+
throw new Error('Invalid JWT header JSON');
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
try {
|
|
164
|
+
payload = JSON.parse(base64UrlDecode(encodedPayload));
|
|
165
|
+
} catch (e) {
|
|
166
|
+
throw new Error('Invalid JWT payload JSON');
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (header.alg !== 'HS256') {
|
|
170
|
+
throw new Error(`Unsupported algorithm '${header.alg}' in JWT header`);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Re-compute signature
|
|
174
|
+
const signingInput = `${encodedHeader}.${encodedPayload}`;
|
|
175
|
+
const expectedSignatureBuf = crypto
|
|
176
|
+
.createHmac('sha256', secret)
|
|
177
|
+
.update(signingInput)
|
|
178
|
+
.digest();
|
|
179
|
+
|
|
180
|
+
const actualSignatureBuf = Buffer.from(encodedSignature.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
|
181
|
+
|
|
182
|
+
if (
|
|
183
|
+
expectedSignatureBuf.length !== actualSignatureBuf.length ||
|
|
184
|
+
!crypto.timingSafeEqual(expectedSignatureBuf, actualSignatureBuf)
|
|
185
|
+
) {
|
|
186
|
+
throw new Error('Invalid JWT signature');
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Check claims
|
|
190
|
+
const nowSec = Math.floor(Date.now() / 1000);
|
|
191
|
+
|
|
192
|
+
if (!options.ignoreExpiration && typeof payload.exp === 'number') {
|
|
193
|
+
if (nowSec >= payload.exp) {
|
|
194
|
+
throw new Error('JWT token has expired');
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (options.issuer && payload.iss !== options.issuer) {
|
|
199
|
+
throw new Error(`Invalid JWT issuer (expected ${options.issuer}, got ${payload.iss})`);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (options.audience && payload.aud !== options.audience) {
|
|
203
|
+
throw new Error(`Invalid JWT audience (expected ${options.audience}, got ${payload.aud})`);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return payload;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Decode JWT without verifying signature
|
|
211
|
+
* @param {string} token
|
|
212
|
+
* @returns {{ header: Object, payload: Object }|null}
|
|
213
|
+
*/
|
|
214
|
+
function decodeJwt(token) {
|
|
215
|
+
if (!token || typeof token !== 'string') return null;
|
|
216
|
+
const parts = token.split('.');
|
|
217
|
+
if (parts.length !== 3) return null;
|
|
218
|
+
|
|
219
|
+
try {
|
|
220
|
+
const header = JSON.parse(base64UrlDecode(parts[0]));
|
|
221
|
+
const payload = JSON.parse(base64UrlDecode(parts[1]));
|
|
222
|
+
return { header, payload };
|
|
223
|
+
} catch (e) {
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
module.exports = {
|
|
229
|
+
signJwt,
|
|
230
|
+
verifyJwt,
|
|
231
|
+
decodeJwt,
|
|
232
|
+
base64UrlEncode,
|
|
233
|
+
base64UrlDecode,
|
|
234
|
+
parseDuration,
|
|
235
|
+
};
|
package/core/auth/manager.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
const { generateToken, hashToken } = require('./hash');
|
|
8
8
|
const { PolicyManager } = require('./policy');
|
|
9
|
+
const { signJwt, verifyJwt, decodeJwt } = require('./jwt');
|
|
9
10
|
const {
|
|
10
11
|
TOKEN_TYPES,
|
|
11
12
|
createAuthToken,
|
|
@@ -47,6 +48,13 @@ const DEFAULT_CONFIG = {
|
|
|
47
48
|
cookieName: 'remember_token',
|
|
48
49
|
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
|
|
49
50
|
},
|
|
51
|
+
jwt: {
|
|
52
|
+
enabled: false,
|
|
53
|
+
secret: null,
|
|
54
|
+
refreshSecret: null,
|
|
55
|
+
expiresIn: '24h',
|
|
56
|
+
refreshExpiresIn: '30d',
|
|
57
|
+
},
|
|
50
58
|
routes: {
|
|
51
59
|
login: '/login',
|
|
52
60
|
logout: '/logout',
|
|
@@ -98,6 +106,30 @@ class AuthManager {
|
|
|
98
106
|
emailVerification: config.notifications?.emailVerification || null,
|
|
99
107
|
welcome: config.notifications?.welcome || null,
|
|
100
108
|
};
|
|
109
|
+
|
|
110
|
+
if (config.jwt) {
|
|
111
|
+
const jwtSecret = typeof config.jwt === 'object' && config.jwt.secret
|
|
112
|
+
? config.jwt.secret
|
|
113
|
+
: (config.session?.secret || process.env.JWT_SECRET || process.env.AUTH_SESSION_SECRET || 'webspresso-jwt-secret');
|
|
114
|
+
const refreshSecret = typeof config.jwt === 'object' && config.jwt.refreshSecret
|
|
115
|
+
? config.jwt.refreshSecret
|
|
116
|
+
: (process.env.JWT_REFRESH_SECRET || jwtSecret);
|
|
117
|
+
const expiresIn = typeof config.jwt === 'object' && config.jwt.expiresIn
|
|
118
|
+
? config.jwt.expiresIn
|
|
119
|
+
: '24h';
|
|
120
|
+
const refreshExpiresIn = typeof config.jwt === 'object' && config.jwt.refreshExpiresIn
|
|
121
|
+
? config.jwt.refreshExpiresIn
|
|
122
|
+
: '30d';
|
|
123
|
+
this.jwt = {
|
|
124
|
+
enabled: true,
|
|
125
|
+
secret: jwtSecret,
|
|
126
|
+
refreshSecret,
|
|
127
|
+
expiresIn,
|
|
128
|
+
refreshExpiresIn,
|
|
129
|
+
};
|
|
130
|
+
} else {
|
|
131
|
+
this.jwt = null;
|
|
132
|
+
}
|
|
101
133
|
|
|
102
134
|
// Policy manager instance
|
|
103
135
|
this.policies = new PolicyManager();
|
|
@@ -144,6 +176,8 @@ class AuthManager {
|
|
|
144
176
|
}
|
|
145
177
|
|
|
146
178
|
const mergedCookie = {
|
|
179
|
+
httpOnly: true,
|
|
180
|
+
sameSite: 'lax',
|
|
147
181
|
...DEFAULT_CONFIG.session.cookie,
|
|
148
182
|
...(config.cookie || {}),
|
|
149
183
|
};
|
|
@@ -170,6 +204,42 @@ class AuthManager {
|
|
|
170
204
|
const self = this;
|
|
171
205
|
|
|
172
206
|
return {
|
|
207
|
+
manager: self,
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Generate JWT access token for user
|
|
211
|
+
*/
|
|
212
|
+
generateUserToken(user, options) {
|
|
213
|
+
return self.generateUserToken(user, options);
|
|
214
|
+
},
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Generate JWT refresh token for user
|
|
218
|
+
*/
|
|
219
|
+
generateRefreshToken(user, options) {
|
|
220
|
+
return self.generateRefreshToken(user, options);
|
|
221
|
+
},
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Refresh access token using refresh token
|
|
225
|
+
*/
|
|
226
|
+
async refreshAccessToken(refreshToken, options) {
|
|
227
|
+
return await self.refreshAccessToken(refreshToken, options);
|
|
228
|
+
},
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Create JWT payload
|
|
232
|
+
*/
|
|
233
|
+
createJwt(payload, options) {
|
|
234
|
+
return self.createJwt(payload, options);
|
|
235
|
+
},
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Verify JWT token
|
|
239
|
+
*/
|
|
240
|
+
verifyJwt(token, options) {
|
|
241
|
+
return self.verifyJwt(token, options);
|
|
242
|
+
},
|
|
173
243
|
/**
|
|
174
244
|
* Attempt login with credentials
|
|
175
245
|
* @param {string} identifier - Email or username
|
|
@@ -598,6 +668,129 @@ class AuthManager {
|
|
|
598
668
|
await this.notifications.welcome(user, {});
|
|
599
669
|
}
|
|
600
670
|
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* Create JWT token
|
|
674
|
+
* @param {Object} payload
|
|
675
|
+
* @param {Object} [options]
|
|
676
|
+
* @returns {string} JWT string
|
|
677
|
+
*/
|
|
678
|
+
createJwt(payload, options = {}) {
|
|
679
|
+
const secret = options.secret || this.jwt?.secret || this.config.session?.secret || process.env.JWT_SECRET;
|
|
680
|
+
if (!secret) {
|
|
681
|
+
throw new Error('JWT secret is missing');
|
|
682
|
+
}
|
|
683
|
+
const expiresIn = options.expiresIn || this.jwt?.expiresIn || '24h';
|
|
684
|
+
return signJwt(payload, secret, { expiresIn, ...options });
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Verify JWT token
|
|
689
|
+
* @param {string} token
|
|
690
|
+
* @param {Object} [options]
|
|
691
|
+
* @returns {Object} Decoded payload
|
|
692
|
+
*/
|
|
693
|
+
verifyJwt(token, options = {}) {
|
|
694
|
+
const secret = options.secret || this.jwt?.secret || this.config.session?.secret || process.env.JWT_SECRET;
|
|
695
|
+
if (!secret) {
|
|
696
|
+
throw new Error('JWT secret is missing');
|
|
697
|
+
}
|
|
698
|
+
const payload = verifyJwt(token, secret, options);
|
|
699
|
+
if (options.isAccess !== false && payload.type === 'refresh') {
|
|
700
|
+
throw new Error('Refresh token cannot be used as an access token');
|
|
701
|
+
}
|
|
702
|
+
return payload;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* Generate JWT token for user
|
|
707
|
+
* @param {Object} user
|
|
708
|
+
* @param {Object} [options]
|
|
709
|
+
* @returns {string} JWT string
|
|
710
|
+
*/
|
|
711
|
+
generateUserToken(user, options = {}) {
|
|
712
|
+
if (!user || !user.id) {
|
|
713
|
+
throw new Error('User object with id is required');
|
|
714
|
+
}
|
|
715
|
+
const payload = {
|
|
716
|
+
id: user.id,
|
|
717
|
+
type: 'access',
|
|
718
|
+
[this.identifierField]: user[this.identifierField],
|
|
719
|
+
...options.payload,
|
|
720
|
+
};
|
|
721
|
+
return this.createJwt(payload, options);
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* Generate JWT Refresh token for user
|
|
726
|
+
* @param {Object} user
|
|
727
|
+
* @param {Object} [options]
|
|
728
|
+
* @returns {string} Refresh token string
|
|
729
|
+
*/
|
|
730
|
+
generateRefreshToken(user, options = {}) {
|
|
731
|
+
if (!user || !user.id) {
|
|
732
|
+
throw new Error('User object with id is required');
|
|
733
|
+
}
|
|
734
|
+
const secret = options.secret || this.jwt?.refreshSecret || this.jwt?.secret || this.config.session?.secret || process.env.JWT_REFRESH_SECRET || process.env.JWT_SECRET;
|
|
735
|
+
if (!secret) {
|
|
736
|
+
throw new Error('JWT refresh secret is missing');
|
|
737
|
+
}
|
|
738
|
+
const expiresIn = options.expiresIn || this.jwt?.refreshExpiresIn || '30d';
|
|
739
|
+
const payload = {
|
|
740
|
+
id: user.id,
|
|
741
|
+
type: 'refresh',
|
|
742
|
+
jti: generateToken(16),
|
|
743
|
+
[this.identifierField]: user[this.identifierField],
|
|
744
|
+
...options.payload,
|
|
745
|
+
};
|
|
746
|
+
return signJwt(payload, secret, { expiresIn, ...options });
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* Refresh access token using valid refresh token
|
|
751
|
+
* @param {string} refreshToken
|
|
752
|
+
* @param {Object} [options]
|
|
753
|
+
* @returns {Promise<{ accessToken: string, refreshToken: string, user: Object }>}
|
|
754
|
+
*/
|
|
755
|
+
async refreshAccessToken(refreshToken, options = {}) {
|
|
756
|
+
const secret = options.secret || this.jwt?.refreshSecret || this.jwt?.secret || this.config.session?.secret || process.env.JWT_REFRESH_SECRET || process.env.JWT_SECRET;
|
|
757
|
+
if (!secret) {
|
|
758
|
+
throw new Error('JWT refresh secret is missing');
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
const payload = verifyJwt(refreshToken, secret, options);
|
|
762
|
+
if (payload.type !== 'refresh') {
|
|
763
|
+
throw new AuthenticationError('Invalid refresh token type', 'INVALID_REFRESH_TOKEN');
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
const user = await this.findUserById(payload.id);
|
|
767
|
+
if (!user) {
|
|
768
|
+
throw new AuthenticationError('User not found for refresh token', 'USER_NOT_FOUND');
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
const accessToken = this.generateUserToken(user, options.accessOptions);
|
|
772
|
+
const rotate = options.rotate ?? true;
|
|
773
|
+
const newRefreshToken = rotate ? this.generateRefreshToken(user, options.refreshOptions) : refreshToken;
|
|
774
|
+
|
|
775
|
+
return {
|
|
776
|
+
accessToken,
|
|
777
|
+
refreshToken: newRefreshToken,
|
|
778
|
+
user,
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/**
|
|
783
|
+
* Get requireJwt guard middleware for Express routes
|
|
784
|
+
* @param {Object} [options]
|
|
785
|
+
* @returns {Function} Express middleware
|
|
786
|
+
*/
|
|
787
|
+
requireJwt(options = {}) {
|
|
788
|
+
if (!this._authMiddleware) {
|
|
789
|
+
const { createAuthMiddleware } = require('./middleware');
|
|
790
|
+
this._authMiddleware = createAuthMiddleware(this);
|
|
791
|
+
}
|
|
792
|
+
return this._authMiddleware.requireJwt(options);
|
|
793
|
+
}
|
|
601
794
|
}
|
|
602
795
|
|
|
603
796
|
module.exports = {
|