emailengine-app 2.87.1 → 2.88.0

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 (73) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/ENVIRONMENT.md +26 -23
  4. package/LICENSE_EMAILENGINE.txt +20 -12
  5. package/app.json +3 -3
  6. package/bin/emailengine.js +7 -11
  7. package/data/google-crawlers.json +1 -1
  8. package/data/public_suffix_list.dat +48 -10
  9. package/lib/account.js +69 -49
  10. package/lib/admin-password.js +85 -0
  11. package/lib/api-routes/license-routes.js +9 -0
  12. package/lib/api-token-auth.js +21 -5
  13. package/lib/calendar-event.js +15 -3
  14. package/lib/consts.js +5 -0
  15. package/lib/db.js +1 -0
  16. package/lib/dbsc/index.js +292 -0
  17. package/lib/dbsc/jwt.js +157 -0
  18. package/lib/dbsc/protocol.js +132 -0
  19. package/lib/dbsc/store.js +136 -0
  20. package/lib/email-client/base-client.js +36 -15
  21. package/lib/email-client/gmail-client.js +20 -6
  22. package/lib/email-client/imap/connection-errors.js +30 -1
  23. package/lib/email-client/imap/session-expiry.js +83 -0
  24. package/lib/email-client/imap-client.js +12 -2
  25. package/lib/email-client/smtp-pool-manager.js +66 -8
  26. package/lib/export.js +147 -22
  27. package/lib/graph-notifications.js +60 -0
  28. package/lib/imap-proxy-auth.js +52 -18
  29. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  30. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  31. package/lib/imapproxy/imap-server.js +10 -1
  32. package/lib/imapproxy/proxy-handoff.js +100 -5
  33. package/lib/license-subscription.js +238 -0
  34. package/lib/oauth/gmail.js +18 -0
  35. package/lib/oauth/outlook-identity.js +54 -12
  36. package/lib/prepared-password.js +38 -0
  37. package/lib/privileged-settings.js +6 -0
  38. package/lib/queue-browser/index.js +6 -6
  39. package/lib/queue-job-actions.js +59 -4
  40. package/lib/read-env-value.js +46 -21
  41. package/lib/redis-url.js +23 -0
  42. package/lib/response-stream.js +69 -1
  43. package/lib/revocation-events.js +79 -0
  44. package/lib/routes-ui.js +4 -1
  45. package/lib/schemas.js +26 -2
  46. package/lib/session-default.js +13 -3
  47. package/lib/settings.js +47 -24
  48. package/lib/sso.js +23 -0
  49. package/lib/submit-penalty.js +24 -0
  50. package/lib/submit-processor.js +10 -2
  51. package/lib/tokens.js +6 -0
  52. package/lib/tools.js +86 -15
  53. package/lib/ui-routes/admin-config-routes.js +30 -281
  54. package/lib/ui-routes/auth-routes.js +17 -64
  55. package/lib/ui-routes/dbsc-routes.js +43 -0
  56. package/lib/ui-routes/license-routes.js +326 -0
  57. package/lib/web-safe-html.js +29 -0
  58. package/lib/webhook-delivery.js +21 -20
  59. package/lib/webhook-penalty.js +18 -17
  60. package/lib/webhooks.js +18 -0
  61. package/package.json +18 -18
  62. package/sbom.json +294 -294
  63. package/scan.js +2 -0
  64. package/server.js +253 -80
  65. package/static/css/flyonui.css +2 -2
  66. package/static/js/ui.js +11 -4
  67. package/static/licenses.html +27 -27
  68. package/translations/messages.pot +17 -17
  69. package/views/config/license.hbs +43 -16
  70. package/views/config/security.hbs +37 -0
  71. package/views/partials/side_menu.hbs +1 -1
  72. package/workers/api.js +128 -109
  73. package/workers/imap.js +4 -6
