emailengine-app 2.84.2 → 2.86.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 (164) hide show
  1. package/.ncurc.js +29 -9
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +107 -0
  6. package/Dockerfile +20 -1
  7. package/ENVIRONMENT.md +139 -0
  8. package/README.md +2 -2
  9. package/bin/emailengine.js +434 -408
  10. package/config/default.toml +2 -0
  11. package/copy-static-files.sh +41 -14
  12. package/data/google-crawlers.json +1 -1
  13. package/data/public_suffix_list.dat +16563 -0
  14. package/eslint.config.js +81 -99
  15. package/lib/account-assignment.js +19 -0
  16. package/lib/account.js +230 -170
  17. package/lib/api-error-codes.js +49 -0
  18. package/lib/api-reference/format.js +4 -3
  19. package/lib/api-reference/model.js +6 -1
  20. package/lib/api-routes/account-routes.js +255 -38
  21. package/lib/api-routes/blocklist-routes.js +91 -4
  22. package/lib/api-routes/delivery-test-routes.js +27 -4
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +110 -12
  25. package/lib/api-routes/index.js +4 -0
  26. package/lib/api-routes/license-routes.js +2 -2
  27. package/lib/api-routes/mailbox-routes.js +44 -5
  28. package/lib/api-routes/message-routes.js +112 -10
  29. package/lib/api-routes/oauth2-app-routes.js +63 -23
  30. package/lib/api-routes/outbox-routes.js +97 -52
  31. package/lib/api-routes/permission-map.js +67 -7
  32. package/lib/api-routes/scoped-routes.js +74 -0
  33. package/lib/api-routes/settings-routes.js +34 -6
  34. package/lib/api-routes/stats-routes.js +5 -1
  35. package/lib/api-routes/submit-routes.js +337 -309
  36. package/lib/api-routes/template-routes.js +45 -8
  37. package/lib/api-routes/token-routes.js +152 -100
  38. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  39. package/lib/api-routes/webhook-route-routes.js +132 -6
  40. package/lib/bounce-detect.js +397 -205
  41. package/lib/calendar-event.js +81 -1
  42. package/lib/consts.js +38 -45
  43. package/lib/db.js +14 -6
  44. package/lib/delivery-error.js +6 -0
  45. package/lib/deprecations.js +270 -0
  46. package/lib/email-client/base-client.js +137 -184
  47. package/lib/email-client/fallback-poll.js +62 -0
  48. package/lib/email-client/gmail-client.js +60 -22
  49. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  50. package/lib/email-client/imap/adaptive-idle.js +278 -0
  51. package/lib/email-client/imap/connection-errors.js +14 -1
  52. package/lib/email-client/imap/idle-settings.js +31 -5
  53. package/lib/email-client/imap/listing-diff.js +37 -0
  54. package/lib/email-client/imap/mailbox.js +372 -242
  55. package/lib/email-client/imap/subconnection.js +8 -30
  56. package/lib/email-client/imap/sync-operations.js +220 -127
  57. package/lib/email-client/imap-client.js +228 -164
  58. package/lib/email-client/message-builder.js +14 -79
  59. package/lib/email-client/notification-handler.js +1 -2
  60. package/lib/email-client/outlook-client.js +372 -338
  61. package/lib/email-client/smtp-pool-manager.js +16 -13
  62. package/lib/email-client/sync-state-fields.js +19 -0
  63. package/lib/encrypt.js +157 -41
  64. package/lib/enum-descriptions.js +3 -1
  65. package/lib/env-setting-overrides.js +288 -0
  66. package/lib/export-worker.js +751 -0
  67. package/lib/export.js +64 -15
  68. package/lib/gateway.js +19 -4
  69. package/lib/get-raw-email.js +25 -107
  70. package/lib/hapi-request-logger.js +107 -0
  71. package/lib/health.js +75 -0
  72. package/lib/imapproxy/imap-core/README.md +6 -5
  73. package/lib/lock-run.js +119 -0
  74. package/lib/logger-consts.js +48 -0
  75. package/lib/logger.js +1 -1
  76. package/lib/lua/z-head-scores.lua +28 -0
  77. package/lib/mcp/tools.js +37 -8
  78. package/lib/network-errors.js +1 -1
  79. package/lib/node-version.js +24 -0
  80. package/lib/notify-attachments.js +36 -0
  81. package/lib/oauth/outlook-mailbox.js +35 -0
  82. package/lib/oauth/state.js +24 -0
  83. package/lib/oauth2-apps.js +631 -656
  84. package/lib/outbox.js +184 -54
  85. package/lib/parse-message.js +3 -3
  86. package/lib/pbkdf2-phc.js +1 -1
  87. package/lib/privileged-settings.js +2 -2
  88. package/lib/queue-browser/definitions.js +11 -0
  89. package/lib/queue-browser/index.js +68 -19
  90. package/lib/queue-job-actions.js +18 -1
  91. package/lib/queue-retention.js +48 -12
  92. package/lib/queue-stats.js +11 -2
  93. package/lib/read-env-value.js +3 -0
  94. package/lib/redis-memory-warnings.js +99 -0
  95. package/lib/redis-reconnect.js +29 -0
  96. package/lib/request-timing.js +23 -0
  97. package/lib/respawn-backoff.js +35 -0
  98. package/lib/rewrite-text-nodes.js +19 -59
  99. package/lib/schemas.js +164 -40
  100. package/lib/settings.js +6 -2
  101. package/lib/smtp-auth.js +19 -1
  102. package/lib/sso.js +1 -1
  103. package/lib/swagger-options.js +1 -1
  104. package/lib/thread-diagnostics.js +63 -0
  105. package/lib/timezones.js +109 -0
  106. package/lib/tls/provision.js +6 -3
  107. package/lib/token-audit-log.js +19 -20
  108. package/lib/token-permission-view.js +7 -6
  109. package/lib/tools.js +48 -51
  110. package/lib/totp.js +2 -5
  111. package/lib/translations.js +1 -2
  112. package/lib/ui-routes/account-routes.js +475 -454
  113. package/lib/ui-routes/account-setup.js +99 -0
  114. package/lib/ui-routes/admin-config-routes.js +152 -100
  115. package/lib/ui-routes/admin-entities-routes.js +93 -21
  116. package/lib/ui-routes/auth-routes.js +90 -38
  117. package/lib/ui-routes/imap-idle-field.js +1 -1
  118. package/lib/ui-routes/internals-routes.js +5 -0
  119. package/lib/ui-routes/oauth-config-routes.js +124 -82
  120. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  121. package/lib/ui-routes/overridable-fields.js +84 -0
  122. package/lib/ui-routes/queue-routes.js +8 -5
  123. package/lib/ui-routes/route-helpers.js +19 -3
  124. package/lib/ui-routes/settings-page.js +6 -0
  125. package/lib/ui-routes/tls-config-routes.js +58 -15
  126. package/lib/utils/back-off.js +82 -0
  127. package/lib/utils/decode-headers.js +3 -12
  128. package/lib/utils/filter-empty.js +20 -0
  129. package/lib/utils/int-setting.js +48 -0
  130. package/lib/utils/murmurhash3.js +66 -0
  131. package/lib/utils/public-suffix.js +122 -0
  132. package/lib/utils/random-id.js +26 -0
  133. package/lib/utils/tracking-settings.js +35 -0
  134. package/lib/utils/version.js +74 -0
  135. package/lib/web-safe-html.js +18 -105
  136. package/lib/webhook-delivery.js +461 -0
  137. package/lib/webhook-failures.js +132 -0
  138. package/lib/webhook-request.js +29 -1
  139. package/lib/webhook-routing.js +56 -0
  140. package/lib/webhook-test.js +88 -0
  141. package/lib/webhooks.js +93 -45
  142. package/lib/worker-rpc-error.js +2 -1
  143. package/package.json +37 -38
  144. package/sbom.json +7902 -1
  145. package/server.js +784 -518
  146. package/static/js/ace/ace.js +1 -1
  147. package/static/licenses.html +225 -1060
  148. package/translations/messages.pot +62 -63
  149. package/views/config/ai.hbs +1 -1
  150. package/views/config/security.hbs +24 -2
  151. package/views/config/service.hbs +47 -0
  152. package/views/config/webhooks.hbs +36 -0
  153. package/views/internals/index.hbs +8 -0
  154. package/views/partials/queue_retention_note.hbs +12 -8
  155. package/views/partials/ui/env-managed-alert.hbs +16 -7
  156. package/views/partials/webhook_form.hbs +1 -1
  157. package/views/suppression-lists/index.hbs +1 -1
  158. package/workers/api.js +840 -611
  159. package/workers/export.js +17 -632
  160. package/workers/imap.js +13 -0
  161. package/workers/smtp.js +9 -11
  162. package/workers/submit.js +1 -1
  163. package/workers/webhooks.js +18 -448
  164. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -24,18 +24,7 @@ const msgpack = require('./msgpack');
