emailengine-app 2.87.2 → 2.89.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 (71) hide show
  1. package/.ncurc.js +24 -44
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +37 -0
  4. package/ENVIRONMENT.md +26 -23
  5. package/LICENSE_EMAILENGINE.txt +20 -12
  6. package/app.json +3 -3
  7. package/bin/emailengine.js +7 -11
  8. package/data/google-crawlers.json +1 -1
  9. package/data/public_suffix_list.dat +155 -16
  10. package/lib/account.js +69 -49
  11. package/lib/admin-password.js +85 -0
  12. package/lib/api-routes/license-routes.js +9 -0
  13. package/lib/api-token-auth.js +21 -5
  14. package/lib/calendar-event.js +15 -3
  15. package/lib/consts.js +5 -0
  16. package/lib/db.js +1 -0
  17. package/lib/email-client/base-client.js +36 -15
  18. package/lib/email-client/gmail-client.js +20 -6
  19. package/lib/email-client/imap/connection-errors.js +30 -1
  20. package/lib/email-client/imap/session-expiry.js +83 -0
  21. package/lib/email-client/imap-client.js +12 -2
  22. package/lib/email-client/smtp-pool-manager.js +66 -8
  23. package/lib/export.js +147 -22
  24. package/lib/graph-notifications.js +60 -0
  25. package/lib/imap-proxy-auth.js +52 -18
  26. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  27. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  28. package/lib/imapproxy/imap-server.js +10 -1
  29. package/lib/imapproxy/proxy-handoff.js +100 -5
  30. package/lib/license-subscription.js +244 -0
  31. package/lib/node-version.js +99 -12
  32. package/lib/oauth/gmail.js +18 -0
  33. package/lib/oauth/outlook-identity.js +54 -12
  34. package/lib/prepared-password.js +38 -0
  35. package/lib/queue-browser/index.js +6 -6
  36. package/lib/queue-job-actions.js +59 -4
  37. package/lib/read-env-value.js +46 -21
  38. package/lib/redis-url.js +23 -0
  39. package/lib/response-stream.js +69 -1
  40. package/lib/revocation-events.js +79 -0
  41. package/lib/schemas.js +18 -2
  42. package/lib/settings.js +50 -24
  43. package/lib/sso.js +23 -0
  44. package/lib/submit-penalty.js +24 -0
  45. package/lib/submit-processor.js +10 -2
  46. package/lib/tokens.js +6 -0
  47. package/lib/tools.js +90 -18
  48. package/lib/ui-routes/admin-config-routes.js +3 -276
  49. package/lib/ui-routes/auth-routes.js +13 -64
  50. package/lib/ui-routes/dashboard-routes.js +4 -0
  51. package/lib/ui-routes/license-routes.js +326 -0
  52. package/lib/web-safe-html.js +74 -1
  53. package/lib/webhook-delivery.js +21 -20
  54. package/lib/webhook-penalty.js +18 -17
  55. package/lib/webhooks.js +18 -0
  56. package/list-generate.js +56 -19
  57. package/package.json +28 -31
  58. package/sbom.json +373 -964
  59. package/scan.js +2 -0
  60. package/server.js +273 -100
  61. package/static/css/flyonui.css +2 -2
  62. package/static/js/ui.js +11 -4
  63. package/static/licenses.html +1108 -504
  64. package/translations/messages.pot +18 -18
  65. package/views/config/license.hbs +43 -16
  66. package/views/dashboard.hbs +9 -0
  67. package/views/partials/side_menu.hbs +1 -1
  68. package/views/upgrade.hbs +25 -0
  69. package/workers/api.js +108 -107
  70. package/workers/imap.js +4 -6
  71. package/lib/net-tos-guard.js +0 -42
package/scan.js CHANGED
@@ -23,6 +23,8 @@ const REDIS_CONF = Object.assign(
23
23
  typeof redisConf === 'string' ? redisUrl(redisConf) : redisConf || {}
24
24
  );
25
25
 
26
+ redisUrl.applyRedisTlsSwitch(REDIS_CONF);
27
+
26
28
  const redis = new Redis(REDIS_CONF);
27
29
 
28
30
  const MAX_PAGE = 1000;
