emailengine-app 2.79.7 → 2.79.8

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 (94) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +17 -0
  3. package/DOCKER_DEPLOYMENT.md +2 -0
  4. package/bin/emailengine.js +29 -13
  5. package/config/default.toml +13 -3
  6. package/data/google-crawlers.json +7 -1
  7. package/docker-compose.yml +12 -3
  8. package/install.sh +2 -0
  9. package/lib/api-routes/account-routes.js +14 -3
  10. package/lib/api-routes/mailbox-routes.js +4 -1
  11. package/lib/api-routes/message-routes.js +6 -5
  12. package/lib/api-routes/outbox-routes.js +7 -4
  13. package/lib/api-routes/settings-routes.js +34 -25
  14. package/lib/api-routes/stats-routes.js +8 -1
  15. package/lib/api-routes/submit-routes.js +2 -1
  16. package/lib/api-routes/template-routes.js +3 -2
  17. package/lib/bounce-detect.js +45 -0
  18. package/lib/consts.js +5 -1
  19. package/lib/egress-filter.js +39 -4
  20. package/lib/email-client/base-client.js +274 -24
  21. package/lib/email-client/gmail/gmail-api.js +15 -7
  22. package/lib/email-client/gmail-client.js +121 -64
  23. package/lib/email-client/imap/mailbox.js +18 -59
  24. package/lib/email-client/imap-client.js +53 -29
  25. package/lib/email-client/notification-handler.js +11 -2
  26. package/lib/email-client/outlook/graph-api.js +106 -90
  27. package/lib/email-client/outlook-client.js +222 -106
  28. package/lib/generate-text-preview.js +10 -5
  29. package/lib/headers-rewriter.js +1 -1
  30. package/lib/llm-pre-process.js +4 -1
  31. package/lib/mcp/json-schema.js +50 -2
  32. package/lib/outbox.js +22 -5
  33. package/lib/pre-process.js +4 -1
  34. package/lib/rewrite-text-nodes.js +12 -1
  35. package/lib/schemas.js +27 -5
  36. package/lib/settings.js +19 -1
  37. package/lib/sso.js +13 -3
  38. package/lib/submit-progress.js +29 -0
  39. package/lib/templates.js +11 -0
  40. package/lib/tools.js +96 -53
  41. package/lib/ui-routes/account-routes.js +70 -11
  42. package/lib/ui-routes/admin-config-routes.js +7 -21
  43. package/lib/ui-routes/admin-entities-routes.js +42 -12
  44. package/lib/ui-routes/auth-routes.js +87 -28
  45. package/lib/ui-routes/dashboard-routes.js +1 -1
  46. package/lib/ui-routes/internals-routes.js +2 -0
  47. package/lib/ui-routes/mcp-consent-routes.js +5 -2
  48. package/lib/ui-routes/network-config-routes.js +2 -2
  49. package/lib/ui-routes/oauth-config-routes.js +12 -1
  50. package/lib/ui-routes/route-helpers.js +41 -6
  51. package/lib/ui-routes/settings-page.js +10 -0
  52. package/lib/ui-routes/suppression-list-routes.js +16 -5
  53. package/lib/ui-routes/unsubscribe-routes.js +22 -3
  54. package/lib/webhooks.js +14 -2
  55. package/package.json +11 -11
  56. package/sbom.json +1 -1
  57. package/server.js +63 -35
  58. package/static/css/flyonui.css +1 -1
  59. package/static/licenses.html +17 -17
  60. package/translations/messages.pot +49 -49
  61. package/views/account/passkeys.hbs +8 -0
  62. package/views/account/password.hbs +11 -0
  63. package/views/account/security.hbs +18 -7
  64. package/views/accounts/account.hbs +6 -1
  65. package/views/accounts/register/imap-server.hbs +10 -2
  66. package/views/config/ai.hbs +2 -0
  67. package/views/config/branding.hbs +2 -0
  68. package/views/config/email-processing.hbs +2 -0
  69. package/views/config/imap-proxy.hbs +2 -0
  70. package/views/config/logging.hbs +3 -1
  71. package/views/config/mcp.hbs +2 -0
  72. package/views/config/network.hbs +2 -0
  73. package/views/config/oauth/app.hbs +2 -2
  74. package/views/config/security.hbs +2 -0
  75. package/views/config/service.hbs +2 -0
  76. package/views/config/smtp.hbs +2 -0
  77. package/views/config/webhooks.hbs +2 -0
  78. package/views/error.hbs +6 -0
  79. package/views/layout/app.hbs +6 -3
  80. package/views/layout/login.hbs +1 -1
  81. package/views/layout/prompt.hbs +1 -1
  82. package/views/layout/public.hbs +1 -1
  83. package/views/legal.hbs +1 -1
  84. package/views/partials/filter_editor_js.hbs +1 -1
  85. package/views/partials/oauth_form.hbs +5 -5
  86. package/views/partials/ui/env-managed-alert.hbs +19 -0
  87. package/views/partials/webhook_form.hbs +1 -1
  88. package/views/unsubscribe.hbs +6 -0
  89. package/workers/api.js +137 -63
  90. package/workers/imap.js +32 -3
  91. package/workers/smtp.js +7 -0
  92. package/workers/submit.js +25 -1
  93. package/workers/webhooks.js +13 -17
  94. package/lib/reconnection-manager.js +0 -106
