webspresso 0.0.84 → 0.0.86

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
@@ -808,6 +808,33 @@ Options:
808
808
 
809
809
  See **`doc/index.html#admin-user-management`** and **Session authentication** in **`.agents/skills/webspresso-usage/REFERENCE-framework.md`** for the split between **`adminUser`** and **`createApp({ auth })`**.
810
810
 
811
+ **3-State Table Column Sorting & Configuration:**
812
+
813
+ Admin Panel table headers support interactive 3-state column sorting:
814
+ - **State 1 (`Unsorted`)**: Default state (`↕` icon).
815
+ - **State 2 (`ASC`)**: 1st click sorts ascending (`▲` icon, `?sort=col&order=asc`).
816
+ - **State 3 (`DESC`)**: 2nd click sorts descending (`▼` icon, `?sort=col&order=desc`).
817
+ - **State 4 (`Unsorted`)**: 3rd click clears sorting and reverts to default primary key ordering.
818
+
819
+ Configuration options:
820
+ - **Column-level**: Standard scalar columns (`string`, `number`, `boolean`, `timestamp`) are sortable by default. Disable or enable per column:
821
+ ```javascript
822
+ schema: zdb.schema({
823
+ name: zdb.string({ sortable: true }),
824
+ secret_notes: zdb.text().config({ sortable: false }), // or zdb.text({ sortable: false })
825
+ })
826
+ ```
827
+ - **Model-level**: Restrict sortable columns or disable sorting completely on a model in `defineModel`:
828
+ ```javascript
829
+ admin: {
830
+ enabled: true,
831
+ sortableColumns: ['name', 'price'], // Only name and price are sortable
832
+ // Or disable all sorting:
833
+ // sortable: false,
834
+ }
835
+ ```
836
+
837
+
811
838
 
812
839
  **Custom Admin Pages (registerModule):**
813
840
 
@@ -1316,6 +1343,86 @@ createApp({
1316
1343
  });
1317
1344
  ```
1318
1345
 
1346
+ ### Authentication & JWT Support (`quickAuth`)
1347
+
1348
+ Webspresso provides a zero-dependency **Dual Authentication** system (`webspresso/core/auth`):
1349
+ - **Session + Cookie**: Stateful auth for browser SSR routes and Admin Panel (`/`, `/_admin`).
1350
+ - **JWT + Refresh Token**: Stateless HS256 auth for REST APIs, Mobile Apps, and SPAs (`/api/*`).
1351
+
1352
+ ```javascript
1353
+ // createApp setup with quickAuth
1354
+ const { quickAuth } = require('webspresso/core/auth');
1355
+
1356
+ const auth = quickAuth({
1357
+ db,
1358
+ userModel: 'User',
1359
+ jwt: {
1360
+ expiresIn: '15m', // Access token duration (default: 24h)
1361
+ refreshExpiresIn: '30d', // Refresh token duration (default: 30d)
1362
+ },
1363
+ });
1364
+
1365
+ createApp({
1366
+ pagesDir: './pages',
1367
+ db,
1368
+ auth,
1369
+ });
1370
+ ```
1371
+
1372
+ **File-Based API Route Examples (`pages/api/*`):**
1373
+
1374
+ ```javascript
1375
+ // 1. pages/api/auth/login.post.js (Login & Token Generation)
1376
+ module.exports = {
1377
+ schema: ({ z }) => ({
1378
+ body: z.object({
1379
+ email: z.string().email(),
1380
+ password: z.string().min(1),
1381
+ }),
1382
+ }),
1383
+ async handler(req, res) {
1384
+ const { email, password } = req.input.body;
1385
+ const user = await req.auth.attempt(email, password);
1386
+ if (!user) return res.status(401).json({ error: 'Invalid credentials' });
1387
+
1388
+ const accessToken = req.auth.generateUserToken(user);
1389
+ const refreshToken = req.auth.generateRefreshToken(user);
1390
+
1391
+ return res.json({ accessToken, refreshToken, user: { id: user.id, email: user.email } });
1392
+ },
1393
+ };
1394
+ ```
1395
+
1396
+ ```javascript
1397
+ // 2. pages/api/auth/refresh.post.js (Token Rotation Endpoint)
1398
+ module.exports = {
1399
+ schema: ({ z }) => ({
1400
+ body: z.object({
1401
+ refreshToken: z.string(),
1402
+ }),
1403
+ }),
1404
+ async handler(req, res) {
1405
+ const { refreshToken } = req.input.body;
1406
+ try {
1407
+ const result = await req.auth.refreshAccessToken(refreshToken, { rotate: true });
1408
+ return res.json({ accessToken: result.accessToken, refreshToken: result.refreshToken });
1409
+ } catch (err) {
1410
+ return res.status(401).json({ error: err.message });
1411
+ }
1412
+ },
1413
+ };
1414
+ ```
1415
+
1416
+ ```javascript
1417
+ // 3. pages/api/profile.get.js (Protected REST API Route)
1418
+ module.exports = {
1419
+ middleware: ['jwt'],
1420
+ async handler(req, res) {
1421
+ return res.json({ user: req.user, token: req.token });
1422
+ },
1423
+ };
1424
+ ```
1425
+
1319
1426
  **With Schema Validation (same object shape):**
1320
1427
 
1321
1428
  ```javascript
@@ -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('cmd', ['/c', 'start', '', fp], { stdio: 'ignore' });
57
+ execFileSync('explorer.exe', [fp.replace(/\//g, '\\')], { stdio: 'ignore' });
58
58
  } else {
59
59
  execFileSync('xdg-open', [fp], { stdio: 'ignore' });
60
60
  }
@@ -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,
@@ -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
+ };
@@ -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 = {