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
@@ -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 };
@@ -13,7 +13,7 @@ class HeadersRewriter extends Transform {
13
13
  }
14
14
 
15
15
  _transform(obj, encoding, callback) {
16
- if (obj.type !== 'node' || !obj.root || !typeof this.headersCb) {
16
+ if (obj.type !== 'node' || !obj.root || typeof this.headersCb !== 'function') {
17
17
  this.push(obj);
18
18
  return callback();
19
19
  }
@@ -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
- 'rNRxgfiwgSb50Gw4NAQaDI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gMBAAEwDQYJKoZIhvcNAQELBQADggEBABXm8GPdY0sc\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);
@@ -67,7 +67,10 @@ class LLMPreProcessHandler {
67
67
  v = Number(v) || 0;
68
68
  if (v !== this.handlerCacheV) {
69
69
  // changes detected
70
- this.handlerCache = this.getHandler();
70
+ this.handlerCache = await this.getHandler();
71
+ // mark the cache as current only after a successful rebuild, so a failure above
72
+ // leaves it stale and the next call retries
73
+ this.handlerCacheV = v;
71
74
  }
72
75
  return this.handlerCache;
73
76
  }
@@ -19,10 +19,58 @@
19
19
  // one field every client shows.
20
20
  //
21
21
  // Everything else the converter emits (properties, required, enum, anyOf, minimum/maxLength and
22
- // friends) is already valid 2020-12.
22
+ // friends) is already valid 2020-12, with one exception: the converter folds joi `.valid()` and
23
+ // `.allow()` into a single `enum`, so `.allow(false)` beside a string or object type arrives as
24
+ // `enum: [false]`. OpenAPI readers treat that as documentation, but in JSON Schema `enum` is
25
+ // exclusive - `{type: "object", enum: [false]}` is a schema nothing satisfies, so a validating
26
+ // client refuses every valid call and a model reading it is told the only accepted value is
27
+ // `false`. splitSentinels() moves such members out into `const` branches beside the schema proper.
23
28
 
24
29
  const { SchemaConverter } = require('../openapi/joi-schema');
25
30
 
31
+ // Keywords that describe a schema rather than constrain it. They stay on the outer node when a
32
+ // schema is split into anyOf branches, so every client still finds them in the usual place.
33
+ const ANNOTATION_KEYS = new Set(['title', 'description', 'examples', 'default', 'deprecated']);
34
+
35
+ function isInstanceOfType(value, types) {
36
+ const valueType = value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
37
+ return types.some(type => type === valueType || (type === 'integer' && valueType === 'number' && Number.isInteger(value)));
38
+ }
39
+
40
+ // An enum member that cannot be an instance of the declared type is a joi `.allow()` sentinel
41
+ // (`false` clearing a block on an update, `false`/`null` for "not set"), not part of the value
42
+ // domain. It leaves the enum and becomes a `const` branch. What remains was a real `.valid()`
43
+ // list and stays as the enum; when only `null` remains (`.allow(false, null)` on a plain string)
44
+ // the type array already admits it and the enum goes.
45
+ function splitSentinels(schema) {
46
+ if (!Array.isArray(schema.enum) || !schema.type) {
47
+ return schema;
48
+ }
49
+
50
+ const types = [].concat(schema.type);
51
+ const sentinels = schema.enum.filter(value => !isInstanceOfType(value, types));
52
+ if (!sentinels.length) {
53
+ return schema;
54
+ }
55
+
56
+ const result = {};
57
+ const branch = {};
58
+ for (const [key, value] of Object.entries(schema)) {
59
+ (ANNOTATION_KEYS.has(key) ? result : branch)[key] = value;
60
+ }
61
+
62
+ const values = schema.enum.filter(value => isInstanceOfType(value, types));
63
+ if (values.some(value => value !== null)) {
64
+ branch.enum = values;
65
+ } else {
66
+ delete branch.enum;
67
+ }
68
+
69
+ result.anyOf = [branch].concat(sentinels.map(value => ({ const: value })));
70
+
71
+ return result;
72
+ }
73
+
26
74
  function toJsonSchema(node) {
27
75
  if (Array.isArray(node)) {
28
76
  return node.map(entry => toJsonSchema(entry));
@@ -98,7 +146,7 @@ function toJsonSchema(node) {
98
146
  }
99
147
  }
100
148
 
101
- return result;
149
+ return splitSentinels(result);
102
150
  }
103
151
 
104
152
  /**
@@ -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
 
@@ -133,18 +160,35 @@ async function list(options) {
133
160
  };
134
161
  }
135
162
 
163
+ // Resolves to { deleted } - with `locked: true` when the message could not be removed because a
164
+ // submit worker is delivering it right now. That is the one refusal a caller can act on (retry
165
+ // once the attempt is over), so it is reported rather than folded into a plain false; a failure to
166
+ // remove for any other reason is thrown.
136
167
  async function del(options) {
137
168
  options = options || {};
138
169
 
139
170
  let logger = options.logger;
140
171
 
141
172
  if (!options.queueId) {
142
- return false;
173
+ return { deleted: false };
143
174
  }
144
175
 
145
176
  let job = await submitQueue.getJob(options.queueId);
146
177
  if (!job) {
147
- return false;
178
+ return { deleted: false };
179
+ }
180
+
181
+ // BullMQ refuses to remove a job a worker holds the lock on, and for the submit queue that is
182
+ // a message in the middle of a delivery attempt. Checked before touching the content: the
183
+ // attempt in flight still needs it, and removing it here would not stop the attempt anyway.
184
+ if (await job.isActive()) {
185
+ logger.info({
186
+ msg: 'Queued message is being delivered, not removed',
187
+ account: job.data.account,
188
+ queueId: job.data.queueId,
189
+ messageId: job.data.messageId
190
+ });
191
+ return { deleted: false, locked: true };
148
192
  }
149
193
 
150
194
  // Delete message content
@@ -158,13 +202,13 @@ async function del(options) {
158
202
  // Delete job entry
159
203
  try {
160
204
  await job.remove();
161
- logger.info({ msg: 'Removed queue entry', account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId });
162
- return true;
163
205
  } catch (err) {
164
206
  logger.error({ msg: 'Failed to remove queue entry', account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId, err });
207
+ throw err;
165
208
  }
166
209
 
167
- return false;
210
+ logger.info({ msg: 'Removed queue entry', account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId });
211
+ return { deleted: true };
168
212
  }
169
213
 
170
214
  async function get(options) {
@@ -248,8 +292,6 @@ async function removeJobs(queueIds, options) {
248
292
  return removed;
249
293
  }
250
294
 
251
- // selectPageRanges is exported for its own tests: it is the pagination arithmetic, and exercising it
252
- // through list() alone would need a queue populated across all four states to cover the cases.
253
295
  // selectPageRanges and JOB_STATES are exported for the pagination tests: exercising the arithmetic
254
296
  // through list() alone would need a queue populated across all four states to cover the cases.
255
- module.exports = { list, del, get, removeJobs, selectPageRanges, JOB_STATES };
297
+ module.exports = { list, del, get, removeJobs, decodeQueueEntry, selectPageRanges, JOB_STATES };
@@ -93,7 +93,10 @@ class PreProcessHandler {
93
93
  v = Number(v) || 0;
94
94
  if (v !== this.handlerCacheV) {
95
95
  // changes detected
96
- this.handlerCache = this.getHandler();
96
+ this.handlerCache = await this.getHandler();
97
+ // mark the cache as current only after a successful rebuild, so a failure above
98
+ // leaves it stale and the next call retries
99
+ this.handlerCacheV = v;
97
100
  }
98
101
  return this.handlerCache;
99
102
  }
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 };
@@ -76,6 +76,9 @@ function rewriteTextNodes(source, options) {
76
76
 
77
77
  const splitter = new Splitter();
78
78
  const joiner = new Joiner();
79
+ // The tail of the pipe chain. Every failure inside the chain is routed to its 'error'
80
+ // handler below, which rejects the returned promise.
81
+ const newlines = new LeWindows();
79
82
 
80
83
  // create a Rewriter for text/html
81
84
  let rewriter = new Rewriter(node => {
@@ -122,6 +125,15 @@ function rewriteTextNodes(source, options) {
122
125
  }
123
126
  }
124
127
 
128
+ // Nothing else listens for errors on the node decoder, so without this a decoder
129
+ // failure would be an uncaughtException that takes the worker with it. None of the
130
+ // decoders used here has a failure path today, so this is a guard against the next
131
+ // dependency update giving one of them one, not a fix for a reachable case. Routed
132
+ // to the tail so it rejects the same way any other pipeline failure does.
133
+ decoder.on('error', err => {
134
+ newlines.emit('error', err);
135
+ });
136
+
125
137
  decoder.on('readable', () => {
126
138
  let chunk;
127
139
  while ((chunk = decoder.read()) !== null) {
@@ -173,7 +185,6 @@ function rewriteTextNodes(source, options) {
173
185
  });
174
186
 
175
187
  // set up pipe chain
176
- let newlines = new LeWindows();
177
188
  splitter.pipe(rewriter).pipe(joiner).pipe(newlines);
178
189
 
179
190
  joiner.on('error', err => {