24
24
  const settings = require('./settings');
25
25
  const { REDIS_PREFIX, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
26
26
  const { extractMultiError } = require('./redis-operations');
27
- const { readEnvValue } = require('./read-env-value');
28
-
29
- // Both overrides below are whole counts that have to be at least 1, and anything else falls back to
30
- // the default rather than being clamped towards it - "0" is not a request for the smallest possible
31
- // log, it is a value this module has no reading for. Each has its own way of going wrong: the entry
32
- // cap floors the log route's `pageSize` ceiling, so a value below 1 left `min(1).max(0)` on the
33
- // query schema and no request could satisfy it, and Redis DELETES a key given a non-positive
34
- // EXPIRE, so a negative age would drop each entry in the transaction that wrote it.
35
- function positiveInt(value, fallback) {
36
- const parsed = Math.floor(Number(value));
37
- return Number.isFinite(parsed) && parsed >= 1 ? parsed : fallback;
38
- }
27
+ const { getOverridableSettings, envOrDefault } = require('./env-setting-overrides');
39
28
 
40
29
  // How many entries to keep per token. The cap is a hard trim rather than a target, and it is what
41
30
  // bounds the whole feature: every write trims, so total storage is a function of how many tokens are
@@ -43,12 +32,20 @@ function positiveInt(value, fallback) {
43
32
  // per token, so a thousand active tokens cost about 170MB - entries carrying a maximum-length
44
33
  // account run some three times that. Raise it against those figures, and against the fact that a log
45
34
  // of who read whose mail carries the sensitivity of the mail itself.
46
- const LOG_ENTRIES = positiveInt(readEnvValue('EENGINE_TOKEN_LOG_ENTRIES'), 1000);
47
-
48
- // How long a token's log survives its last use, in seconds. Refreshed on every write, so this bounds
49
- // how long a log outlives the credential's activity rather than how long each entry lives - which is
50
- // the useful bound, because a token nobody has used is a log nobody needs.
51
- const LOG_AGE = positiveInt(readEnvValue('EENGINE_TOKEN_LOG_AGE'), 7 * 24 * 3600);
35
+ //
36
+ // The age is how long a token's log survives its last use. Refreshed on every write, so it bounds how
37
+ // long a log outlives the credential's activity rather than how long each entry lives - which is the
38
+ // useful bound, because a token nobody has used is a log nobody needs.
39
+ //
40
+ // Both are settings as well (tokenLogEntries, tokenLogAge), the environment winning, and each write
41
+ // reads the values in effect (lib/env-setting-overrides.js, which also parses both: a whole count of
42
+ // at least 1, anything else falling back to the default rather than being clamped towards it - "0"
43
+ // is not a request for the smallest possible log. Each has its own way of going wrong otherwise: the
44
+ // entry cap floors the log route's `pageSize` ceiling, so a value below 1 left `min(1).max(0)` on the
45
+ // query schema and no request could satisfy it, and Redis DELETES a key given a non-positive EXPIRE,
46
+ // so a negative age would drop each entry in the transaction that wrote it). The constant here is
47
+ // the environment-or-default entry cap, which the log route's page size bound below is fixed from.
48
+ const LOG_ENTRIES = envOrDefault('tokenLogEntries');
52
49
 
53
50
  // The largest page the log route will serve. Deliberately not the retention cap: one bounds a single
54
51
  // response, the other bounds stored data, and while they were the same constant raising retention
@@ -157,11 +154,13 @@ function record(entry) {
157
154
  reason: entry.reason || null
158
155
  };
159
156
 
157
+ const { tokenLogEntries, tokenLogAge } = await getOverridableSettings('tokenLogEntries', 'tokenLogAge');
158
+
160
159
  const results = await redis
161
160
  .multi()
162
161
  .lpushBuffer(key, msgpack.encode(stored))
163
- .ltrim(key, 0, LOG_ENTRIES - 1)
164
- .expire(key, LOG_AGE)
162
+ .ltrim(key, 0, tokenLogEntries - 1)
163
+ .expire(key, tokenLogAge)
165
164
  .exec();
166
165
 
167
166
  const err = extractMultiError(results);
@@ -40,7 +40,8 @@ const GROUP_LABELS = {
40
40
  [GROUP.OAUTH2]: 'OAuth2 applications',
41
41
  [GROUP.LICENSE]: 'License',
42
42
  [GROUP.TOKEN]: 'Access tokens',
43
- [GROUP.PROVISIONING]: 'Account and gateway setup'
43
+ [GROUP.PROVISIONING]: 'Account and gateway setup',
44
+ [GROUP.WEBHOOK_DELIVERIES]: 'Failed webhook deliveries'
44
45
  };
45
46
 
46
47
  // The one spelling of the slug-to-label lookup. Object.hasOwn rather than a bare lookup: a slug
@@ -62,7 +63,7 @@ const GROUP_CLUSTERS = [
62
63
  { label: 'Mail', groups: [GROUP.ACCOUNT, GROUP.MAILBOX, GROUP.MESSAGE, GROUP.SUBMIT, GROUP.OUTBOX, GROUP.EXPORT] },
63
64
  { label: 'Configuration', groups: [GROUP.TEMPLATE, GROUP.BLOCKLIST, GROUP.WEBHOOK, GROUP.GATEWAY] },
64
65
  { label: 'Monitoring', groups: [GROUP.EVENTS, GROUP.DIAGNOSTICS, GROUP.LOGS] },
65
- { label: 'Instance', groups: [GROUP.SETTINGS, GROUP.PROVISIONING, GROUP.OAUTH2, GROUP.TOKEN, GROUP.LICENSE] }
66
+ { label: 'Instance', groups: [GROUP.SETTINGS, GROUP.WEBHOOK_DELIVERIES, GROUP.PROVISIONING, GROUP.OAUTH2, GROUP.TOKEN, GROUP.LICENSE] }
66
67
  ];
67
68
 
68
69
  // How the token list names the sections an absent `groups` axis reaches (IMPLICIT_GROUPS): by
@@ -172,7 +173,7 @@ const MCP_SECTIONS = {
172
173
  {
173
174
  value: 'operate',
174
175
  label: 'Operate',
175
- hint: 'Also reconnect, add and test accounts, change settings, retry or expedite queued messages, and manage OAuth2 applications, gateways and templates.',
176
+ hint: 'Also reconnect, add and test accounts, change settings, retry or expedite queued messages and failed webhook deliveries, and manage OAuth2 applications, gateways and templates.',
176
177
  caveat: 'Settings changes take effect at once, and moving the webhook target sends future message notifications, message text included, elsewhere. Reconfiguring an account or gateway can send its stored credential to a new host, and reconfiguring an OAuth2 application can redirect where future sign-ins deliver their authorization codes. It cannot delete anything, create tokens or read stored credentials.',
177
178
  pairs: pairsOf(MCP_SCOPES.manage, grant => grant.action !== ACTION.DESTRUCTIVE)
178
179
  },
@@ -205,14 +206,14 @@ const MCP_SECTIONS = {
205
206
  {
206
207
  value: 'mail',
207
208
  label: 'Mail agent',
208
- hint: 'Read, organize, draft and send mail - everything except the delete tool.',
209
- caveat: 'Everything except the delete tool. Instructions inside received mail are a real prompt-injection risk once sending is granted.',
209
+ hint: 'Read, organize, draft and send mail, and create and rename folders - everything except deleting.',
210
+ caveat: 'Everything except deleting messages and folders. Instructions inside received mail are a real prompt-injection risk once sending is granted.',
210
211
  pairs: pairsOf(MCP_SCOPES.mail, grant => grant.action !== ACTION.DESTRUCTIVE)
211
212
  },
212
213
  {
213
214
  value: 'full',
214
215
  label: 'Full access',
215
- hint: 'Every mail tool, including deleting messages.',
216
+ hint: 'Every mail tool, including deleting messages and folders.',
216
217
  caveat: 'Instructions inside received mail are a real prompt-injection risk once sending is granted.',
217
218
  pairs: pairsOf(MCP_SCOPES.mail, () => true)
218
219
  }
package/lib/tools.js CHANGED
@@ -2,8 +2,11 @@
2
2
 
3
3
  'use strict';
4
4
 
5
+ const { filterEmptyObjectValues } = require('./utils/filter-empty');
6
+
5
7
  const msgpack = require('./msgpack');
6
8
  const enumMessageFlags = require('./enum-message-flags');
9
+ const { redisMemoryWarnings } = require('./redis-memory-warnings');
7
10
  const Joi = require('joi');
8
11
  const packageData = require('../package.json');
9
12
  const { TLS_CERTIFICATE_SETTINGS } = require('./tls/listeners');
@@ -27,17 +30,18 @@ const punycode = require('punycode.js');
27
30
  const { PassThrough } = require('stream');
28
31
  const socks = require('socks');
29
32
  const os = require('os');
33
+ const { monitorEventLoopDelay } = require('perf_hooks');
30
34
  const Fs = require('fs');
31
35
  const fs = Fs.promises;
32
36
  const pathlib = require('path');
33
37
  const { randomUUID: uuid } = require('crypto');
34
38
  const mimeTypes = require('nodemailer/lib/mime-funcs/mime-types');
35
- const { v3: murmurhash } = require('murmurhash');
39
+ const { murmurhash3 } = require('./utils/murmurhash3');
36
40
  const { isEmail } = require('./utils/is-email');
37
41
  const { toCamelCase } = require('./utils/to-camel-case');
38
42
  const { normalizePath } = require('./utils/mailbox-path');
39
43
  const { applyRequireTls } = require('./utils/require-tls');
40
- const { compare: compareVersions, validate: validateVersion } = require('compare-versions');
44
+ const { compareVersions, parseVersion } = require('./utils/version');
41
45
 
42
46
  // Largest decompressed license blob accepted, well above any real license
43
47
  const MAX_LICENSE_SIZE = 1024 * 1024;
@@ -1304,6 +1308,13 @@ module.exports = {
1304
1308
  return processCount;
1305
1309
  },
1306
1310
 
1311
+ // A worker pool size: the environment value if it gives one, else the configuration file's, else
1312
+ // the pool's default. Both accept "cpus", and a fraction is rounded down so a pool never gets
1313
+ // more threads than asked for.
1314
+ workerPoolSize(envValue, configValue, defaultCount = 1) {
1315
+ return Math.floor(module.exports.getWorkerCount(envValue)) || Math.floor(module.exports.getWorkerCount(configValue)) || defaultCount;
1316
+ },
1317
+
1307
1318
  getDuration(val, opts = {}) {
1308
1319
  val = (val || '').toString().replace(/^([\d.]+)\s*([smhdy][a-z]*)$/i, (o, num, m) => {
1309
1320
  if (!num || isNaN(num)) {
@@ -1564,7 +1575,7 @@ module.exports = {
1564
1575
  },
1565
1576
 
1566
1577
  getRendezvousScore(key, shardId) {
1567
- return murmurhash(`${(shardId || '').toString()}\x00${key}`);
1578
+ return murmurhash3(`${(shardId || '').toString()}\x00${key}`);
1568
1579
  },
1569
1580
 
1570
1581
  selectRendezvousNode(key, workers) {
@@ -1826,7 +1837,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1826
1837
  });
1827
1838
  imapClient
1828
1839
  .connect()
1829
- .then(() => resolve(imapClient._mailboxList))
1840
+ .then(() => resolve(imapClient.mailboxList))
1830
1841
  .catch(reject);
1831
1842
  });
1832
1843
 
@@ -2262,37 +2273,8 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2262
2273
  });
2263
2274
  }
2264
2275
 
2265
- // EmailEngine uses Redis as a database, not a cache. Any eviction silently drops sync state,
2266
- // which makes already-synced messages look new and triggers duplicate webhooks.
2267
- let maxmemoryPolicy = typeof redisInfo.maxmemory_policy === 'string' ? redisInfo.maxmemory_policy : null;
2268
- let maxmemory = Number(redisInfo.maxmemory) || 0;
2269
- let evictedKeys = Number(redisInfo.evicted_keys) || 0;
2270
-
2271
- if (evictedKeys > 0) {
2272
- // Definitive: Redis has already evicted keys
2273
- redisWarnings.push({
2274
- key: 'evicted-keys',
2275
- color: 'danger',
2276
- title: 'Redis eviction detected',
2277
- details: [
2278
- `Redis has evicted ${evictedKeys.toLocaleString('en-US')} key${evictedKeys === 1 ? '' : 's'} after reaching its memory limit.`,
2279
- 'EmailEngine uses Redis as its primary database, not a cache. Evicted keys cause already-synced messages to be reprocessed - generating duplicate webhooks - and can lead to data loss.',
2280
- 'Set the Redis "maxmemory-policy" to "noeviction" and provision enough memory so Redis never reaches its limit.'
2281
- ]
2282
- });
2283
- } else if (maxmemoryPolicy && maxmemoryPolicy !== 'noeviction') {
2284
- // Latent risk: an eviction policy is configured but nothing has been evicted yet
2285
- redisWarnings.push({
2286
- key: 'maxmemory-policy',
2287
- color: maxmemory > 0 ? 'danger' : 'warning',
2288
- title: 'Unsafe Redis eviction policy',
2289
- details: [
2290
- `The Redis "maxmemory-policy" is set to "${maxmemoryPolicy}", but EmailEngine requires "noeviction".`,
2291
- 'With any other policy, Redis can delete EmailEngine sync state under memory pressure, causing already-synced messages to be reprocessed - generating duplicate webhooks - and possible data loss.',
2292
- 'Set "maxmemory-policy noeviction" and make sure Redis has enough memory for your workload.'
2293
- ]
2294
- });
2295
- }
2276
+ // Eviction and the maxmemory limit, see lib/redis-memory-warnings.js
2277
+ redisWarnings.push(...redisMemoryWarnings(redisInfo));
2296
2278
  } catch (err) {
2297
2279
  logger.error({ msg: 'Failed to get stats', err });
2298
2280
  redisVersion = err.message;
@@ -2383,11 +2365,11 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2383
2365
  }
2384
2366
 
2385
2367
  let releaseVersion = (releaseData.tag_name || '').toString().replace(/^v/, '');
2386
- if (!validateVersion(releaseVersion)) {
2368
+ if (!parseVersion(releaseVersion)) {
2387
2369
  return { current: packageData.version, available: false, canUpgrade: false };
2388
2370
  }
2389
2371
 
2390
- if (compareVersions(releaseVersion, packageData.version, '>')) {
2372
+ if (compareVersions(releaseVersion, packageData.version) > 0) {
2391
2373
  return { current: packageData.version, available: releaseVersion, canUpgrade: true };
2392
2374
  }
2393
2375
 
@@ -2593,15 +2575,8 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2593
2575
  return module.exports.getSignedFormDataSync(serviceSecret, opts);
2594
2576
  },
2595
2577
 
2596
- filterEmptyObjectValues(obj) {
2597
- let res = {};
2598
- for (let key of Object.keys(obj)) {
2599
- if (obj[key]) {
2600
- res[key] = obj[key];
2601
- }
2602
- }
2603
- return res;
2604
- },
2578
+ // lib/utils/filter-empty.js, kept here for the callers that take it from tools
2579
+ filterEmptyObjectValues,
2605
2580
 
2606
2581
  // Signs a hosted setup-form blob (the default purpose), a tracking blob or an unsubscribe
2607
2582
  // blob; the purpose picks the derived key the matching verifier checks against
@@ -2698,8 +2673,8 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2698
2673
  },
2699
2674
 
2700
2675
  // Redis key for a hosted-form single-use nonce (`n` inside the signed blob). Built in one place so
2701
- // the sites that must agree on it - the consumed-nonce check below, the IMAP-arm claim
2702
- // (lib/ui-routes/account-routes.js) and the OAuth callback claim (workers/api.js) - cannot drift.
2676
+ // the sites that must agree on it - the consumed-nonce check below and the claim both setup arms
2677
+ // make through lib/ui-routes/account-setup.js - cannot drift.
2703
2678
  formNonceKey(n) {
2704
2679
  return `${REDIS_PREFIX}account:form:${n}`;
2705
2680
  },
@@ -2707,8 +2682,8 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2707
2682
  // Atomically claim a hosted-form single-use nonce (SET NX). Returns true when THIS caller won the
2708
2683
  // claim, false when the key already existed (the signed URL was already used). Throws on a Redis error
2709
2684
  // - a Redis failure is NOT a consumed nonce, so callers must map it to a retryable 5xx, not a 403.
2710
- // Shared by the IMAP-arm submit and the OAuth callback so the EX/NX/TTL semantics of the double-spend
2711
- // guard cannot drift between the two arms; each caller keeps its own Boom 403/500 messages.
2685
+ // Called from lib/ui-routes/account-setup.js, which both setup arms complete through, and which maps
2686
+ // the outcome to its 403/500 refusals.
2712
2687
  async claimFormNonce(redis, n, t) {
2713
2688
  const claimed = await redis.set(module.exports.formNonceKey(n), (t || '0').toString(), 'EX', Math.floor(MAX_FORM_TTL / 1000), 'NX');
2714
2689
  return !!claimed;
@@ -2919,8 +2894,30 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2919
2894
  heapTotal: memUsage.heapTotal,
2920
2895
  external: memUsage.external,
2921
2896
  rss: memUsage.rss,
2922
- arrayBuffers: memUsage.arrayBuffers || 0
2897
+ arrayBuffers: memUsage.arrayBuffers || 0,
2898
+ eventLoopDelay: this.readEventLoopDelay()
2923
2899
  };
2900
+ },
2901
+
2902
+ // How late this thread's event loop ran since the previous reading, in milliseconds. The
2903
+ // main thread's metrics collector reads every thread every 15 seconds, so a reading covers
2904
+ // that window. The histogram starts with the first reading, which therefore has nothing
2905
+ // to report.
2906
+ readEventLoopDelay() {
2907
+ if (!this.delayHistogram) {
2908
+ this.delayHistogram = monitorEventLoopDelay({ resolution: 20 });
2909
+ this.delayHistogram.enable();
2910
+ return null;
2911
+ }
2912
+ let histogram = this.delayHistogram;
2913
+ let reading = histogram.count
2914
+ ? {
2915
+ max: histogram.max / 1e6,
2916
+ p99: histogram.percentile(99) / 1e6
2917
+ }
2918
+ : null;
2919
+ histogram.reset();
2920
+ return reading;
2924
2921
  }
