emailengine-app 2.87.1 → 2.87.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,136 @@
1
+ 'use strict';
2
+
3
+ // What the server remembers about device-bound admin sessions, in Redis so every API worker sees
4
+ // the same state:
5
+ //
6
+ // dbsc:b:{sid} the binding: the session key the browser registered (JSON), for as long as the
7
+ // admin session itself can live. Its existence is what makes the session bound,
8
+ // and it is never deleted, not on a refusal and not on logout (which marks it
9
+ // `ended`): a session cookie whose binding was removed would read as unbound and
10
+ // be accepted on its own again
11
+ // dbsc:c:{value} a challenge, single use and short-lived, naming the sid and step it was minted
12
+ // for, so a proof signed over one session's challenge cannot serve another
13
+ // dbsc:o:{sid} an offer throttle, so a browser that cannot bind (or will not) is asked about
14
+ // once a minute rather than on every page
15
+ // dbsc:f:{sid} failed refresh proofs, so a browser stuck on a bad key is told to stop rather
16
+ // than retried for ever (the spec puts no bound on its 403 loop)
17
+
18
+ const crypto = require('crypto');
19
+
20
+ const { REDIS_PREFIX } = require('../consts');
21
+ const { incrementCounter } = require('../rate-limit');
22
+
23
+ const CHALLENGE_TTL = 120;
24
+ const OFFER_INTERVAL = 60;
25
+ const FAILURE_WINDOW = 300;
26
+ const MAX_REFRESH_FAILURES = 3;
27
+
28
+ const bindingKey = sid => `${REDIS_PREFIX}dbsc:b:${sid}`;
29
+ const challengeKey = challenge => `${REDIS_PREFIX}dbsc:c:${challenge}`;
30
+ const offerKey = sid => `${REDIS_PREFIX}dbsc:o:${sid}`;
31
+ const failureKey = sid => `${REDIS_PREFIX}dbsc:f:${sid}`;
32
+
33
+ /**
34
+ * @param {Object} redis - ioredis client
35
+ */
36
+ function createDbscStore(redis) {
37
+ return {
38
+ /**
39
+ * Claims the right to offer registration to a session, at most once per OFFER_INTERVAL
40
+ * @param {string} sid
41
+ * @returns {Promise<boolean>}
42
+ */
43
+ async claimOffer(sid) {
44
+ return (await redis.set(offerKey(sid), '1', 'EX', OFFER_INTERVAL, 'NX')) === 'OK';
45
+ },
46
+
47
+ /**
48
+ * @param {string} sid
49
+ * @param {'register'|'refresh'} purpose
50
+ * @returns {Promise<string>} a new challenge
51
+ */
52
+ async mintChallenge(sid, purpose) {
53
+ const challenge = crypto.randomBytes(24).toString('base64url');
54
+ await redis.set(challengeKey(challenge), JSON.stringify({ sid, purpose }), 'EX', CHALLENGE_TTL);
55
+ return challenge;
56
+ },
57
+
58
+ /**
59
+ * Spends a challenge. Answers true only for one minted for this session and step
60
+ * @param {string} challenge
61
+ * @param {string} sid
62
+ * @param {'register'|'refresh'} purpose
63
+ * @returns {Promise<boolean>}
64
+ */
65
+ async consumeChallenge(challenge, sid, purpose) {
66
+ const stored = await redis.getdel(challengeKey(challenge));
67
+ if (!stored) {
68
+ return false;
69
+ }
70
+ try {
71
+ const parsed = JSON.parse(stored);
72
+ return parsed.sid === sid && parsed.purpose === purpose;
73
+ } catch (err) {
74
+ return false;
75
+ }
76
+ },
77
+
78
+ /**
79
+ * Stores a session's key unless the session already has one: a session is bound once, so a
80
+ * stolen session cookie cannot be re-bound to a key of the thief's
81
+ * @param {string} sid
82
+ * @param {Object} binding - { id, alg, jwk }
83
+ * @param {number} ttlSeconds - the admin session's remaining life
84
+ * @returns {Promise<boolean>} false when the session was already bound
85
+ */
86
+ async bind(sid, binding, ttlSeconds) {
87
+ const value = JSON.stringify(Object.assign({}, binding, { created: Date.now() }));
88
+ return (await redis.set(bindingKey(sid), value, 'EX', Math.max(1, Math.ceil(ttlSeconds)), 'NX')) === 'OK';
89
+ },
90
+
91
+ /**
92
+ * @param {string} sid
93
+ * @returns {Promise<Object|null>}
94
+ */
95
+ async getBinding(sid) {
96
+ const stored = await redis.get(bindingKey(sid));
97
+ if (!stored) {
98
+ return null;
99
+ }
100
+ try {
101
+ return JSON.parse(stored);
102
+ } catch (err) {
103
+ return null;
104
+ }
105
+ },
106
+
107
+ /**
108
+ * Ends a binding with its session (logout) by marking it, never by deleting it: the key is
109
+ * what keeps a copied session cookie refused, so it stays for the session's remaining life
110
+ * and no key can be bound to that session again
111
+ * @param {string} sid
112
+ */
113
+ async endBinding(sid) {
114
+ const binding = await this.getBinding(sid);
115
+ if (binding && !binding.ended) {
116
+ await redis.set(bindingKey(sid), JSON.stringify(Object.assign(binding, { ended: Date.now() })), 'XX', 'KEEPTTL');
117
+ }
118
+ await redis.del(offerKey(sid), failureKey(sid));
119
+ },
120
+
121
+ /**
122
+ * Counts a failed refresh proof
123
+ * @param {string} sid
124
+ * @returns {Promise<boolean>} true while the session may still be asked again
125
+ */
126
+ async recordRefreshFailure(sid) {
127
+ return (await incrementCounter(failureKey(sid), 1, FAILURE_WINDOW)) <= MAX_REFRESH_FAILURES;
128
+ },
129
+
130
+ async clearRefreshFailures(sid) {
131
+ await redis.del(failureKey(sid));
132
+ }
133
+ };
134
+ }
135
+
136
+ module.exports = { createDbscStore, MAX_REFRESH_FAILURES, bindingKey, offerKey, failureKey };
@@ -118,6 +118,12 @@ const PRIVILEGED_SETTINGS_GROUPS = [
118
118
  label: 'the MCP and audit switches',
119
119
  keys: ['mcpEnabled', 'mcpOAuthEnabled', 'tokenAuditLog', 'tokenLogEntries', 'tokenLogAge']
120
120
  },
