emailengine-app 2.79.8 → 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 (133) 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 +20 -0
  5. package/DOCKER_DEPLOYMENT.md +6 -7
  6. package/Dockerfile +35 -11
  7. package/config/default.toml +2 -1
  8. package/copy-static-files.sh +23 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/lib/account.js +26 -1
  11. package/lib/api-routes/bull-board-routes.js +3 -2
  12. package/lib/api-routes/route-helpers.js +8 -0
  13. package/lib/auth-token.js +73 -2
  14. package/lib/autodetect-imap-settings.js +33 -25
  15. package/lib/consts.js +8 -1
  16. package/lib/egress-fetch.js +133 -0
  17. package/lib/export.js +35 -2
  18. package/lib/handlebars-helpers.js +129 -0
  19. package/lib/imap-proxy-auth.js +41 -21
  20. package/lib/imapproxy/imap-core/README.md +1 -0
  21. package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
  22. package/lib/imapproxy/imap-server.js +9 -10
  23. package/lib/openapi/index.js +3 -0
  24. package/lib/outbox.js +28 -3
  25. package/lib/rate-limit.js +23 -4
  26. package/lib/schemas.js +10 -3
  27. package/lib/security-headers.js +396 -0
  28. package/lib/sentry.js +36 -4
  29. package/lib/smtp-auth.js +86 -7
  30. package/lib/tools.js +265 -120
  31. package/lib/ui-routes/account-routes.js +4 -3
  32. package/lib/ui-routes/export-routes.js +4 -0
  33. package/lib/ui-routes/mcp-consent-routes.js +7 -0
  34. package/lib/ui-routes/network-config-routes.js +4 -3
  35. package/lib/ui-routes/route-helpers.js +24 -8
  36. package/lib/ui-routes/smtp-test-routes.js +7 -0
  37. package/lib/webhook-egress.js +5 -0
  38. package/package.json +21 -24
  39. package/sbom.json +1 -1
  40. package/server.js +37 -36
  41. package/static/js/ace/css/ace.css +1462 -0
  42. package/static/js/ace/css/kuroir-1.png +0 -0
  43. package/static/js/ace/css/kuroir-2.png +0 -0
  44. package/static/js/ace/css/main-1.png +0 -0
  45. package/static/js/ace/css/main-10.svg +4 -0
  46. package/static/js/ace/css/main-11.svg +5 -0
  47. package/static/js/ace/css/main-12.svg +4 -0
  48. package/static/js/ace/css/main-13.png +0 -0
  49. package/static/js/ace/css/main-14.png +0 -0
  50. package/static/js/ace/css/main-15.png +0 -0
  51. package/static/js/ace/css/main-16.png +0 -0
  52. package/static/js/ace/css/main-17.png +0 -0
  53. package/static/js/ace/css/main-18.png +0 -0
  54. package/static/js/ace/css/main-19.png +0 -0
  55. package/static/js/ace/css/main-2.png +0 -0
  56. package/static/js/ace/css/main-20.png +0 -0
  57. package/static/js/ace/css/main-21.png +0 -0
  58. package/static/js/ace/css/main-22.png +0 -0
  59. package/static/js/ace/css/main-23.png +0 -0
  60. package/static/js/ace/css/main-24.png +0 -0
  61. package/static/js/ace/css/main-25.svg +1 -0
  62. package/static/js/ace/css/main-26.png +0 -0
  63. package/static/js/ace/css/main-3.png +0 -0
  64. package/static/js/ace/css/main-4.png +0 -0
  65. package/static/js/ace/css/main-5.svg +7 -0
  66. package/static/js/ace/css/main-6.svg +9 -0
  67. package/static/js/ace/css/main-7.svg +7 -0
  68. package/static/js/ace/css/main-8.svg +9 -0
  69. package/static/js/ace/css/main-9.svg +6 -0
  70. package/static/js/ace/css/theme/kuroir.css +78 -0
  71. package/static/js/ace/css/theme/tomorrow_night.css +128 -0
  72. package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
  73. package/static/js/ace/css/theme/xcode.css +106 -0
  74. package/static/js/ace/css/tomorrow_night-1.png +0 -0
  75. package/static/js/ace/css/tomorrow_night-2.png +0 -0
  76. package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
  77. package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
  78. package/static/js/ace/css/xcode-1.png +0 -0
  79. package/static/js/ace/css/xcode-2.png +0 -0
  80. package/static/js/ee-client.js +256 -102
  81. package/static/js/public.js +7 -0
  82. package/static/js/ui.js +32 -0
  83. package/static/licenses.html +331 -291
  84. package/static/vendor/simplewebauthn/browser.min.js +2 -2
  85. package/translations/messages.pot +203 -157
  86. package/views/accounts/account.hbs +15 -37
  87. package/views/accounts/browse.hbs +3 -1
  88. package/views/accounts/edit.hbs +1 -1
  89. package/views/accounts/register/imap-server.hbs +1 -1
  90. package/views/config/ai.hbs +1 -1
  91. package/views/config/branding.hbs +2 -2
  92. package/views/config/document-store/chat.hbs +1 -1
  93. package/views/config/document-store/index.hbs +1 -1
  94. package/views/config/imap-proxy.hbs +1 -1
  95. package/views/config/license.hbs +1 -1
  96. package/views/config/mcp.hbs +1 -1
  97. package/views/config/network.hbs +14 -16
  98. package/views/config/oauth/app.hbs +2 -2
  99. package/views/config/service.hbs +1 -1
  100. package/views/config/smtp.hbs +1 -1
  101. package/views/config/webhooks.hbs +2 -2
  102. package/views/error.hbs +4 -2
  103. package/views/internals/index.hbs +1 -1
  104. package/views/layout/app.hbs +3 -11
  105. package/views/mcp/authorize.hbs +1 -1
  106. package/views/partials/ace_assets.hbs +13 -0
  107. package/views/partials/add_account_modal.hbs +1 -1
  108. package/views/partials/address_list.hbs +4 -4
  109. package/views/partials/filter_editor_js.hbs +2 -2
  110. package/views/partials/gateway_js.hbs +1 -1
  111. package/views/partials/oauth_form.hbs +1 -1
  112. package/views/partials/public_theme_init.hbs +1 -1
  113. package/views/partials/template_form.hbs +2 -2
  114. package/views/partials/test_send.hbs +7 -4
  115. package/views/partials/theme_init.hbs +1 -1
  116. package/views/partials/ui/details.hbs +2 -2
  117. package/views/partials/webhooks_editor_functions.hbs +1 -1
  118. package/views/reference/redirect.hbs +1 -1
  119. package/views/templates/template.hbs +2 -2
  120. package/views/tokens/new.hbs +1 -1
  121. package/views/unsubscribe.hbs +1 -1
  122. package/views/webhooks/webhook.hbs +2 -2
  123. package/workers/api.js +42 -112
  124. package/workers/export.js +1 -5
  125. package/workers/imap.js +1 -3
  126. package/workers/smtp.js +12 -43
  127. package/workers/submit.js +6 -12
  128. package/workers/webhooks.js +6 -17
  129. package/static/front/EmailEngine_logo_horiz.png +0 -0
  130. package/static/front/EmailEngine_logo_vert.png +0 -0
  131. package/static/front/index.html +0 -57
  132. package/static/front/logo.png +0 -0
  133. package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
