@zero-server/auth 0.9.0 → 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.
@@ -0,0 +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
+ };