121
+ {
122
+ // Whether the admin session must prove it is still on the device that signed in. A
123
+ // narrowed credential switching it off would make a copied admin cookie usable again
124
+ label: 'admin session binding',
125
+ keys: ['dbscEnabled']
126
+ },
121
127
  {
122
128
  // The error reporting target
123
129
  label: 'error reporting',
package/lib/routes-ui.js CHANGED
@@ -16,6 +16,7 @@ const accountRoutes = require('./ui-routes/account-routes');
16
16
  const mcpConsentRoutes = require('./ui-routes/mcp-consent-routes');
17
17
  const tlsConfigRoutes = require('./ui-routes/tls-config-routes');
18
18
  const queueRoutes = require('./ui-routes/queue-routes');
19
+ const dbscRoutes = require('./ui-routes/dbsc-routes');
19
20
 
20
21
  function applyRoutes(server, call) {
21
22
  // Initialize admin entity routes (webhooks, templates, gateways, tokens)
@@ -52,8 +53,10 @@ function applyRoutes(server, call) {
52
53
  // TLS certificates: the configuration page, and the ACME challenge route the CA calls
53
54
  tlsConfigRoutes({ server, call });
54
55
 
55
- // Admin auth and user-profile routes (login, logout, TOTP, passkeys, password)
56
+ // Admin auth and user-profile routes (login, logout, TOTP, passkeys, password), and the
57
+ // device-bound session endpoints the browser calls (registration, refresh)
56
58
  authRoutes({ server });
59
+ dbscRoutes({ server });
57
60
 
58
61
  // OAuth2 application config routes
59
62
  oauthConfigRoutes({ server, call });
package/lib/schemas.js CHANGED
@@ -351,6 +351,14 @@ const settingsSchema = {
351
351
  .description('External authentication service URL for retrieving mailbox credentials dynamically')
352
352
  .label('AuthServer'),
353
353
 
354
+ // Off by default: browser support is still limited, the protocol is a draft standard, and a
355
+ // bound session that cannot renew its credential is signed out (lib/dbsc)
356
+ dbscEnabled: formBoolean()
357
+ .example(false)
358
+ .description(
359
+ "Bind admin sessions to a key kept in the signed-in device's security hardware (Device Bound Session Credentials), in browsers that support it, so a copied session cookie stops working within minutes. Requires an https serviceUrl. Disabled by default"
360
+ ),
361
+
354
362
  // Off by default: it adds a write to the hot path of every authenticated request, and most
355
363
  // instances will never read the result
356
364
  tokenAuditLog: formBoolean()
@@ -43,8 +43,18 @@ function requireSessionOnceSecured({ server, isInstanceSecured, logger }) {
43
43
  // Every other route sends such a session to the TOTP prompt (registerTotpExtension() in
44
44
  // workers/api.js). The login and TOTP pages have to be here or the prompt could never be answered,
45
45
  // the passkey login endpoints because a passkey is a factor of its own, and the catch-all 404 so a
46
- // mistyped URL does not bounce. test/admin-auth-guardrail-test.js checks every entry against the
47
- // route table, so a renamed route cannot leave a stale entry that silently drops the exemption.
48
- const TOTP_EXEMPT_PATHS = Object.freeze(['/{any*}', '/admin/totp', '/admin/login', '/admin/passkey/auth/options', '/admin/passkey/auth/verify']);
46
+ // mistyped URL does not bounce. The device-bound session refresh is here because the browser
47
+ // ignores a redirect there, and a session that has not passed its second factor has no binding
48
+ // for it to renew anyway (lib/dbsc answers that itself). test/admin-auth-guardrail-test.js checks
49
+ // every entry against the route table, so a renamed route cannot leave a stale entry that silently
50
+ // drops the exemption.
51
+ const TOTP_EXEMPT_PATHS = Object.freeze([
52
+ '/{any*}',
53
+ '/admin/totp',
54
+ '/admin/login',
55
+ '/admin/passkey/auth/options',
56
+ '/admin/passkey/auth/verify',
57
+ '/admin/dbsc/refresh'
58
+ ]);
49
59
 
50
60
  module.exports = { requireSessionOnceSecured, TOTP_EXEMPT_PATHS };
@@ -22,6 +22,7 @@ const { getByteSize, formatByteSize, getDuration, failAction, readEnvValue, read
22
22
  const { sendTestWebhook, testEventBody } = require('../webhook-test');
23
23
  const { llmPreProcess, buildSummaryInput, authenticationTrust } = require('../llm-pre-process');
24
24
  const { decodeHeaders } = require('../utils/decode-headers');
25
+ const { isSecureOrigin } = require('../security-headers');
25
26
  const { mcpFeatureEnabled } = require('../mcp');
26
27
  const { mcpResource } = require('../mcp/oauth');
27
28
  const { getToolRegistry } = require('../mcp/tools');
@@ -426,6 +427,15 @@ function registerConfigServicePage(server, args) {
426
427
  });
427
428
  }
428
429
 
430
+ // What the Security page says about device-bound sessions: whether the setting can take effect on
431
+ // this instance (an https Service URL, which browsers require), and whether the browser looking at
432
+ // the page is bound right now, which is the one way an operator can see it working
433
+ async function dbscStatus(request) {
434
+ const dbsc = request.server.app.dbsc;
435
+ const [serviceUrl, currentBound] = await Promise.all([settings.get('serviceUrl'), !!dbsc && dbsc.isBound(request)]);
436
+ return { active: isSecureOrigin(serviceUrl), currentBound };
437
+ }
438
+
429
439
  function registerConfigSecurityPage(server) {
430
440
  registerSettingsPage(server, {
431
441
  path: '/admin/config/security',
@@ -436,6 +446,7 @@ function registerConfigSecurityPage(server) {
436
446
  serviceSecret: settingsSchema.serviceSecret,
437
447
  ignoreMailCertErrors: settingsSchema.ignoreMailCertErrors.default(false),
438
448
  tokenAuditLog: settingsSchema.tokenAuditLog.default(false),
449
+ dbscEnabled: settingsSchema.dbscEnabled.default(false),
439
450
  tokenLogEntries: settingsSchema.tokenLogEntries.allow(null).default(null),
440
451
  // days on the form, seconds in the setting
441
452
  tokenLogAge: Joi.number().empty('').positive().precision(2).allow(null).default(null),
@@ -446,7 +457,14 @@ function registerConfigSecurityPage(server) {
446
457
  },
447
458
 
448
459
  async loadValues() {
449
- const storedValues = await settings.getMulti('serviceSecret', 'disableTokens', 'enableOAuthTokensApi', 'ignoreMailCertErrors', 'tokenAuditLog');
460
+ const storedValues = await settings.getMulti(
461
+ 'serviceSecret',
462
+ 'disableTokens',
463
+ 'enableOAuthTokensApi',
464
+ 'ignoreMailCertErrors',
465
+ 'tokenAuditLog',
466
+ 'dbscEnabled'
467
+ );
450
468
 
451
469
  return {
452
470
  ...(await overridableFormValues('tokenLogEntries', 'tokenLogAge')),
@@ -454,14 +472,17 @@ function registerConfigSecurityPage(server) {
454
472
  enableTokens: !storedValues.disableTokens,
455
473
  enableOAuthTokensApi: storedValues.enableOAuthTokensApi || false,
456
474
  ignoreMailCertErrors: storedValues.ignoreMailCertErrors || false,
457
- tokenAuditLog: storedValues.tokenAuditLog || false
475
+ tokenAuditLog: storedValues.tokenAuditLog || false,
476
+ dbscEnabled: storedValues.dbscEnabled || false
458
477
  };
459
478
  },
460
479
 
461
- async viewContext() {
480
+ async viewContext(request) {
481
+ const [encryption, dbsc] = await Promise.all([getSecret(), dbscStatus(request)]);
462
482
  return {
463
- encryption: await getSecret(),
464
- adminAccessLimit: ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length
483
+ encryption,
484
+ adminAccessLimit: ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length,
485
+ dbsc
465
486
  };
466
487
  },
467
488
 
@@ -471,6 +492,7 @@ function registerConfigSecurityPage(server) {
471
492
  enableOAuthTokensApi: request.payload.enableOAuthTokensApi,
472
493
  ignoreMailCertErrors: request.payload.ignoreMailCertErrors,
473
494
  tokenAuditLog: request.payload.tokenAuditLog,
495
+ dbscEnabled: request.payload.dbscEnabled,
474
496
  ...overridableSettingsFromForm(request.payload, 'tokenLogEntries', 'tokenLogAge')
475
497
  };
476
498
 
@@ -30,6 +30,7 @@ const PASSKEY_ALGORITHMS = [-7, -257];
30
30
  const settings = require('../settings');
31
31
  const consts = require('../consts');
32
32
  const { readEnvValue, setAdminSession } = require('../tools');
33
+ const { endDeviceBinding } = require('../dbsc');
33
34
  const passkeys = require('../passkeys');
34
35
  const sso = require('../sso');
35
36
  const { redis } = require('../db');
@@ -333,6 +334,9 @@ function registerGetLogout(server) {
333
334
  logoutUrl = await h.oidcLogoutUrl(artifacts.idToken);
334
335
  }
335
336
 
337
+ // Before the cookie is cleared: the binding is found by the session's sid
338
+ await endDeviceBinding(request, h);
339
+
336
340
  if (request.cookieAuth) {
337
341
  request.cookieAuth.clear();
338
342
  }
@@ -0,0 +1,43 @@
1
+ 'use strict';
2
+
3
+ // The two endpoints of device-bound admin sessions (lib/dbsc/). The browser calls both on its own,
4
+ // not a page, which is why neither carries a crumb: what stands in for one is a signature over a
5
+ // challenge only this server issued, to this session, minutes ago.
6
+
7
+ const { REGISTRATION_PATH, REFRESH_PATH } = require('../dbsc/protocol');
8
+
9
+ /**
10
+ * The handlers find the DBSC instance on server.app, where workers/api.js publishes it with the
11
+ * session strategy (setupDbsc() in lib/dbsc), so registration needs nothing but the server
12
+ * @param {Object} args
13
+ * @param {Object} args.server - hapi server
14
+ */
15
+ function init(args) {
16
+ const { server } = args;
17
+
18
+ server.route({
19
+ method: 'POST',
20
+ path: REGISTRATION_PATH,
21
+ // The default session strategy: only a signed-in admin session can bind itself
22
+ handler: (request, h) => request.server.app.dbsc.register(request, h),
23
+ options: {
24
+ plugins: { crumb: false }
25
+ }
26
+ });
27
+
28
+ server.route({
29
+ method: 'POST',
30
+ path: REFRESH_PATH,
31
+ // Reads the session without requiring it. The browser acts on the status of this answer, and
32
+ // the redirect to the login page a required session would produce is one it ignores, so an
33
+ // ended session has to be told so in a body it understands instead
34
+ handler: (request, h) => request.server.app.dbsc.refresh(request, h),
35
+ options: {
36
+ auth: { strategy: 'session', mode: 'try' },
37
+ // dbsc.enforce: false - a missing bound cookie is what this route renews
38
+ plugins: { crumb: false, dbsc: { enforce: false } }
39
+ }
40
+ });
41
+ }
42
+
43
+ module.exports = init;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "emailengine-app",
3
- "version": "2.87.1",
3
+ "version": "2.87.2",
4
4
  "private": false,
5
5
  "productTitle": "EmailEngine",
6
6
  "description": "Email Sync Engine",