package/server.js CHANGED
@@ -40,28 +40,35 @@ if (!process.env.EE_ENV_LOADED) {
40
40
  // Set process title for easier identification in process lists
41
41
  process.title = 'emailengine';
42
42
 
43
- // EmailEngine and its dependencies need Node 20 or newer. Checked before anything is required, so an
44
- // older runtime gets this line instead of a syntax error from a dependency. The check used to be a
45
- // structuredClone probe, which only caught Node 16 and older.
46
- if (Number(process.versions.node.split('.')[0]) < 20) {
47
- console.error(`Node.js version ${process.version} is not supported. Please upgrade to Node.js 20 or later.`);
43
+ // Every EENGINE_*_FILE is read now: a file the operator named and the process can not read stops
44
+ // the boot here, once and by name, rather than resolving to an empty value (which every reader
45
+ // takes for "not configured") or crashing each worker thread that reads it later.
46
+ try {
47
+ require('./lib/read-env-value').resolveEnvFiles();
48
+ } catch (err) {
49
+ console.error(err.message);
48
50
  process.exit(1);
49
51
  }
50
52
 
51
- // Within Node 20 the dependency tree itself asks for 20.19.0 (html-to-text 10, the entities release
52
- // node-html-parser pulls in) or 20.18.1 (undici 7), which is what the engines field declares. npm
53
- // treats that field as advice, and an older 20.x starts and then fails somewhere in a dependency at
54
- // runtime, so it is named here. Only a warning: one-click DigitalOcean images upgrade EmailEngine on
55
- // their own but not the Node they run on, and an instance that works today must not stop at its next
56
- // self-upgrade over a minor version it may never exercise.
57
- const { accountDataKey } = require('./lib/redis-keys');
58
- const { MIN_SUPPORTED_NODE, isBelowSupportedNode } = require('./lib/node-version');
59
- if (isBelowSupportedNode(process.versions.node)) {
60
- console.error(
61
- `Node.js version ${process.version} is older than ${MIN_SUPPORTED_NODE}, the oldest release EmailEngine's dependencies support. Some features may fail at runtime. Please upgrade Node.js.`
62
- );
53
+ // Checked before anything else is required. Below MIN_NODE undici, which every thread loads at
54
+ // startup, throws when it is loaded, so an older runtime gets this message and the commands to fix it
55
+ // instead of a TypeError from inside a dependency. A one-click DigitalOcean droplet upgrades
56
+ // EmailEngine on its own but not the Node.js it runs on, and that log line is all its operator sees.
57
+ // A release that starts but is outside the supported range is only warned about here and on the
58
+ // dashboard (see lib/node-version.js for the two thresholds).
59
+ const { MIN_NODE, SUPPORTED_RANGE_LABEL, nodeSupport, nodeUpgradeHint } = require('./lib/node-version');
60
+ const nodeSupportLevel = nodeSupport(process.versions.node);
61
+ if (nodeSupportLevel === 'unsupported') {
62
+ console.error(`EmailEngine requires Node.js ${MIN_NODE} or newer, this is Node.js ${process.version}.\n\n${nodeUpgradeHint()}`);
63
+ process.exit(1);
64
+ }
65
+ if (nodeSupportLevel === 'outside-range') {
66
+ console.error(`Node.js ${process.version} is outside the range EmailEngine supports (${SUPPORTED_RANGE_LABEL}). It runs, but please upgrade Node.js.`);
63
67
  }
64
68
 
69
+ const { accountDataKey } = require('./lib/redis-keys');
70
+ const { importPreparedPassword } = require('./lib/prepared-password');
71
+
65
72
  const os = require('os');
66
73
 
67
74
  // Set UV thread pool size for better async I/O performance
@@ -149,8 +156,19 @@ const { settingsSchema } = require('./lib/schemas');
149
156
  const settings = require('./lib/settings');
150
157
  const { oauth2Apps } = require('./lib/oauth2-apps');
151
158
  const { backfillAuthFailureDisabled } = require('./lib/account/auth-failure-backfill');
159
+ const { backfillExportIndex } = require('./lib/export');
152
160
  const { sweepBounceStore } = require('./lib/account/bounce-store-sweep');
153
161
  const { attachBeacon, persistBeaconMarkers } = require('./lib/license-beacon');
162
+ const {
163
+ decide,
164
+ startupPlan,
165
+ expiredSuspension,
166
+ checkInterval,
167
+ subscriptionView,
168
+ parseSuspension,
169
+ isSubscriptionLicense,
170
+ toTime
171
+ } = require('./lib/license-subscription');
154
172
  const tokens = require('./lib/tokens');
155
173
 
156
174
  const { checkRateLimit } = require('./lib/rate-limit');
@@ -231,11 +249,6 @@ const EENGINE_TIMEOUT = getDuration(readEnvValue('EENGINE_TIMEOUT') || config.se
231
249
  // Size limits
232
250
  const DEFAULT_MAX_ATTACHMENT_SIZE = 5 * 1024 * 1024; // 5MB
233
251
 
234
- // License check intervals
235
- const SUBSCRIPTION_CHECK_TIMEOUT = 1 * 24 * 60 * 60 * 1000; // 24 hours
236
- const SUBSCRIPTION_RECHECK_TIMEOUT = 1 * 60 * 60 * 1000; // 1 hour
237
- const SUBSCRIPTION_ALLOW_DELAY = 28 * 24 * 60 * 60 * 1000; // 28 days grace period
238
-
239
252
  // Delay between account connection setups (to avoid overwhelming the system)
240
253
  const CONNECTION_SETUP_DELAY = getDuration(readEnvValue('EENGINE_CONNECTION_SETUP_DELAY') || config.service.setupDelay) || 0;
241
254
 
@@ -333,7 +346,6 @@ WORKER_DIED_RESP_ERR.code = 'WorkerNotAvailable';
333
346
  // Update check intervals
334
347
  const UPGRADE_CHECK_TIMEOUT = 1 * 24 * 3600 * 1000; // 24 hours
335
348
  const LICENSE_CHECK_TIMEOUT = 20 * 60 * 1000; // 20 minutes
336
- const MAX_LICENSE_CHECK_DELAY = 30 * 24 * 60 * 60 * 1000; // 30 days
337
349
 
338
350
  /**
339
351
  * License information object
@@ -2147,28 +2159,136 @@ async function assignAccounts() {
2147
2159
  // License checking state
2148
2160
  let licenseCheckTimer = false;
2149
2161
  let checkingLicense = false;
2162
+ // set by startApplication: the stored subscription state asks for an online check at startup
2163
+ let startupLicenseCheck = false;
2164
+
2165
+ // The worker types that run only under a valid license; everything but the API server
2166
+ const LICENSED_WORKER_TYPES = ['imap', 'submit', 'smtp', 'webhooks', 'imapProxy'];
2167
+
2168
+ // The stored subscription deadline (`subexp`, ms) as last written by this thread, so the license
2169
+ // command answering every request does not read Redis for it
2170
+ let subscriptionDeadline = null;
2171
+
2172
+ /**
2173
+ * Records a subscription license as suspended, or no longer suspended. The workers follow at the
2174
+ * end of the next license check (licenseCheckHandler)
2175
+ * @param {Object|null} suspension - the subsusp record, or null to lift a suspension
2176
+ * @returns {void}
2177
+ */
2178
+ const setSuspension = suspension => {
2179
+ if (suspension) {
2180
+ licenseInfo.active = false;
2181
+ licenseInfo.suspension = suspension;
2182
+ } else {
2183
+ licenseInfo.active = true;
2184
+ delete licenseInfo.suspension;
2185
+ }
2186
+ };
2187
+
2188
+ /**
2189
+ * Forgets the registered license in this thread, after settings.removeLicense()
2190
+ * @returns {void}
2191
+ */
2192
+ const clearLicenseInfo = () => {
2193
+ licenseInfo.active = false;
2194
+ licenseInfo.details = false;
2195
+ delete licenseInfo.suspension;
2196
+ subscriptionDeadline = null;
2197
+ licenseInfo.type = packageData.license;
2198
+ };
2199
+
2200
+ /**
2201
+ * Applies one decision of lib/license-subscription.js to the stored state and to licenseInfo
2202
+ * @param {Object} decision - decide() output
2203
+ * @param {Object} data - the license server's answer
2204
+ * @returns {Promise<void>}
2205
+ */
2206
+ const applySubscriptionDecision = async (decision, data) => {
2207
+ const settingsKey = `${REDIS_PREFIX}settings`;
2208
+
2209
+ if (decision.removeLicense) {
2210
+ // what a license server that names no deadline and does not ask to keep the key gets
2211
+ logger.warn({ msg: 'License validation failed', license: redactLicense(licenseInfo.details), data });
2212
+ await settings.removeLicense();
2213
+ clearLicenseInfo();
2214
+ return;
2215
+ }
2216
+
2217
+ let multi = redis.multi();
2218
+ if (decision.clear) {
2219
+ multi = multi.hdel(settingsKey, 'subexp', 'subsusp');
2220
+ subscriptionDeadline = null;
2221
+ } else if (decision.resume) {
2222
+ multi = multi.hdel(settingsKey, 'subsusp');
2223
+ }
2224
+ if (decision.subexp) {
2225
+ multi = multi.hset(settingsKey, 'subexp', decision.subexp.toString());
2226
+ subscriptionDeadline = decision.subexp;
2227
+ }
2228
+ if (decision.suspend) {
2229
+ multi = multi.hset(settingsKey, 'subsusp', JSON.stringify(decision.suspend));
2230
+ }
2231
+ if (decision.nextCheck) {
2232
+ multi = multi.hset(settingsKey, 'ks', new Date(decision.nextCheck).getTime().toString(16));
2233
+ }
2234
+ await multi.exec();
2235
+
2236
+ if (decision.resume && licenseInfo.suspension) {
2237
+ logger.info({
2238
+ msg: decision.clear ? 'Subscription in good standing again, resuming' : 'Subscription inside its payment window again, resuming',
2239
+ license: redactLicense(licenseInfo.details)
2240
+ });
2241
+ setSuspension(null);
2242
+ }
2243
+
2244
+ if (decision.suspend) {
2245
+ if (!licenseInfo.suspension) {
2246
+ logger.warn({ msg: 'Subscription not in good standing, suspending until it is', license: redactLicense(licenseInfo.details), data });
2247
+ }
2248
+ setSuspension(decision.suspend);
2249
+ }
2250
+ };
2251
+
2252
+ /**
2253
+ * Tells the API workers to run their prechecks again, so the REST API follows a suspension or a
2254
+ * resume at once instead of at the next ten-minute tick
2255
+ * @returns {void}
2256
+ */
2257
+ const notifyApiLicenseState = () => {
2258
+ for (let worker of workers.get('api') || []) {
2259
+ try {
2260
+ postMessage(worker, { cmd: 'licenseState' }, true);
2261
+ } catch (err) {
2262
+ logger.error({ msg: 'Unable to notify worker about the license state', worker: worker.threadId, err });
2263
+ }
2264
+ }
2265
+ };
2150
2266
 
2151
2267
  /**
2152
2268
  * Check and validate license status
2153
2269
  * @param {Object} opts - Options
2154
- * @param {number} opts.subscriptionCheckTimeout - Timeout for subscription check
2155
- * @returns {Promise<void>}
2270
+ * @param {number} opts.subscriptionCheckTimeout - Minimum time since the last online check
2271
+ * @param {boolean} opts.force - Check online now, whatever the schedule says
2272
+ * @returns {Promise<Object>} { outcome }: ok, refused, error, unreachable, skipped or busy
2156
2273
  */
2157
2274
  let licenseCheckHandler = async opts => {
2158
2275
  if (checkingLicense) {
2159
- return;
2276
+ return { outcome: 'busy' };
2160
2277
  }
2161
2278
  checkingLicense = true;
2162
2279
  clearTimeout(licenseCheckTimer);
2163
2280
 
2281
+ let outcome = 'skipped';
2282
+ let wasActive = licenseInfo.active;
2283
+
2164
2284
  try {
2165
2285
  opts = opts || {};
2166
- let { subscriptionCheckTimeout } = opts;
2167
2286
  let now = Date.now();
2168
- subscriptionCheckTimeout = subscriptionCheckTimeout || SUBSCRIPTION_CHECK_TIMEOUT;
2287
+ let [subexp, subsusp, kv, ks] = await redis.hmget(`${REDIS_PREFIX}settings`, 'subexp', 'subsusp', 'kv', 'ks');
2288
+ // daily, and hourly while the subscription is not in good standing
2289
+ let subscriptionCheckTimeout = opts.subscriptionCheckTimeout || checkInterval({ subexp, subsusp });
2169
2290
 
2170
2291
  // Check if we need to validate the license
2171
- let kv = await redis.hget(`${REDIS_PREFIX}settings`, 'kv');
2172
2292
  let checkKv = true;
2173
2293
  // an unreadable record means checking again, which also rewrites it
2174
2294
  let validatedVersion = kv && typeof kv === 'string' ? Buffer.from(kv, 'hex').toString() : null;
@@ -2176,7 +2296,6 @@ let licenseCheckHandler = async opts => {
2176
2296
  checkKv = false;
2177
2297
  }
2178
2298
 
2179
- let ks = await redis.hget(`${REDIS_PREFIX}settings`, 'ks');
2180
2299
  if (ks && typeof ks === 'string') {
2181
2300
  let ksDate = new Date(parseInt(ks, 16));
2182
2301
  if (ksDate < now) {
@@ -2187,18 +2306,35 @@ let licenseCheckHandler = async opts => {
2187
2306
  }
2188
2307
 
2189
2308
  // Clean up for lifetime licenses
2190
- if (licenseInfo.details.lt) {
2191
- await redis.hdel(`${REDIS_PREFIX}settings`, 'subexp');
2309
+ if (licenseInfo.details && licenseInfo.details.lt) {
2310
+ await redis.hdel(`${REDIS_PREFIX}settings`, 'subexp', 'subsusp');
2311
+ subscriptionDeadline = null;
2312
+ }
2313
+
2314
+ // A suspended license is still registered and still checked, which is how it resumes
2315
+ let subscriptionLicense = (licenseInfo.active || !!licenseInfo.suspension) && isSubscriptionLicense(licenseInfo.details);
2316
+
2317
+ // A stored deadline that has passed suspends on its own, whether or not the license server
2318
+ // can be reached to say so; its next answer decides what happens after that
2319
+ let localSuspension = subscriptionLicense && !licenseInfo.suspension ? expiredSuspension(subexp, subsusp, now) : null;
2320
+ if (localSuspension) {
2321
+ await redis.hset(`${REDIS_PREFIX}settings`, 'subsusp', JSON.stringify(localSuspension));
2322
+ logger.warn({
2323
+ msg: 'Subscription deadline passed, suspending until the license server says otherwise',
2324
+ license: redactLicense(licenseInfo.details)
2325
+ });
2326
+ setSuspension(localSuspension);
2327
+ }
2328
+ let due = false;
2329
+ if (subscriptionLicense && opts.force) {
2330
+ await redis.hset(`${REDIS_PREFIX}settings`, 'subcheck', now.toString());
2331
+ due = true;
2332
+ } else if (subscriptionLicense && checkKv) {
2333
+ due = !!(await redis.hUpdateBigger(`${REDIS_PREFIX}settings`, 'subcheck', now - subscriptionCheckTimeout, now));
2192
2334
  }
2193
2335
 
2194
2336
  // Validate subscription license
2195
- if (
2196
- checkKv &&
2197
- licenseInfo.active &&
2198
- !(licenseInfo.details && licenseInfo.details.expires) &&
2199
- !licenseInfo.details.lt &&
2200
- (await redis.hUpdateBigger(`${REDIS_PREFIX}settings`, 'subcheck', now - subscriptionCheckTimeout, now))
2201
- ) {
2337
+ if (due) {
2202
2338
  try {
2203
2339
  let body = {
2204
2340
  key: licenseInfo.details.key,
@@ -2228,32 +2364,11 @@ let licenseCheckHandler = async opts => {
2228
2364
 
2229
2365
  let data = await res.json();
2230
2366
 
2231
- if (!res.ok) {
2232
- if (data.invalidate) {
2233
- // License validation failed - start grace period
2234
- let res = await redis.hUpdateBigger(`${REDIS_PREFIX}settings`, 'subexp', now, now + SUBSCRIPTION_ALLOW_DELAY);
2235
- if (res === 2) {
2236
- // Grace period expired
2237
- logger.warn({ msg: 'License validation failed', license: redactLicense(licenseInfo.details), data });
2238
- await settings.removeLicense();
2239
- licenseInfo.active = false;
2240
- licenseInfo.details = false;
2241
- licenseInfo.type = packageData.license;
2242
- } else {
2243
- // Still in grace period - check again soon
2244
- let nextCheck = now + SUBSCRIPTION_RECHECK_TIMEOUT;
2245
- await redis.hset(`${REDIS_PREFIX}settings`, 'ks', new Date(nextCheck).getTime().toString(16));
2246
- }
2247
- }
2248
- } else {
2249
- // License validated successfully
2250
- await redis.hdel(`${REDIS_PREFIX}settings`, 'subexp');
2367
+ await applySubscriptionDecision(decide({ ok: res.ok, data, now, subexp }), data);
2368
+ outcome = res.ok ? 'ok' : data && data.invalidate ? 'refused' : 'error';
2369
+
2370
+ if (res.ok) {
2251
2371
  await redis.hset(`${REDIS_PREFIX}settings`, 'kv', Buffer.from(packageData.version).toString('hex'));
2252
- if (data.validatedUntil) {
2253
- let validatedUntil = new Date(data.validatedUntil);
2254
- let nextCheck = Math.min(now + MAX_LICENSE_CHECK_DELAY, validatedUntil.getTime());
2255
- await redis.hset(`${REDIS_PREFIX}settings`, 'ks', new Date(nextCheck).getTime().toString(16));
2256
- }
2257
2372
 
2258
2373
  // Persist beacon markers so the full snapshot is only resent when it changes.
2259
2374
  if (!BEACON_DISABLED) {
@@ -2261,6 +2376,8 @@ let licenseCheckHandler = async opts => {
2261
2376
  }
2262
2377
  }
2263
2378
  } catch (err) {
2379
+ // never a reason to stop: an unreachable license server leaves the stored state as it was
2380
+ outcome = 'unreachable';
2264
2381
  logger.warn({ msg: 'License validation error', err });
2265
2382
  }
2266
2383
  }
@@ -2281,7 +2398,7 @@ let licenseCheckHandler = async opts => {
2281
2398
  logger.info({ msg: 'No active license. Suspending every worker except the API server.' });
2282
2399
 
2283
2400
  // Suspend all worker types except API
2284
- for (let type of ['imap', 'submit', 'smtp', 'webhooks', 'imapProxy']) {
2401
+ for (let type of LICENSED_WORKER_TYPES) {
2285
2402
  suspendedWorkerTypes.add(type);
2286
2403
  if (workers.has(type)) {
2287
2404
  for (let worker of workers.get(type).values()) {
@@ -2317,11 +2434,16 @@ let licenseCheckHandler = async opts => {
2317
2434
  // worker ready handler only reassigns after crashes (reassignmentPending)
2318
2435
  assignAccounts().catch(err => logger.error({ msg: 'Unable to assign accounts after license activation', err }));
2319
2436
  }
2437
+ if (wasActive !== licenseInfo.active) {
2438
+ notifyApiLicenseState();
2439
+ }
2320
2440
  } finally {
2321
2441
  checkingLicense = false;
2322
2442
  licenseCheckTimer = setTimeout(checkActiveLicense, LICENSE_CHECK_TIMEOUT);
2323
2443
  licenseCheckTimer.unref();
2324
2444
  }
2445
+
2446
+ return { outcome };
2325
2447
  };
2326
2448
 
2327
2449
  /**
@@ -2768,24 +2890,38 @@ async function commandImapWorkerCount() {
2768
2890
  return { workers: availableIMAPWorkers.size };
2769
2891
  }
2770
2892
 
2771
- async function commandCheckLicense() {
2772
- // Force license check
2893
+ async function commandCheckLicense(worker, message) {
2894
+ // The license page asks on every view (60 s gate); the "Check subscription now" button forces a
2895
+ // check, at most once a minute per instance, so the button cannot be used to hammer the server
2896
+ let result = { outcome: 'skipped' };
2773
2897
  try {
2774
- await licenseCheckHandler({
2775
- subscriptionCheckTimeout: 60 * 1000
2776
- });
2898
+ if (message && message.force) {
2899
+ let acquired = await redis.set(`${REDIS_PREFIX}license:recheck`, '1', 'PX', 60 * 1000, 'NX');
2900
+ result = acquired ? await licenseCheckHandler({ force: true }) : { outcome: 'throttled' };
2901
+ } else {
2902
+ result = await licenseCheckHandler({ subscriptionCheckTimeout: 60 * 1000 });
2903
+ }
2777
2904
  } catch (err) {
2778
2905
  // ignore
2779
2906
  }
2780
- return licenseInfo;
2907
+ return Object.assign(await commandLicense(), { checkOutcome: result.outcome });
2781
2908
  }
2782
2909
 
2783
2910
  async function commandLicense() {
2784
- // Return license info with suspension status
2911
+ // Return license info with suspension status and, for a subscription license that is not in
2912
+ // good standing, the deadline or the suspension (lib/license-subscription.js)
2913
+ let info = Object.assign({}, licenseInfo);
2914
+ delete info.suspension;
2785
2915
  if (!licenseInfo.active && suspendedWorkerTypes.size) {
2786
- return Object.assign({}, licenseInfo, { suspended: true });
2916
+ info.suspended = true;
2917
+ }
2918
+ if (isSubscriptionLicense(licenseInfo.details)) {
2919
+ let subscription = subscriptionView({ subexp: subscriptionDeadline, suspension: licenseInfo.suspension, now: Date.now() });
2920
+ if (subscription) {
2921
+ info.subscription = subscription;
2922
+ }
2787
2923
  }
2788
- return licenseInfo;
2924
+ return info;
2789
2925
  }
2790
2926
 
2791
2927
  async function commandUpdateLicense(worker, message) {
@@ -2802,14 +2938,24 @@ async function commandUpdateLicense(worker, message) {
2802
2938
 
2803
2939
  await setLicense(licenseData, licenseFile);
2804
2940
 
2805
- licenseInfo.active = true;
2806
2941
  licenseInfo.details = licenseData;
2807
2942
  licenseInfo.type = 'EmailEngine License';
2808
2943
 
2809
- // Re-enable workers
2810
- checkActiveLicense();
2944
+ // The same key registered again keeps a suspension (setLicense keeps the stored state), so
2945
+ // posting the file again does not lift one; a subscription license is checked online before
2946
+ // the workers start, and the answer decides
2947
+ let subscriptionLicense = isSubscriptionLicense(licenseData);
2948
+ let [subexp, subsusp] = await redis.hmget(`${REDIS_PREFIX}settings`, 'subexp', 'subsusp');
2949
+ subscriptionDeadline = subscriptionLicense ? toTime(subexp) : null;
2950
+ setSuspension(subscriptionLicense ? parseSuspension(subsusp) : null);
2951
+
2952
+ if (!subscriptionLicense || (await licenseCheckHandler({ force: true })).outcome === 'busy') {
2953
+ // Re-enable workers
2954
+ checkActiveLicense();
2955
+ }
2956
+ notifyApiLicenseState();
2811
2957
 
2812
- return licenseInfo;
2958
+ return await commandLicense();
2813
2959
  } catch (err) {
2814
2960
  logger.warn({ msg: 'License update failed', source: 'API', err });
2815
2961
  return false;
@@ -2821,9 +2967,8 @@ async function commandRemoveLicense() {
2821
2967
  try {
2822
2968
  await settings.removeLicense();
2823
2969
 
2824
- licenseInfo.active = false;
2825
- licenseInfo.details = false;
2826
- licenseInfo.type = packageData.license;
2970
+ clearLicenseInfo();
2971
+ notifyApiLicenseState();
2827
2972
 
2828
2973
  return licenseInfo;
2829
2974
  } catch (err) {
@@ -3514,6 +3659,28 @@ const loadStoredLicense = async () => {
3514
3659
  }
3515
3660
  };
3516
3661
 
3662
+ /**
3663
+ * Applies the stored subscription state before any worker starts (lib/license-subscription.js): a
3664
+ * license suspended when EmailEngine stopped, or whose deadline ran out while it was not running,
3665
+ * starts suspended rather than running until the first check
3666
+ * @returns {Promise<boolean>} whether to check the subscription online right away
3667
+ */
3668
+ const applyStartupSubscriptionState = async () => {
3669
+ let [subexp, subsusp, subcheck] = await redis.hmget(`${REDIS_PREFIX}settings`, 'subexp', 'subsusp', 'subcheck');
3670
+ subscriptionDeadline = toTime(subexp);
3671
+ let plan = startupPlan({ details: licenseInfo.active && licenseInfo.details, subexp, subsusp, subcheck, now: Date.now() });
3672
+
3673
+ if (plan.suspension) {
3674
+ logger.warn({ msg: 'Subscription not in good standing, starting suspended', license: redactLicense(licenseInfo.details), suspension: plan.suspension });
3675
+ setSuspension(plan.suspension);
3676
+ for (let type of LICENSED_WORKER_TYPES) {
3677
+ suspendedWorkerTypes.add(type);
3678
+ }
3679
+ }
3680
+
3681
+ return plan.checkNow;
3682
+ };
3683
+
3517
3684
  /**
3518
3685
  * One-time data migrations that run before the workers spawn. None of them is fatal
3519
3686
  * @returns {Promise<void>}
@@ -3537,6 +3704,14 @@ const runStartupMigrations = async () => {
3537
3704
  logger.error({ msg: 'Failed to backfill the auth-failure disable marker', err });
3538
3705
  }
3539
3706
 
3707
+ // Index the exports created before the per-account export index, so deleting an account removes
3708
+ // them too. Not fatal: the completion key is written last, so the next startup re-enters
3709
+ try {
3710
+ await backfillExportIndex();
3711
+ } catch (err) {
3712
+ logger.error({ msg: 'Failed to backfill the export index', err });
3713
+ }
3714
+
3540
3715
  // One-time delete of the store behind the retired `bounces` field; not fatal, the completion key is written last
3541
3716
  try {
3542
3717
  await sweepBounceStore();
@@ -3727,22 +3902,7 @@ const importPreparedCredentials = async () => {
3727
3902
  // Import prepared password
3728
3903
  if (preparedPassword) {
3729
3904
  try {
3730
- let authData = await settings.get('authData');
3731
-
3732
- // Written only when the stored hash differs: passwordVersion is what every admin
3733
- // session and message-browser token is checked against, so rewriting the same hash
3734
- // on each boot would log every operator out at every restart
3735
- if (!authData || authData.password !== preparedPassword) {
3736
- authData = authData || {};
3737
- authData.user = authData.user || 'admin';
3738
- authData.password = preparedPassword;
3739
- authData.passwordVersion = Date.now();
3740
-
3741
- await settings.set('authData', authData);
3742
- logger.debug({ msg: 'Password imported' });
3743
- } else {
3744
- logger.debug({ msg: 'Password already imported' });
3745
- }
3905
+ await importPreparedPassword(preparedPassword, { settings, passkeys: require('./lib/passkeys'), logger });
3746
3906
  } catch (err) {
3747
3907
  logger.error({ msg: 'Password import failed', err });
3748
3908
  }
@@ -3961,6 +4121,8 @@ const startApplication = async () => {
3961
4121
 
3962
4122
  await loadStoredLicense();
3963
4123
 
4124
+ startupLicenseCheck = await applyStartupSubscriptionState();
4125
+
3964
4126
  // Check for updates
3965
4127
  processCheckUpgrade().catch(err => {
3966
4128
  logger.warn({ msg: 'Update check failed', err });
@@ -3987,6 +4149,11 @@ const startApplication = async () => {
3987
4149
 
3988
4150
  await startApiWorkers();
3989
4151
 
4152
+ if (licenseInfo.suspension) {
4153
+ // the API answers like an unlicensed instance from the start, not from the next precheck tick
4154
+ notifyApiLicenseState();
4155
+ }
4156
+
3990
4157
  // Small delay to allow API to start
3991
4158
  await new Promise(r => setTimeout(r, 100));
3992
4159
 
@@ -4006,9 +4173,15 @@ startApplication()
4006
4173
  collectMetrics().catch(err => logger.error({ msg: 'Metrics collection failed', err }));
4007
4174
  }, 1000).unref();
4008
4175
 
4009
- // Schedule periodic checks
4010
- licenseCheckTimer = setTimeout(checkActiveLicense, LICENSE_CHECK_TIMEOUT);
4011
- licenseCheckTimer.unref();
4176
+ // Schedule periodic checks. A monthly-plan license, or one that is not in good standing, is
4177
+ // checked right away (unless an hour has not passed since the last check, so a restart
4178
+ // loop costs one call an hour); everything else after the usual first delay
4179
+ if (startupLicenseCheck) {
4180
+ licenseCheckHandler({ force: true }).catch(err => logger.error({ msg: 'License check error', err }));
4181
+ } else {
4182
+ licenseCheckTimer = setTimeout(checkActiveLicense, LICENSE_CHECK_TIMEOUT);
4183
+ licenseCheckTimer.unref();
4184
+ }
4012
4185
 
4013
4186
  upgradeCheckTimer = setTimeout(checkUpgrade, UPGRADE_CHECK_TIMEOUT);
4014
4187
  upgradeCheckTimer.unref();