emailengine-app 2.77.0 → 2.79.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 (189) hide show
  1. package/.github/workflows/test.yml +80 -0
  2. package/.ncurc.js +23 -13
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +60 -0
  5. package/bin/emailengine.js +1 -1
  6. package/config/e2e.toml +2 -1
  7. package/config/test.toml +2 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +1 -1
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +145 -61
  12. package/lib/api-reference/format.js +105 -4
  13. package/lib/api-reference/index.js +24 -7
  14. package/lib/api-reference/model.js +148 -21
  15. package/lib/api-reference/schema-tree.js +282 -28
  16. package/lib/api-routes/account-routes.js +99 -36
  17. package/lib/api-routes/behavior-notes.js +3 -0
  18. package/lib/api-routes/blocklist-routes.js +21 -47
  19. package/lib/api-routes/chat-routes.js +10 -12
  20. package/lib/api-routes/delivery-test-routes.js +6 -26
  21. package/lib/api-routes/export-routes.js +2 -0
  22. package/lib/api-routes/gateway-routes.js +52 -11
  23. package/lib/api-routes/license-routes.js +2 -0
  24. package/lib/api-routes/mailbox-routes.js +29 -26
  25. package/lib/api-routes/message-routes.js +27 -21
  26. package/lib/api-routes/oauth2-app-routes.js +11 -29
  27. package/lib/api-routes/operation-impact.js +80 -0
  28. package/lib/api-routes/outbox-routes.js +15 -5
  29. package/lib/api-routes/permission-map.js +397 -0
  30. package/lib/api-routes/route-helpers.js +223 -9
  31. package/lib/api-routes/route-metadata.js +28 -0
  32. package/lib/api-routes/settings-routes.js +30 -25
  33. package/lib/api-routes/stats-routes.js +2 -2
  34. package/lib/api-routes/submit-routes.js +53 -31
  35. package/lib/api-routes/template-routes.js +3 -0
  36. package/lib/api-routes/token-routes.js +319 -33
  37. package/lib/api-routes/webhook-route-routes.js +14 -4
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/auth-token.js +80 -8
  41. package/lib/autodetect-imap-settings.js +40 -16
  42. package/lib/base32.js +30 -0
  43. package/lib/bounce-detect.js +182 -62
  44. package/lib/consts.js +10 -0
  45. package/lib/db.js +20 -2
  46. package/lib/delivery-error.js +30 -1
  47. package/lib/egress-filter.js +89 -8
  48. package/lib/email-client/base-client.js +35 -113
  49. package/lib/email-client/gmail-client.js +22 -13
  50. package/lib/email-client/imap/listing-diff.js +3 -3
  51. package/lib/email-client/imap/mailbox.js +28 -93
  52. package/lib/email-client/imap/subconnection.js +10 -7
  53. package/lib/email-client/imap/sync-operations.js +46 -46
  54. package/lib/email-client/imap-client.js +39 -28
  55. package/lib/email-client/message-builder.js +15 -15
  56. package/lib/email-client/notification-handler.js +1 -1
  57. package/lib/email-client/outlook/graph-api.js +10 -4
  58. package/lib/email-client/outlook-client.js +54 -55
  59. package/lib/email-client/smtp-pool-manager.js +1 -1
  60. package/lib/enum-descriptions.js +92 -2
  61. package/lib/export.js +2 -2
  62. package/lib/field-usage.js +133 -0
  63. package/lib/gateway.js +2 -2
  64. package/lib/get-raw-email.js +1 -1
  65. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  66. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  67. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  68. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  69. package/lib/imapproxy/imap-core/lib/imap-connection.js +17 -7
  70. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  71. package/lib/imapproxy/imap-server.js +40 -10
  72. package/lib/license-beacon.js +5 -10
  73. package/lib/lists.js +49 -1
  74. package/lib/llm-pre-process.js +6 -6
  75. package/lib/logger.js +5 -1
  76. package/lib/metrics-collector.js +2 -2
  77. package/lib/msgpack.js +62 -0
  78. package/lib/oauth/decode-jwt-payload.js +39 -0
  79. package/lib/oauth/gmail.js +9 -12
  80. package/lib/oauth/mail-ru.js +5 -7
  81. package/lib/oauth/outlook-identity.js +61 -0
  82. package/lib/oauth/outlook.js +9 -9
  83. package/lib/oauth/pubsub/google.js +25 -10
  84. package/lib/oauth/retry-setup.js +38 -0
  85. package/lib/oauth/scope-checker.js +1 -1
  86. package/lib/oauth2-apps.js +224 -295
  87. package/lib/openapi/build-document.js +15 -7
  88. package/lib/openapi/joi-schema.js +20 -0
  89. package/lib/outbox.js +145 -14
  90. package/lib/pre-process.js +9 -9
  91. package/lib/queue-stats.js +49 -0
  92. package/lib/read-env-value.js +37 -0
  93. package/lib/reconnection-manager.js +2 -2
  94. package/lib/rewrite-text-nodes.js +4 -3
  95. package/lib/routes-ui.js +4 -0
  96. package/lib/schemas.js +223 -155
  97. package/lib/settings.js +84 -5
  98. package/lib/sub-script.js +2 -1
  99. package/lib/swagger-options.js +2 -1
  100. package/lib/templates.js +5 -5
  101. package/lib/threads.js +2 -2
  102. package/lib/token-audit-log.js +208 -0
  103. package/lib/token-permission-view.js +219 -0
  104. package/lib/token-permissions.js +172 -0
  105. package/lib/tokens.js +100 -16
  106. package/lib/tools.js +259 -85
  107. package/lib/totp.js +67 -0
  108. package/lib/ui-routes/account-routes.js +122 -26
  109. package/lib/ui-routes/admin-config-routes.js +20 -17
  110. package/lib/ui-routes/admin-entities-routes.js +66 -22
  111. package/lib/ui-routes/auth-routes.js +36 -48
  112. package/lib/ui-routes/export-routes.js +10 -4
  113. package/lib/ui-routes/oauth-config-routes.js +5 -5
  114. package/lib/ui-routes/reference-routes.js +11 -8
  115. package/lib/ui-routes/route-helpers.js +79 -2
  116. package/lib/ui-routes/settings-page.js +1 -1
  117. package/lib/ui-routes/smtp-test-routes.js +1 -1
  118. package/lib/ui-routes/suppression-list-routes.js +294 -0
  119. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  120. package/lib/utils/is-email.js +34 -0
  121. package/lib/utils/network.js +2 -2
  122. package/lib/utils/to-camel-case.js +17 -0
  123. package/lib/web-safe-html.js +1 -1
  124. package/lib/webhook-egress.js +37 -0
  125. package/lib/webhook-routing.js +80 -0
  126. package/lib/webhooks.js +21 -15
  127. package/package.json +26 -27
  128. package/sbom.json +1 -0
  129. package/server.js +81 -42
  130. package/static/css/flyonui.css +1 -1
  131. package/static/css/public.css +3 -0
  132. package/static/css/src/app.tailwind.css +159 -9
  133. package/static/js/app.js +69 -0
  134. package/static/js/reference.js +741 -10
  135. package/static/js/ui.js +43 -0
  136. package/static/licenses.html +698 -1590
  137. package/translations/README.md +64 -0
  138. package/translations/de.mo +0 -0
  139. package/translations/de.po +164 -120
  140. package/translations/en.po +200 -161
  141. package/translations/et.mo +0 -0
  142. package/translations/et.po +163 -120
  143. package/translations/fr.mo +0 -0
  144. package/translations/fr.po +163 -120
  145. package/translations/ja.mo +0 -0
  146. package/translations/ja.po +163 -120
  147. package/translations/messages.pot +94 -64
  148. package/translations/nl.mo +0 -0
  149. package/translations/nl.po +164 -120
  150. package/translations/pl.mo +0 -0
  151. package/translations/pl.po +163 -120
  152. package/views/account-identity-error.hbs +34 -0
  153. package/views/accounts/account.hbs +69 -7
  154. package/views/accounts/browse.hbs +18 -35
  155. package/views/accounts/edit.hbs +1 -0
  156. package/views/accounts/register/imap.hbs +12 -2
  157. package/views/config/logging.hbs +6 -0
  158. package/views/config/oauth/app.hbs +0 -2
  159. package/views/config/security.hbs +13 -0
  160. package/views/layout/app.hbs +29 -5
  161. package/views/oauth-scope-error.hbs +1 -1
  162. package/views/partials/oauth_form.hbs +0 -15
  163. package/views/partials/reference/disclosure.hbs +8 -2
  164. package/views/partials/reference/nav.hbs +36 -9
  165. package/views/partials/reference/operation.hbs +48 -14
  166. package/views/partials/reference/params.hbs +17 -1
  167. package/views/partials/reference/schema-node.hbs +112 -54
  168. package/views/partials/reference/schema-tools.hbs +25 -0
  169. package/views/partials/reference/token-alert.hbs +35 -10
  170. package/views/partials/reference/try-it.hbs +84 -11
  171. package/views/partials/side_menu.hbs +1 -0
  172. package/views/partials/ui/checkbox.hbs +2 -2
  173. package/views/partials/ui/tabs.hbs +7 -1
  174. package/views/reference/index.hbs +1 -1
  175. package/views/reference/token.hbs +4 -0
  176. package/views/suppression-lists/index.hbs +85 -0
  177. package/views/suppression-lists/list.hbs +87 -0
  178. package/views/templates/index.hbs +8 -2
  179. package/views/tokens/index.hbs +31 -4
  180. package/views/tokens/new.hbs +324 -2
  181. package/workers/api.js +299 -140
  182. package/workers/documents.js +46 -26
  183. package/workers/export.js +20 -8
  184. package/workers/imap-proxy.js +2 -2
  185. package/workers/imap.js +13 -7
  186. package/workers/smtp.js +13 -7
  187. package/workers/submit.js +41 -31
  188. package/workers/webhooks.js +60 -37
  189. package/lib/feature-flags.js +0 -48
