@zero-server/sdk 0.9.1 → 0.9.2

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.
Files changed (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -443
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +465 -465
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +137 -137
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +255 -255
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/cluster.d.ts +75 -75
  113. package/types/env.d.ts +80 -80
  114. package/types/errors.d.ts +316 -316
  115. package/types/fetch.d.ts +43 -43
  116. package/types/grpc.d.ts +432 -432
  117. package/types/index.d.ts +384 -384
  118. package/types/lifecycle.d.ts +60 -60
  119. package/types/middleware.d.ts +320 -320
  120. package/types/observe.d.ts +304 -304
  121. package/types/orm.d.ts +1887 -1887
  122. package/types/request.d.ts +109 -109
  123. package/types/response.d.ts +157 -157
  124. package/types/router.d.ts +78 -78
  125. package/types/sse.d.ts +78 -78
  126. package/types/websocket.d.ts +126 -126
@@ -1,409 +1,409 @@
1
- /**
2
- * @module auth/trustedDevice
3
- * @description Trusted Device / "Remember Me" middleware for 2FA.
4
- * After successful 2FA verification, issues an encrypted device-trust
5
- * token stored as an HttpOnly, Secure, SameSite=Strict cookie.
6
- *
7
- * Subsequent requests skip the 2FA prompt if the trust token is valid.
8
- * Supports secret rotation, IP binding, and revocation.
9
- *
10
- * Uses AES-256-GCM encryption — tokens are encrypted, not just signed,
11
- * preventing information leakage.
12
- *
13
- * @example
14
- * const { trustedDevice, twoFactor } = require('@zero-server/sdk');
15
- *
16
- * app.post('/verify-2fa', twoFactor.verifyTOTPMiddleware({
17
- * getSecret: (req) => req.user.totpSecret,
18
- * }), trustedDevice.issue({
19
- * secret: process.env.DEVICE_TRUST_SECRET,
20
- * }));
21
- *
22
- * app.use(twoFactor.require2FA({
23
- * isEnabled: (req) => req.user.totpEnabled,
24
- * trustedDevice: trustedDevice.verify({
25
- * secret: process.env.DEVICE_TRUST_SECRET,
26
- * }),
27
- * }));
28
- */
29
-
30
- const crypto = require('crypto');
31
- const log = require('../debug')('zero:trustedDevice');
32
-
33
- // -- Constants -----------------------------------------------
34
-
35
- const DEFAULT_MAX_AGE = 30 * 24 * 60 * 60 * 1000; // 30 days
36
- const DEFAULT_COOKIE_NAME = '_dt';
37
- const IV_LENGTH = 12;
38
- const TAG_LENGTH = 16;
39
-
40
- // -- Encryption Helpers --------------------------------------
41
-
42
- /**
43
- * Derive a 256-bit key from a secret string using SHA-256.
44
- * @private
45
- * @param {string} secret
46
- * @returns {Buffer}
47
- */
48
- function _deriveKey(secret)
49
- {
50
- return crypto.createHash('sha256').update(secret).digest();
51
- }
52
-
53
- /**
54
- * Encrypt a payload using AES-256-GCM.
55
- * @private
56
- * @param {object} payload
57
- * @param {string} secret
58
- * @returns {string} Base64-encoded encrypted token.
59
- */
60
- function _encrypt(payload, secret)
61
- {
62
- const key = _deriveKey(secret);
63
- const iv = crypto.randomBytes(IV_LENGTH);
64
- const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
65
-
66
- const json = JSON.stringify(payload);
67
- const encrypted = Buffer.concat([cipher.update(json, 'utf8'), cipher.final()]);
68
- const tag = cipher.getAuthTag();
69
-
70
- // Format: iv || tag || ciphertext
71
- return Buffer.concat([iv, tag, encrypted]).toString('base64url');
72
- }
73
-
74
- /**
75
- * Decrypt a token using AES-256-GCM.
76
- * @private
77
- * @param {string} token
78
- * @param {string} secret
79
- * @returns {object|null} Decoded payload or null if invalid.
80
- */
81
- function _decrypt(token, secret)
82
- {
83
- try
84
- {
85
- const buf = Buffer.from(token, 'base64url');
86
- if (buf.length < IV_LENGTH + TAG_LENGTH + 1) return null;
87
-
88
- const key = _deriveKey(secret);
89
- const iv = buf.subarray(0, IV_LENGTH);
90
- const tag = buf.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH);
91
- const ciphertext = buf.subarray(IV_LENGTH + TAG_LENGTH);
92
-
93
- const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
94
- decipher.setAuthTag(tag);
95
-
96
- const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
97
- return JSON.parse(decrypted.toString('utf8'));
98
- }
99
- catch (_)
100
- {
101
- return null;
102
- }
103
- }
104
-
105
- // -- Cookie Helpers ------------------------------------------
106
-
107
- /**
108
- * Set a cookie on the response.
109
- * @private
110
- */
111
- function _setCookie(res, name, value, maxAgeMs)
112
- {
113
- const maxAgeSec = Math.floor(maxAgeMs / 1000);
114
- const raw = res.raw || res;
115
- const existing = raw.getHeader('set-cookie') || [];
116
- const cookies = Array.isArray(existing) ? existing : [existing];
117
- cookies.push(
118
- `${name}=${value}; HttpOnly; Secure; SameSite=Strict; Max-Age=${maxAgeSec}; Path=/`
119
- );
120
- raw.setHeader('Set-Cookie', cookies);
121
- }
122
-
123
- /**
124
- * Clear a cookie.
125
- * @private
126
- */
127
- function _clearCookie(res, name)
128
- {
129
- const raw = res.raw || res;
130
- const existing = raw.getHeader('set-cookie') || [];
131
- const cookies = Array.isArray(existing) ? existing : [existing];
132
- cookies.push(
133
- `${name}=; HttpOnly; Secure; SameSite=Strict; Max-Age=0; Path=/`
134
- );
135
- raw.setHeader('Set-Cookie', cookies);
136
- }
137
-
138
- /**
139
- * Read a cookie value from the request.
140
- * @private
141
- */
142
- function _readCookie(req, name)
143
- {
144
- // Use parsed cookies if available (cookieParser middleware)
145
- if (req.cookies && req.cookies[name]) return req.cookies[name];
146
-
147
- // Manual parse from header
148
- const header = req.headers && req.headers.cookie;
149
- if (!header) return null;
150
-
151
- const match = header.split(';').find(c => c.trim().startsWith(name + '='));
152
- if (!match) return null;
153
- return match.split('=').slice(1).join('=').trim();
154
- }
155
-
156
- // -- Issue Middleware -----------------------------------------
157
-
158
- /**
159
- * Middleware that issues a trusted-device token after successful 2FA.
160
- * Should be placed AFTER the 2FA verification middleware in the chain.
161
- *
162
- * @param {object} opts - Options.
163
- * @param {string} opts.secret - Encryption secret (min 32 chars recommended).
164
- * @param {number} [opts.maxAge=2592000000] - Trust duration in ms (default 30 days).
165
- * @param {string} [opts.cookieName='_dt'] - Cookie name.
166
- * @param {Function} [opts.fingerprint] - `(req) => string` device fingerprint.
167
- * Defaults to User-Agent hash.
168
- * @param {Function} [opts.getUserId] - `(req) => string` user identifier.
169
- * Defaults to `req.user.id || req.user.sub`.
170
- * @returns {Function} Middleware `(req, res, next) => void`.
171
- *
172
- * @example
173
- * app.post('/verify-2fa', verifyTOTPMiddleware({...}), trustedDevice.issue({
174
- * secret: process.env.DEVICE_TRUST_SECRET,
175
- * maxAge: 30 * 24 * 60 * 60 * 1000,
176
- * fingerprint: (req) => req.body.deviceFingerprint,
177
- * }));
178
- */
179
- function issue(opts)
180
- {
181
- if (!opts || !opts.secret)
182
- throw new Error('trustedDevice.issue() requires a secret');
183
-
184
- const secret = opts.secret;
185
- const maxAge = opts.maxAge || DEFAULT_MAX_AGE;
186
- const cookieName = opts.cookieName || DEFAULT_COOKIE_NAME;
187
- const getFingerprint = opts.fingerprint || _defaultFingerprint;
188
- const getUserId = opts.getUserId || _defaultGetUserId;
189
-
190
- return async function _issueDeviceTrust(req, res, next)
191
- {
192
- try
193
- {
194
- const userId = await getUserId(req);
195
- const fp = await getFingerprint(req);
196
-
197
- const payload = {
198
- uid: userId,
199
- fp: fp ? crypto.createHash('sha256').update(fp).digest('hex').substring(0, 16) : null,
200
- iat: Date.now(),
201
- exp: Date.now() + maxAge,
202
- };
203
-
204
- const token = _encrypt(payload, secret);
205
- _setCookie(res, cookieName, token, maxAge);
206
-
207
- log.info('device trust token issued for user %s', userId);
208
- }
209
- catch (err)
210
- {
211
- log.error('device trust issue error: %s', err.message);
212
- }
213
-
214
- next();
215
- };
216
- }
217
-
218
- // -- Verify Function -----------------------------------------
219
-
220
- /**
221
- * Create a verification function for use with `require2FA` middleware.
222
- * Returns a function `(req) => boolean` that checks for a valid trust token.
223
- *
224
- * @param {object} opts - Options.
225
- * @param {string} opts.secret - Encryption secret.
226
- * @param {string|string[]} [opts.previousSecrets] - Previous secrets for rotation.
227
- * @param {string} [opts.cookieName='_dt'] - Cookie name.
228
- * @param {Function} [opts.fingerprint] - `(req) => string` device fingerprint.
229
- * @param {Function} [opts.getUserId] - `(req) => string`.
230
- * @param {boolean} [opts.checkIP=false] - Verify IP range (/24 CIDR match).
231
- * @returns {Function} `(req) => Promise<boolean>` trust check function.
232
- *
233
- * @example
234
- * app.use(require2FA({
235
- * isEnabled: (req) => req.user.totpEnabled,
236
- * trustedDevice: trustedDevice.verify({
237
- * secret: process.env.DEVICE_TRUST_SECRET,
238
- * }),
239
- * }));
240
- */
241
- function verify(opts)
242
- {
243
- if (!opts || !opts.secret)
244
- throw new Error('trustedDevice.verify() requires a secret');
245
-
246
- const secrets = [opts.secret];
247
- if (opts.previousSecrets)
248
- {
249
- const prev = Array.isArray(opts.previousSecrets) ? opts.previousSecrets : [opts.previousSecrets];
250
- secrets.push(...prev);
251
- }
252
-
253
- const cookieName = opts.cookieName || DEFAULT_COOKIE_NAME;
254
- const getFingerprint = opts.fingerprint || _defaultFingerprint;
255
- const getUserId = opts.getUserId || _defaultGetUserId;
256
- const checkIP = opts.checkIP || false;
257
-
258
- return async function _verifyDeviceTrust(req)
259
- {
260
- const token = _readCookie(req, cookieName);
261
- if (!token) return false;
262
-
263
- // Try each secret (current + rotated)
264
- let payload = null;
265
- for (const s of secrets)
266
- {
267
- payload = _decrypt(token, s);
268
- if (payload) break;
269
- }
270
-
271
- if (!payload) return false;
272
-
273
- // Check expiry
274
- if (Date.now() >= payload.exp)
275
- {
276
- log.debug('device trust token expired');
277
- return false;
278
- }
279
-
280
- // Check user ID
281
- try
282
- {
283
- const userId = await getUserId(req);
284
- if (String(payload.uid) !== String(userId)) return false;
285
- }
286
- catch (_)
287
- {
288
- return false;
289
- }
290
-
291
- // Check fingerprint if present
292
- if (payload.fp)
293
- {
294
- try
295
- {
296
- const fp = await getFingerprint(req);
297
- if (fp)
298
- {
299
- const currentFP = crypto.createHash('sha256').update(fp).digest('hex').substring(0, 16);
300
- if (payload.fp !== currentFP)
301
- {
302
- log.debug('device fingerprint mismatch');
303
- return false;
304
- }
305
- }
306
- }
307
- catch (_)
308
- {
309
- return false;
310
- }
311
- }
312
-
313
- // Optional IP range check (/24 CIDR)
314
- if (checkIP && payload.ip)
315
- {
316
- const currentIP = req.ip || req.socket?.remoteAddress || '';
317
- if (!_matchIPSubnet(payload.ip, currentIP))
318
- {
319
- log.debug('IP range mismatch');
320
- return false;
321
- }
322
- }
323
-
324
- log.debug('device trust token valid for user %s', payload.uid);
325
- return true;
326
- };
327
- }
328
-
329
- // -- Revocation Middleware ------------------------------------
330
-
331
- /**
332
- * Middleware that revokes the trusted-device cookie.
333
- * Call this on logout, password change, or 2FA re-enrollment.
334
- *
335
- * @param {object} [opts] - Options.
336
- * @param {string} [opts.cookieName='_dt'] - Cookie name.
337
- * @returns {Function} Middleware `(req, res, next) => void`.
338
- *
339
- * @example
340
- * app.post('/logout', trustedDevice.revoke(), (req, res) => {
341
- * res.json({ ok: true });
342
- * });
343
- */
344
- function revoke(opts = {})
345
- {
346
- const cookieName = opts.cookieName || DEFAULT_COOKIE_NAME;
347
-
348
- return function _revokeDeviceTrust(req, res, next)
349
- {
350
- _clearCookie(res, cookieName);
351
- log.info('device trust token revoked');
352
- next();
353
- };
354
- }
355
-
356
- // -- Internal Helpers ----------------------------------------
357
-
358
- /**
359
- * Default fingerprint: hash of User-Agent.
360
- * @private
361
- */
362
- function _defaultFingerprint(req)
363
- {
364
- return req.headers && req.headers['user-agent'] || '';
365
- }
366
-
367
- /**
368
- * Default user ID extraction.
369
- * @private
370
- */
371
- function _defaultGetUserId(req)
372
- {
373
- if (!req.user) throw new Error('No user on request — authentication middleware required');
374
- return req.user.id || req.user.sub || req.user._id;
375
- }
376
-
377
- /**
378
- * Check if two IPs are in the same /24 subnet (IPv4 only).
379
- * @private
380
- * @param {string} storedIP
381
- * @param {string} currentIP
382
- * @returns {boolean}
383
- */
384
- function _matchIPSubnet(storedIP, currentIP)
385
- {
386
- const storedParts = storedIP.split('.');
387
- const currentParts = currentIP.split('.');
388
- if (storedParts.length !== 4 || currentParts.length !== 4) return false;
389
- return storedParts[0] === currentParts[0] &&
390
- storedParts[1] === currentParts[1] &&
391
- storedParts[2] === currentParts[2];
392
- }
393
-
394
- // -- Exports -------------------------------------------------
395
-
396
- const trustedDevice = {
397
- issue,
398
- verify,
399
- revoke,
400
- };
401
-
402
- module.exports = {
403
- trustedDevice,
404
- // Internals for testing
405
- _encrypt,
406
- _decrypt,
407
- _deriveKey,
408
- _matchIPSubnet,
409
- };
1
+ /**
2
+ * @module auth/trustedDevice
3
+ * @description Trusted Device / "Remember Me" middleware for 2FA.
4
+ * After successful 2FA verification, issues an encrypted device-trust
5
+ * token stored as an HttpOnly, Secure, SameSite=Strict cookie.
6
+ *
7
+ * Subsequent requests skip the 2FA prompt if the trust token is valid.
8
+ * Supports secret rotation, IP binding, and revocation.
9
+ *
10
+ * Uses AES-256-GCM encryption — tokens are encrypted, not just signed,
11
+ * preventing information leakage.
12
+ *
13
+ * @example
14
+ * const { trustedDevice, twoFactor } = require('@zero-server/sdk');
15
+ *
16
+ * app.post('/verify-2fa', twoFactor.verifyTOTPMiddleware({
17
+ * getSecret: (req) => req.user.totpSecret,
18
+ * }), trustedDevice.issue({
19
+ * secret: process.env.DEVICE_TRUST_SECRET,
20
+ * }));
21
+ *
22
+ * app.use(twoFactor.require2FA({
23
+ * isEnabled: (req) => req.user.totpEnabled,
24
+ * trustedDevice: trustedDevice.verify({
25
+ * secret: process.env.DEVICE_TRUST_SECRET,
26
+ * }),
27
+ * }));
28
+ */
29
+
30
+ const crypto = require('crypto');
31
+ const log = require('../debug')('zero:trustedDevice');
32
+
33
+ // -- Constants -----------------------------------------------
34
+
35
+ const DEFAULT_MAX_AGE = 30 * 24 * 60 * 60 * 1000; // 30 days
36
+ const DEFAULT_COOKIE_NAME = '_dt';
37
+ const IV_LENGTH = 12;
38
+ const TAG_LENGTH = 16;
39
+
40
+ // -- Encryption Helpers --------------------------------------
41
+
42
+ /**
43
+ * Derive a 256-bit key from a secret string using SHA-256.
44
+ * @private
45
+ * @param {string} secret
46
+ * @returns {Buffer}
47
+ */
48
+ function _deriveKey(secret)
49
+ {
50
+ return crypto.createHash('sha256').update(secret).digest();
51
+ }
52
+
53
+ /**
54
+ * Encrypt a payload using AES-256-GCM.
55
+ * @private
56
+ * @param {object} payload
57
+ * @param {string} secret
58
+ * @returns {string} Base64-encoded encrypted token.
59
+ */
60
+ function _encrypt(payload, secret)
61
+ {
62
+ const key = _deriveKey(secret);
63
+ const iv = crypto.randomBytes(IV_LENGTH);
64
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
65
+
66
+ const json = JSON.stringify(payload);
67
+ const encrypted = Buffer.concat([cipher.update(json, 'utf8'), cipher.final()]);
68
+ const tag = cipher.getAuthTag();
69
+
70
+ // Format: iv || tag || ciphertext
71
+ return Buffer.concat([iv, tag, encrypted]).toString('base64url');
72
+ }
73
+
74
+ /**
75
+ * Decrypt a token using AES-256-GCM.
76
+ * @private
77
+ * @param {string} token
78
+ * @param {string} secret
79
+ * @returns {object|null} Decoded payload or null if invalid.
80
+ */
81
+ function _decrypt(token, secret)
82
+ {
83
+ try
84
+ {
85
+ const buf = Buffer.from(token, 'base64url');
86
+ if (buf.length < IV_LENGTH + TAG_LENGTH + 1) return null;
87
+
88
+ const key = _deriveKey(secret);
89
+ const iv = buf.subarray(0, IV_LENGTH);
90
+ const tag = buf.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH);
91
+ const ciphertext = buf.subarray(IV_LENGTH + TAG_LENGTH);
92
+
93
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
94
+ decipher.setAuthTag(tag);
95
+
96
+ const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
97
+ return JSON.parse(decrypted.toString('utf8'));
98
+ }
99
+ catch (_)
100
+ {
101
+ return null;
102
+ }
103
+ }
104
+
105
+ // -- Cookie Helpers ------------------------------------------
106
+
107
+ /**
108
+ * Set a cookie on the response.
109
+ * @private
110
+ */
111
+ function _setCookie(res, name, value, maxAgeMs)
112
+ {
113
+ const maxAgeSec = Math.floor(maxAgeMs / 1000);
114
+ const raw = res.raw || res;
115
+ const existing = raw.getHeader('set-cookie') || [];
116
+ const cookies = Array.isArray(existing) ? existing : [existing];
117
+ cookies.push(
118
+ `${name}=${value}; HttpOnly; Secure; SameSite=Strict; Max-Age=${maxAgeSec}; Path=/`
119
+ );
120
+ raw.setHeader('Set-Cookie', cookies);
121
+ }
122
+
123
+ /**
124
+ * Clear a cookie.
125
+ * @private
126
+ */
127
+ function _clearCookie(res, name)
128
+ {
129
+ const raw = res.raw || res;
130
+ const existing = raw.getHeader('set-cookie') || [];
131
+ const cookies = Array.isArray(existing) ? existing : [existing];
132
+ cookies.push(
133
+ `${name}=; HttpOnly; Secure; SameSite=Strict; Max-Age=0; Path=/`
134
+ );
135
+ raw.setHeader('Set-Cookie', cookies);
136
+ }
137
+
138
+ /**
139
+ * Read a cookie value from the request.
140
+ * @private
141
+ */
142
+ function _readCookie(req, name)
143
+ {
144
+ // Use parsed cookies if available (cookieParser middleware)
145
+ if (req.cookies && req.cookies[name]) return req.cookies[name];
146
+
147
+ // Manual parse from header
148
+ const header = req.headers && req.headers.cookie;
149
+ if (!header) return null;
150
+
151
+ const match = header.split(';').find(c => c.trim().startsWith(name + '='));
152
+ if (!match) return null;
153
+ return match.split('=').slice(1).join('=').trim();
154
+ }
155
+
156
+ // -- Issue Middleware -----------------------------------------
157
+
158
+ /**
159
+ * Middleware that issues a trusted-device token after successful 2FA.
160
+ * Should be placed AFTER the 2FA verification middleware in the chain.
161
+ *
162
+ * @param {object} opts - Options.
163
+ * @param {string} opts.secret - Encryption secret (min 32 chars recommended).
164
+ * @param {number} [opts.maxAge=2592000000] - Trust duration in ms (default 30 days).
165
+ * @param {string} [opts.cookieName='_dt'] - Cookie name.
166
+ * @param {Function} [opts.fingerprint] - `(req) => string` device fingerprint.
167
+ * Defaults to User-Agent hash.
168
+ * @param {Function} [opts.getUserId] - `(req) => string` user identifier.
169
+ * Defaults to `req.user.id || req.user.sub`.
170
+ * @returns {Function} Middleware `(req, res, next) => void`.
171
+ *
172
+ * @example
173
+ * app.post('/verify-2fa', verifyTOTPMiddleware({...}), trustedDevice.issue({
174
+ * secret: process.env.DEVICE_TRUST_SECRET,
175
+ * maxAge: 30 * 24 * 60 * 60 * 1000,
176
+ * fingerprint: (req) => req.body.deviceFingerprint,
177
+ * }));
178
+ */
179
+ function issue(opts)
180
+ {
181
+ if (!opts || !opts.secret)
182
+ throw new Error('trustedDevice.issue() requires a secret');
183
+
184
+ const secret = opts.secret;
185
+ const maxAge = opts.maxAge || DEFAULT_MAX_AGE;
186
+ const cookieName = opts.cookieName || DEFAULT_COOKIE_NAME;
187
+ const getFingerprint = opts.fingerprint || _defaultFingerprint;
188
+ const getUserId = opts.getUserId || _defaultGetUserId;
189
+
190
+ return async function _issueDeviceTrust(req, res, next)
191
+ {
192
+ try
193
+ {
194
+ const userId = await getUserId(req);
195
+ const fp = await getFingerprint(req);
196
+
197
+ const payload = {
198
+ uid: userId,
199
+ fp: fp ? crypto.createHash('sha256').update(fp).digest('hex').substring(0, 16) : null,
200
+ iat: Date.now(),
201
+ exp: Date.now() + maxAge,
202
+ };
203
+
204
+ const token = _encrypt(payload, secret);
205
+ _setCookie(res, cookieName, token, maxAge);
206
+
207
+ log.info('device trust token issued for user %s', userId);
208
+ }
209
+ catch (err)
210
+ {
211
+ log.error('device trust issue error: %s', err.message);
212
+ }
213
+
214
+ next();
215
+ };
216
+ }
217
+
218
+ // -- Verify Function -----------------------------------------
219
+
220
+ /**
221
+ * Create a verification function for use with `require2FA` middleware.
222
+ * Returns a function `(req) => boolean` that checks for a valid trust token.
223
+ *
224
+ * @param {object} opts - Options.
225
+ * @param {string} opts.secret - Encryption secret.
226
+ * @param {string|string[]} [opts.previousSecrets] - Previous secrets for rotation.
227
+ * @param {string} [opts.cookieName='_dt'] - Cookie name.
228
+ * @param {Function} [opts.fingerprint] - `(req) => string` device fingerprint.
229
+ * @param {Function} [opts.getUserId] - `(req) => string`.
230
+ * @param {boolean} [opts.checkIP=false] - Verify IP range (/24 CIDR match).
231
+ * @returns {Function} `(req) => Promise<boolean>` trust check function.
232
+ *
233
+ * @example
234
+ * app.use(require2FA({
235
+ * isEnabled: (req) => req.user.totpEnabled,
236
+ * trustedDevice: trustedDevice.verify({
237
+ * secret: process.env.DEVICE_TRUST_SECRET,
238
+ * }),
239
+ * }));
240
+ */
241
+ function verify(opts)
242
+ {
243
+ if (!opts || !opts.secret)
244
+ throw new Error('trustedDevice.verify() requires a secret');
245
+
246
+ const secrets = [opts.secret];
247
+ if (opts.previousSecrets)
248
+ {
249
+ const prev = Array.isArray(opts.previousSecrets) ? opts.previousSecrets : [opts.previousSecrets];
250
+ secrets.push(...prev);
251
+ }
252
+
253
+ const cookieName = opts.cookieName || DEFAULT_COOKIE_NAME;
254
+ const getFingerprint = opts.fingerprint || _defaultFingerprint;
255
+ const getUserId = opts.getUserId || _defaultGetUserId;
256
+ const checkIP = opts.checkIP || false;
257
+
258
+ return async function _verifyDeviceTrust(req)
259
+ {
260
+ const token = _readCookie(req, cookieName);
261
+ if (!token) return false;
262
+
263
+ // Try each secret (current + rotated)
264
+ let payload = null;
265
+ for (const s of secrets)
266
+ {
267
+ payload = _decrypt(token, s);
268
+ if (payload) break;
269
+ }
270
+
271
+ if (!payload) return false;
272
+
273
+ // Check expiry
274
+ if (Date.now() >= payload.exp)
275
+ {
276
+ log.debug('device trust token expired');
277
+ return false;
278
+ }
279
+
280
+ // Check user ID
281
+ try
282
+ {
283
+ const userId = await getUserId(req);
284
+ if (String(payload.uid) !== String(userId)) return false;
285
+ }
286
+ catch (_)
287
+ {
288
+ return false;
289
+ }
290
+
291
+ // Check fingerprint if present
292
+ if (payload.fp)
293
+ {
294
+ try
295
+ {
296
+ const fp = await getFingerprint(req);
297
+ if (fp)
298
+ {
299
+ const currentFP = crypto.createHash('sha256').update(fp).digest('hex').substring(0, 16);
300
+ if (payload.fp !== currentFP)
301
+ {
302
+ log.debug('device fingerprint mismatch');
303
+ return false;
304
+ }
305
+ }
306
+ }
307
+ catch (_)
308
+ {
309
+ return false;
310
+ }
311
+ }
312
+
313
+ // Optional IP range check (/24 CIDR)
314
+ if (checkIP && payload.ip)
315
+ {
316
+ const currentIP = req.ip || req.socket?.remoteAddress || '';
317
+ if (!_matchIPSubnet(payload.ip, currentIP))
318
+ {
319
+ log.debug('IP range mismatch');
320
+ return false;
321
+ }
322
+ }
323
+
324
+ log.debug('device trust token valid for user %s', payload.uid);
325
+ return true;
326
+ };
327
+ }
328
+
329
+ // -- Revocation Middleware ------------------------------------
330
+
331
+ /**
332
+ * Middleware that revokes the trusted-device cookie.
333
+ * Call this on logout, password change, or 2FA re-enrollment.
334
+ *
335
+ * @param {object} [opts] - Options.
336
+ * @param {string} [opts.cookieName='_dt'] - Cookie name.
337
+ * @returns {Function} Middleware `(req, res, next) => void`.
338
+ *
339
+ * @example
340
+ * app.post('/logout', trustedDevice.revoke(), (req, res) => {
341
+ * res.json({ ok: true });
342
+ * });
343
+ */
344
+ function revoke(opts = {})
345
+ {
346
+ const cookieName = opts.cookieName || DEFAULT_COOKIE_NAME;
347
+
348
+ return function _revokeDeviceTrust(req, res, next)
349
+ {
350
+ _clearCookie(res, cookieName);
351
+ log.info('device trust token revoked');
352
+ next();
353
+ };
354
+ }
355
+
356
+ // -- Internal Helpers ----------------------------------------
357
+
358
+ /**
359
+ * Default fingerprint: hash of User-Agent.
360
+ * @private
361
+ */
362
+ function _defaultFingerprint(req)
363
+ {
364
+ return req.headers && req.headers['user-agent'] || '';
365
+ }
366
+
367
+ /**
368
+ * Default user ID extraction.
369
+ * @private
370
+ */
371
+ function _defaultGetUserId(req)
372
+ {
373
+ if (!req.user) throw new Error('No user on request — authentication middleware required');
374
+ return req.user.id || req.user.sub || req.user._id;
375
+ }
376
+
377
+ /**
378
+ * Check if two IPs are in the same /24 subnet (IPv4 only).
379
+ * @private
380
+ * @param {string} storedIP
381
+ * @param {string} currentIP
382
+ * @returns {boolean}
383
+ */
384
+ function _matchIPSubnet(storedIP, currentIP)
385
+ {
386
+ const storedParts = storedIP.split('.');
387
+ const currentParts = currentIP.split('.');
388
+ if (storedParts.length !== 4 || currentParts.length !== 4) return false;
389
+ return storedParts[0] === currentParts[0] &&
390
+ storedParts[1] === currentParts[1] &&
391
+ storedParts[2] === currentParts[2];
392
+ }
393
+
394
+ // -- Exports -------------------------------------------------
395
+
396
+ const trustedDevice = {
397
+ issue,
398
+ verify,
399
+ revoke,
400
+ };
401
+
402
+ module.exports = {
403
+ trustedDevice,
404
+ // Internals for testing
405
+ _encrypt,
406
+ _decrypt,
407
+ _deriveKey,
408
+ _matchIPSubnet,
409
+ };