emailengine-app 2.79.7 → 2.79.9

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 (188) hide show
  1. package/.github/dependabot.yml +22 -0
  2. package/.github/workflows/test.yml +39 -0
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +37 -0
  5. package/DOCKER_DEPLOYMENT.md +8 -7
  6. package/Dockerfile +35 -11
  7. package/bin/emailengine.js +29 -13
  8. package/config/default.toml +15 -4
  9. package/copy-static-files.sh +23 -5
  10. package/data/google-crawlers.json +7 -1
  11. package/docker-compose.yml +12 -3
  12. package/install.sh +2 -0
  13. package/lib/account.js +26 -1
  14. package/lib/api-routes/account-routes.js +14 -3
  15. package/lib/api-routes/bull-board-routes.js +3 -2
  16. package/lib/api-routes/mailbox-routes.js +4 -1
  17. package/lib/api-routes/message-routes.js +6 -5
  18. package/lib/api-routes/outbox-routes.js +7 -4
  19. package/lib/api-routes/route-helpers.js +8 -0
  20. package/lib/api-routes/settings-routes.js +34 -25
  21. package/lib/api-routes/stats-routes.js +8 -1
  22. package/lib/api-routes/submit-routes.js +2 -1
  23. package/lib/api-routes/template-routes.js +3 -2
  24. package/lib/auth-token.js +73 -2
  25. package/lib/autodetect-imap-settings.js +33 -25
  26. package/lib/bounce-detect.js +45 -0
  27. package/lib/consts.js +13 -2
  28. package/lib/egress-fetch.js +133 -0
  29. package/lib/egress-filter.js +39 -4
  30. package/lib/email-client/base-client.js +274 -24
  31. package/lib/email-client/gmail/gmail-api.js +15 -7
  32. package/lib/email-client/gmail-client.js +121 -64
  33. package/lib/email-client/imap/mailbox.js +18 -59
  34. package/lib/email-client/imap-client.js +53 -29
  35. package/lib/email-client/notification-handler.js +11 -2
  36. package/lib/email-client/outlook/graph-api.js +106 -90
  37. package/lib/email-client/outlook-client.js +222 -106
  38. package/lib/export.js +35 -2
  39. package/lib/generate-text-preview.js +10 -5
  40. package/lib/handlebars-helpers.js +129 -0
  41. package/lib/headers-rewriter.js +1 -1
  42. package/lib/imap-proxy-auth.js +41 -21
  43. package/lib/imapproxy/imap-core/README.md +1 -0
  44. package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
  45. package/lib/imapproxy/imap-server.js +9 -10
  46. package/lib/llm-pre-process.js +4 -1
  47. package/lib/mcp/json-schema.js +50 -2
  48. package/lib/openapi/index.js +3 -0
  49. package/lib/outbox.js +50 -8
  50. package/lib/pre-process.js +4 -1
  51. package/lib/rate-limit.js +23 -4
  52. package/lib/rewrite-text-nodes.js +12 -1
  53. package/lib/schemas.js +37 -8
  54. package/lib/security-headers.js +396 -0
  55. package/lib/sentry.js +36 -4
  56. package/lib/settings.js +19 -1
  57. package/lib/smtp-auth.js +86 -7
  58. package/lib/sso.js +13 -3
  59. package/lib/submit-progress.js +29 -0
  60. package/lib/templates.js +11 -0
  61. package/lib/tools.js +361 -173
  62. package/lib/ui-routes/account-routes.js +73 -13
  63. package/lib/ui-routes/admin-config-routes.js +7 -21
  64. package/lib/ui-routes/admin-entities-routes.js +42 -12
  65. package/lib/ui-routes/auth-routes.js +87 -28
  66. package/lib/ui-routes/dashboard-routes.js +1 -1
  67. package/lib/ui-routes/export-routes.js +4 -0
  68. package/lib/ui-routes/internals-routes.js +2 -0
  69. package/lib/ui-routes/mcp-consent-routes.js +12 -2
  70. package/lib/ui-routes/network-config-routes.js +6 -5
  71. package/lib/ui-routes/oauth-config-routes.js +12 -1
  72. package/lib/ui-routes/route-helpers.js +65 -14
  73. package/lib/ui-routes/settings-page.js +10 -0
  74. package/lib/ui-routes/smtp-test-routes.js +7 -0
  75. package/lib/ui-routes/suppression-list-routes.js +16 -5
  76. package/lib/ui-routes/unsubscribe-routes.js +22 -3
  77. package/lib/webhook-egress.js +5 -0
  78. package/lib/webhooks.js +14 -2
  79. package/package.json +23 -26
  80. package/sbom.json +1 -1
  81. package/server.js +100 -71
  82. package/static/css/flyonui.css +1 -1
  83. package/static/js/ace/css/ace.css +1462 -0
  84. package/static/js/ace/css/kuroir-1.png +0 -0
  85. package/static/js/ace/css/kuroir-2.png +0 -0
  86. package/static/js/ace/css/main-1.png +0 -0
  87. package/static/js/ace/css/main-10.svg +4 -0
  88. package/static/js/ace/css/main-11.svg +5 -0
  89. package/static/js/ace/css/main-12.svg +4 -0
  90. package/static/js/ace/css/main-13.png +0 -0
  91. package/static/js/ace/css/main-14.png +0 -0
  92. package/static/js/ace/css/main-15.png +0 -0
  93. package/static/js/ace/css/main-16.png +0 -0
  94. package/static/js/ace/css/main-17.png +0 -0
  95. package/static/js/ace/css/main-18.png +0 -0
  96. package/static/js/ace/css/main-19.png +0 -0
  97. package/static/js/ace/css/main-2.png +0 -0
  98. package/static/js/ace/css/main-20.png +0 -0
  99. package/static/js/ace/css/main-21.png +0 -0
  100. package/static/js/ace/css/main-22.png +0 -0
  101. package/static/js/ace/css/main-23.png +0 -0
  102. package/static/js/ace/css/main-24.png +0 -0
  103. package/static/js/ace/css/main-25.svg +1 -0
  104. package/static/js/ace/css/main-26.png +0 -0
  105. package/static/js/ace/css/main-3.png +0 -0
  106. package/static/js/ace/css/main-4.png +0 -0
  107. package/static/js/ace/css/main-5.svg +7 -0
  108. package/static/js/ace/css/main-6.svg +9 -0
  109. package/static/js/ace/css/main-7.svg +7 -0
  110. package/static/js/ace/css/main-8.svg +9 -0
  111. package/static/js/ace/css/main-9.svg +6 -0
  112. package/static/js/ace/css/theme/kuroir.css +78 -0
  113. package/static/js/ace/css/theme/tomorrow_night.css +128 -0
  114. package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
  115. package/static/js/ace/css/theme/xcode.css +106 -0
  116. package/static/js/ace/css/tomorrow_night-1.png +0 -0
  117. package/static/js/ace/css/tomorrow_night-2.png +0 -0
  118. package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
  119. package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
  120. package/static/js/ace/css/xcode-1.png +0 -0
  121. package/static/js/ace/css/xcode-2.png +0 -0
  122. package/static/js/ee-client.js +256 -102
  123. package/static/js/public.js +7 -0
  124. package/static/js/ui.js +32 -0
  125. package/static/licenses.html +338 -298
  126. package/static/vendor/simplewebauthn/browser.min.js +2 -2
  127. package/translations/messages.pot +158 -112
  128. package/views/account/passkeys.hbs +8 -0
  129. package/views/account/password.hbs +11 -0
  130. package/views/account/security.hbs +18 -7
  131. package/views/accounts/account.hbs +21 -38
  132. package/views/accounts/browse.hbs +3 -1
  133. package/views/accounts/edit.hbs +1 -1
  134. package/views/accounts/register/imap-server.hbs +11 -3
  135. package/views/config/ai.hbs +3 -1
  136. package/views/config/branding.hbs +4 -2
  137. package/views/config/document-store/chat.hbs +1 -1
  138. package/views/config/document-store/index.hbs +1 -1
  139. package/views/config/email-processing.hbs +2 -0
  140. package/views/config/imap-proxy.hbs +3 -1
  141. package/views/config/license.hbs +1 -1
  142. package/views/config/logging.hbs +3 -1
  143. package/views/config/mcp.hbs +3 -1
  144. package/views/config/network.hbs +16 -16
  145. package/views/config/oauth/app.hbs +4 -4
  146. package/views/config/security.hbs +2 -0
  147. package/views/config/service.hbs +3 -1
  148. package/views/config/smtp.hbs +3 -1
  149. package/views/config/webhooks.hbs +4 -2
  150. package/views/error.hbs +10 -2
  151. package/views/internals/index.hbs +1 -1
  152. package/views/layout/app.hbs +9 -14
  153. package/views/layout/login.hbs +1 -1
  154. package/views/layout/prompt.hbs +1 -1
  155. package/views/layout/public.hbs +1 -1
  156. package/views/legal.hbs +1 -1
  157. package/views/mcp/authorize.hbs +1 -1
  158. package/views/partials/ace_assets.hbs +13 -0
  159. package/views/partials/add_account_modal.hbs +1 -1
  160. package/views/partials/address_list.hbs +4 -4
  161. package/views/partials/filter_editor_js.hbs +3 -3
  162. package/views/partials/gateway_js.hbs +1 -1
  163. package/views/partials/oauth_form.hbs +6 -6
  164. package/views/partials/public_theme_init.hbs +1 -1
  165. package/views/partials/template_form.hbs +2 -2
  166. package/views/partials/test_send.hbs +7 -4
  167. package/views/partials/theme_init.hbs +1 -1
  168. package/views/partials/ui/details.hbs +2 -2
  169. package/views/partials/ui/env-managed-alert.hbs +19 -0
  170. package/views/partials/webhook_form.hbs +1 -1
  171. package/views/partials/webhooks_editor_functions.hbs +1 -1
  172. package/views/reference/redirect.hbs +1 -1
  173. package/views/templates/template.hbs +2 -2
  174. package/views/tokens/new.hbs +1 -1
  175. package/views/unsubscribe.hbs +7 -1
  176. package/views/webhooks/webhook.hbs +2 -2
  177. package/workers/api.js +179 -175
  178. package/workers/export.js +1 -5
  179. package/workers/imap.js +33 -6
  180. package/workers/smtp.js +19 -43
  181. package/workers/submit.js +31 -13
  182. package/workers/webhooks.js +9 -24
  183. package/lib/reconnection-manager.js +0 -106
  184. package/static/front/EmailEngine_logo_horiz.png +0 -0
  185. package/static/front/EmailEngine_logo_vert.png +0 -0
  186. package/static/front/index.html +0 -57
  187. package/static/front/logo.png +0 -0
  188. package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