package/lib/tools.js CHANGED
@@ -2,12 +2,17 @@
2
2
 
3
3
  'use strict';
4
4
 
5
- const msgpack = require('msgpack5')();
5
+ const msgpack = require('./msgpack');
6
6
  const enumMessageFlags = require('./enum-message-flags');
7
7
  const Joi = require('joi');
8
8
  const he = require('he');
9
9
  const packageData = require('../package.json');
10
10
  const settings = require('./settings');
11
+ // Safe to require at load time despite db.js opening Redis clients: settings.js above already
12
+ // requires it, so db.js is in this file's dependency graph either way. db.js does not require
13
+ // tools.js back (it inlines readEnvValue precisely to avoid that), so there is no cycle.
14
+ const { QUEUES_BY_NAME } = require('./db');
15
+ const { queueStats } = require('./queue-stats');
11
16
  const { brotliDecompress } = require('zlib');
12
17
  const util = require('util');
13
18
  const brotliDecompressAsync = util.promisify(brotliDecompress);
@@ -27,6 +32,8 @@ const pathlib = require('path');
27
32
  const { randomUUID: uuid } = require('crypto');
28
33
  const mimeTypes = require('nodemailer/lib/mime-funcs/mime-types');
29
34
  const { v3: murmurhash } = require('murmurhash');