@@ -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
  /**
package/lib/outbox.js CHANGED
@@ -133,18 +133,35 @@ async function list(options) {
133
133
  };
134
134
  }
135
135
 
136
+ // Resolves to { deleted } - with `locked: true` when the message could not be removed because a
137
+ // submit worker is delivering it right now. That is the one refusal a caller can act on (retry
138
+ // once the attempt is over), so it is reported rather than folded into a plain false; a failure to
139
+ // remove for any other reason is thrown.
136
140
  async function del(options) {
137
141
  options = options || {};
138
142
 
139
143
  let logger = options.logger;
140
144
 
141
145
  if (!options.queueId) {
142
- return false;
146
+ return { deleted: false };
143
147
  }
144
148
 
145
149
  let job = await submitQueue.getJob(options.queueId);
146
150
  if (!job) {
147
- return false;
151
+ return { deleted: false };
152
+ }
153
+
154
+ // BullMQ refuses to remove a job a worker holds the lock on, and for the submit queue that is
155
+ // a message in the middle of a delivery attempt. Checked before touching the content: the
156
+ // attempt in flight still needs it, and removing it here would not stop the attempt anyway.
157
+ if (await job.isActive()) {
158
+ logger.info({
159
+ msg: 'Queued message is being delivered, not removed',
160
+ account: job.data.account,
161
+ queueId: job.data.queueId,
162
+ messageId: job.data.messageId
163
+ });
164
+ return { deleted: false, locked: true };
148
165
  }
149
166
 
150
167
  // Delete message content
@@ -158,13 +175,13 @@ async function del(options) {
158
175
  // Delete job entry
159
176
  try {
160
177
  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
178
  } catch (err) {
164
179
  logger.error({ msg: 'Failed to remove queue entry', account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId, err });
180
+ throw err;
165
181
  }
166
182
 
167
- return false;
183
+ logger.info({ msg: 'Removed queue entry', account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId });
184
+ return { deleted: true };
168
185
  }
169
186
 
170
187
  async function get(options) {
@@ -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
  }
@@ -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 => {
package/lib/schemas.js CHANGED
@@ -43,6 +43,11 @@ const MAX_ATTACHMENT_SIZE = getByteSize(process.env.EENGINE_MAX_SIZE || config.a
43
43
 
44
44
  const accountIdSchema = Joi.string().empty('').trim().max(MAX_ACCOUNT_ID_LENGTH).example('user123').description('Unique identifier for the email account');
45
45
 
46
+ // The message id path parameter, shared by every /message/{message} route so they all refuse the
47
+ // same input: EmailEngine ids are base64url, and an id that is not decodes to garbage the client
48
+ // code then fails on, which used to be a 500 on the routes that accepted any string
49
+ const messageIdSchema = Joi.string().base64({ paddingRequired: false, urlSafe: true }).max(256).example('AAAAAQAACnA').description('Message ID');
50
+
46
51
  // Suppression list identifier, shared by the Blocklists API and the suppression-list admin UI
47
52
  // so the two surfaces cannot drift on what a valid list ID is
48
53
  const blocklistListIdSchema = Joi.string()
@@ -2351,7 +2356,9 @@ const headerTimeoutSchema = Joi.number()
2351
2356
  .max(2 * 3600 * 1000)
2352
2357
  .optional()
2353
2358
  .example(30000)
2354
- .description('Request timeout in milliseconds (overrides EENGINE_TIMEOUT environment variable)')
2359
+ .description(
2360
+ 'Request timeout in milliseconds. Raises the command timeout above the EENGINE_TIMEOUT default for a long-running request; a value below the default has no effect'
2361
+ )
2355
2362
  .label('X-EE-Timeout');
2356
2363
 
2357
2364
  // Headers every API route accepts, applied as a server-wide route default in workers/api.js rather
@@ -2488,17 +2495,24 @@ const errorResponseSchemas = {
2488
2495
  messageExample: 'Invalid input',
2489
2496
  label: 'ValidationErrorResponse',
2490
2497
  title: 'Validation error',
2491
- description: 'Invalid input - the path parameters, query arguments, or request payload did not pass validation',
2498
+ description:
2499
+ 'Invalid input - the path parameters, query arguments, or request payload did not pass validation. Also returned when the email server refused the request, in which case the response carries a code and the server response instead of a field list',
2492
2500
  fields: {
2493
2501
  fields: Joi.array()
2494
2502
  .items(
2495
2503
  Joi.object({
2496
2504
  message: Joi.string().example('"pageSize" must be less than or equal to 1000').description('Description of the validation failure'),
2497
- key: Joi.string().example('pageSize').description('Name of the input field that failed validation')
2505
+ key: Joi.string().example('pageSize').description('Name of the input field that failed validation'),
2506
+ path: Joi.string()
2507
+ .example('to.0.address')
2508
+ .description('Full path of the input field that failed validation. Same as key for a top-level field, dotted for a nested one')
2498
2509
  }).label('ValidationErrorField')
2499
2510
  )
2500
2511
  .description('List of input fields that failed validation')
2501
- .label('ValidationErrorFields')
2512
+ .label('ValidationErrorFields'),
2513
+ code: Joi.string().example('MailboxNotFound').description('Machine-readable error code, if available'),
2514
+ details: Joi.any().description('Additional error details, if available. The email server response for a refused mailbox operation'),
2515
+ info: Joi.any().description('Additional error details, if available. The email server response for a refused message operation')
2502
2516
  }
2503
2517
  }),
2504
2518
 
@@ -2517,7 +2531,14 @@ const errorResponseSchemas = {
2517
2531
  messageExample: 'Unauthorized scope',
2518
2532
  label: 'AccessDeniedErrorResponse',
2519
2533
  title: 'Access denied error',
2520
- description: 'Access denied - the access token does not grant permission for this operation (token scope, account, or IP address restriction)'
2534
+ description: 'Access denied - the access token does not grant permission for this operation (token scope, account, or IP address restriction)',
2535
+ fields: {
2536
+ requestedScope: Joi.string().example('api').description('The scope the operation needed, when the token does not carry it'),
2537
+ requiredPermission: Joi.string()
2538
+ .example('messages:write')
2539
+ .description('The permission grant the operation needed, when the token permissions do not include it'),
2540
+ remoteAddress: Joi.string().example('203.0.113.1').description('The client IP address, when the token is restricted to other addresses')
2541
+ }
2521
2542
  }),
2522
2543
 
2523
2544
  404: errorResponseEntry({
@@ -2642,6 +2663,7 @@ module.exports = {
2642
2663
  tokenRestrictionsSchema,
2643
2664
  tokenPermissionsSchema,
2644
2665
  accountIdSchema,
2666
+ messageIdSchema,
2645
2667
  blocklistListIdSchema,
2646
2668
  oauth2ProviderSchema,
2647
2669
  accountTypeSchema,
package/lib/settings.js CHANGED
@@ -10,7 +10,9 @@ const { DEFAULT_MAX_LOG_LINES, REDIS_PREFIX } = require('./consts');
10
10
 
11
11
  config.service = config.service || {};
12
12
 
13
- const ENCRYPTED_KEYS = [
13
+ // Values that are secrets in their entirety. Encrypted at rest, and the settings API returns a
14
+ // boolean marker in their place rather than the value.
15
+ const SECRET_KEYS = [
14
16
  // The gmail*/outlook*/mailRu* secrets belong to the retired settings-based OAuth2