@@ -151,9 +151,7 @@ async function init(args) {
151
151
 
152
152
  async handler(request) {
153
153
  try {
154
- return {
155
- deleted: await outbox.del({ queueId: request.params.queueId, logger })
156
- };
154
+ return await outbox.del({ queueId: request.params.queueId, logger });
157
155
  } catch (err) {
158
156
  handleError(request, err);
159
157
  }
@@ -191,7 +189,12 @@ async function init(args) {
191
189
 
192
190
  response: {
193
191
  schema: Joi.object({
194
- deleted: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the message deleted')
192
+ deleted: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the message deleted'),
193
+ locked: Joi.boolean()
194
+ .example(true)
195
+ .description(
196
+ 'Present when the message was not deleted because a delivery attempt is running for it right now. Retry once the attempt has finished'
197
+ )
195
198
  }).label('DeleteOutboxEntryResponse'),
196
199
  failAction: 'log'
197
200
  }
@@ -224,6 +224,14 @@ function maskSecrets(entry) {
224
224
  }
225
225
  }
226
226
 
227
+ // A failed delivery records the target it was aimed at on the webhook route, the account or
228
+ // the settings. The worker stores it with the credentials already stripped, but a flag written
229
+ // by an older release still carries the raw URL - the same one field over from the masked
230
+ // `targetUrl` / `webhooks` beside it, readable by any token that can list webhook routes.
231
+ if (entry.webhookErrorFlag && typeof entry.webhookErrorFlag === 'object' && entry.webhookErrorFlag.url) {
232
+ entry.webhookErrorFlag.url = maskUrlPassword(entry.webhookErrorFlag.url);
233
+ }
234
+
227
235
  return entry;
228
236
  }
229
237
 
@@ -15,7 +15,7 @@ const { settingsSchema, settingsQuerySchema, apiResponses, ENUM_DESCRIPTIONS } =
15
15
  // not part of the stored settings.
16
16
  const settingsOutputSchema = {};
17
17
  for (let key of Object.keys(settingsSchema)) {
18
- if (settings.encryptedKeys.includes(key)) {
18
+ if (settings.secretKeys.includes(key)) {
19
19
  settingsOutputSchema[key] = Joi.boolean()
20
20
  .allow(null)
21
21
  .example(true)
@@ -40,32 +40,37 @@ async function init(args) {
40
40
 
41
41
  async handler(request) {
42
42
  let values = {};
43
- for (let key of Object.keys(request.query)) {
44
- if (request.query[key]) {
45
- if (key === 'eventTypes') {
46
- values[key] = Object.keys(consts)
47
- .filter(key => /_NOTIFY?/.test(key))
48
- .map(key => consts[key]);
49
- continue;
50
- }
43
+ try {
44
+ for (let key of Object.keys(request.query)) {
45
+ if (request.query[key]) {
46
+ if (key === 'eventTypes') {
47
+ values[key] = Object.keys(consts)
48
+ .filter(key => /_NOTIFY?/.test(key))
49
+ .map(key => consts[key]);
50
+ continue;
51
+ }
51
52
 
52
- let value = await settings.get(key);
53
+ let value = await settings.get(key);
53
54
 
54
- if (settings.encryptedKeys.includes(key)) {
55
- // do not reveal secret values
56
- // instead show boolean value true if value is set, or false if it's not
57
- value = value ? true : false;
58
- }
55
+ if (settings.secretKeys.includes(key)) {
56
+ // do not reveal secret values
57
+ // instead show boolean value true if value is set, or false if it's not
58
+ value = value ? true : false;
59
+ }
59
60
 
60
- values[key] = value;
61
+ values[key] = value;
62
+ }
61
63
  }
64
+ } catch (err) {
65
+ handleError(request, err);
62
66
  }
63
67
 
64
- // The global equivalents of the credential-bearing account fields. encryptedKeys above
65
- // covers what is encrypted at rest, which is not the same set: proxyUrl, httpProxyUrl,
66
- // webhooks and webhooksCustomHeaders are stored in the clear and were returned in full,
67
- // so this endpoint disclosed exactly what the account getters were masking. It sits in
68
- // the never-grantable admin group, so no narrowed token reaches it - but leaving the
68
+ // The global equivalents of the credential-bearing account fields. secretKeys above
69
+ // covers the values that are hidden behind a boolean, which is not the same set:
70
+ // proxyUrl, httpProxyUrl, webhooks and webhooksCustomHeaders are returned as values
71
+ // (they are useful to read back) and used to be returned in full, so this endpoint
72
+ // disclosed exactly what the account getters were masking. It sits in the
73
+ // never-grantable admin group, so no narrowed token reaches it - but leaving the
69
74
  // asymmetry here is how the next reader learns the wrong pattern.
70
75
  maskSecrets(values);
71
76
 
@@ -141,12 +146,16 @@ async function init(args) {
141
146
  }
142
147
  } catch (err) {
143
148
  handleError(request, err);
149
+ } finally {
150
+ // Broadcast to all workers (including this one); each reloads its HTTP proxy agent
151
+ // via the 'settings' message handler, so no inline reload is needed here. Only the
152
+ // keys that were actually written: a skipped masked echo must not trigger reloads
153
+ // either. In a finally because the keys are written one at a time: when a later
154
+ // key fails, the earlier ones are already stored and the other workers still have
155
+ // to reload for them, or they keep running on settings Redis no longer holds.
156
+ notify('settings', applied);
144
157
  }
145
158
 
146
- // Broadcast to all workers (including this one); each reloads its HTTP proxy agent via
147
- // the 'settings' message handler, so no inline reload is needed here. Only the keys
148
- // that were actually written: a skipped masked echo must not trigger reloads either.
149
- notify('settings', applied);
150
159
  return { updated: Object.keys(applied) };
151
160
  },
152
161
  options: {
@@ -5,6 +5,7 @@ const { redis } = require('../db');
5
5
  const { failAction, getStats } = require('../tools');
6
6
  const { MAX_DAYS_STATS } = require('../consts');
7
7
  const { apiResponses } = require('../schemas');
8
+ const { handleError } = require('./route-helpers');
8
9
  const packageData = require('../../package.json');
9
10
 
10
11
  async function init(args) {
@@ -15,7 +16,13 @@ async function init(args) {
15
16
  path: '/v1/stats',
16
17
 
17
18
  async handler(request) {
18
- return await getStats(redis, call, request.query.seconds);
19
+ try {
20
+ return await getStats(redis, call, request.query.seconds);
21
+ } catch (err) {
22
+ // The metrics come from a main-thread RPC, so a timeout there carries its own
23
+ // status code, which the shared handler keeps instead of a generic 500
24
+ handleError(request, err);
25
+ }
19
26
  },
20
27
 
21
28
  options: {
@@ -16,6 +16,7 @@ const {
16
16
  idempotencyKeySchema,
17
17
  headerTimeoutSchema,
18
18
  accountIdSchema,
19
+ messageIdSchema,
19
20
  templateSchemas,
20
21
  settingsSchema,
21
22
  ipSchema,
@@ -622,7 +623,7 @@ async function init(args) {
622
623
 
623
624
  params: Joi.object({
624
625
  account: accountIdSchema.required(),
625
- message: Joi.string().max(256).required().example('AAAAAQAACnA').description('Message ID of the draft')
626
+ message: messageIdSchema.required().description('Message ID of the draft')
626
627
  }),
627
628
 
628
629
  headers: submitHeadersSchema,
@@ -177,11 +177,12 @@ async function init(args) {
177
177
  .example('Something about the template')
178
178
  .description('Optional description of the template')
179
179
  .label('TemplateDescription'),
180
+ // No default on purpose: the handler copies every present key over the stored
181
+ // metadata, so a defaulted format would turn any partial update into "html"
180
182
  format: Joi.string()
181
183
  .empty('')
182
184
  .valid('html', 'markdown')
183
- .default('html')
184
- .description('Markup language for HTML ("html" or "markdown")')
185
+ .description('Markup language for HTML ("html" or "markdown"). Leave out to keep the stored value')
185
186
  .label('TemplateUpdateFormat'),
186
187
  content: Joi.object({
187
188
  subject: templateSchemas.subject,
package/lib/auth-token.js CHANGED
@@ -12,6 +12,7 @@ const tokenPermissions = require('./token-permissions');
12
12
  const tokenAuditLog = require('./token-audit-log');
13
13
  const { SURFACE_GRANTS } = require('./api-routes/permission-map');
14
14
  const { matchIp } = require('./utils/network');
15
+ const { checkRateLimit, peekRateLimit } = require('./rate-limit');
15
16
 
16
17
  // Reason-specific denial messages, shared verbatim by both auth handlers. The
17
18
  // generic "failed to authenticate" fallback and any protocol-specific error
@@ -20,9 +21,72 @@ const REASON_MESSAGES = {
20
21
  username: 'Access denied, invalid username',
21
22
  scope: 'Access denied, invalid scope',
22
23
  ip: 'Access denied, traffic not accepted from this IP',
23
- permissions: 'Access denied, token permissions do not allow this'
24
+ permissions: 'Access denied, token permissions do not allow this',
25
+ limited: 'Too many failed authentication attempts, try again later'
24
26
  };
25
27
 
28
+ // Failed logins a client address may accumulate against one username before the surface stops
29
+ // answering that pair for the rest of the window. The guard exists for the shared server
30
+ // password, which is operator-chosen with no entropy requirement and was guessable at the full
31
+ // speed of a Redis lookup; the 64-hex API tokens are not guessable at any rate this allows.
32
+ //
33
+ // Keyed on address AND username on purpose. The submission surfaces are typically driven by one
34
+ // application host sending for many accounts, and a single stale credential in that host's
35
+ // configuration must not lock its other accounts out. The username buys an attacker nothing:
36
+ // a guess needs a real account id either way, and each id they know only adds one more budget.
37
+ //
38
+ // Only failures count. A busy sender authenticating on every connection would exhaust an
39
+ // attempt-based budget by itself.
40
+ const AUTH_FAILURE_LIMIT = 20;
41
+ const AUTH_FAILURE_WINDOW = 5 * 60; // seconds
42
+
43
+ const authFailureKey = (remoteAddress, account) => `auth:fail:${remoteAddress || 'unknown'}:${account || ''}`;
44
+
45
+ /**
46
+ * Runs a credential check under the client's failed-login budget.
47
+ *
48
+ * Looks before the attempt (a peek, so an accepted login spends nothing) and records only a
49
+ * refusal. Everything `attempt` throws counts as one: the caller decides what belongs inside
50
+ * the budget by what it puts in the function, so a refusal that is about the account rather
51
+ * than the credential (an API-only account on the IMAP proxy) is left outside it.
52
+ *
53
+ * @param {Object} client
54
+ * @param {String} client.remoteAddress - client IP
55
+ * @param {String} client.account - username the client is authenticating as
56
+ * @param {Function} attempt - async () => result; the credential check
57
+ * @param {Function} limitedError - () => Error; the protocol-specific refusal for a spent budget
58
+ * @returns {Promise<*>} whatever `attempt` resolves with
59
+ */
60
+ async function withAuthFailureBudget({ remoteAddress, account }, attempt, limitedError) {
61
+ const key = authFailureKey(remoteAddress, account);
62
+
63
+ let limit = await peekRateLimit(key, AUTH_FAILURE_LIMIT, AUTH_FAILURE_WINDOW);
64
+ if (!limit.success) {
65
+ logger.warn({
66
+ msg: 'Refusing authentication attempt, failure limit reached',
67
+ remoteAddress,
68
+ account,
69
+ count: limit.count,
70
+ allowed: limit.allowed,
71
+ ttlReset: limit.ttlReset
72
+ });
73
+ throw limitedError();
74
+ }
75
+
76
+ try {
77
+ return await attempt();
78
+ } catch (err) {
79
+ // Never masks the refusal: a counter that could not be written is logged, and the
80
+ // client still gets the error the attempt raised
81
+ try {
82
+ await checkRateLimit(key, 1, AUTH_FAILURE_LIMIT, AUTH_FAILURE_WINDOW);
83
+ } catch (recordErr) {
84
+ logger.error({ msg: 'Failed to record authentication failure', remoteAddress, account, err: recordErr });
85
+ }
86
+ throw err;
87
+ }
88
+ }
89
+
26
90
  /**
27
91
  * Validates a 64-char hex API token supplied as a server password.
28
92
  *
@@ -152,4 +216,11 @@ async function validateAuthToken({ password, account, requiredScope, remoteAddre
152
216
  return { authenticated: true, reason: null };
153
217
  }
154
218
 
155
- module.exports = { validateAuthToken, REASON_MESSAGES };
219
+ module.exports = {
220
+ validateAuthToken,
221
+ withAuthFailureBudget,
222
+ authFailureKey,
223
+ AUTH_FAILURE_LIMIT,
224
+ AUTH_FAILURE_WINDOW,
225
+ REASON_MESSAGES
226
+ };
@@ -40,6 +40,8 @@ function parseXml(text) {
40
40
 
41
41
  const { fetch: fetchCmd } = require('undici');
42
42
  const { httpAgent } = require('./tools');
43
+ const { fetchWithVettedRedirects } = require('./egress-fetch');
44
+ const { validateWebhookTarget } = require('./webhook-egress');
43
45
 
44
46
  const RESOLV_TIMEOUT = 5 * 1000;
45
47
 
@@ -255,6 +257,29 @@ async function processAutoconfigFile(email, domain, text, source) {
255
257
  return { imap, smtp, _source: source };
256
258
  }
257
259
 
260
+ // Every HTTP lookup below reaches a destination derived from the email address a caller typed:
261
+ // autoconfig.<domain>, <domain>/.well-known, an autodiscover host a DNS SRV record names, port
262
+ // included. That is the same class of destination as a webhook target, so the requests go through
263
+ // the same egress policy (lib/webhook-egress.js): the policy-bound dispatcher resolves the name at
264
+ // connect time, the pre-check refuses a blocked address up front, and each redirect hop is vetted
265
+ // before it is taken. Without this, a DNS record under the caller's control pointed the lookup at
266
+ // the cloud metadata service or at whatever else the host can route to.
267
+ //
268
+ // Not the retrying dispatcher: a lookup that fails is skipped in favor of the next resolver, and
269
+ // the retry agent would only stretch the timeout budget of a dead one.
270
+ async function fetchAutodiscoveryResource(url, opts) {
271
+ opts = opts || {};
272
+ return await fetchWithVettedRedirects(
273
+ fetchCmd,
274
+ url,
275
+ Object.assign({}, opts, {
276
+ headers: Object.assign({ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})` }, opts.headers),
277
+ dispatcher: httpAgent.webhook,
278
+ validateTarget: validateWebhookTarget
279
+ })
280
+ );
281
+ }
282
+
258
283
  async function resolveUsingMozillaDirectory(email, domain, source) {
259
284
  domain = domain || email.split('@').pop().trim().toLowerCase();
260
285
 
@@ -264,12 +289,7 @@ async function resolveUsingMozillaDirectory(email, domain, source) {
264
289
  //ignore
265
290
  }
266
291
 
267
- let res = await fetchCmd(`https://autoconfig.thunderbird.net/v1.1/${domain}`, {
268
- headers: {
269
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
270
- },
271
- dispatcher: httpAgent.retry
272
- });
292
+ let res = await fetchAutodiscoveryResource(`https://autoconfig.thunderbird.net/v1.1/${domain}`);
273
293
 
274
294
  if (!res.ok) {
275
295
  throw new Error('Invalid response');
@@ -289,12 +309,9 @@ async function resolveUsingAutoconfig(email, domain, source) {
289
309
  //ignore
290
310
  }
291
311
 
292
- let res = await fetchCmd(`https://autoconfig.${encodeURIComponent(domain)}/mail/config-v1.1.xml?emailaddress=${encodeURIComponent(email)}`, {
293
- headers: {
294
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
295
- },
296
- dispatcher: httpAgent.retry
297
- });
312
+ let res = await fetchAutodiscoveryResource(
313
+ `https://autoconfig.${encodeURIComponent(domain)}/mail/config-v1.1.xml?emailaddress=${encodeURIComponent(email)}`
314
+ );
298
315
 
299
316
  if (!res.ok) {
300
317
  throw new Error('Invalid response');
@@ -314,12 +331,7 @@ async function resolveUsingWellKnown(email, domain, source) {
314
331
  //ignore
315
332
  }
316
333
 
317
- let res = await fetchCmd(`http://${encodeURIComponent(domain)}/.well-known/autoconfig/mail/config-v1.1.xml`, {
318
- headers: {
319
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
320
- },
321
- dispatcher: httpAgent.retry
322
- });
334
+ let res = await fetchAutodiscoveryResource(`http://${encodeURIComponent(domain)}/.well-known/autoconfig/mail/config-v1.1.xml`);
323
335
 
324
336
  if (!res.ok) {
325
337
  throw new Error('Invalid response');
@@ -700,14 +712,10 @@ async function resolveUsingAutodiscovery(email, domain, source) {
700
712
 
701
713
  let discoveryUrl = `https://${discoveryDomain}/autodiscover/autodiscover.xml`;
702
714
 
703
- let res = await fetchCmd(discoveryUrl, {
715
+ let res = await fetchAutodiscoveryResource(discoveryUrl, {
704
716
  method: 'post',
705
- headers: {
706
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`,
707
- 'Content-type': 'application/xml'
708
- },
709
- body,
710
- dispatcher: httpAgent.retry
717
+ headers: { 'Content-type': 'application/xml' },
718
+ body
711
719
  });
712
720
 
713
721
  if (!res.ok) {
@@ -28,6 +28,35 @@ const { pushHeaderValue } = require('./utils/header-map');
28
28
  const simpleParser = require('mailparser').simpleParser;
29
29
  const { toCamelCase } = require('./utils/to-camel-case');
30
30
 
31
+ // Wording of a notice that reports a delay rather than a failure. Sendmail and qmail-style MTAs
32
+ // send these as plain text, with the same "<user@example.com>:" recipient block a bounce carries
33
+ const DELAY_NOTICE_RE =
34
+ /WARNING MESSAGE ONLY|DO NOT NEED TO RESEND|has not yet been delivered|will keep trying|delivery attempts will continue|delivery (?:is|has been) delayed/i;
35
+
36
+ // Wording that says the MTA gave up. A final bounce often quotes the last temporary reply the
37
+ // remote host gave ("Sorry, I wasn't able to establish an SMTP connection. (#4.4.1)" followed by
38
+ // "I'm not going to try again"), so a 4.x.x status on its own does not make a notice a delay
39
+ const GAVE_UP_RE = /permanent error|given up|not going to try again|retry timeout exceeded|will not be retried|could not be delivered/i;
40
+
41
+ /**
42
+ * Tells whether a notice the text heuristics matched reports a delay rather than a failure
43
+ *
44
+ * @param {string} text - Body text the heuristics ran over
45
+ * @param {Object} [response] - The response the heuristics extracted
46
+ * @returns {Boolean} True for a temporary failure the MTA is still retrying
47
+ */
48
+ function isDelayNotice(text, response) {
49
+ if (DELAY_NOTICE_RE.test(text)) {
50
+ return true;
51
+ }
52
+
53
+ let status = (response && response.status) || '';
54
+ let message = (response && response.message) || '';
55
+ let temporary = /^4\./.test(status) || /^4\d{2}[\s-]/.test(message);
56
+
57
+ return temporary && !GAVE_UP_RE.test(text);
58
+ }
59
+
31
60
  /**
32
61
  * Splits the address type off a DSN value, eg. "rfc822; user@example.com"
33
62
  *
@@ -484,6 +513,10 @@ async function bounceDetect(sourceStream) {
484
513
  }
485
514
  }
486
515
 
516
+ // What the structured parts said, if anything; the text heuristics below only fill gaps, and
517
+ // only a claim they made is reconsidered at the end
518
+ let structuredAction = result.action;
519
+
487
520
  // Extract text content for pattern matching
488
521
  let text = (parsed.text || '').toString();
489
522
 
@@ -928,6 +961,18 @@ async function bounceDetect(sourceStream) {
928
961
  }
929
962
  }
930
963
 
964
+ // The heuristics above claim 'failed' for any recipient block or quoted reply they recognize,
965
+ // but a delay notice has the same shape: a Sendmail-style "THIS IS A WARNING MESSAGE ONLY"
966
+ // carries a "<user@example.com>: ... (#4.4.1)" block, and a plain-text notice may quote a
967
+ // "said: 450 4.2.1 ..." reply. A delay reported as a DSN never gets here (it is applied as a
968
+ // delivery report first, see applyDeliveryReport), so only a claim the heuristics made is
969
+ // reconsidered. The action is cleared rather than set to 'delayed': every caller treats a set
970
+ // action as a bounce to store and to fire emailBounce for, and a message the remote host is
971
+ // still retrying is not one
972
+ if (!structuredAction && result.action === 'failed' && isDelayNotice(text, result.response)) {
973
+ delete result.action;
974
+ }
975
+
931
976
  // Include parsed message headers in the result
932
977
  result.messageHeaders = parsedMessageHeaders || null;
933
978
 
package/lib/consts.js CHANGED
@@ -204,7 +204,11 @@ module.exports = {
204
204
  // history cursor only moves after processing completes
205
205
  GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS: 3,
206
206
 
207
- TOTP_WINDOW_SIZE: 6,
207
+ // Time steps accepted either side of the current one when verifying a TOTP code: 1 means the
208
+ // current code plus the previous and the next (a 90-second span). RFC 6238 suggests at most
209
+ // one step - it absorbs the clock drift a phone accumulates between network syncs, while
210
+ // every extra step is another valid six-digit code for a guess to land on
211
+ TOTP_WINDOW_SIZE: 1,
208
212
 
209
213
  WEBAUTHN_CHALLENGE_TTL: 300, // 5 minutes
210
214
  MAX_PASSKEYS_PER_USER: 20,
@@ -240,6 +244,10 @@ module.exports = {
240
244
 
241
245
  NONCE_BYTES: 16,
242
246
 
247
+ // Where the bull-board queue browser is mounted (lib/api-routes/bull-board-routes.js); the
248
+ // security headers key their bull-board profile on it
249
+ BULL_BOARD_BASE_PATH: '/admin/bull-board',
250
+
243
251
  // Longest account id EmailEngine accepts. Defined here rather than only on `accountIdSchema`
244
252
  // because the token audit log truncates to it while writing, before route validation has had a
245
253
  // chance to reject a longer one, and the two have to agree: a log that trimmed at a different
@@ -340,7 +348,10 @@ module.exports = {
340
348
  'req.query.access_token',
341
349
  'err.rawPacket',
342
350
  'err._original',
343
- 'err.details[*].context.value'
351
+ 'err.details[*].context.value',
352
+ // the WHATWG URL parser attaches the string it rejected, and a stored proxy or webhook URL
353
+ // carries its credentials inline
354
+ 'err.input'
344
355
  ],
345
356
 
346
357
  generateWebhookTable() {
@@ -0,0 +1,133 @@
1
+ 'use strict';
2
+
3
+ // fetch() with every redirect hop vetted by an egress policy.
4
+ //
5
+ // undici follows redirects on its own and offers no hook to look at the intermediate hops, so a
6
+ // permitted destination can hand a request on to one the policy refuses: a domain whose
7
+ // autoconfig answers 302 to http://169.254.169.254/ gets the metadata service fetched on its
8
+ // behalf. Webhook deliveries solve this by not following at all (lib/webhook-request.js), because
9
+ // there is an operator to publish the final URL. Autodiscovery has neither: the destination is
10
+ // derived from whatever email address a caller typed, and a domain's autoconfig commonly lives
11
+ // behind a redirect or two. So here redirects are followed by hand, and each hop goes through the
12
+ // same check the first request did.
13
+ //
14
+ // No dependency on lib/tools.js on purpose: that module opens Redis on require, and this one has
15
+ // to stay testable as a pure helper.
16
+
17
+ // A domain's autoconfig commonly sits behind one or two hops (http to https, apex to www); five
18
+ // is generous for that and small enough that a redirect loop costs nothing worth mentioning
19
+ const MAX_REDIRECTS = 5;
20
+
21
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
22
+
23
+ // The only schemes a redirect may lead to. A Location of `file:` or `ftp:` is not a web hop, and
24
+ // undici would refuse it anyway - refusing it here names the reason
25
+ const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);
26
+
27
+ // Headers that describe a request body. Dropped when a redirect turns the request into a GET,
28
+ // which is what fetch() does too (a Content-Length for a body that is no longer sent breaks the
29
+ // request outright)
30
+ const BODY_HEADERS = new Set(['content-type', 'content-length', 'content-encoding', 'content-language', 'content-location']);
31
+
32
+ function redirectError(message, code) {
33
+ let err = new Error(message);
34
+ err.code = code;
35
+ return err;
36
+ }
37
+
38
+ /**
39
+ * Resolves the Location header of a redirect against the URL that answered it.
40
+ *
41
+ * @param {string} location - Raw Location header
42
+ * @param {string} base - URL of the response carrying it
43
+ * @returns {string} Absolute URL of the next hop
44
+ * @throws {Error} EREDIRECTINVALID for an unparseable target, EREDIRECTSCHEME for a non-web one
45
+ */
46
+ function resolveRedirect(location, base) {
47
+ let next;
48
+ try {
49
+ next = new URL(location, base);
50
+ } catch (err) {
51
+ throw redirectError(`Redirect from ${base} points at an invalid URL`, 'EREDIRECTINVALID');
52
+ }
53
+
54
+ if (!ALLOWED_PROTOCOLS.has(next.protocol)) {
55
+ throw redirectError(`Redirect from ${base} points at an unsupported scheme (${next.protocol})`, 'EREDIRECTSCHEME');
56
+ }
57
+
58
+ return next.toString();
59
+ }
60
+
61
+ /**
62
+ * Drops body-describing headers from a plain header object (the only shape the callers pass).
63
+ *
64
+ * @param {Object} [headers] - Header name to value
65
+ * @returns {Object|undefined} Filtered copy
66
+ */
67
+ function withoutBodyHeaders(headers) {
68
+ return headers && Object.fromEntries(Object.entries(headers).filter(([name]) => !BODY_HEADERS.has(name.toLowerCase())));
69
+ }
70
+
71
+ /**
72
+ * Performs a fetch, following redirects one vetted hop at a time.
73
+ *
74
+ * `validateTarget(url)` runs before the first request and before every hop; whatever it throws
75
+ * ends the fetch. Redirect semantics match fetch(): 303 always becomes a bodyless GET, 301 and 302
76
+ * do so for anything but GET and HEAD, 307 and 308 replay the request unchanged. A 3xx without a
77
+ * Location is returned as it is, since it is not a redirect anyone can follow.
78
+ *
79
+ * @param {Function} fetchImpl - fetch implementation (undici fetch)
80
+ * @param {string} url - Destination URL
81
+ * @param {Object} [options] - fetch options (method, body, headers, dispatcher, signal) plus
82
+ * `validateTarget` (async url => void)
83
+ * @returns {Promise<Response>} The final response, with its body unread
84
+ * @throws {Error} EMAXREDIRECTS when the hop budget is spent, EREDIRECTINVALID / EREDIRECTSCHEME
85
+ * for a redirect that cannot be taken, or whatever validateTarget throws for a refused hop
86
+ */
87
+ async function fetchWithVettedRedirects(fetchImpl, url, options) {
88
+ let { validateTarget, ...fetchOptions } = options || {};
89
+
90
+ let method = (fetchOptions.method || 'GET').toUpperCase();
91
+ let body = fetchOptions.body;
92
+ let headers = fetchOptions.headers;
93
+ let current = url;
94
+
95
+ for (let hop = 0; ; hop++) {
96
+ if (validateTarget) {
97
+ await validateTarget(current);
98
+ }
99
+
100
+ // redirect:'manual' makes undici return the 3xx itself, headers included, rather than
101
+ // the opaque response the browser spec prescribes
102
+ const res = await fetchImpl(current, Object.assign({}, fetchOptions, { method, body, headers, redirect: 'manual' }));
103
+
104
+ if (!REDIRECT_STATUSES.has(res.status)) {
105
+ return res;
106
+ }
107
+
108
+ const location = res.headers.get('location');
109
+ if (!location) {
110
+ return res;
111
+ }
112
+
113
+ // The hop is not taken, so its body is never read by the caller. Drain it here so the
114
+ // keep-alive socket goes back to the pool instead of staying pinned
115
+ await res.text().catch(() => false);
116
+
117
+ if (hop >= MAX_REDIRECTS) {
118
+ throw redirectError(`Too many redirects, gave up at ${current}`, 'EMAXREDIRECTS');
119
+ }
120
+
121
+ const next = resolveRedirect(location, current);
122
+
123
+ if (res.status === 303 || ((res.status === 301 || res.status === 302) && method !== 'GET' && method !== 'HEAD')) {
124
+ method = 'GET';
125
+ body = undefined;
126
+ headers = withoutBodyHeaders(headers);
127
+ }
128
+
129
+ current = next;
130
+ }
131
+ }
132
+
133
+ module.exports = { fetchWithVettedRedirects, MAX_REDIRECTS };