35
+ const { isEmail } = require('./utils/is-email');
36
+ const { toCamelCase } = require('./utils/to-camel-case');
30
37
  const { compare: compareVersions, validate: validateVersion } = require('compare-versions');
31
38
  const {
32
39
  REDIS_PREFIX,
@@ -49,6 +56,8 @@ const { getLocalAddress } = require('./utils/network');
49
56
  const { fetch: fetchCmd, Agent, RetryAgent, ProxyAgent } = require('undici');
50
57
  const tls = require('tls');
51
58
  const { SocksClient } = require('socks');
59
+ const { createWebhookLookup, WEBHOOK_EGRESS_POLICY } = require('./webhook-egress');
60
+ const { readEnvValue } = require('./read-env-value');
52
61
 
53
62
  const AGENT_OPTS = {
54
63
  strictContentLength: false,
@@ -82,19 +91,46 @@ const RETRY_OPTS = {
82
91
  ]
83
92
  };
84
93
 
94
+ // Webhook deliveries are the one outbound path whose destination the operator supplies, so they
95
+ // get a dispatcher that resolves through the egress policy (lib/webhook-egress.js) rather than the
96
+ // shared resolver. It is built here because its lifetime is tied to the other agents': a proxy
97
+ // setting change swaps them all out together.
98
+ function buildWebhookDispatcher(proxied, existing) {
99
+ const lookup = createWebhookLookup();
100
+
101
+ // Behind a proxy the target hostname is resolved by the proxy, not here, so a local lookup can
102
+ // only vet the route to the proxy itself. There is nothing to bind; fall back to the shared
103
+ // dispatcher and leave assertAllowedUrl() as the advisory check it can only be in that setup.
104
+ if (proxied || !lookup) {
105
+ return httpAgent.retry;
106
+ }
107
+
108
+ // Nothing a reload changes can affect a dedicated dispatcher - the policy is fixed at startup
109
+ // and the Agent never references httpAgent.fetch - so reuse it rather than discarding warm
110
+ // sockets. Saving the network settings form reloads on any field, not just a proxy one.
111
+ return existing || new RetryAgent(new Agent(Object.assign({}, AGENT_OPTS, { connect: { lookup } })), RETRY_OPTS);
112
+ }
113
+
85
114
  // Shared mutable object -- consumers import the object reference and access
86
- // .fetch / .retry at call time, so replacing properties here is visible everywhere.
115
+ // .fetch / .retry / .webhook at call time, so replacing properties here is visible everywhere.
87
116
  const httpAgent = {
88
117
  fetch: new Agent(AGENT_OPTS),
89
- retry: null
118
+ retry: null,
119
+ webhook: null
90
120
  };
91
121
  httpAgent.retry = new RetryAgent(httpAgent.fetch, RETRY_OPTS);
122
+ httpAgent.webhook = buildWebhookDispatcher(false, null);
92
123
 
93
124
  // Backward-compat aliases (read from httpAgent at call time via getter)
94
125
  // backward-compat aliases are defined as getters on module.exports below
95
126
 
96
127
  const SOCKS4_PROTOCOLS = new Set(['socks4:', 'socks4a:']);
97
128
 
129
+ // Accounts a stale-useAuthServer warning was already logged for, keyed by account:target.
130
+ // getActiveAccessTokenData() runs once per API request, so an unconditional warn would repeat
131
+ // the same line for the lifetime of the stale flag.
132
+ const AUTH_SERVER_FALLBACK_WARNED = new Set();
133
+
98
134
  function createSocksAgent(proxyUrl, agentOpts) {
99
135
  let parsed = new URL(proxyUrl);
100
136
  let proxyType = SOCKS4_PROTOCOLS.has(parsed.protocol) ? 4 : 5;
@@ -194,6 +230,9 @@ async function _doReloadHttpProxyAgent() {
194
230
  }
195
231
 
196
232
  let oldFetch = httpAgent.fetch;
233
+ // Only a dedicated dispatcher is ours to close; when webhooks share the general one it is
234
+ // closed via oldFetch. Read before anything is swapped, while the comparison still holds.
235
+ let oldWebhook = httpAgent.webhook !== httpAgent.retry ? httpAgent.webhook : null;
197
236
 
198
237
  try {
199
238
  if (enabled && proxyUrl) {
@@ -217,20 +256,27 @@ async function _doReloadHttpProxyAgent() {
217
256
  }
218
257
 
219
258
  httpAgent.retry = new RetryAgent(httpAgent.fetch, RETRY_OPTS);
259
+ httpAgent.webhook = buildWebhookDispatcher(!!(enabled && proxyUrl), oldWebhook);
220
260
 
221
261
  logger.info({
222
262
  msg: 'HTTP proxy agent reloaded',
223
263
  httpProxyEnabled: !!enabled,
224
- httpProxyUrl: enabled && proxyUrl ? proxyUrl : null
264
+ httpProxyUrl: enabled && proxyUrl ? proxyUrl : null,
265
+ webhookEgressPolicy: WEBHOOK_EGRESS_POLICY,
266
+ webhookEgressPinned: httpAgent.webhook !== httpAgent.retry
225
267
  });
226
268
 
227
- if (oldFetch && oldFetch !== httpAgent.fetch) {
228
- try {
229
- await oldFetch.close();
230
- } catch (err) {
231
- // ignore close errors
232
- }
233
- }
269
+ // Closing is graceful, so it waits for whatever is still in flight to drain. Overlap the
270
+ // two rather than making one agent's slow request hold the other's sockets open.
271
+ // Closing a RetryAgent closes the Agent it wraps.
272
+ await Promise.all(
273
+ [
274
+ [oldFetch, httpAgent.fetch],
275
+ [oldWebhook, httpAgent.webhook]
276
+ ]
277
+ .filter(([stale, current]) => stale && stale !== current)
278
+ .map(([stale]) => stale.close().catch(() => false))
279
+ );
234
280
  } catch (err) {
235
281
  logger.error({ msg: 'Failed to create HTTP proxy agent, keeping existing agent', err });
236
282
  }
@@ -277,7 +323,76 @@ function resolveOAuthErrorStatus(responseError, err) {
277
323
  return typeof fallback === 'number' && fallback >= 400 ? fallback : 500;
278
324
  }
279
325
 
326
+ // Key names whose value must never be rendered into a validation message. Deliberately broad:
327
+ // a false positive only replaces the value with a placeholder in an error message, while a miss
328
+ // writes a credential to the log and returns it to the client.
329
+ const CREDENTIAL_KEY_REGEX = /pass|secret|token|key|seed|credential|signature/i;
330
+
331
+ /**
332
+ * Strips the submitted values out of a joi ValidationError, in place, so it can be logged.
333
+ *
334
+ * A joi error exposes the rejected input in four places: the whole submitted payload in
335
+ * `_original`, the value in every detail context, and - for the `string.pattern` family, the only
336
+ * common rule that renders it - the value inlined into `message` and into the `stack` snapshot
337
+ * taken when the error was constructed. Deleting the first two is not enough, so values belonging
338
+ * to credential-shaped keys are masked in the text as well.
339
+ */
340
+ function redactValidationError(err) {
341
+ if (!err || typeof err !== 'object') {
342
+ return err;
343
+ }
344
+
345
+ delete err._original;
346
+
347
+ let secrets = new Set();
348
+ for (let detail of err.details || []) {
349
+ if (!detail.context) {
350
+ continue;
351
+ }
352
+
353
+ if (typeof detail.context.value === 'string' && detail.context.value) {
354
+ if (CREDENTIAL_KEY_REGEX.test(detail.context.key) || CREDENTIAL_KEY_REGEX.test(detail.context.label)) {
355
+ secrets.add(detail.context.value);
356
+ }
357
+ }
358
+
359
+ delete detail.context.value;
360
+ }
361
+
362
+ if (!secrets.size) {
363
+ return err;
364
+ }
365
+
366
+ let mask = text => {
367
+ for (let secret of secrets) {
368
+ text = text.replaceAll(secret, '(hidden)');
369
+ }
370
+ return text;
371
+ };
372
+
373
+ for (let detail of err.details || []) {
374
+ if (typeof detail.message === 'string') {
375
+ detail.message = mask(detail.message);
376
+ }
377
+ }
378
+
379
+ // `stack` is a plain string snapshot that already embeds the original message, so it has to be
380
+ // masked separately - reassigning `message` does not rewrite it
381
+ if (typeof err.stack === 'string') {
382
+ err.stack = mask(err.stack);
383
+ }
384
+
385
+ if (typeof err.message === 'string') {
386
+ err.message = mask(err.message);
387
+ }
388
+
389
+ return err;
390
+ }
391
+
280
392
  module.exports = {
393
+ // keep the re-export, lib/utils/to-camel-case.js holds it so pure modules can use it too
394
+ toCamelCase,
395
+
281
396
  /**
282
397
  * Establish an admin session: every full session write goes through here
283
398
  * so the session always carries a random sid. The message browser binds
@@ -608,12 +723,72 @@ module.exports = {
608
723
  });
609
724
 
610
725
  if (error) {
611
- throw error;
726
+ // Every caller logs this error, and two of them (imap-client, message-builder) log it at
727
+ // error level to a logger that persists to the per-account log store and to Sentry. The
728
+ // raw joi error carries the auth server's `pass` and `accessToken` in `_original`.
729
+ throw redactValidationError(error);
612
730
  }
613
731
 
614
732
  return value;
615
733
  },
616
734
 
735
+ // Whether a `useAuthServer` flag should be honored. The flag was accepted and stored but
736
+ // silently ignored on several code paths for years, so long-lived instances carry it on
737
+ // accounts that were never auth-server backed and sync fine on their stored credentials.
738
+ // Honoring such a stale flag on an instance with no auth server configured can only fail,
739
+ // so when the caller has stored credentials to fall back to, the flag is ignored with a
740
+ // warning instead of parking the account. Call sites use the useAuthServerForOAuth2() /
741
+ // useAuthServerForConnection() wrappers below, which pair the config shape with the right
742
+ // credential predicate.
743
+ async shouldUseAuthServer(hasStoredCredentials, logger, meta) {
744
+ if (!hasStoredCredentials) {
745
+ // Nothing to fall back to - consult the auth server and let resolveCredentials()
746
+ // report the missing configuration.
747
+ return true;
748
+ }
749
+
750
+ if (await settings.get('authServer')) {
751
+ return true;
752
+ }
753
+
754
+ const warnKey = `${meta && meta.account}:${meta && meta.target}`;
755
+ if (!AUTH_SERVER_FALLBACK_WARNED.has(warnKey)) {
756
+ AUTH_SERVER_FALLBACK_WARNED.add(warnKey);
757
+ logger.warn({
758
+ msg: 'Ignoring the useAuthServer flag: no authentication server is configured, using stored credentials instead',
759
+ ...meta
760
+ });
761
+ }
762
+
763
+ return false;
764
+ },
765
+
766
+ // Whether an oauth2 block holds tokens EmailEngine can use on its own: a refresh token to
767
+ // renew from, or an access token that may still be valid. Only the top-level fields count -
768
+ // the renew and cached-token paths never read tokens nested under `auth`.
769
+ hasStoredOAuth2Tokens(oauth2Data) {
770
+ return Boolean(oauth2Data.refreshToken || oauth2Data.accessToken);
771
+ },
772
+
773
+ // Whether an imap/smtp connection config carries complete stored credentials.
774
+ hasStoredServerCredentials(connectionConfig) {
775
+ const auth = connectionConfig.auth;
776
+ return Boolean(auth && auth.user && (auth.pass || auth.accessToken));
777
+ },
778
+
779
+ // Should this oauth2 block be resolved through the external auth server?
780
+ async useAuthServerForOAuth2(oauth2Data, logger, meta) {
781
+ return Boolean(oauth2Data.useAuthServer) && (await module.exports.shouldUseAuthServer(module.exports.hasStoredOAuth2Tokens(oauth2Data), logger, meta));
782
+ },
783
+
784
+ // Should this imap/smtp connection config be resolved through the external auth server?
785
+ async useAuthServerForConnection(connectionConfig, logger, meta) {
786
+ return (
787
+ Boolean(connectionConfig.useAuthServer) &&
788
+ (await module.exports.shouldUseAuthServer(module.exports.hasStoredServerCredentials(connectionConfig), logger, meta))
789
+ );
790
+ },
791
+
617
792
  getWorkerCount(processCount) {
618
793
  if (/^\s*cpus\s*$/i.test(processCount)) {
619
794
  processCount = os.cpus().length;
@@ -1039,29 +1214,31 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1039
1214
  }
1040
1215
  },
1041
1216
 
1217
+ redactValidationError,
1218
+
1042
1219
  async failAction(request, h, err) {
1220
+ let error;
1043
1221
  try {
1044
- let details = (err.details || []).map(detail => ({ message: detail.message, key: detail.context.key }));
1222
+ redactValidationError(err);
1045
1223
 
1046
- delete err._original;
1224
+ let details = (err.details || []).map(detail => ({ message: detail.message, key: detail.context.key }));
1047
1225
 
1048
- logger.error({
1226
+ request.logger.debug({
1049
1227
  msg: 'Request failed',
1050
1228
  method: request.method,
1051
1229
  route: request.route.path,
1052
- statusCode: request.response && request.response.statusCode,
1053
1230
  err
1054
1231
  });
1055
1232
 
1056
1233
  let message = request.app.gt.gettext('Invalid input');
1057
- let error = Boom.boomify(new Error(message), { statusCode: 400 });
1234
+ error = Boom.boomify(new Error(message), { statusCode: 400 });
1058
1235
  error.output.payload.fields = details;
1059
-
1060
- throw error;
1061
1236
  } catch (E) {
1062
- request.logger.error({ err: E });
1237
+ request.logger.error({ msg: 'Failed to process a validation failure', err: E });
1063
1238
  throw E;
1064
1239
  }
1240
+
1241
+ throw error;
1065
1242
  },
1066
1243
 
1067
1244
  async verifyAccountInfo(redis, accountData, logger) {
@@ -1163,7 +1340,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1163
1340
  response.mailboxes = mailboxList;
1164
1341
  }
1165
1342
  } catch (err) {
1166
- logger.error({ msg: 'Account verification failed', err });
1343
+ logger.debug({ msg: 'Account verification failed', err });
1167
1344
  response.imap = {
1168
1345
  success: false,
1169
1346
  error: err.message,
@@ -1320,26 +1497,9 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1320
1497
  }
1321
1498
  },
1322
1499
 
1323
- isEmail(str) {
1324
- const schema = Joi.object({
1325
- email: Joi.string().email().required()
1326
- });
1327
-
1328
- const { error, value } = schema.validate(
1329
- { email: str },
1330
- {
1331
- abortEarly: false,
1332
- stripUnknown: true,
1333
- convert: true
1334
- }
1335
- );
1336
-
1337
- if (error) {
1338
- return false;
1339
- }
1340
-
1341
- return value.email;
1342
- },
1500
+ // Re-exported from lib/utils/is-email.js so pure modules can use the same check without requiring
1501
+ // this file (and with it settings and Redis). Keep the re-export - callers import it from here.
1502
+ isEmail,
1343
1503
 
1344
1504
  async emitChangeEvent(logger, account, type, key, payload) {
1345
1505
  try {
@@ -1610,34 +1770,19 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1610
1770
  redisVersion = err.message;
1611
1771
  }
1612
1772
 
1773
+ // Counted concurrently: the queues are independent, so serializing them only adds their
1774
+ // round trips together on a path that renders the admin dashboard. A queue that fails to
1775
+ // count is left out and the rest of the stats response still goes out.
1613
1776
  let queues = {};
1614
- for (let queue of ['notify', 'submit', 'documents']) {
1615
- try {
1616
- const [resActive, resDelayed, resWaiting, resPaused, resMeta] = await redis
1617
- .multi()
1618
- .llen(`${REDIS_PREFIX}bull:${queue}:active`)
1619
- .zcard(`${REDIS_PREFIX}bull:${queue}:delayed`)
1620
- .llen(`${REDIS_PREFIX}bull:${queue}:wait`)
1621
- .llen(`${REDIS_PREFIX}bull:${queue}:paused`)
1622
- .hget(`${REDIS_PREFIX}bull:${queue}:meta`, 'paused')
1623
- .exec();
1624
- if (resActive[0] || resDelayed[0] || resWaiting[0] || resPaused[0] || resMeta[0]) {
1625
- // counting failed, skip this queue but keep the rest of the stats response
1626
- logger.error({ msg: 'Failed to count queue length', queue, active: resActive, delayed: resDelayed, waiting: resWaiting });
1627
- continue;
1777
+ await Promise.all(
1778
+ Object.entries(QUEUES_BY_NAME).map(async ([queue, queueObj]) => {
1779
+ try {
1780
+ queues[queue] = await queueStats(queueObj);
1781
+ } catch (err) {
1782
+ logger.error({ msg: 'Failed to count queue length', queue, err });
1628
1783
  }
1629
- queues[queue] = {
1630
- active: Number(resActive[1]) || 0,
1631
- delayed: Number(resDelayed[1]) || 0,
1632
- waiting: Number(resWaiting[1]) || 0,
1633
- paused: Number(resPaused[1]) || 0,
1634
- isPaused: !!Number(resMeta[1]) || false
1635
- };
1636
- queues[queue].total = queues[queue].active + queues[queue].delayed + queues[queue].waiting + queues[queue].paused;
1637
- } catch (err) {
1638
- logger.error({ msg: 'Failed to count queue length', queue, err });
1639
- }
1640
- }
1784
+ })
1785
+ );
1641
1786
 
1642
1787
  let stats = Object.assign(
1643
1788
  {
@@ -1725,6 +1870,20 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1725
1870
  return secretKey.replace(/^(.{8}).*$/, `$1... (${secretKey.length}B)`);
1726
1871
  },
1727
1872
 
1873
+ // Returns the URL with any embedded basic auth credentials removed, safe for logging. Never
1874
+ // throws: an unparseable value is replaced with a static placeholder rather than echoed back,
1875
+ // because the raw string could itself carry the credentials that made it unparseable.
1876
+ redactUrlCredentials(url) {
1877
+ try {
1878
+ let parsed = new URL(url);
1879
+ parsed.username = '';
1880
+ parsed.password = '';
1881
+ return parsed.toString();
1882
+ } catch {
1883
+ return 'invalid url';
1884
+ }
1885
+ },
1886
+
1728
1887
  validUidValidity(value) {
1729
1888
  if (typeof value === 'bigint') {
1730
1889
  return value > BigInt(0);
@@ -1813,6 +1972,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1813
1972
  account: opts.account,
1814
1973
  name: opts.name,
1815
1974
  email: opts.email,
1975
+ expectedEmail: opts.expectedEmail,
1816
1976
  syncFrom: (opts.syncFrom && opts.syncFrom.toISOString()) || null,
1817
1977
  notifyFrom: (opts.notifyFrom && opts.notifyFrom.toISOString()) || null,
1818
1978
  subconnections: opts.subconnections && opts.subconnections.length ? opts.subconnections : null,
@@ -1834,6 +1994,36 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1834
1994
  return { data: data.toString('base64url'), signature };
1835
1995
  },
1836
1996
 
1997
+ // Builds the signed public subscription-management URL for one recipient on one list - the
1998
+ // same URL every outgoing message with a listId embeds as its List-Unsubscribe target, and
1999
+ // the page where a recipient can re-subscribe. Shared by the mailer (lib/email-client/
2000
+ // base-client.js) and the suppression-list admin UI so the two cannot drift. The signed blob
2001
+ // deliberately carries no nonce and no expiry (see parseSignedFormData): the link stays
2002
+ // valid for as long as the service secret does. messageId is optional - admin generated
2003
+ // links have no originating message. Returns an absolute URL when baseUrl is set and a
2004
+ // host-relative one when it is not, so a missing service URL never leaks a placeholder host.
2005
+ buildUnsubscribeUrl(serviceSecret, baseUrl, opts) {
2006
+ let payload = {
2007
+ act: 'unsub',
2008
+ acc: opts.account,
2009
+ list: opts.list,
2010
+ rcpt: opts.recipient
2011
+ };
2012
+ if (opts.messageId) {
2013
+ payload.msg = opts.messageId;
2014
+ }
2015
+
2016
+ let { data: signedData, signature } = module.exports.getSignedFormDataSync(serviceSecret, payload, true);
2017
+
2018
+ let unsubscribeUrlObj = new URL('/unsubscribe', baseUrl || 'http://localhost');
2019
+ unsubscribeUrlObj.searchParams.append('data', signedData);
2020
+ if (signature) {
2021
+ unsubscribeUrlObj.searchParams.append('sig', signature);
2022
+ }
2023
+
2024
+ return baseUrl ? unsubscribeUrlObj.href : unsubscribeUrlObj.pathname + unsubscribeUrlObj.search;
2025
+ },
2026
+
1837
2027
  // Fail-closed HMAC check for service-secret-signed blobs, shared by every verification site.
1838
2028
  // getServiceSecret() generates and persists a secret when missing, so verification is never
1839
2029
  // silently skipped (an empty secret would otherwise accept forged, unsigned data). Returns true
@@ -2060,23 +2250,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2060
2250
  .filter(v => v);
2061
2251
  },
2062
2252
 
2063
- readEnvValue(key) {
2064
- if (key in process.env) {
2065
- return process.env[key];
2066
- }
2067
-
2068
- if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
2069
- try {
2070
- // try to load from file
2071
- process.env[key] = Fs.readFileSync(process.env[`${key}_FILE`], 'utf-8').replace(/\r?\n/g, '\n').trim();
2072
- logger.trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
2073
- } catch (err) {
2074
- logger.fatal({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
2075
- process.env[key] = '';
2076
- }
2077
- return process.env[key];
2078
- }
2079
- },
2253
+ readEnvValue,
2080
2254
 
2081
2255
  convertDataUrisToAttachments(data) {
2082
2256
  if (data.html) {
@@ -2137,7 +2311,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2137
2311
  logger.trace({ msg: 'Loaded environment TLS value from file', path, file: ref[path] });
2138
2312
  delete ref[path];
2139
2313
  } catch (err) {
2140
- logger.fatal({ msg: 'Failed to load TLS value from file', path, file: ref[path], err });
2314
+ logger.error({ msg: 'Failed to load TLS value from file', path, file: ref[path], err });
2141
2315
  ref[key] = null;
2142
2316
  }
2143
2317
  }
package/lib/totp.js ADDED
@@ -0,0 +1,67 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const { base32Encode } = require('./base32');
5
+
6
+ // In-house RFC 4226 / RFC 6238 TOTP implementation (SHA-1, 6 digits, 30-second period).
7
+ // Replaces the unmaintained speakeasy package while staying byte-compatible with seeds it
8
+ // generated: `totpSeed` is stored as an ASCII string and its raw bytes are the shared secret.
9
+
10
+ const TOTP_STEP_SECONDS = 30;
11
+ const TOTP_DIGITS = 6;
12
+ const TOTP_TOKEN_RE = new RegExp(`^[0-9]{${TOTP_DIGITS}}$`);
13
+
14
+ const SEED_LENGTH = 20;
15
+ const SEED_CHARSET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
16
+
17
+ function hotp(secret, counter) {
18
+ let counterBuf = Buffer.alloc(8);
19
+ counterBuf.writeBigUInt64BE(BigInt(counter));
20
+
21
+ let digest = crypto.createHmac('sha1', secret).update(counterBuf).digest();
22
+
23
+ let offset = digest[digest.length - 1] & 0x0f;
24
+ let code = (digest.readUInt32BE(offset) & 0x7fffffff) % 10 ** TOTP_DIGITS;
25
+
26
+ return code.toString().padStart(TOTP_DIGITS, '0');
27
+ }
28
+
29
+ function generateTotpSeed() {
30
+ let seed = '';
31
+ for (let i = 0; i < SEED_LENGTH; i++) {
32
+ seed += SEED_CHARSET[crypto.randomInt(SEED_CHARSET.length)];
33
+ }
34
+ return seed;
35
+ }
36
+
37
+ function verifyTotp(seed, token, options) {
38
+ let { window = 0, now = Date.now() } = options || {};
39
+
40
+ token = (token || '').toString().trim();
41
+ if (!TOTP_TOKEN_RE.test(token)) {
42
+ return false;
43
+ }
44
+
45
+ let secret = Buffer.from(seed);
46
+ let tokenBuf = Buffer.from(token);
47
+ let counter = Math.floor(now / 1000 / TOTP_STEP_SECONDS);
48
+
49
+ let verified = false;
50
+ for (let delta = -window; delta <= window; delta++) {
51
+ if (counter + delta < 0) {
52
+ continue;
53
+ }
54
+ // no early break - every offset is checked so response timing does not depend on which one matched
55
+ if (crypto.timingSafeEqual(Buffer.from(hotp(secret, counter + delta)), tokenBuf)) {
56
+ verified = true;
57
+ }
58
+ }
59
+
60
+ return verified;
61
+ }
62
+
63
+ function generateTotpUrl(seed, { label, issuer }) {
64
+ return `otpauth://totp/${encodeURIComponent(label)}?secret=${base32Encode(Buffer.from(seed))}&issuer=${encodeURIComponent(issuer)}`;
65
+ }
66
+
67
+ module.exports = { generateTotpSeed, verifyTotp, generateTotpUrl };