emailengine-app 2.87.2 → 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 (64) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +23 -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/email-client/base-client.js +36 -15
  17. package/lib/email-client/gmail-client.js +20 -6
  18. package/lib/email-client/imap/connection-errors.js +30 -1
  19. package/lib/email-client/imap/session-expiry.js +83 -0
  20. package/lib/email-client/imap-client.js +12 -2
  21. package/lib/email-client/smtp-pool-manager.js +66 -8
  22. package/lib/export.js +147 -22
  23. package/lib/graph-notifications.js +60 -0
  24. package/lib/imap-proxy-auth.js +52 -18
  25. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  26. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  27. package/lib/imapproxy/imap-server.js +10 -1
  28. package/lib/imapproxy/proxy-handoff.js +100 -5
  29. package/lib/license-subscription.js +238 -0
  30. package/lib/oauth/gmail.js +18 -0
  31. package/lib/oauth/outlook-identity.js +54 -12
  32. package/lib/prepared-password.js +38 -0
  33. package/lib/queue-browser/index.js +6 -6
  34. package/lib/queue-job-actions.js +59 -4
  35. package/lib/read-env-value.js +46 -21
  36. package/lib/redis-url.js +23 -0
  37. package/lib/response-stream.js +69 -1
  38. package/lib/revocation-events.js +79 -0
  39. package/lib/schemas.js +18 -2
  40. package/lib/settings.js +47 -24
  41. package/lib/sso.js +23 -0
  42. package/lib/submit-penalty.js +24 -0
  43. package/lib/submit-processor.js +10 -2
  44. package/lib/tokens.js +6 -0
  45. package/lib/tools.js +86 -15
  46. package/lib/ui-routes/admin-config-routes.js +3 -276
  47. package/lib/ui-routes/auth-routes.js +13 -64
  48. package/lib/ui-routes/license-routes.js +326 -0
  49. package/lib/web-safe-html.js +29 -0
  50. package/lib/webhook-delivery.js +21 -20
  51. package/lib/webhook-penalty.js +18 -17
  52. package/lib/webhooks.js +18 -0
  53. package/package.json +18 -18
  54. package/sbom.json +294 -294
  55. package/scan.js +2 -0
  56. package/server.js +253 -80
  57. package/static/css/flyonui.css +2 -2
  58. package/static/js/ui.js +11 -4
  59. package/static/licenses.html +27 -27
  60. package/translations/messages.pot +17 -17
  61. package/views/config/license.hbs +43 -16
  62. package/views/partials/side_menu.hbs +1 -1
  63. package/workers/api.js +108 -107
  64. package/workers/imap.js +4 -6
@@ -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/schemas.js CHANGED
@@ -1542,12 +1542,28 @@ const licenseSchema = Joi.object({
1542
1542
  created: Joi.date().example('2021-10-13T07:47:42.695Z').description('License creation date'),
1543
1543
  trial: Joi.boolean().example(false).description('Whether this is a trial license'),
1544
1544
  lt: Joi.boolean().example(false).description('Whether this is a lifetime license'),
1545
- 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')
1546
1547
  })
1547
1548
  .allow(false)
1548
1549
  .description('Details of the registered license. False when no license is registered.')
1549
1550
  .label('LicenseDetails'),
1550
- 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')
1551
1567
  }).label('LicenseInfo');
1552
1568
 
1553
1569
  const lastErrorSchema = Joi.object({
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
  }
package/lib/sso.js CHANGED
@@ -384,7 +384,30 @@ function buildOidcBellProvider(discoveryDoc, options) {
384
384
  };
385
385
  }
386
386
 