@@ -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 };
package/lib/export.js CHANGED
@@ -89,6 +89,31 @@ function parseActiveEntry(entry) {
89
89
  return { account, exportId };
90
90
  }
91
91
 
92
+ const EXPORT_FILE_EXTENSION = '.ndjson.gz';
93
+ const EXPORT_FILE_EXTENSION_ENCRYPTED = '.ndjson.gz.enc';
94
+
95
+ /**
96
+ * Tells whether a stored file path is the export's own file.
97
+ *
98
+ * `filePath` is read back from Redis by the download and delete paths. Nothing but this module
99
+ * writes it, but a path trusted only because it was stored is exactly the field a later bug, or
100
+ * write access to Redis, would use to make the download route serve or the delete route unlink
101
+ * an arbitrary file. The basename is checked rather than the directory, because the export
102
+ * directory setting can change between an export and its download, and an older export still
103
+ * lives where it was written.
104
+ *
105
+ * @param {string} exportId - Export id the record belongs to
106
+ * @param {string} filePath - Stored path
107
+ * @returns {boolean} true when the path names the export's own file
108
+ */
109
+ function isOwnExportFile(exportId, filePath) {
110
+ if (!exportId || typeof filePath !== 'string') {
111
+ return false;
112
+ }
113
+ const base = pathlib.basename(filePath);
114
+ return [EXPORT_FILE_EXTENSION, EXPORT_FILE_EXTENSION_ENCRYPTED].some(ext => base === `${exportId}${ext}`);
115
+ }
116
+
92
117
  function generateExportId() {
93
118
  return EXPORT_ID_PREFIX + crypto.randomBytes(12).toString('hex');
94
119
  }
