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
@@ -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',
@@ -22,7 +22,7 @@ const { buildRetentionPolicy } = require('../queue-retention');
22
22
  const { getFailedJobRetention } = require('../env-setting-overrides');
23
23
  const { maskSecrets } = require('../api-routes/route-helpers');
24
24
  const { statusError } = require('../utils/status-error');
25
- const { retryFailedJob, promoteDelayedJob, assertJobState } = require('../queue-job-actions');
25
+ const { retryFailedJob, promoteDelayedJob, assertJobState, loadRealJob } = require('../queue-job-actions');
26
26
  const { QUEUES, QUEUES_BY_NAME, STATES, STATES_BY_NAME, STATE_NAMES, SCAN_LIMIT, BATCH_SIZE } = require('./definitions');
27
27
  const { formatJob, matchesQuery, rawJob, humanSize, notifyPayloadSize, entryUrl } = require('./format');
28
28
 
@@ -42,7 +42,7 @@ function queueObject(queueDef) {
42
42
  * @returns {Promise<string|null>} BullMQ state, or null when there is no such job
43
43
  */
44
44
  async function jobState(queueDef, jobId) {
45
- const job = await queueObject(queueDef).getJob(jobId);
45
+ const job = await loadRealJob(queueObject(queueDef), jobId);
46
46
  return job ? await job.getState() : null;
47
47
  }
48
48
 
@@ -50,7 +50,7 @@ async function jobState(queueDef, jobId) {
50
50
  * Removes a job through BullMQ alone: refused, as `locked`, when a worker is running it.
51
51
  */
52
52
  async function removeBullJob(queueDef, jobId, logger) {
53
- const job = await queueObject(queueDef).getJob(jobId);
53
+ const job = await loadRealJob(queueObject(queueDef), jobId);
54
54
  if (!job) {
55
55
  return { removed: false };
56
56
  }
@@ -71,7 +71,7 @@ async function removeBullJob(queueDef, jobId, logger) {
71
71
  }
72
72
 
73
73
  async function retryBullJob(queueDef, jobId, logger) {
74
- const job = await queueObject(queueDef).getJob(jobId);
74
+ const job = await loadRealJob(queueObject(queueDef), jobId);
75
75
  if (!job) {
76
76
  return false;
77
77
  }
@@ -82,7 +82,7 @@ async function retryBullJob(queueDef, jobId, logger) {
82
82
  }
83
83
 
84
84
  async function promoteBullJob(queueDef, jobId, logger) {
85
- const job = await queueObject(queueDef).getJob(jobId);
85
+ const job = await loadRealJob(queueObject(queueDef), jobId);
86
86
  if (!job) {
87
87
  return false;
88
88
  }
@@ -502,7 +502,7 @@ async function listJobs(options) {
502
502
  async function getJob(options) {
503
503
  const { queue: queueDef, jobId, logger } = options;
504
504
 
505
- const job = await queueObject(queueDef).getJob(jobId);
505
+ const job = await loadRealJob(queueObject(queueDef), jobId);
506
506
  if (!job) {
507
507
  return null;
508
508
  }
@@ -5,9 +5,11 @@
5
5
  // running. The submit queue's own rules (the message content that lives beside the job) are
6
6
  // layered on top of these by lib/outbox.js; the webhook queue uses them as they are.
7
7
  //
8
- // Dependency-free apart from the error shape, so lib/outbox.js can use it without a cycle
9
- // through the queue browser.
8
+ // It depends on nothing but BullMQ's DelayedError and the error shape, so lib/outbox.js can use it
9
+ // without a cycle through the queue browser. The penalty helpers at the end are shared by the
10
+ // webhook and submit queues.
10
11
 
12
+ const { DelayedError } = require('bullmq');
11
13
  const { statusError } = require('./utils/status-error');
12
14
 
13
15
  /**
@@ -82,11 +84,64 @@ async function assertJobState(job, state, noun, verb) {
82
84
  * @returns {Promise<Object|null>} The job, or null
83
85
  */
84
86
  async function getAccountJob(queue, id, account) {
85
- const job = id ? await queue.getJob(id) : null;
87
+ const job = await loadRealJob(queue, id);
86
88
  if (!job || (account && (!job.data || job.data.account !== account))) {
87
89
  return null;
88
90
  }
89
91
  return job;
90
92
  }
91
93
 
92
- module.exports = { retryFailedJob, promoteDelayedJob, assertJobState, getAccountJob };
94
+ /**
95
+ * Loads a job by an id a caller supplied. BullMQ resolves an id to the hash under the queue prefix,
96
+ * and the queue keeps its own state in hashes beside the jobs: getJob('meta') returned a job made of
97
+ * the queue's metadata, and removing it deleted the pause flag, which released every message an
98
+ * operator had held. A real job always carries a name and a creation time.
99
+ * @param {Object} queue - BullMQ queue
100
+ * @param {string} id - Job ID
101
+ * @returns {Promise<Object|null>} The job, or null
102
+ */
103
+ async function loadRealJob(queue, id) {
104
+ const job = id ? await queue.getJob(id) : null;
105
+ return job && typeof job.name === 'string' && job.timestamp ? job : null;
106
+ }
107
+
108
+ /**
109
+ * Moves a job back to the delayed set while a penalty key is set, without spending an attempt: the
110
+ * webhook queue penalises a slow target and the submit queue a stalling account the same way.
111
+ * @param {Object} job - BullMQ job
112
+ * @param {string} token - The worker's lock token
113
+ * @param {Object} redis - ioredis client
114
+ * @param {string} key - Penalty key
115
+ * @param {Function} [onDelay] - Called with the delay before the job is moved
116
+ * @throws {DelayedError} When the job was moved to the delayed set
117
+ */
118
+ async function delayWhilePenalised(job, token, redis, key, onDelay) {
119
+ const remaining = await redis.pttl(key);
120
+ if (remaining > 0) {
121
+ if (onDelay) {
122
+ onDelay(remaining);
123
+ }
124
+ await job.moveToDelayed(Date.now() + remaining, token);
125
+ throw new DelayedError();
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Sets a penalty key for `ms` milliseconds; a zero penalty sets nothing. A missed penalty costs
131
+ * the queue one more slow attempt and nothing else, so a failed write is not an error.
132
+ * @param {Object} redis - ioredis client
133
+ * @param {string} key - Penalty key
134
+ * @param {number} ms - Penalty length
135
+ */
136
+ async function setPenalty(redis, key, ms) {
137
+ if (!ms) {
138
+ return;
139
+ }
140
+ try {
141
+ await redis.set(key, '1', 'PX', ms);
142
+ } catch (err) {
143
+ // see above
144
+ }
145
+ }
146
+
147
+ module.exports = { retryFailedJob, promoteDelayedJob, assertJobState, getAccountJob, loadRealJob, delayWhilePenalised, setPenalty };
@@ -36,6 +36,7 @@ const LEGACY_UNTRIMMED_KEYS = new Set(['EENGINE_SECRET', 'EENGINE_REDIS', 'REDIS
36
36
  *
37
37
  * @param {string} key - Environment variable name
38
38
  * @returns {string|undefined} The value, or undefined when neither form is set
39
+ * @throws {Error} code `EnvFileUnreadable` when `<KEY>_FILE` names a file that can not be read
39
40
  */
40
41
  function readEnvValue(key) {
41
42
  if (key in process.env) {
@@ -43,30 +44,38 @@ function readEnvValue(key) {
43
44
  }
44
45
 
45
46
  if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
47
+ const file = process.env[`${key}_FILE`];
48
+ let contents;
46
49
  try {
47
- // try to load from file
48
- const contents = Fs.readFileSync(process.env[`${key}_FILE`], 'utf-8');
49
- const value = contents.replace(/\r?\n/g, '\n').trim();
50
- process.env[key] = value;
50
+ contents = Fs.readFileSync(file, 'utf-8');
51
+ } catch (err) {
52
+ // Fail closed. This used to resolve to an empty value, which every caller reads as
53
+ // "not configured": a missing admin password hash booted with /admin open, a missing
54
+ // address allow-list with no restriction. A file the operator named and the process
55
+ // can not read is a broken deployment, so it stops the process instead.
56
+ let error = new Error(`Can not read ${key}_FILE (${file}): ${err.message}`);
57
+ error.code = 'EnvFileUnreadable';
58
+ error.key = key;
59
+ throw error;
60
+ }
51
61
 
52
- // What the private copies in lib/db.js and lib/get-secret.js resolved the same file to.
53
- // Neither the value nor the whitespace around it is logged: the key and the file are what
54
- // the operator needs to find it, and the value is what the warning exists to protect.
55
- const legacyValue = contents.replace(/\r?\n$/, '');
56
- if (LEGACY_UNTRIMMED_KEYS.has(key) && value !== legacyValue) {
57
- getLogger().warn({
58
- msg: 'Environment value read from file carries whitespace that is now trimmed, so it resolves differently than in earlier releases. Set the variable itself rather than the file to keep the old value, as one given in the environment is used verbatim.',
59
- key,
60
- file: process.env[`${key}_FILE`]
61
- });
62
- }
62
+ const value = contents.replace(/\r?\n/g, '\n').trim();
63
+ process.env[key] = value;
63
64
 
64
- getLogger().trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
65
- } catch (err) {
66
- getLogger().error({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
67
- process.env[key] = '';
65
+ // What the private copies in lib/db.js and lib/get-secret.js resolved the same file to.
66
+ // Neither the value nor the whitespace around it is logged: the key and the file are what
67
+ // the operator needs to find it, and the value is what the warning exists to protect.
68
+ const legacyValue = contents.replace(/\r?\n$/, '');
69
+ if (LEGACY_UNTRIMMED_KEYS.has(key) && value !== legacyValue) {
70
+ getLogger().warn({
71
+ msg: 'Environment value read from file carries whitespace that is now trimmed, so it resolves differently than in earlier releases. Set the variable itself rather than the file to keep the old value, as one given in the environment is used verbatim.',
72
+ key,
73
+ file
74
+ });
68
75
  }
69
- return process.env[key];
76
+
77
+ getLogger().trace({ msg: 'Loaded environment value from file', key, file });
78
+ return value;
70
79
  }
71
80
  }
72
81
 
@@ -80,4 +89,20 @@ function hasEnvValue(key) {
80
89
  return key in process.env || `${key}_FILE` in process.env;
81
90
  }
82
91
 
83
- module.exports = { readEnvValue, hasEnvValue };
92
+ /**
93
+ * Resolves every `EENGINE_*_FILE` (and `REDIS_URL_FILE`) variable now. Called once at the start of
94
+ * the main process, so a file that can not be read stops the boot with its name instead of the
95
+ * first worker thread that reads the value crashing, and then crashing again on every respawn.
96
+ *
97
+ * @throws {Error} code `EnvFileUnreadable` for the first file that can not be read
98
+ */
99
+ function resolveEnvFiles() {
100
+ for (const name of Object.keys(process.env)) {
101
+ const match = /^(EENGINE_[A-Z0-9_]+|REDIS_URL)_FILE$/.exec(name);
102
+ if (match) {
103
+ readEnvValue(match[1]);
104
+ }
105
+ }
106
+ }
107
+
108
+ module.exports = { readEnvValue, hasEnvValue, resolveEnvFiles };
package/lib/redis-url.js CHANGED
@@ -1,5 +1,26 @@
1
1
  'use strict';
2
2
 
3
+ const { readEnvValue } = require('./read-env-value');
4
+ const { getBoolean } = require('./get-boolean');
5
+
6
+ /**
7
+ * Some managed Redis services (the Heroku Redis add-on among them) present a certificate no CA
8
+ * signed. `EENGINE_REDIS_TLS_REJECT_UNAUTHORIZED=false` relaxes verification for the Redis
9
+ * connection alone. The Heroku manifest used to set NODE_TLS_REJECT_UNAUTHORIZED=0 for that, which
10
+ * switched certificate checks off for every outbound connection of the instance: OAuth2 token
11
+ * refreshes, webhooks, IMAP and SMTP included.
12
+ *
13
+ * @param {Object} conf - ioredis options; changed in place
14
+ * @returns {Object} conf
15
+ */
16
+ function applyRedisTlsSwitch(conf) {
17
+ const value = readEnvValue('EENGINE_REDIS_TLS_REJECT_UNAUTHORIZED');
18
+ if (conf.tls && typeof value === 'string' && value.trim() && !getBoolean(value)) {
19
+ conf.tls = Object.assign({}, conf.tls, { rejectUnauthorized: false });
20
+ }
21
+ return conf;
22
+ }
23
+
3
24
  module.exports = redisConf => {
4
25
  let parsedRedisUrl = new URL(redisConf);
5
26
  let parsedUrl = {};
@@ -78,3 +99,5 @@ module.exports = redisConf => {
78
99
 
79
100
  return parsedUrl;
80
101
  };
102
+
103
+ module.exports.applyRedisTlsSwitch = applyRedisTlsSwitch;
@@ -174,6 +174,67 @@ function openSseStream(h, options) {
174
174
  return { stream, response };
175
175
  }
176
176
 
177
+ // How often an open change stream re-asks whether the credential that opened it still admits it.
178
+ // Revocations announced over lib/revocation-events.js are acted on at once; this catches the rest
179
+ // (an expired token, a session ended by a password change).
180
+ const CHANGE_STREAM_RECHECK_INTERVAL = 60 * 1000;
181
+
182
+ let changeStreamRecheckTimer = null;
183
+ let changeStreamRecheckInFlight = null;
184
+
185
+ /**
186
+ * Re-runs the authentication of every open change stream through the strategy that admitted it,
187
+ * against the request that opened it, and closes the streams whose credential is refused now. The
188
+ * feed used to be authorized once, at open, so a revoked or expired token, an ended admin session
189
+ * and an SSO user removed from the allow-list kept receiving every account's change events for as
190
+ * long as the client held the connection. A call made while a pass runs joins it.
191
+ *
192
+ * @returns {Promise<void>}
193
+ */
194
+ function recheckChangeStreams() {
195
+ if (!changeStreamRecheckInFlight) {
196
+ changeStreamRecheckInFlight = (async () => {
197
+ const streams = [...registeredPublishers].filter(stream => stream.recheckAuth && !stream._finalized);
198
+ if (!streams.length && changeStreamRecheckTimer) {
199
+ // the last change stream is gone; the next one to open starts the timer again
200
+ clearInterval(changeStreamRecheckTimer);
201
+ changeStreamRecheckTimer = null;
202
+ }
203
+ const answers = await Promise.all(streams.map(stream => stream.recheckAuth()));
204
+ streams.forEach((stream, i) => {
205
+ if (!answers[i] && !stream._finalized) {
206
+ stream.finalize();
207
+ }
208
+ });
209
+ })().finally(() => {
210
+ changeStreamRecheckInFlight = null;
211
+ });
212
+ }
213
+ return changeStreamRecheckInFlight;
214
+ }
215
+
216
+ /**
217
+ * Whether the credential behind `request` still passes its route's strategy. A refusal is false:
218
+ * a 401 or 403, or the redirect to the login page the admin session strategy answers a refused
219
+ * session with (thrown by auth.test() as a response, not as an error). Anything else (a Redis
220
+ * fault) says nothing about the credential and keeps the stream.
221
+ *
222
+ * @param {Object} request - The hapi request that opened the stream
223
+ * @returns {Promise<boolean>}
224
+ */
225
+ async function credentialStillAdmits(request) {
226
+ request.app.authRecheck = true;
227
+ try {
228
+ await request.server.auth.test(request.auth.strategy, request);
229
+ return true;
230
+ } catch (err) {
231
+ const status = (err && ((err.output && err.output.statusCode) || err.statusCode)) || 0;
232
+ return !(status === 401 || status === 403 || (status >= 300 && status < 400));
233
+ } finally {
234
+ request.app.authRecheck = false;
235
+ }
236
+ }
237
+
177
238
  /**
178
239
  * Opens the SSE change feed shared by /admin/changes and /v1/changes.
179
240
  *
@@ -184,7 +245,14 @@ function openSseStream(h, options) {
184
245
  function openChangeStream(request, h) {
185
246
  const { stream, response } = openSseStream(h);
186
247
  request.app.stream = stream;
248
+ if (request.auth && request.auth.strategy) {
249
+ stream.recheckAuth = () => credentialStillAdmits(request);
250
+ if (!changeStreamRecheckTimer) {
251
+ changeStreamRecheckTimer = setInterval(recheckChangeStreams, CHANGE_STREAM_RECHECK_INTERVAL);
252
+ changeStreamRecheckTimer.unref();
253
+ }
254
+ }
187
255
  return response;
188
256
  }
189
257
 
190
- module.exports = { ResponseStream, registeredPublishers, openChangeStream, openSseStream, MAX_BUFFERED_BYTES };
258
+ module.exports = { ResponseStream, registeredPublishers, openChangeStream, openSseStream, recheckChangeStreams, MAX_BUFFERED_BYTES };
@@ -0,0 +1,79 @@
1
+ 'use strict';
2
+
3
+ // Tells long-lived sessions that a credential or account they may depend on has changed, so they
4
+ // re-check it now instead of at their next periodic check. The message names what changed only
5
+ // as a hint: every subscriber re-checks its own sessions against the stored state, so a lost or
6
+ // duplicated message costs at most one periodic interval, never a wrong decision.
7
+ //
8
+ // Redis pub/sub rather than a worker message, because a credential can be revoked from a process
9
+ // that has no worker channel at all (the `emailengine tokens delete` command).
10
+
11
+ const logger = require('./logger');
12
+ const { redis, watchRedisReconnect } = require('./db');
13
+ const { REDIS_PREFIX } = require('./consts');
14
+
15
+ const REVOCATION_CHANNEL = `${REDIS_PREFIX}ee:revocations`;
16
+
17
+ let subscriber = null;
18
+ const handlers = new Set();
19
+
20
+ /**
21
+ * Announces that a credential or account changed in a way that may end open sessions.
22
+ * Never throws: the periodic re-check is the fallback for a message that is not delivered.
23
+ *
24
+ * @param {Object} detail - What changed, e.g. `{ type: 'token' }` or `{ type: 'account', account }`
25
+ * @returns {Promise<void>}
26
+ */
27
+ async function publishRevocation(detail) {
28
+ try {
29
+ await redis.publish(REVOCATION_CHANNEL, JSON.stringify(detail));
30
+ } catch (err) {
31
+ logger.warn({ msg: 'Failed to announce a credential change', detail, err });
32
+ }
33
+ }
34
+
35
+ function dispatch(message) {
36
+ let detail = {};
37
+ try {
38
+ detail = JSON.parse(message) || {};
39
+ } catch (err) {
40
+ // a malformed message still means "re-check"
41
+ }
42
+ for (const handler of handlers) {
43
+ try {
44
+ handler(detail);
45
+ } catch (err) {
46
+ logger.error({ msg: 'Credential change handler failed', err });
47
+ }
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Calls `handler(detail)` for every announced change. The subscriber connection is opened on the
53
+ * first registration and shared by every handler in this process.
54
+ *
55
+ * @param {Function} handler
56
+ * @returns {Function} Removes the handler
57
+ */
58
+ function onRevocation(handler) {
59
+ handlers.add(handler);
60
+ if (!subscriber) {
61
+ subscriber = redis.duplicate();
62
+ subscriber.on('error', err => logger.warn({ msg: 'Credential change subscriber error', err }));
63
+ subscriber.on('message', (channel, message) => dispatch(message));
64
+ // Whatever was published while the connection was down is lost, so every handler
65
+ // re-checks everything once it is back
66
+ watchRedisReconnect(subscriber, () => dispatch('{}'));
67
+ subscriber.subscribe(REVOCATION_CHANNEL).catch(err => logger.error({ msg: 'Failed to subscribe to credential changes', err }));
68
+ }
69
+ return () => {
70
+ handlers.delete(handler);
71
+ if (!handlers.size && subscriber) {
72
+ const closing = subscriber;
73
+ subscriber = null;
74
+ closing.quit().catch(() => closing.disconnect());
75
+ }
76
+ };
77
+ }
78
+
79
+ module.exports = { publishRevocation, onRevocation, REVOCATION_CHANNEL };
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()
@@ -1534,12 +1542,28 @@ const licenseSchema = Joi.object({
1534
1542
  created: Joi.date().example('2021-10-13T07:47:42.695Z').description('License creation date'),
1535
1543
  trial: Joi.boolean().example(false).description('Whether this is a trial license'),
1536
1544
  lt: Joi.boolean().example(false).description('Whether this is a lifetime license'),
1537
- expires: Joi.date().iso().example('2026-01-01T00:00:00.000Z').description('License expiration time, if the license is time-limited')
1545
+ expires: Joi.date().iso().example('2026-01-01T00:00:00.000Z').description('License expiration time, if the license is time-limited'),
1546
+ billing: Joi.string().valid('monthly').example('monthly').description('Set for the license of a monthly plan').label('LicenseBilling')
1538
1547
  })
1539
1548
  .allow(false)
1540
1549
  .description('Details of the registered license. False when no license is registered.')
1541
1550
  .label('LicenseDetails'),
1542
- suspended: Joi.boolean().example(false).description('Whether email operations are suspended due to license issues')
1551
+ suspended: Joi.boolean().example(false).description('Whether email operations are suspended due to license issues'),
1552
+ subscription: Joi.object({
1553
+ status: Joi.string()
1554
+ .valid('overdue', 'suspended')
1555
+ .example('overdue')
1556
+ .description(
1557
+ 'overdue: a payment is due and EmailEngine keeps working until `until`; suspended: email processing has stopped until the subscription is in good standing'
1558
+ )
1559
+ .label('LicenseSubscriptionStatus'),
1560
+ code: Joi.string().allow(null).example('PaymentOverdue').description('Reason reported by the license server'),
1561
+ error: Joi.string().allow(null).example('Subscription payment overdue').description('Human-readable reason'),
1562
+ since: Joi.date().iso().allow(null).example('2026-12-01T10:00:00.000Z').description('When the payment became overdue or the subscription ended'),
1563
+ until: Joi.date().iso().allow(null).example('2026-12-08T10:00:00.000Z').description('When EmailEngine pauses, or paused')
1564
+ })
1565
+ .description('Present only while the subscription behind a subscription license is not in good standing')
1566
+ .label('LicenseSubscription')
1543
1567
  }).label('LicenseInfo');
1544
1568
 
1545
1569
  const lastErrorSchema = Joi.object({
@@ -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 };
package/lib/settings.js CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { accountDataKey } = require('./redis-keys');
4
+ const { keepsSubscriptionState } = require('./license-subscription');
4
5
  const { redis } = require('./db');
5
6
  const logger = require('./logger');
6
7
  const { encrypt, decryptField } = require('./encrypt');
@@ -9,6 +10,14 @@ const getSecret = require('./get-secret');
9
10
 
10
11
  const { DEFAULT_MAX_LOG_LINES, REDIS_PREFIX } = require('./consts');
11
12
  const { PRIVILEGED_SETTINGS_KEYS } = require('./privileged-settings');
13
+ const { publishRevocation } = require('./revocation-events');
14
+
15
+ // A rotated IMAP proxy password ends the sessions the old one opened
16
+ async function announceRevokingChange(keys) {
17
+ if (keys.includes('imapProxyServerPassword')) {
18
+ await publishRevocation({ type: 'setting', key: 'imapProxyServerPassword' });
19
+ }
20
+ }
12
21
 
13
22
  config.service = config.service || {};
14
23
 
@@ -296,7 +305,9 @@ module.exports = {
296
305
  }
297
306
  }
298
307
 
299
- return await redis.hset(`${REDIS_PREFIX}settings`, key, value);
308
+ let result = await redis.hset(`${REDIS_PREFIX}settings`, key, value);
309
+ await announceRevokingChange([key]);
310
+ return result;
300
311
  },
301
312
 
302
313
  // Store a value only if the key does not exist yet (atomic HSETNX). Meant for one-shot
@@ -342,7 +353,9 @@ module.exports = {
342
353
  await module.exports.clear('sentryAutoEnabled');
343
354
  }
344
355
 
345
- return await redis.hmset(`${REDIS_PREFIX}settings`, storeObj);
356
+ let result = await redis.hmset(`${REDIS_PREFIX}settings`, storeObj);
357
+ await announceRevokingChange(Object.keys(storeObj));
358
+ return result;
346
359
  },
347
360
 
348
361
  async clear(...keys) {
@@ -350,7 +363,9 @@ module.exports = {
350
363
  if (!keys.length) {
351
364
  return 0;
352
365
  }
353
- return await redis.hdel(`${REDIS_PREFIX}settings`, ...keys);
366
+ let result = await redis.hdel(`${REDIS_PREFIX}settings`, ...keys);
367
+ await announceRevokingChange(keys);
368
+ return result;
354
369
  },
355
370
 
356
371
  async getLoggingInfo(account, settingData) {
@@ -423,28 +438,33 @@ ${Buffer.from(licenseFile, 'base64url').toString('base64')}
423
438
  throw err;
424
439
  }
425
440
 
426
- if (licenseData.trial) {
427
- // check if can activate a trial license
428
- let trialActivated = await redis.hget(`${REDIS_PREFIX}settings`, 'tract');
429
- if (trialActivated) {
430
- let trialData;
431
- try {
432
- trialData = JSON.parse(trialActivated);
433
- } catch (err) {
434
- // ignore?
435
- }
436
- if (trialData && trialData.key !== licenseData.key) {
437
- let err = new Error('Trial already activated');
438
- err.code = 'ETrialActive';
439
- throw err;
440
- }
441
- }
441
+ // The last registered license (tract): a trial may not be swapped for another trial, and the
442
+ // same key registered again keeps the subscription deadline and any suspension, since otherwise
443
+ // posting the file again, or the restart that re-imports a license file or
444
+ // EENGINE_PREPARED_LICENSE, would lift a suspension (lib/license-subscription.js). An unreadable
445
+ // record counts as no record.
446
+ let storedRecord = await redis.hget(`${REDIS_PREFIX}settings`, 'tract');
447
+ let stored;
448
+ try {
449
+ stored = JSON.parse(storedRecord || 'null');
450
+ } catch (err) {
451
+ stored = null;
452
+ }
453
+
454
+ if (licenseData.trial && stored && stored.key !== licenseData.key) {
455
+ let err = new Error('Trial already activated');
456
+ err.code = 'ETrialActive';
457
+ throw err;
442
458
  }
443
459
 
444
- await redis
445
- .multi()
446
- .hset(`${REDIS_PREFIX}settings`, 'license', licenseFile)
447
- .hdel(`${REDIS_PREFIX}settings`, 'subexp')
460
+ let storedKey = stored && typeof stored.key === 'string' ? stored.key : null;
461
+ let keepState = keepsSubscriptionState(storedKey, licenseData.key);
462
+
463
+ let multi = redis.multi().hset(`${REDIS_PREFIX}settings`, 'license', licenseFile);
464
+ if (!keepState) {
465
+ multi = multi.hdel(`${REDIS_PREFIX}settings`, 'subexp', 'subsusp');
466
+ }
467
+ await multi
448
468
  .hset(
449
469
  `${REDIS_PREFIX}settings`,
450
470
  'tract',
@@ -501,7 +521,10 @@ ${Buffer.from(licenseFile, 'base64url').toString('base64')}
501
521
  // and the trial Sentry default that activation may have applied. Used by the explicit
502
522
  // remove-license actions and by the grace-period expiry in server.js.
503
523
  async removeLicense() {
504
- await redis.multi().hdel(`${REDIS_PREFIX}settings`, 'license').hdel(`${REDIS_PREFIX}settings`, 'subexp').exec();
524
+ // The subscription deadline and any suspension stay, tied to the key in `tract`: registering the
525
+ // same key again must find them, or removing and re-adding it would lift a suspension. A
526
+ // different key clears them (setLicense)
527
+ await redis.hdel(`${REDIS_PREFIX}settings`, 'license');
505
528
  await module.exports.clearTrialSentryDefault('license removal');
506
529
  return true;
507
530
  }