387
+ /**
388
+ * Whether the identity provider of an SSO admin session still admits its user: a profile with an id
389
+ * for Okta and OIDC, and for OIDC the email and group allow-lists, re-checked on every request so a
390
+ * change to them (after a restart) takes effect without waiting out the session cookie. Asked by
391
+ * both the session strategy and the message browser's `sess_` token, which rides the same cookie and
392
+ * used to skip the allow-list, so it kept working for a removed user. A local session is admitted.
393
+ *
394
+ * @param {Object} session - The `ee` session cookie
395
+ * @param {Object} allowList - parseAllowList() result
396
+ * @param {Object} allowGroups - parseGroupList() result
397
+ * @returns {boolean}
398
+ */
399
+ function ssoSessionAdmitted(session, allowList, allowGroups) {
400
+ if (!session || (session.provider !== 'oidc' && session.provider !== 'okta')) {
401
+ return true;
402
+ }
403
+ if (!session.profile || !session.profile.id) {
404
+ return false;
405
+ }
406
+ return session.provider !== 'oidc' || isAuthorized(session.profile, allowList, allowGroups);
407
+ }
408
+
387
409
  module.exports = {
410
+ ssoSessionAdmitted,
388
411
  OIDC_ISSUER,
389
412
  OIDC_CLIENT_ID,
390
413
  OIDC_CLIENT_SECRET,
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ // A delivery penalty per account, for the submit queue. The queue is shared by every account and
4
+ // runs one delivery at a time by default, so an account whose SMTP server holds each delivery until
5
+ // the deadline used to hold the whole queue: a few such messages delayed every other account's mail
6
+ // by the full deadline each. An account whose delivery ran into the deadline is penalised: for a
7
+ // while its next messages are moved back to the delayed set instead of being attempted, with their
8
+ // attempt count unchanged, and the queue spends its time on accounts whose servers answer. Mirrors
9
+ // lib/webhook-penalty.js.
10
+
11
+ const { REDIS_PREFIX } = require('./consts');
12
+
13
+ // How long an account is penalised after a delivery ran into the deadline
14
+ const SUBMIT_PENALTY_MS = 10 * 60 * 1000;
15
+
16
+ /**
17
+ * @param {string} account - Account id
18
+ * @returns {string} The Redis key of the account's penalty
19
+ */
20
+ function submitPenaltyKey(account) {
21
+ return `${REDIS_PREFIX}submit:penalty:${account}`;
22
+ }
23
+
24
+ module.exports = { submitPenaltyKey, SUBMIT_PENALTY_MS };
@@ -14,6 +14,8 @@
14
14
  // completes keeps its marker until the marker expires.
15
15
 
16
16
  const { UnrecoverableError } = require('bullmq');
17
+ const { delayWhilePenalised } = require('./queue-job-actions');
18
+ const { submitPenaltyKey } = require('./submit-penalty');
17
19
 
18
20
  const { decodeQueueEntry, outboxKey } = require('./outbox');
19
21
  const { shouldDiscardJob, willBeFinalAttempt, nextAttemptWhileProcessing } = require('./delivery-error');
@@ -37,10 +39,10 @@ function normalizeQueueId(job) {
37
39
  * @param {Object} deps.logger
38
40
  * @param {Object} deps.submitQueue - the BullMQ queue the jobs belong to, read back for a job's stored progress
39
41
  * @param {Function} deps.getAccount - async (accountId) => object with submitMessage(queueEntry)
40
- * @returns {Function} async (job) => processes one queued message
42
+ * @returns {Function} async (job, token) => processes one queued message
41
43
  */
42
44
  function createSubmitProcessor({ redis, logger, submitQueue, getAccount }) {
43
- return async job => {
45
+ return async (job, token) => {
44
46
  normalizeQueueId(job);
45
47
 
46
48
  // A job re-run after a stall (heartbeat kill, crash, a shutdown drain that could not cover
@@ -93,6 +95,12 @@ function createSubmitProcessor({ redis, logger, submitQueue, getAccount }) {
93
95
  return;
94
96
  }
95
97
 
98
+ // An account whose last delivery ran into the deadline waits, so its server does not hold
99
+ // the queue every other account shares; see lib/submit-penalty.js
100
+ await delayWhilePenalised(job, token, redis, submitPenaltyKey(job.data.account), delay =>
101
+ logger.info({ msg: 'Account is penalised for a stalled delivery, delaying message', account: job.data.account, job: job.id, delay })
102
+ );
103
+
96
104
  let accountObject = await getAccount(job.data.account);
97
105
 
98
106
  logger.trace({
package/lib/tokens.js CHANGED
@@ -8,6 +8,7 @@ const { REDIS_PREFIX } = require('./consts');
8
8
  const { constantTimeEqual, matchesListQuery } = require('./tools');
9
9
  const { extractMultiError } = require('./redis-operations');
10
10
  const tokenAuditLog = require('./token-audit-log');
11
+ const { publishRevocation } = require('./revocation-events');
11
12
 
12
13
  const SESS_PREFIX = 'sess_';
13
14
 
@@ -370,6 +371,9 @@ module.exports = {
370
371
 
371
372
  logger.info(Object.assign({}, tokenData, { msg: 'Deleted an access token', remoteAddress: opts.remoteAddress }));
372
373
 
374
+ // Sessions this token opened end now
375
+ await publishRevocation({ type: 'token', account: tokenData.account || null });
376
+
373
377
  return true;
374
378
  },
375
379
 
@@ -424,6 +428,8 @@ module.exports = {
424
428
 
425
429
  logger.info({ msg: 'Deleted the access tokens of an account', account, tokens: hashedTokens.length });
426
430
 
431
+ await publishRevocation({ type: 'token', account });
432
+
427
433
  return hashedTokens.length;
428
434
  },
429
435