15
17
  // configuration. They stay listed so oauth2Apps.migrateLegacyApps() can still decrypt
16
18
  // stored values through settings.get() before moving them into the app registry.
@@ -28,6 +30,16 @@ const ENCRYPTED_KEYS = [
28
30
  'totpSeed'
29
31
  ];
30
32
 
33
+ // Values that carry a secret without being one: URLs that may embed `user:pass@` credentials
34
+ // (a SOCKS or HTTP proxy, a webhook target, a Sentry DSN with its key) and the custom webhook
35
+ // headers, whose example is an Authorization bearer. Encrypted at rest like the secrets, but the
36
+ // API reads them back with only the credential part masked (route-helpers maskSecrets()), so they
37
+ // are not in the list it turns into booleans. Encryption applies to the JSON encoding, so the
38
+ // header list being an array rather than a string makes no difference.
39
+ const CREDENTIAL_BEARING_KEYS = ['webhooks', 'webhooksCustomHeaders', 'proxyUrl', 'httpProxyUrl', 'sentryDsn'];
40
+
41
+ const ENCRYPTED_KEYS = SECRET_KEYS.concat(CREDENTIAL_BEARING_KEYS);
42
+
31
43
  // getValue() runs on an uncached read path - settings.get() is called several times per synced
32
44
  // message and once per webhook delivery - and a decrypt/parse failure is permanent rather than