@@ -0,0 +1,85 @@
1
+ 'use strict';
2
+
3
+ // The admin password checks the admin UI's sign-in and step-down routes share. Split out of
4
+ // lib/ui-routes/auth-routes.js.
5
+
6
+ const pbkdf2 = require('./pbkdf2-phc');
7
+
8
+ // Single place that knows how a failed password check is interpreted: an absent password and a
9
+ // verify() that throws (which happens only on a malformed stored hash, never on a wrong password)
10
+ // are both failures, never a pass. Sign-in, the password change and both passkey registration
11
+ // steps all come through here, so a change to how the account password is checked - a KDF swap,
12
+ // a dummy verify to flatten timing - lands in one place.
13
+ async function verifyAdminPassword(hash, password, logger) {
14
+ if (!password) {
15
+ return false;
16
+ }
17
+ try {
18
+ return await pbkdf2.verify(hash, password);
19
+ } catch (err) {
20
+ logger.error({ msg: 'Failed to verify password hash', err });
21
+ return false;
22
+ }
23
+ }
24
+
25
+ // The current-password check behind the security page's step-down actions (the password change
26
+ // and switching the second factor off). A live session alone is not supposed to reveal the
27
+ // password, and unthrottled the field let a hijacked session guess it at full speed, so the
28
+ // check is rate limited the way the login form is: keyed on the account rather than the address
29
+ // because the caller is already authenticated as it, and with the login form's per-username
30
+ // budget. Owns the limiter and the warn logs; the caller decides how to report the failure.
31
+ //
32
+ // @returns {Promise<{ ok: true } | { ok: false, reason: 'rateLimited' | 'invalid', message: String, statusCode: Number }>}
33
+ async function verifyCurrentPassword(request, h, authData, password) {
34
+ let rateLimit = await h.checkRateLimit(`password:verify:${authData.user || 'admin'}`, 1, 10, 60);
35
+ if (!rateLimit.success) {
36
+ request.logger.warn({ msg: 'Rate limited', rateLimit, remoteAddress: request.app.ip });
37
+ return { ok: false, reason: 'rateLimited', message: 'Rate limited, please wait and try again', statusCode: 429 };
38
+ }
39
+
40
+ if (!(await verifyAdminPassword(authData.password, password, request.logger))) {
41
+ request.logger.warn({ msg: 'Invalid current password', remoteAddress: request.app.ip });
42
+ return { ok: false, reason: 'invalid', message: 'Invalid password', statusCode: 403 };
43
+ }
44
+
45
+ return { ok: true };
46
+ }
47
+
48
+ /**
49
+ * Replaces the admin password: stores the hash, ends every session and message-browser token by
50
+ * bumping passwordVersion, and removes every passkey of the user. Registering a passkey takes the
51
+ * password, so a passkey that outlived a password change could belong to whoever had the old one,
52
+ * and a passkey signs in without the second factor. The one place a password is replaced (the
53
+ * security page, the `emailengine password` command, EENGINE_PREPARED_PASSWORD), so a new way of
54
+ * replacing it can not forget the passkeys again.
55
+ *
56
+ * @param {string} passwordHash - PBKDF2 hash of the new password
57
+ * @param {Object} deps
58
+ * @param {Object} deps.settings - settings store (`get()`, `set()`)
59
+ * @param {Object} deps.passkeys - passkey store (`deleteAllCredentials()`)
60
+ * @param {Object} deps.logger
61
+ * @param {Object} [authData] - The stored authData, when the caller already read it
62
+ * @returns {Promise<{ authData: Object, clearedPasskeys: number }>}
63
+ */
64
+ async function setAdminPassword(passwordHash, { settings, passkeys, logger }, authData) {
65
+ // read only when the caller did not: a caller that read nothing passes null, not undefined
66
+ authData = (authData === undefined ? await settings.get('authData') : authData) || {};
67
+ authData.user = authData.user || 'admin';
68
+ authData.password = passwordHash;
69
+ authData.passwordVersion = Date.now();
70
+
71
+ await settings.set('authData', authData);
72
+
73
+ let clearedPasskeys = 0;
74
+ try {
75
+ clearedPasskeys = await passkeys.deleteAllCredentials(authData.user);
76
+ logger.info({ msg: 'All passkeys cleared after password change', user: authData.user, cleared: clearedPasskeys });
77
+ } catch (err) {
78
+ // The password is replaced either way; say loudly that the passkeys are not gone
79
+ logger.error({ msg: 'Failed to clear passkeys after password change', err });
80
+ }
81
+
82
+ return { authData, clearedPasskeys };
83
+ }
84
+
85
+ module.exports = { verifyAdminPassword, verifyCurrentPassword, setAdminPassword };
@@ -32,6 +32,9 @@ async function init(args) {
32
32
  tags: ['api', 'License'],
33
33
 
34
34
  plugins: {
35
+ // open while the license is missing or suspended (workers/api.js preResponse), so an
36
+ // instance can still report its state and register a key
37
+ licensePrecheck: false,
35
38
  mcp: {
36
39
  name: 'get_license',
37
40
  title: 'Get license',
@@ -78,6 +81,9 @@ async function init(args) {
78
81
  tags: ['api', 'License'],
79
82
 
80
83
  plugins: {
84
+ // open while the license is missing or suspended (workers/api.js preResponse), so an
85
+ // instance can still report its state and register a key
86
+ licensePrecheck: false,
81
87
  openapi: {
82
88
  'x-ee-impact': IMPACT.DESTRUCTIVE,
83
89
  responses: apiResponses('Returns an empty license object. EmailEngine drops to limited mode.', 401, 403, 429, 500)
@@ -124,6 +130,9 @@ async function init(args) {
124
130
  tags: ['api', 'License'],
125
131
 
126
132
  plugins: {
133
+ // open while the license is missing or suspended (workers/api.js preResponse), so an
134
+ // instance can still report its state and register a key
135
+ licensePrecheck: false,
127
136
  mcp: {
128
137
  name: 'set_license',
129
138
  title: 'Apply license',
@@ -30,11 +30,22 @@ const { mcpOptions } = require('./api-routes/route-metadata');
30
30
  * @param {Object} deps.redis - Redis client, for the template ownership lookup
31
31
  * @param {Function} deps.checkRateLimit - async (key, count, allowed, windowSize) => { success, allowed, count, ttl }
32
32
  * @param {Function} deps.sessionPasswordVersion - async () => the password version sessions are stamped with
33
+ * @param {Function} deps.sessionAdmitted - (session) => whether the session's SSO provider still admits its user
33
34
  * @param {String[]} [deps.adminAccessAddresses] - EENGINE_ADMIN_ACCESS_ADDRESSES, the admin perimeter
34
35
  * @param {Object} deps.logger
35
36
  * @returns {Function} async (request, token) => { isValid, credentials, artifacts }
36
37
  */
37
- function createApiTokenValidator({ settings, tokens, tokenAuditLog, redis, checkRateLimit, sessionPasswordVersion, adminAccessAddresses, logger }) {
38
+ function createApiTokenValidator({
39
+ settings,
40
+ tokens,
41
+ tokenAuditLog,
42
+ redis,
43
+ checkRateLimit,
44
+ sessionPasswordVersion,
45
+ sessionAdmitted,
46
+ adminAccessAddresses,
47
+ logger
48
+ }) {
38
49
  return async function validateApiToken(request, token) {
39
50
  let disableTokens = await settings.get('disableTokens');
40
51
  if (disableTokens && (!token || token === 'preauth')) {
@@ -75,7 +86,8 @@ function createApiTokenValidator({ settings, tokens, tokenAuditLog, redis, check
75
86
  // that was supposed to end every session. Same predicate as the session strategy,
76
87
  // including its "only when a local password exists" condition, so a session stamped
77
88
  // before this shipped is not force-expired.
78
- if (isEndedSession(await sessionPasswordVersion(), session)) {
89
+ // The same goes for an SSO user the identity provider's allow-list no longer admits
90
+ if (isEndedSession(await sessionPasswordVersion(), session) || !sessionAdmitted(session)) {
79
91
  logger.warn({
80
92
  msg: 'Session token presented for an ended session',
81
93
  account: request.params.account,
@@ -139,7 +151,7 @@ function createApiTokenValidator({ settings, tokens, tokenAuditLog, redis, check
139
151
  // The last-use record is skipped on MCP-dispatched injects: the outer /mcp
140
152
  // request just wrote the same credential's entry, and the second write would
141
153
  // only repeat it
142
- tokenData = await tokens.get(token, false, { log: !request.app.mcpInternal, remoteAddress: request.app.ip });
154
+ tokenData = await tokens.get(token, false, { log: !request.app.mcpInternal && !request.app.authRecheck, remoteAddress: request.app.ip });
143
155
  } catch (err) {
144
156
  // A thrown Boom reaches the client the way the scope and permission refusals
145
157
  // below do (the api-token scheme does not catch it), so the reason travels as a
@@ -353,7 +365,8 @@ function createApiTokenValidator({ settings, tokens, tokenAuditLog, redis, check
353
365
  // /mcp request already spent one unit of this token's budget at the door, and
354
366
  // counting the inner request too silently halved every restricted token's
355
367
  // effective limit over MCP.
356
- if (tokenData.restrictions.rateLimit && !request.app.mcpInternal) {
368
+ // A re-check of an open stream (request.app.authRecheck) is not a request either.
369
+ if (tokenData.restrictions.rateLimit && !request.app.mcpInternal && !request.app.authRecheck) {
357
370
  let rateLimit = await checkRateLimit(
358
371
  `api:${tokenData.id}`,
359
372
  1,
@@ -395,7 +408,10 @@ function createApiTokenValidator({ settings, tokens, tokenAuditLog, redis, check
395
408
  // check above was deferred): every tool call writes its own row as the injected API
396
409
  // request it becomes, and a second content-free row per call would halve the capped
397
410
  // audit retention for MCP traffic. Denials at the door are still recorded above.
398
- if (!mcpEndpoint) {
411
+ //
412
+ // Nor for the periodic re-check of an open change stream, which asks whether the token still
413
+ // admits a request it already accepted.
414
+ if (!mcpEndpoint && !request.app.authRecheck) {
399
415
  tokenAuditLog.allowed(auditEntry);
400
416
  }
401
417
 
@@ -8,6 +8,7 @@
8
8
  // VCALENDAR (ical.js 2.x; 1.x read such a value as floating, in the server's own zone), so the
9
9
  // ISO timestamps are the instant the invite means wherever EmailEngine happens to run.
10
10
 
11
+ const { withinNotifyAttachmentSize } = require('./notify-attachments');
11
12
  const ical = require('ical.js');
12
13
  const { filterEmptyObjectValues } = require('./utils/filter-empty');
13
14
 
@@ -76,6 +77,10 @@ function parseCalendarEvent(content) {
76
77
  };
77
78
  }
78
79
 
80
+ // The largest calendar file read for the webhook. Any sender can attach one, and it was loaded,
81
+ // parsed and copied into the payload whole: a real invite is a few kilobytes.
82
+ const MAX_CALENDAR_SIZE = 1024 * 1024;
83
+
79
84
  /**
80
85
  * The calendar events of a new message, for the messageNew webhook (`notifyCalendarEvents`).
81
86
  * Shared by the IMAP mailbox and the Gmail API and Graph clients, which differ only in how an
@@ -90,13 +95,14 @@ async function collectCalendarEvents(attachments, load, logger) {
90
95
  const events = new Map();
91
96
 
92
97
  for (const attachment of [...(attachments || [])].sort(sortCalendarAttachments)) {
93
- if (!CALENDAR_CONTENT_TYPES.includes(attachment.contentType)) {
98
+ if (!CALENDAR_CONTENT_TYPES.includes(attachment.contentType) || !withinNotifyAttachmentSize(attachment, MAX_CALENDAR_SIZE)) {
94
99
  continue;
95
100
  }
96
101
  if (!attachment.content) {
97
102
  await load(attachment);
98
103
  }
99
- if (!attachment.content) {
104
+ // a part without a reported size is measured once loaded
105
+ if (!attachment.content || !withinNotifyAttachmentSize(attachment, MAX_CALENDAR_SIZE)) {
100
106
  continue;
101
107
  }
102
108
 
@@ -155,4 +161,10 @@ async function collectCalendarEvents(attachments, load, logger) {
155
161
  });
156
162
  }
157
163
 
158
- module.exports = { CALENDAR_CONTENT_TYPES, sortCalendarAttachments, parseCalendarEvent, collectCalendarEvents };
164
+ module.exports = {
165
+ MAX_CALENDAR_SIZE,
166
+ CALENDAR_CONTENT_TYPES,
167
+ sortCalendarAttachments,
168
+ parseCalendarEvent,
169
+ collectCalendarEvents
170
+ };
package/lib/consts.js CHANGED
@@ -269,6 +269,11 @@ module.exports = {
269
269
  // drops the connection would otherwise cause an unthrottled login loop
270
270
  STABLE_CONNECTION_TIME: 5 * 60 * 1000, // 5 min
271
271
 
272
+ // How much lifetime a stored OAuth2 access token must have left to be used as is rather than
273
+ // renewed first. An IMAP login on a provider that ends the session with its token asks for more,
274
+ // see lib/email-client/imap/session-expiry.js
275
+ OAUTH_TOKEN_MIN_VALIDITY: 30 * 1000,
276
+
272
277
  MAX_INLINE_ATTACHMENT_SIZE: 2 * 1024 * 1024,
273
278
 
274
279
  // How many times processing of the same Gmail history entry may start
package/lib/db.js CHANGED
@@ -49,6 +49,7 @@ const REDIS_CONF = Object.assign(
49
49
  },
50
50
  typeof redisConf === 'string' ? redisUrl(redisConf) : redisConf || {}
51
51
  );
52
+ redisUrl.applyRedisTlsSwitch(REDIS_CONF);
52
53
 
53
54
  const getRedisURL = (masked = true) => {
54
55
  let redisUrlParts = [`redis${REDIS_CONF.tls ? 's' : ''}://`];
@@ -0,0 +1,292 @@
1
+ 'use strict';
2
+
3
+ // Device-bound admin sessions (DBSC, https://w3c.github.io/webappsec-dbsc/). An opt-in hardening of
4
+ // the admin session cookie: a browser that supports it creates a key pair it cannot export (the TPM
5
+ // on Windows, the Secure Enclave on macOS) and from then on proves possession of the key every few
6
+ // minutes to renew a short-lived second cookie. A session cookie copied off the machine stops
7
+ // working within BOUND_COOKIE_TTL, because nothing but the key can renew the second one.
8
+ //
9
+ // Opportunistic by design: a browser that does not support it never registers, and its session
10
+ // works exactly as before. Once a session HAS registered, the binding lives in Redis (store.js) and
11
+ // every request carrying that session's cookie must carry a valid bound cookie too - the session
12
+ // cookie says nothing about being bound, so it cannot be stripped of it.
13
+ //
14
+ // The pieces:
15
+ // offer() onPreResponse: asks an authenticated admin page's browser to register
16
+ // register() POST /admin/dbsc/start (lib/ui-routes/dbsc-routes.js)
17
+ // refresh() POST /admin/dbsc/refresh
18
+ // mustRefuse() onPostAuth: a bound session's request without the bound cookie is refused
19
+ // end() logout: marks the binding ended, which refuses the session cookie everywhere
20
+ //
21
+ // Verified end to end against Chrome 156 on macOS (Secure Enclave keys) on 2026-11-05. Chrome only
22
+ // registers on a trusted https origin: not on http, not on localhost, not with a certificate error.
23
+
24
+ const crypto = require('crypto');
25
+ const Boom = require('@hapi/boom');
26
+
27
+ const { ADMIN_SESSION_MAX_AGE } = require('../consts');
28
+ const { createDbscStore } = require('./store');
29
+ const { verifyRegistrationProof, verifyRefreshProof } = require('./jwt');
30
+ const {
31
+ BOUND_COOKIE,
32
+ BOUND_COOKIE_TTL,
33
+ readSfString,
34
+ registrationHeader,
35
+ challengeHeader,
36
+ registrationAnswer,
37
+ boundCookieValid,
38
+ boundCookieSpec
39
+ } = require('./protocol');
40
+
41
+ const RESPONSE_HEADER = 'secure-session-response';
42
+
43
+ // The admin session cookie's sid, which keys everything DBSC stores
44
+ const sidOf = request => (request.state && request.state.ee && request.state.ee.sid) || null;
45
+ const SESSION_ID_HEADER = 'sec-secure-session-id';
46
+ const SKIPPED_HEADER = 'secure-session-skipped';
47
+
48
+ /**
49
+ * @param {Object} deps
50
+ * @param {Object} deps.store - createDbscStore()
51
+ * @param {Object} deps.logger
52
+ * @param {string} deps.attributes - the bound cookie's attributes string (boundCookieSpec())
53
+ */
54
+ function createDbsc({ store, logger, attributes }) {
55
+ const issueBoundCookie = (h, sid, id) => h.state(BOUND_COOKIE, { sid, id, exp: Date.now() + BOUND_COOKIE_TTL });
56
+
57
+ // Seconds the admin session behind this cookie can still live, which bounds its binding
58
+ const sessionTtl = session => (Number(session.issuedAt) + ADMIN_SESSION_MAX_AGE - Date.now()) / 1000;
59
+
60
+ return {
61
+ async offer(request, h) {
62
+ const response = request.response;
63
+ if (!request.app.dbscEnabled || request.method !== 'get' || !request.auth.isAuthenticated || request.auth.strategy !== 'session') {
64
+ return h.continue;
65
+ }
66
+ if (response.isBoom || response.variety !== 'view' || response.statusCode !== 200) {
67
+ return h.continue;
68
+ }
69
+ const session = request.auth.artifacts || {};
70
+ if (!session.sid || session.requireTotp || boundCookieValid(request.state[BOUND_COOKIE], session.sid)) {
71
+ return h.continue;
72
+ }
73
+ try {
74
+ // The throttle first: on a browser that never binds, that is the only round trip
75
+ if (!(await store.claimOffer(session.sid)) || (!request.app.dbscUnbound && (await store.getBinding(session.sid)))) {
76
+ return h.continue;
77
+ }
78
+ response.header('Secure-Session-Registration', registrationHeader(await store.mintChallenge(session.sid, 'register')));
79
+ } catch (err) {
80
+ // An offer is an invitation, never a reason to fail the page
81
+ logger.warn({ msg: 'Failed to offer a device-bound session', err });
82
+ }
83
+ return h.continue;
84
+ },
85
+
86
+ async register(request, h) {
87
+ const session = request.auth.artifacts || {};
88
+ if (!request.app.dbscEnabled || !session.sid) {
89
+ return h.response().code(404);
90
+ }
91
+
92
+ const refuse = reason => {
93
+ logger.info({ msg: 'Refused a device-bound session registration', reason, remoteAddress: request.app.ip });
94
+ return h.response().code(400);
95
+ };
96
+
97
+ let proof;
98
+ try {
99
+ proof = verifyRegistrationProof(readSfString(request.headers[RESPONSE_HEADER]));
100
+ } catch (err) {
101
+ return refuse(err.message);
102
+ }
103
+ if (!(await store.consumeChallenge(proof.jti, session.sid, 'register'))) {
104
+ return refuse('unknown or spent challenge');
105
+ }
106
+
107
+ const id = crypto.randomBytes(16).toString('hex');
108
+ if (!(await store.bind(session.sid, { id, alg: proof.alg, jwk: proof.jwk }, sessionTtl(session)))) {
109
+ // Bound already. A second registration would let whoever holds the session cookie
110
+ // replace the key, which is the one thing the binding exists to prevent
111
+ return h.response().code(409);
112
+ }
113
+
114
+ logger.info({
115
+ msg: 'Admin session bound to a device key',
116
+ user: request.auth.credentials && request.auth.credentials.user,
117
+ alg: proof.alg,
118
+ remoteAddress: request.app.ip
119
+ });
120
+ issueBoundCookie(h, session.sid, id);
121
+ return h.response(registrationAnswer({ sessionId: id, attributes })).type('application/json');
122
+ },
123
+
124
+ async refresh(request, h) {
125
+ // A 4xx other than 403 ends the session in the browser, a 3xx is ignored by it, so the
126
+ // answers here are chosen by what the browser does with them
127
+ const stop = () => h.response({ continue: false }).type('application/json');
128
+
129
+ const session = request.auth.isAuthenticated ? request.auth.artifacts || {} : null;
130
+ if (!request.app.dbscEnabled || !session || !session.sid) {
131
+ return stop();
132
+ }
133
+ const binding = await store.getBinding(session.sid);
134
+ if (!binding || binding.ended || binding.id !== readSfString(request.headers[SESSION_ID_HEADER])) {
135
+ // A session the browser still holds from an earlier sign-in
136
+ return stop();
137
+ }
138
+
139
+ const challengeAgain = async () =>
140
+ h
141
+ .response()
142
+ .code(403)
143
+ .header('Secure-Session-Challenge', challengeHeader(await store.mintChallenge(session.sid, 'refresh'), binding.id));
144
+
145
+ const token = readSfString(request.headers[RESPONSE_HEADER]);
146
+ if (!token) {
147
+ return await challengeAgain();
148
+ }
149
+
150
+ let jti;
151
+ try {
152
+ ({ jti } = verifyRefreshProof(token, binding));
153
+ } catch (err) {
154
+ // counted as a failed proof below
155
+ }
156
+ // Chrome signs proactive refreshes over the challenge it has cached, which this server
157
+ // has already spent: that is answered with a fresh one, and the browser retries
158
+ if (!jti || !(await store.consumeChallenge(jti, session.sid, 'refresh'))) {
159
+ if (await store.recordRefreshFailure(session.sid)) {
160
+ return await challengeAgain();
161
+ }
162
+ logger.warn({ msg: 'Ended a device-bound session after repeated bad proofs', remoteAddress: request.app.ip });
163
+ return h.response().code(401);
164
+ }
165
+
166
+ await store.clearRefreshFailures(session.sid);
167
+ issueBoundCookie(h, session.sid, binding.id);
168
+ return h.response().code(200);
169
+ },
170
+
171
+ /**
172
+ * @returns {Promise<boolean>} true when the request carries a bound session without its
173
+ * bound cookie and has to be refused
174
+ */
175
+ async mustRefuse(request) {
176
+ // The refresh route opts out: it is where a missing bound cookie gets renewed
177
+ const routeOptions = request.route.settings.plugins.dbsc;
178
+ if (!request.app.dbscEnabled || (routeOptions && routeOptions.enforce === false)) {
179
+ return false;
180
+ }
181
+ // Both credentials the session cookie carries: the admin session, and the message
182
+ // browser's session token on /v1 (lib/api-token-auth.js), which reads the same cookie
183
+ const viaSession = request.auth.isAuthenticated && request.auth.strategy === 'session';
184
+ if (!viaSession && !request.app.sessionToken) {
185
+ return false;
186
+ }
187
+ const sid = sidOf(request);
188
+ if (!sid || boundCookieValid(request.state[BOUND_COOKIE], sid)) {
189
+ return false;
190
+ }
191
+ if (!(await store.getBinding(sid))) {
192
+ // Known unbound for the rest of this request, so the offer need not ask again
193
+ request.app.dbscUnbound = true;
194
+ return false;
195
+ }
196
+ // A binding and no valid bound cookie: the session cookie is being used without the device
197
+ // that holds the key. An ended binding (logout) is refused the same way; a bound cookie
198
+ // issued before the logout still passes until it runs out, which is the price of not
199
+ // reading Redis on every request that carries one
200
+
201
+ logger.warn({
202
+ msg: 'Refused a device-bound admin session without its bound credential',
203
+ path: request.path,
204
+ skipped: request.headers[SKIPPED_HEADER],
205
+ remoteAddress: request.app.ip
206
+ });
207
+ return true;
208
+ },
209
+
210
+ /**
211
+ * Whether the session making this request is bound to a device key, for the Security
212
+ * page's "this browser" line
213
+ * @returns {Promise<boolean>}
214
+ */
215
+ async isBound(request) {
216
+ const sid = sidOf(request);
217
+ if (!sid) {
218
+ return false;
219
+ }
220
+ const binding = await store.getBinding(sid);
221
+ return !!binding && !binding.ended;
222
+ },
223
+
224
+ async end(sid) {
225
+ await store.endBinding(sid);
226
+ }
227
+ };
228
+ }
229
+
230
+ /**
231
+ * Registers the bound cookie and publishes the DBSC instance on server.app, where the routes and
232
+ * the logout handlers find it. Called with the session strategy, from the same cookie settings
233
+ * @param {Object} server - hapi server
234
+ * @param {Object} opts
235
+ * @param {Object} opts.redis
236
+ * @param {Object} opts.logger
237
+ * @param {boolean} opts.secure - whether the admin cookies are Secure
238
+ * @param {string} opts.password - cookiePassword
239
+ */
240
+ function setupDbsc(server, { redis, logger, secure, password }) {
241
+ const spec = boundCookieSpec({ secure, password });
242
+ server.state(BOUND_COOKIE, spec.state);
243
+ server.app.dbsc = createDbsc({ store: createDbscStore(redis), logger, attributes: spec.attributes });
244
+ }
245
+
246
+ /**
247
+ * The offer (onPreResponse) and the enforcement (onPostAuth). Registered after the TOTP step, so a
248
+ * session still owing its second factor is sent there first, and after the error-page extension,
249
+ * so an offer is only ever attached to a page that is actually rendered
250
+ * @param {Object} server - hapi server, after setupDbsc()
251
+ */
252
+ function registerDbscExtensions(server) {
253
+ const dbsc = server.app.dbsc;
254
+
255
+ server.ext('onPostAuth', async (request, h) => {
256
+ if (!(await dbsc.mustRefuse(request))) {
257
+ return h.continue;
258
+ }
259
+ // The session is over on this browser. Its binding stays: deleting it would let the same
260
+ // session cookie, wherever it was copied to, pass as an unbound session
261
+ h.unstate('ee');
262
+ h.unstate(BOUND_COOKIE);
263
+ if (request.app.sessionToken) {
264
+ throw Boom.unauthorized('Session could not be confirmed on this device');
265
+ }
266
+ await request.flash({
267
+ type: 'warning',
268
+ message: 'You were signed out because this browser could not confirm it is the device you signed in on. Sign in again to continue.'
269
+ });
270
+ const next = request.method === 'get' ? `?next=${encodeURIComponent(request.url.pathname + request.url.search)}` : '';
271
+ return h.redirect(`/admin/login${next}`).takeover();
272
+ });
273
+
274
+ server.ext('onPreResponse', (request, h) => dbsc.offer(request, h));
275
+ }
276
+
277
+ /**
278
+ * Ends the binding of the session a logout ends. A no-op where DBSC was never set up
279
+ * @param {Object} request
280
+ * @param {Object} h
281
+ */
282
+ async function endDeviceBinding(request, h) {
283
+ const dbsc = request.server.app.dbsc;
284
+ const sid = sidOf(request);
285
+ if (!dbsc || !sid) {
286
+ return;
287
+ }
288
+ h.unstate(BOUND_COOKIE);
289
+ await dbsc.end(sid);
290
+ }
291
+
292
+ module.exports = { setupDbsc, registerDbscExtensions, endDeviceBinding };