2925
2922
  },
2926
2923
 
package/lib/totp.js CHANGED
@@ -3,6 +3,7 @@
3
3
  const crypto = require('crypto');
4
4
  const { base32Encode } = require('./base32');
5
5
  const qrcode = require('qrcode-generator');
6
+ const { randomId } = require('./utils/random-id');
6
7
 
7
8
  // The otpauth URL is percent-encoded ASCII, but the encoder qrcode-generator selects by default
8
9
  // keeps one byte per character, so it is switched to UTF-8 once here rather than relied on
@@ -32,11 +33,7 @@ function hotp(secret, counter) {
32
33
  }
33
34
 
34
35
  function generateTotpSeed() {
35
- let seed = '';
36
- for (let i = 0; i < SEED_LENGTH; i++) {
37
- seed += SEED_CHARSET[crypto.randomInt(SEED_CHARSET.length)];
38
- }
39
- return seed;
36
+ return randomId(SEED_CHARSET, SEED_LENGTH);
40
37
  }
41
38
 
42
39
  function verifyTotp(seed, token, options) {
@@ -3,7 +3,6 @@
3
3
  const fs = require('fs').promises;
4
4
  const Path = require('path');
5
5
  const Gettext = require('@postalsys/gettext');
6
- const { mo } = require('gettext-parser');
7
6
  const locales = require('../translations/locales.json');
8
7
  const joiMessages = require('@postalsys/joi-messages');
9
8
 
@@ -25,7 +24,7 @@ async function loadTranslations() {
25
24
  // Gettext translations
26
25
  for (let locale of locales) {
27
26
  let fContent = await fs.readFile(Path.join(translationsDir, locale.file || `${locale.locale}.mo`));
28
- let parsedTranslations = mo.parse(fContent);
27
+ let parsedTranslations = Gettext.parseMo(fContent);
29
28
  gt.addTranslations(locale.locale, domain, parsedTranslations);
30
29
  }
31
30
  }