33
45
  // transient (a rotated EENGINE_SECRET, a corrupt stored value). Reporting every occurrence would
@@ -36,8 +48,14 @@ const ENCRYPTED_KEYS = [
36
48
  const reportedParseFailures = new Set();
37
49
 
38
50
  module.exports = {
51
+ // Everything encrypted at rest: what `emailengine encrypt` re-encrypts on a secret rotation
39
52
  encryptedKeys: ENCRYPTED_KEYS,
40
53
 
54
+ // The subset the settings API returns as a boolean marker (lib/api-routes/settings-routes.js).
55
+ // The credential-bearing URLs are encrypted too but are returned with just the credentials
56
+ // masked, so a consumer that hides values has to read this list, not encryptedKeys.
57
+ secretKeys: SECRET_KEYS,
58
+
41
59
  /**
42
60
  * Whether admin authentication is configured for this instance.
43
61
  *
package/lib/sso.js CHANGED
@@ -99,14 +99,24 @@ function parseScopes(scopeStr) {
99
99
  }
100
100
 
101
101
  // Parse OIDC_ALLOWED_USERS into a normalized list of allow-list entries. Entries
102
- // starting with "@" are treated as domain matches, everything else as an exact
103
- // email match. Matching is case-insensitive.
102
+ // containing "@" are exact email matches, unless the "@" comes first, which makes
103
+ // the entry a domain match. An entry with no "@" at all cannot be an email, so it
104
+ // is read as a domain too: as an exact-email rule it could never match, and a bare
105
+ // "example.com" would have locked every user out with a generic "not authorized".
106
+ // Matching is case-insensitive.
104
107
  function parseAllowList(str) {
105
108
  return (str || '')
106
109
  .split(',')
107
110
  .map(entry => entry.trim().toLowerCase())
108
111
  .filter(entry => entry)
109
- .map(entry => (entry.charAt(0) === '@' ? { type: 'domain', value: entry.slice(1) } : { type: 'email', value: entry }));
112
+ .map(entry => {
113
+ const at = entry.indexOf('@');
114
+ if (at > 0) {
115
+ return { type: 'email', value: entry };
116
+ }
117
+ return { type: 'domain', value: at === 0 ? entry.slice(1) : entry };
118
+ })
119
+ .filter(entry => entry.value);
110
120
  }
111
121
 
112
122
  // Normalize a single group name: coerce to string, trim, and strip leading slashes
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ // Progress states a submit job reaches only once the message has been accepted. The email client
4
+ // writes 'smtp-completed' right after the MTA's 250 (or the provider API's accept), and the submit
5
+ // worker writes 'submitted' once the post-send bookkeeping is through as well. Everything a job
6
+ // does after either state is bookkeeping (Sent-folder copy, draft cleanup, flag updates, gateway
7
+ // stats), so a job that is running again in one of these states must not send the message again.
8
+ //
9
+ // Split out of workers/submit.js because the worker boots a BullMQ consumer on require, which
10
+ // keeps the decision itself out of reach of a unit test.
11
+ const SENT_PROGRESS_STATES = new Set(['smtp-completed', 'submitted']);
12
+
13
+ /**
14
+ * Tells whether a submit job's stored progress says the message was already accepted.
15
+ *
16
+ * BullMQ hands a re-run job the progress its previous run stored, so this is what a stalled job
17
+ * (heartbeat kill, crash, a shutdown drain that could not cover a long SMTP transaction) looks
18
+ * like when it comes back. A retry after a real delivery failure never carries one of these states:
19
+ * the failure path writes 'error' before it throws, and a run cut short before the 250 leaves
20
+ * 'processing' or 'smtp-starting' behind.
21
+ *
22
+ * @param {*} progress - job.progress as BullMQ hydrates it (an object, or 0 when never set)
23
+ * @returns {boolean} True when the message was already sent
24
+ */
25
+ function isAlreadySent(progress) {
26
+ return !!(progress && typeof progress === 'object' && SENT_PROGRESS_STATES.has(progress.status));
27
+ }
28
+
29
+ module.exports = { isAlreadySent, SENT_PROGRESS_STATES };
package/lib/templates.js CHANGED
@@ -84,8 +84,19 @@ class TemplateHandler {
84
84
  return id;
85
85
  }
86
86
 
87
+ // The inverse of generateId(): an 8-byte timestamp, a 4-byte counter, then the account id.
88
+ // Anything shorter than the fixed 12-byte header cannot be an id this module issued, and the
89
+ // routes accept any string up to 256 characters, so a malformed id is refused as "not found"
90
+ // here rather than failing on the header read.
87
91
  unpackId(id) {
88
92
  let idBuf = Buffer.from(id, 'base64');
93
+ if (idBuf.length < 4 + 8) {
94
+ let err = new Error('Document was not found');
95
+ err.code = 'NotFound';
96
+ err.statusCode = 404;
97
+ throw err;
98
+ }
99
+
89
100
  return {
90
101
  counter: idBuf.readUInt32BE(8),
91
102
  created: new Date(Number(idBuf.readBigUInt64BE(0))).toISOString(),
package/lib/tools.js CHANGED
@@ -5,7 +5,6 @@
5
5
  const msgpack = require('./msgpack');
6
6
  const enumMessageFlags = require('./enum-message-flags');
7
7
  const Joi = require('joi');
8
- const he = require('he');
9
8
  const packageData = require('../package.json');
10
9
  const settings = require('./settings');
11
10
  // Safe to require at load time despite db.js opening Redis clients: settings.js above already
@@ -95,6 +94,12 @@ const RETRY_OPTS = {
95
94
  // get a dispatcher that resolves through the egress policy (lib/webhook-egress.js) rather than the
96
95
  // shared resolver. It is built here because its lifetime is tied to the other agents': a proxy
97
96
  // setting change swaps them all out together.
97
+ //
98
+ // Deliberately NOT a RetryAgent. A webhook is a POST the receiver acts on, and RETRY_OPTS retries
99
+ // POSTs on a dropped socket or a 429: a receiver that processed the event and then reset the
100
+ // connection, or a stale keep-alive socket, would get the same event up to six times with an
101
+ // identical X-EE-Wh-Id and attempts-made 0, invisible to the worker's logs and metrics. Retrying
102
+ // is the notify queue's job, where every attempt is counted, logged and spaced out by backoff.
98
103
  function buildWebhookDispatcher(proxied, existing) {
99
104
  const lookup = createWebhookLookup();
100
105
 
@@ -102,13 +107,13 @@ function buildWebhookDispatcher(proxied, existing) {
102
107
  // only vet the route to the proxy itself. There is nothing to bind; fall back to the shared
103
108
  // dispatcher and leave assertAllowedUrl() as the advisory check it can only be in that setup.
104
109
  if (proxied || !lookup) {
105
- return httpAgent.retry;
110
+ return httpAgent.fetch;
106
111
  }
107
112
 
108
113
  // Nothing a reload changes can affect a dedicated dispatcher - the policy is fixed at startup
109
114
  // and the Agent never references httpAgent.fetch - so reuse it rather than discarding warm
110
115
  // sockets. Saving the network settings form reloads on any field, not just a proxy one.
111
- return existing || new RetryAgent(new Agent(Object.assign({}, AGENT_OPTS, { connect: { lookup } })), RETRY_OPTS);
116
+ return existing || new Agent(Object.assign({}, AGENT_OPTS, { connect: { lookup } }));
112
117
  }
113
118
 
114
119
  // Shared mutable object -- consumers import the object reference and access
@@ -232,7 +237,7 @@ async function _doReloadHttpProxyAgent() {
232
237
  let oldFetch = httpAgent.fetch;
233
238
  // Only a dedicated dispatcher is ours to close; when webhooks share the general one it is
234
239
  // closed via oldFetch. Read before anything is swapped, while the comparison still holds.
235
- let oldWebhook = httpAgent.webhook !== httpAgent.retry ? httpAgent.webhook : null;
240
+ let oldWebhook = httpAgent.webhook !== httpAgent.fetch ? httpAgent.webhook : null;
236
241
 
237
242
  try {
238
243
  if (enabled && proxyUrl) {
@@ -263,7 +268,7 @@ async function _doReloadHttpProxyAgent() {
263
268
  httpProxyEnabled: !!enabled,
264
269
  httpProxyUrl: enabled && proxyUrl ? proxyUrl : null,
265
270
  webhookEgressPolicy: WEBHOOK_EGRESS_POLICY,
266
- webhookEgressPinned: httpAgent.webhook !== httpAgent.retry
271
+ webhookEgressPinned: httpAgent.webhook !== httpAgent.fetch
267
272
  });
268
273
 
269
274
  // Closing is graceful, so it waits for whatever is still in flight to drain. Overlap the
@@ -777,6 +782,35 @@ module.exports = {
777
782
  return `${REDIS_PREFIX}iam:${account}:h:${module.exports.mailboxPathHash(path)}`;
778
783
  },
779
784
 
785
+ // Splits basic-auth credentials embedded in a URL ("https://user:pass@host/") into the
786
+ // Authorization header value to send and the URL to send it to, which no longer carries them.
787
+ // The URL parser keeps userinfo percent-encoded, so each part is decoded before being joined:
788
+ // a password typed as "p@ss" arrives here as "p%40ss", and it is the typed form the receiver
789
+ // compares against. A malformed escape keeps the raw value rather than throwing. No HTML entity
790
+ // handling takes place: an earlier version ran he.encode() over the parts, which turned every
791
+ // "&", "<", ">" or quote in a password into an entity reference and made it fail forever.
792
+ splitUrlCredentials(url) {
793
+ const decode = value => {
794
+ try {
795
+ return decodeURIComponent(value);
796
+ } catch {
797
+ return value;
798
+ }
799
+ };
800
+
801
+ let parsed = new URL(url);
802
+ let username = decode(parsed.username);
803
+ let password = decode(parsed.password);
804
+
805
+ parsed.username = '';
806
+ parsed.password = '';
807
+
808
+ return {
809
+ url: parsed,
810
+ authorization: username || password ? `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}` : null
811
+ };
812
+ },
813
+
780
814
  async resolveCredentials(account, proto) {
781
815
  let authServer = await settings.get('authServer');
782
816
  if (!authServer) {
@@ -788,21 +822,9 @@ module.exports = {
788
822
  'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
789
823
  };
790
824
 
791
- let parsed = new URL(authServer);
792
- let username, password;
793
-
794
- if (parsed.username) {
795
- username = he.decode(parsed.username);
796
- parsed.username = '';
797
- }
798
-
799
- if (parsed.password) {
800
- password = he.decode(parsed.password);
801
- parsed.password = '';
802
- }
803
-
804
- if (username || password) {
805
- headers.Authorization = `Basic ${Buffer.from(he.encode(username || '') + ':' + he.encode(password || '')).toString('base64')}`;
825
+ let { url: parsed, authorization } = module.exports.splitUrlCredentials(authServer);
826
+ if (authorization) {
827
+ headers.Authorization = authorization;
806
828
  }
807
829
 
808
830
  parsed.searchParams.set('account', account);
@@ -1336,7 +1358,13 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1336
1358
  try {
1337
1359
  redactValidationError(err);
1338
1360
 
1339
- let details = (err.details || []).map(detail => ({ message: detail.message, key: detail.context.key }));
1361
+ // `key` is the leaf name only, which cannot tell to[0].address from from.address;
1362
+ // `path` is the full dotted location. Both are kept: key is what clients already read
1363
+ let details = (err.details || []).map(detail => ({
1364
+ message: detail.message,
1365
+ key: detail.context.key,
1366
+ path: Array.isArray(detail.path) ? detail.path.join('.') : undefined
1367
+ }));
1340
1368
 
1341
1369
  request.logger.debug({
1342
1370
  msg: 'Request failed',
@@ -1366,6 +1394,9 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1366
1394
  // IP blocklist here without making it opt-in; it would break legitimate local-mail setups.
1367
1395
  let response = {};
1368
1396
 
1397
+ // Connect and greeting budget for both probes, in ms
1398
+ const VERIFY_TIMEOUT = 30 * 1000;
1399
+
1369
1400
  let proxyUrl = await settings.get('proxyUrl');
1370
1401
  let proxyEnabled = await settings.get('proxyEnabled');
1371
1402
 
@@ -1380,7 +1411,11 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1380
1411
  verifyOnly: true,
1381
1412
  includeMailboxes: accountData.mailboxes,
1382
1413
 
1383
- greetingTimeout: 90 * 1000,
1414
+ // A verification answers a person waiting at a form, so it gives up
1415
+ // well before the sync client's defaults would (the hosted form's
1416
+ // test fetch has no client-side timeout of its own)
1417
+ connectionTimeout: VERIFY_TIMEOUT,
1418
+ greetingTimeout: VERIFY_TIMEOUT,
1384
1419
 
1385
1420
  clientInfo: {
1386
1421
  name: (await settings.get('imapClientName')) || packageData.name,
@@ -1480,7 +1515,12 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1480
1515
  name,
1481
1516
  localAddress: address,
1482
1517
  transactionLog: true,
1483
- logger: smtpLogger
1518
+ logger: smtpLogger,
1519
+
1520
+ // see the IMAP side above; Nodemailer's own defaults are 2 minutes
1521
+ // to connect and 30 seconds for the greeting
1522
+ connectionTimeout: VERIFY_TIMEOUT,
1523
+ greetingTimeout: VERIFY_TIMEOUT
1484
1524
  },
1485
1525
  accountData.smtp
1486
1526
  );
@@ -1630,8 +1670,14 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1630
1670
  }
1631
1671
  },
1632
1672
 
1633
- getLogs(redis, account) {
1673
+ // Resolves to a readable stream of the account's stored log, one JSON entry per line. The rows
1674
+ // are read before the stream is handed out, so a Redis failure rejects and becomes a proper
1675
+ // error response instead of a 200 whose body trails off into an error, and it never carries a
1676
+ // stack trace into the download.
1677
+ async getLogs(redis, account) {
1634
1678
  let logKey = `${REDIS_PREFIX}iam:${account}:g`;
1679
+ let rows = await redis.lrangeBuffer(logKey, 0, -1);
1680
+
1635
1681
  let passThrough = new PassThrough();
1636
1682
 
1637
1683
  passThrough.headers = {
@@ -1639,39 +1685,36 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1639
1685
  'content-disposition': `attachment; filename=${JSON.stringify(`logs.${account}.txt`)}`
1640
1686
  };
1641
1687
 
1642
- redis
1643
- .lrangeBuffer(logKey, 0, -1)
1644
- .then(rows => {
1645
- if (!rows || !Array.isArray(rows) || !rows.length) {
1646
- return passThrough.end(`No logs found for ${account}\n`);
1647
- }
1648
- let processNext = () => {
1649
- if (!rows.length) {
1650
- return passThrough.end();
1651
- }
1688
+ if (!rows || !Array.isArray(rows) || !rows.length) {
1689
+ passThrough.end(`No logs found for ${account}\n`);
1690
+ return passThrough;
1691
+ }
1652
1692
 
1653
- let row = rows.shift();
1654
- let entry;
1655
- try {
1656
- entry = msgpack.decode(row);
1657
- } catch (err) {
1658
- entry = { error: err.stack };
1659
- }
1693
+ let processNext = () => {
1694
+ if (!rows.length) {
1695
+ return passThrough.end();
1696
+ }
1660
1697
 
1661
- if (entry) {
1662
- if (!passThrough.write(JSON.stringify(entry) + '\n')) {
1663
- return passThrough.once('drain', processNext);
1664
- }
1665
- }
1698
+ let row = rows.shift();
1699
+ let entry;
1700
+ try {
1701
+ entry = msgpack.decode(row);
1702
+ } catch (err) {
1703
+ // A row that does not decode is reported in place, so the download stays
1704
+ // complete, but with the message only - the stack names nothing the reader can act on
1705
+ entry = { error: 'Failed to decode log entry', message: err.message };
1706
+ }
1707
+
1708
+ if (entry) {
1709
+ if (!passThrough.write(JSON.stringify(entry) + '\n')) {
1710
+ return passThrough.once('drain', processNext);
1711
+ }
1712
+ }
1666
1713
 
1667
- setImmediate(processNext);
1668
- };
1714
+ setImmediate(processNext);
1715
+ };
1669
1716
 
1670
- processNext();
1671
- })
1672
- .catch(err => {
1673
- passThrough.end(`\nFailed to process logs\n${err.stack}\n`);
1674
- });
1717
+ processNext();
1675
1718
 
1676
1719
  return passThrough;
1677
1720
  },