@@ -278,7 +303,7 @@ class Export {
278
303
 
279
304
  const secret = await getSecret();
280
305
  const isEncrypted = !!secret;
281
- const fileExtension = isEncrypted ? '.ndjson.gz.enc' : '.ndjson.gz';
306
+ const fileExtension = isEncrypted ? EXPORT_FILE_EXTENSION_ENCRYPTED : EXPORT_FILE_EXTENSION;
282
307
  const filePath = pathlib.join(exportPath, `${exportId}${fileExtension}`);
283
308
  const startDate = toTimestamp(options.startDate);
284
309
  const endDate = toTimestamp(options.endDate);
@@ -432,8 +457,10 @@ class Export {
432
457
  if (!isActive) {
433
458
  await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId)).exec();
434
459
 
435
- if (data.filePath) {
460
+ if (isOwnExportFile(exportId, data.filePath)) {
436
461
  await fs.promises.unlink(data.filePath).catch(() => {});
462
+ } else if (data.filePath) {
463
+ logger.error({ msg: 'Refusing to delete a file that is not the export file', account, exportId, filePath: data.filePath });
437
464
  }
438
465
  }
439
466
 
@@ -671,6 +698,11 @@ class Export {
671
698
  throw createError('Export file not found', 'FileNotFound', 404);
672
699
  }
673
700
 
701
+ if (!isOwnExportFile(exportId, data.filePath)) {
702
+ logger.error({ msg: 'Refusing to serve a file that is not the export file', account, exportId, filePath: data.filePath });
703
+ throw createError('Export file not found', 'FileNotFound', 404);
704
+ }
705
+
674
706
  try {
675
707
  await fs.promises.access(data.filePath, fs.constants.R_OK);
676
708
  } catch {
@@ -690,6 +722,7 @@ class Export {
690
722
  module.exports = {
691
723
  Export,
692
724
  generateExportId,
725
+ isOwnExportFile,
693
726
  calculateScore,
694
727
  getExportKey,
695
728
  getExportQueueKey,
@@ -0,0 +1,129 @@
1
+ 'use strict';
2
+
3
+ // The Handlebars helpers the admin views render with. Registered on the shared handlebars
4
+ // instance by workers/api.js at startup; kept apart from the worker so a test can register
5
+ // the same helpers and render a template that relies on them (the delivery-test fragment in
6
+ // lib/ui-routes/route-helpers.js is compiled with this instance too).
7
+
8
+ const util = require('util');
9
+
10
+ /**
11
+ * Registers every view helper on the given handlebars instance.
12
+ *
13
+ * @param {Object} handlebars - The handlebars module instance vision renders with
14
+ * @param {Object} options
15
+ * @param {Object} options.gt - Gettext instance for the translation helpers
16
+ */
17
+ function registerHandlebarsHelpers(handlebars, { gt }) {
18
+ handlebars.registerHelper('_', (...args) => {
19
+ let params = args.slice(1, args.length - 1);
20
+
21
+ let locale = params.shift();
22
+
23
+ let localGt = locale ? gt.useLocale(locale) : gt;
24
+
25
+ let translated = localGt.gettext(args[0]);
26
+ if (params.length) {
27
+ translated = util.format(translated, ...params);
28
+ }
29
+
30
+ return new handlebars.SafeString(translated);
31
+ });
32
+
33
+ // HTML-escape a value for safe interpolation into an otherwise-unescaped context - e.g. a
34
+ // dynamic `%s` argument to the SafeString-returning `_` helper. Returns a plain string so
35
+ // the surrounding markup stays live while the value itself is entity-escaped.
36
+ handlebars.registerHelper('escapeHtml', value => handlebars.escapeExpression(value));
37
+
38
+ // Translate Bootstrap-era color names emitted by server code (flash types,
39
+ // systemAlerts levels) into the FlyonUI color vocabulary used by the admin
40
+ // theme, so templates interpolate a single closed set of class suffixes
41
+ // (which the stylesheet safelists). Single translation point - producers
42
+ // keep using "danger" etc.
43
+ handlebars.registerHelper('eeColor', value => (value === 'danger' ? 'error' : value || 'neutral'));
44
+
45
+ // Percent-encode a value for interpolation into a URL path segment. Handlebars escapes for
46
+ // HTML, which leaves "#", "/", "?" and "%" untouched - and an account ID is free text, so
47
+ // href="/admin/accounts/{{account}}" resolves somewhere else entirely for an ID carrying one.
48
+ handlebars.registerHelper('urlpart', value => encodeURIComponent(value === null || value === undefined ? '' : value));
49
+
50
+ // Join string fragments in subexpressions, e.g. building composed partial
51
+ // hash values: text=(concat "Up to " (formatInteger n locale) " lines")
52
+ handlebars.registerHelper('concat', (...args) => args.slice(0, -1).join(''));
53
+
54
+ // Ternary for subexpressions: placeholder=(when hasPass "set..." "")
55
+ handlebars.registerHelper('when', (cond, truthyValue, falsyValue) => (cond ? truthyValue : typeof falsyValue === 'string' ? falsyValue : ''));
56
+
57
+ handlebars.registerHelper('isodate', time => new Date(Number(time)).toISOString());
58
+
59
+ handlebars.registerHelper('ngettext', (msgid, plural, count) => util.format(gt.ngettext(msgid, plural, count), count));
60
+
61
+ handlebars.registerHelper('equals', function (compareVal, baseVal, options) {
62
+ if (baseVal === compareVal) {
63
+ return options.fn(this);
64
+ }
65
+ return options.inverse(this);
66
+ });
67
+
68
+ handlebars.registerHelper('inc', (nr, inc) => Number(nr) + Number(inc));
69
+
70
+ // Delivery-test verdict (SPF/DKIM/DMARC status.result) to the FlyonUI color and icon the
71
+ // results fragment (views/partials/test_send.hbs) shows next to each check
72
+ const STATUS_COLORS = { pass: 'success', softfail: 'warning', fail: 'error', permerror: 'info', temperror: 'info' };
73
+ handlebars.registerHelper('statusColor', result => STATUS_COLORS[result] || 'neutral');
74
+
75
+ handlebars.registerHelper('statusIcon', result => {
76
+ switch (result) {
77
+ case 'pass':
78
+ return 'icon-[tabler--circle-check]';
79
+ case 'neutral':
80
+ case 'none':
81
+ return 'icon-[tabler--circle-off]';
82
+ default:
83
+ return 'icon-[tabler--alert-triangle]';
84
+ }
85
+ });
86
+
87
+ handlebars.registerHelper('json', payload => {
88
+ let res;
89
+ try {
90
+ res = typeof payload === 'undefined' ? 'undefined' : JSON.stringify(payload, false, 2);
91
+ } catch (err) {
92
+ res = util.inspect(payload, false, 4, false);
93
+ }
94
+ // SECURITY: return a plain string (NOT a SafeString) so Handlebars HTML-escapes the
95
+ // output. `payload` can carry attacker-controlled data (e.g. inbound email fields in
96
+ // webhook / pre-processing error logs); wrapping it in a SafeString allowed a stored
97
+ // XSS via a </textarea> breakout in the error-log views (security review H1). In the
98
+ // <textarea> render contexts this is display-identical (the browser decodes entities).
99
+ return res;
100
+ });
101
+
102
+ handlebars.registerHelper('lastVal', (value, separator) => {
103
+ separator = separator || '/';
104
+
105
+ let res = (value || '').toString().split(separator).pop();
106
+
107
+ return new handlebars.SafeString(res);
108
+ });
109
+
110
+ handlebars.registerHelper('formatInteger', (intVal, locale) => {
111
+ if (isNaN(intVal)) {
112
+ // ignore non-numbers
113
+ return intVal;
114
+ }
115
+
116
+ locale = (locale || 'en_US').replace(/_/g, '-');
117
+
118
+ let formatter;
119
+ try {
120
+ formatter = new Intl.NumberFormat(locale, {});
121
+ } catch (err) {
122
+ formatter = new Intl.NumberFormat('en-US', {});
123
+ }
124
+
125
+ return formatter.format(intVal);
126
+ });
127
+ }
128
+
129
+ module.exports = { registerHandlebarsHelpers };
@@ -11,9 +11,25 @@ const { redis } = require('./db');
11
11
  const { Account } = require('./account');
12
12
  const getSecret = require('./get-secret');
13
13
  const { isApiBasedApp } = require('./oauth2-apps');
14
- const { validateAuthToken, REASON_MESSAGES } = require('./auth-token');
14
+ const { validateAuthToken, withAuthFailureBudget, REASON_MESSAGES } = require('./auth-token');
15
15
  const { constantTimeEqual } = require('./tools');
16
16
 
17
+ /**
18
+ * Tags an error as an IMAP authentication rejection for the proxy client. Shared with the
19
+ * server, which raises the same rejection for a credential it could not load.
20
+ *
21
+ * @param {Error} err - Error to tag
22
+ * @returns {Error} the same error
23
+ */
24
+ function failImapAuth(err) {
25
+ err.authenticationFailed = true;
26
+ err.serverResponseCode = 'AUTHENTICATIONFAILED';
27
+ err.responseStatus = 'NO';
28
+ return err;
29
+ }
30
+
31
+ const authenticationFailedError = message => failImapAuth(new Error(message));
32
+
17
33
  /**
18
34
  * Builds the IMAP proxy authentication handler.
19
35
  *
@@ -22,7 +38,9 @@ const { constantTimeEqual } = require('./tools');
22
38
  * @returns {Function} async authenticate(auth, session) -> { accountObject, accountData }
23
39
  */
24
40
  function createImapProxyAuthHandler({ call }) {
25
- return async function authenticate(auth, session) {
41
+ // The credential check proper. Everything it throws is a refusal the client caused, which
42
+ // is what the failure budget in authenticate() counts.
43
+ async function verifyCredentials(auth, session) {
26
44
  let account = auth.username;
27
45
 
28
46
  let imapPassword = await settings.get('imapProxyServerPassword');
@@ -36,10 +54,7 @@ function createImapProxyAuthHandler({ call }) {
36
54
  });
37
55
 
38
56
  if (!result.authenticated) {
39
- let err = new Error(REASON_MESSAGES[result.reason] || 'Access denied, failed to authenticate user');
40
- err.serverResponseCode = 'AUTHENTICATIONFAILED';
41
- err.responseStatus = 'NO';
42
- throw err;
57
+ throw authenticationFailedError(REASON_MESSAGES[result.reason] || 'Access denied, failed to authenticate user');
43
58
  }
44
59
  }
45
60
 
@@ -48,19 +63,31 @@ function createImapProxyAuthHandler({ call }) {
48
63
  try {
49
64
  accountData = await accountObject.loadAccountData();
50
65
  } catch (err) {
51
- let respErr = new Error('Failed to authenticate user');
52
- respErr.serverResponseCode = 'AUTHENTICATIONFAILED';
53
- respErr.responseStatus = 'NO';
54
-
55
66
  if (!err.output || err.output.statusCode !== 404) {
56
67
  // only log non-obvious errors
57
68
  logger.error({ msg: 'Failed to load account data', account: auth.username, err });
58
69
  }
59
70
 
60
- throw respErr;
71
+ throw authenticationFailedError('Failed to authenticate user');
61
72
  }
62
73
 
63
- if (isApiBasedApp(accountData?._app)) {
74
+ if (!accountData) {
75
+ throw authenticationFailedError('Access denied, failed to authenticate user');
76
+ }
77
+
78
+ return { accountObject, accountData };
79
+ }
80
+
81
+ return async function authenticate(auth, session) {
82
+ let verified = await withAuthFailureBudget(
83
+ { remoteAddress: session.remoteAddress, account: auth.username },
84
+ () => verifyCredentials(auth, session),
85
+ () => authenticationFailedError(REASON_MESSAGES.limited)
86
+ );
87
+
88
+ // Past the credential check: a refusal from here on is about the account, not about
89
+ // what the client presented, so it does not count against the client's budget
90
+ if (isApiBasedApp(verified.accountData?._app)) {
64
91
  let respErr = new Error('IMAP is not supported for API-based accounts');
65
92
  respErr.authenticationFailed = true;
66
93
  respErr.serverResponseCode = 'ACCOUNTDISABLED';
@@ -68,15 +95,8 @@ function createImapProxyAuthHandler({ call }) {
68
95
  throw respErr;
69
96
  }
70
97
 
71
- if (!accountData) {
72
- let err = new Error('Access denied, failed to authenticate user');
73
- err.serverResponseCode = 'AUTHENTICATIONFAILED';
74
- err.responseStatus = 'NO';
75
- throw err;
76
- }
77
-
78
- return { accountObject, accountData };
98
+ return verified;
79
99
  };
80
100
  }
81
101
 
82
- module.exports = { createImapProxyAuthHandler };
102
+ module.exports = { createImapProxyAuthHandler, failImapAuth };
@@ -30,6 +30,7 @@ means re-applying these.
30
30
  | `e97950e7` | 2026-06-05 | Close leaks and a worker crash found in the connection hardening review |
31
31
  | `d51e92d2` | 2026-06-06 | Prevent post-BYE command dispatch during teardown |
32
32
  | `31f6a590` | 2026-07-26 | Fix the dead teardown guard in the notification listener |
33
+ | `74856cf6` | 2026-09-02 | Drop the built-in self-signed key/certificate pair from `tls-options.js`; a listener with TLS and no certificate is refused at startup instead of served with a key that ships in every copy |
33
34
 
34
35
  Earlier local changes (`09085d12`, `0a389560`, `7e2e94f3`, `04c2aa90`, `1d6df05e`, `612d9f96`,
35
36
  `13edec58`, `2e0bf1ce`, `b9a3e06c`, `b58a827e`, `1813f089`) are maintenance: dependency swaps
@@ -5,53 +5,12 @@ const crypto = require('crypto');
5
5
  // Expose to the world
6
6
  module.exports = getTLSOptions;
7
7
 
8
+ // No built-in key or certificate. Upstream ships a self-signed localhost pair here as the
9
+ // fallback for a server configured with TLS but no certificate, and that private key is the
10
+ // same in every copy of the library, so a listener secured by it is readable by anyone with the
11
+ // source. EmailEngine's IMAP proxy refuses to start with TLS and no certificate instead
12
+ // (assertTlsCredentials in lib/tools.js), and the STARTTLS upgrade is disabled in proxy mode.
8
13
  const tlsDefaults = {
9
- key:
10
- '-----BEGIN RSA PRIVATE KEY-----\n' +
11
- 'MIIEpAIBAAKCAQEA6Z5Qqhw+oWfhtEiMHE32Ht94mwTBpAfjt3vPpX8M7DMCTwHs\n' +
12
- '1xcXvQ4lQ3rwreDTOWdoJeEEy7gMxXqH0jw0WfBx+8IIJU69xstOyT7FRFDvA1yT\n' +
13
- 'RXY2yt9K5s6SKken/ebMfmZR+03ND4UFsDzkz0FfgcjrkXmrMF5Eh5UXX/+9YHeU\n' +
14
- 'xlp0gMAt+/SumSmgCaysxZLjLpd4uXz+X+JVxsk1ACg1NoEO7lWJC/3WBP7MIcu2\n' +
15
- 'wVsMd2XegLT0gWYfT1/jsIH64U/mS/SVXC9QhxMl9Yfko2kx1OiYhDxhHs75RJZh\n' +
16
- 'rNRxgfiwgSb50Gw4NAQaDIxr/DJPdLhgnpY6UQIDAQABAoIBAE+tfzWFjJbgJ0ql\n' +
17
- 's6Ozs020Sh4U8TZQuonJ4HhBbNbiTtdDgNObPK1uNadeNtgW5fOeIRdKN6iDjVeN\n' +
18
- 'AuXhQrmqGDYVZ1HSGUfD74sTrZQvRlWPLWtzdhybK6Css41YAyPFo9k4bJ2ZW2b/\n' +
19
- 'p4EEQ8WsNja9oBpttMU6YYUchGxo1gujN8hmfDdXUQx3k5Xwx4KA68dveJ8GasIt\n' +
20
- 'd+0Jd/FVwCyyx8HTiF1FF8QZYQeAXxbXJgLBuCsMQJghlcpBEzWkscBR3Ap1U0Zi\n' +
21
- '4oat8wrPZGCblaA6rNkRUVbc/+Vw0stnuJ/BLHbPxyBs6w495yBSjBqUWZMvljNz\n' +
22
- 'm9/aK0ECgYEA9oVIVAd0enjSVIyAZNbw11ElidzdtBkeIJdsxqhmXzeIFZbB39Gd\n' +
23
- 'bjtAVclVbq5mLsI1j22ER2rHA4Ygkn6vlLghK3ZMPxZa57oJtmL3oP0RvOjE4zRV\n' +
24
- 'dzKexNGo9gU/x9SQbuyOmuauvAYhXZxeLpv+lEfsZTqqrvPUGeBiEQcCgYEA8poG\n' +
25
- 'WVnykWuTmCe0bMmvYDsWpAEiZnFLDaKcSbz3O7RMGbPy1cypmqSinIYUpURBT/WY\n' +
26
- 'wVPAGtjkuTXtd1Cy58m7PqziB7NNWMcsMGj+lWrTPZ6hCHIBcAImKEPpd+Y9vGJX\n' +
27
- 'oatFJguqAGOz7rigBq6iPfeQOCWpmprNAuah++cCgYB1gcybOT59TnA7mwlsh8Qf\n' +
28
- 'bm+tSllnin2A3Y0dGJJLmsXEPKtHS7x2Gcot2h1d98V/TlWHe5WNEUmx1VJbYgXB\n' +
29
- 'pw8wj2ACxl4ojNYqWPxegaLd4DpRbtW6Tqe9e47FTnU7hIggR6QmFAWAXI+09l8y\n' +
30
- 'amssNShqjE9lu5YDi6BTKwKBgQCuIlKGViLfsKjrYSyHnajNWPxiUhIgGBf4PI0T\n' +
31
- '/Jg1ea/aDykxv0rKHnw9/5vYGIsM2st/kR7l5mMecg/2Qa145HsLfMptHo1ZOPWF\n' +
32
- '9gcuttPTegY6aqKPhGthIYX2MwSDMM+X0ri6m0q2JtqjclAjG7yG4CjbtGTt/UlE\n' +
33
- 'WMlSZwKBgQDslGeLUnkW0bsV5EG3AKRUyPKz/6DVNuxaIRRhOeWVKV101claqXAT\n' +
34
- 'wXOpdKrvkjZbT4AzcNrlGtRl3l7dEVXTu+dN7/ZieJRu7zaStlAQZkIyP9O3DdQ3\n' +
35
- 'rIcetQpfrJ1cAqz6Ng0pD0mh77vQ13WG1BBmDFa2A9BuzLoBituf4g==\n' +
36
- '-----END RSA PRIVATE KEY-----',
37
- cert:
38
- '-----BEGIN CERTIFICATE-----\n' +
39
- 'MIICpDCCAYwCCQCuVLVKVTXnAjANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDEwls\n' +
40
- 'b2NhbGhvc3QwHhcNMTUwMjEyMTEzMjU4WhcNMjUwMjA5MTEzMjU4WjAUMRIwEAYD\n' +
41
- 'VQQDEwlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDp\n' +
42
- 'nlCqHD6hZ+G0SIwcTfYe33ibBMGkB+O3e8+lfwzsMwJPAezXFxe9DiVDevCt4NM5\n' +
43
- 'Z2gl4QTLuAzFeofSPDRZ8HH7wgglTr3Gy07JPsVEUO8DXJNFdjbK30rmzpIqR6f9\n' +
44
- '5sx+ZlH7Tc0PhQWwPOTPQV+ByOuReaswXkSHlRdf/71gd5TGWnSAwC379K6ZKaAJ\n' +
45
- 'rKzFkuMul3i5fP5f4lXGyTUAKDU2gQ7uVYkL/dYE/swhy7bBWwx3Zd6AtPSBZh9P\n' +
46
- 'X+OwgfrhT+ZL9JVcL1CHEyX1h+SjaTHU6JiEPGEezvlElmGs1HGB+LCBJvnQbDg0\n' +
47
- 'BBoMjGv8Mk90uGCeljpRAgMBAAEwDQYJKoZIhvcNAQELBQADggEBABXm8GPdY0sc\n' +
48
- 'mMUFlgDqFzcevjdGDce0QfboR+M7WDdm512Jz2SbRTgZD/4na42ThODOZz9z1AcM\n' +
49
- 'zLgx2ZNZzVhBz0odCU4JVhOCEks/OzSyKeGwjIb4JAY7dh+Kju1+6MNfQJ4r1Hza\n' +
50
- 'SVXH0+JlpJDaJ73NQ2JyfqELmJ1mTcptkA/N6rQWhlzycTBSlfogwf9xawgVPATP\n' +
51
- '4AuwgjHl12JI2HVVs1gu65Y3slvaHRCr0B4+Kg1GYNLLcbFcK+NEHrHmPxy9TnTh\n' +
52
- 'Zwp1dsNQU+Xkylz8IUANWSLHYZOMtN2e5SKIdwTtl5C8YxveuY8YKb1gDExnMraT\n' +
53
- 'VGXQDqPleug=\n' +
54
- '-----END CERTIFICATE-----',
55
14
  honorCipherOrder: true,
56
15
  requestOCSP: false,
57
16
  sessionIdContext: crypto.createHash('sha256').update(process.argv.join(' ')).digest('hex').slice(0, 32),
@@ -15,12 +15,14 @@ const {
15
15
  hasEnvValue,
16
16
  readEnvValue,
17
17
  emitChangeEvent,
18
- loadTlsConfig
18
+ loadTlsConfig,
19
+ assertTlsCredentials,
20
+ httpAgent
19
21
  } = require('../tools');
20
22
  const { getLocalAddress } = require('../utils/network');
21
23
 
22
24
  const { redis } = require('../db');
23
- const { createImapProxyAuthHandler } = require('../imap-proxy-auth');
25
+ const { createImapProxyAuthHandler, failImapAuth } = require('../imap-proxy-auth');
24
26
  const getSecret = require('../get-secret');
25
27
  const settings = require('../settings');
26
28
 
@@ -163,14 +165,6 @@ class PassThroughLogger extends PassThrough {
163
165
  // without booting this worker. call() is injected for the Account instance.
164
166
  const authenticateImapProxy = createImapProxyAuthHandler({ call });
165
167
 
166
- // Tag a credential-loading failure as an IMAP authentication rejection for the proxy client.
167
- function failImapAuth(err) {
168
- err.authenticationFailed = true;
169
- err.serverResponseCode = 'AUTHENTICATIONFAILED';
170
- err.responseStatus = 'NO';
171
- return err;
172
- }
173
-
174
168
  async function onAuth(auth, session) {
175
169
  let account = auth.username;
176
170
 
@@ -513,6 +507,9 @@ module.exports.run = async () => {
513
507
 
514
508
  environment: 'ee',
515
509
 
510
+ // long-lived client, see LiveDispatcher in lib/tools.js
511
+ dispatcher: httpAgent.live,
512
+
516
513
  logger: logger.child({ sub: 'acme' }),
517
514
 
518
515
  encryptFn: async value => {
@@ -550,6 +547,8 @@ module.exports.run = async () => {
550
547
  serverOptions.key = certificateData.privateKey;
551
548
  }
552
549
  }
550
+
551
+ assertTlsCredentials(serverOptions, 'The IMAP proxy');
553
552
  }
554
553
 
555
554
  const server = createServer(serverOptions);
@@ -80,6 +80,9 @@ function registerOpenApiRoute(server, options) {
80
80
  options: {
81
81
  auth: false,
82
82
  cors: options.cors,
83
+ // A machine-facing document: JSON errors, no CSRF check, the API response headers.
84
+ // Not `api`, which would list this route in the document it serves
85
+ tags: ['external'],
83
86
 
84
87
  handler(request, h) {
85
88
  // Shallow copy: `servers` already exists in the built document, so replacing it here
package/lib/outbox.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  const { submitQueue, redis } = require('./db');
4
4
  const { REDIS_PREFIX } = require('../lib/consts');
5
+ const msgpack = require('./msgpack');
5
6
 
6
7
  // Job reads and removals are issued in bounded batches. ioredis writes each command as it is
7
8
  // issued, so a batch costs one round trip rather than one per job, while the bound keeps an account
@@ -18,6 +19,32 @@ function outboxKey(account) {
18
19
  return `${REDIS_PREFIX}iaq:${account}`;
19
20
  }
20
21
 
22
+ /**
23
+ * Decodes a message stored in an account's outbox hash.
24
+ *
25
+ * The stored value is always a msgpack map. lib/msgpack decodes the first value of a buffer and
26
+ * ignores whatever follows, so a foreign or truncated value does not necessarily throw: a buffer
27
+ * that happens to start with a byte that is a valid scalar comes back as that scalar. Anything
28
+ * other than a map is unusable as a queued message and must be treated like an undecodable one -
29
+ * the submit worker stamps its job metadata onto the entry, and doing that to a scalar throws a
30
+ * TypeError that would otherwise be reported and retried as a delivery failure.
31
+ *
32
+ * @param {Buffer} entryBuf - Raw hash field value
33
+ * @returns {Object} Decoded queue entry
34
+ * @throws {Error} If the value is not a msgpack map
35
+ */
36
+ function decodeQueueEntry(entryBuf) {
37
+ let queueEntry = msgpack.decode(entryBuf);
38
+
39
+ // Every other msgpack type decodes to something a queued message can never be: nil, a scalar,
40
+ // a Buffer (bin), an array, or a Date (timestamp extension)
41
+ if (!queueEntry || typeof queueEntry !== 'object' || Array.isArray(queueEntry) || Buffer.isBuffer(queueEntry) || queueEntry instanceof Date) {
42
+ throw new Error('Unexpected outbox entry format');
43
+ }
44
+
45
+ return queueEntry;
46
+ }
47
+
21
48
  function formatQueueEntry(job) {
22
49
  let scheduled = job.timestamp + (Number(job.opts.delay) || 0);
23
50
 
@@ -265,8 +292,6 @@ async function removeJobs(queueIds, options) {
265
292
  return removed;
266
293
  }
267
294
 
268
- // selectPageRanges is exported for its own tests: it is the pagination arithmetic, and exercising it
269
- // through list() alone would need a queue populated across all four states to cover the cases.
270
295
  // selectPageRanges and JOB_STATES are exported for the pagination tests: exercising the arithmetic
271
296
  // through list() alone would need a queue populated across all four states to cover the cases.
272
- module.exports = { list, del, get, removeJobs, selectPageRanges, JOB_STATES };
297
+ module.exports = { list, del, get, removeJobs, decodeQueueEntry, selectPageRanges, JOB_STATES };
package/lib/rate-limit.js CHANGED
@@ -41,14 +41,33 @@ const checkRateLimit = async (key, count, allowed, windowSize) => {
41
41
  throw resErr || expireErr;
42
42
  }
43
43
 
44
+ // Inclusive: the request that was just counted is admitted up to and including the limit
45
+ return windowResult({ key, count: resVal, success: resVal <= allowed, allowed, now, windowEnds });
46
+ };
47
+
48
+ // Reads a window's counter without adding to it. For guards that count failures only: the check
49
+ // ahead of an authentication attempt must not spend the budget of the client making it, so it
50
+ // only looks, and only a refusal is recorded (through checkRateLimit) afterwards.
51
+ const peekRateLimit = async (key, allowed, windowSize) => {
52
+ let now = Date.now();
53
+ let { windowKey, windowEnds } = rateLimitWindowKey(key, windowSize, now);
54
+
55
+ let count = Number(await redis.get(windowKey)) || 0;
56
+
57
+ // Exclusive: nothing was counted, so the question is whether one more attempt still fits
58
+ return windowResult({ key, count, success: count < allowed, allowed, now, windowEnds });
59
+ };
60
+
61
+ // One result shape for both reads, so a field added to one cannot silently miss the other
62
+ function windowResult({ key, count, success, allowed, now, windowEnds }) {
44
63
  return {
45
64
  key,
46
- success: resVal <= allowed,
47
- count: resVal,
65
+ success,
66
+ count,
48
67
  allowed,
49
68
  ttl: (windowEnds - now) / 1000,
50
69
  ttlReset: new Date(windowEnds).toISOString()
51
70
  };
52
- };
71
+ }
53
72
 
54
- module.exports = { checkRateLimit, rateLimitWindowKey };
73
+ module.exports = { checkRateLimit, peekRateLimit, rateLimitWindowKey };