emailengine-app 2.82.0 → 2.82.1

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 (65) hide show
  1. package/.ncurc.js +23 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +44 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/bin/emailengine.js +77 -7
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +35 -10
  8. package/lib/api-routes/account-binding.js +58 -0
  9. package/lib/api-routes/account-routes.js +48 -9
  10. package/lib/api-routes/behavior-notes.js +4 -0
  11. package/lib/api-routes/gateway-routes.js +10 -2
  12. package/lib/api-routes/message-routes.js +10 -3
  13. package/lib/api-routes/outbox-routes.js +1 -1
  14. package/lib/api-routes/settings-routes.js +1 -2
  15. package/lib/api-routes/token-routes.js +1 -1
  16. package/lib/autodetect-imap-settings.js +146 -4
  17. package/lib/consts.js +12 -0
  18. package/lib/db.js +1 -19
  19. package/lib/delivery-error.js +68 -1
  20. package/lib/email-client/base-client.js +6 -13
  21. package/lib/email-client/credential-errors.js +21 -5
  22. package/lib/email-client/gmail-client.js +2 -2
  23. package/lib/email-client/imap-client.js +2 -1
  24. package/lib/email-client/message-builder.js +41 -11
  25. package/lib/email-client/outlook-client.js +196 -67
  26. package/lib/enum-descriptions.js +5 -1
  27. package/lib/export.js +8 -2
  28. package/lib/gateway.js +5 -0
  29. package/lib/get-secret.js +1 -21
  30. package/lib/mcp/tools.js +95 -36
  31. package/lib/oauth/gmail.js +42 -12
  32. package/lib/oauth/mail-ru.js +24 -17
  33. package/lib/oauth/outlook.js +34 -24
  34. package/lib/oauth/scope-checker.js +35 -1
  35. package/lib/oauth/scope-list.js +55 -0
  36. package/lib/oauth/token-fetch.js +47 -0
  37. package/lib/oauth2-apps.js +16 -47
  38. package/lib/outbox.js +2 -7
  39. package/lib/queue-retention.js +4 -2
  40. package/lib/read-env-value.js +33 -2
  41. package/lib/schemas.js +62 -15
  42. package/lib/token-audit-log.js +3 -2
  43. package/lib/tools.js +1 -1
  44. package/lib/ui-routes/account-routes.js +40 -7
  45. package/lib/ui-routes/oauth-config-routes.js +3 -14
  46. package/lib/ui-routes/route-helpers.js +23 -23
  47. package/lib/ui-routes/special-use-paths.js +33 -0
  48. package/lib/utils/network.js +9 -17
  49. package/package.json +18 -18
  50. package/sbom.json +1 -1
  51. package/server.js +21 -3
  52. package/setup-production.sh +16 -7
  53. package/static/licenses.html +30 -20
  54. package/translations/messages.pot +74 -56
  55. package/views/account-workspace-error.hbs +30 -0
  56. package/views/accounts/account.hbs +9 -4
  57. package/views/accounts/edit.hbs +11 -2
  58. package/views/internals/index.hbs +1 -1
  59. package/views/partials/gmail_api_scopes.hbs +16 -0
  60. package/views/partials/oauth_form.hbs +67 -94
  61. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  62. package/views/partials/scope_info.hbs +14 -23
  63. package/workers/api.js +62 -27
  64. package/workers/imap.js +6 -3
  65. package/workers/submit.js +2 -5
@@ -10,7 +10,7 @@ const { tlsSettingChanged } = require('../tls/store');
10
10
  const { queueStats } = require('../queue-stats');
11
11
  const Boom = require('@hapi/boom');
12
12
  const { handleError, maskSecrets, containsMaskedSecret, isMaskedRoundTrip, assertNoPrivilegedSettings, MASKED } = require('./route-helpers');
13
- const { settingsSchema, settingsQuerySchema, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
13
+ const { settingsSchema, settingsQuerySchema, isHiddenSetting, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
14
14
 
15
15
  // Response variant of the settings schema. Secret values are masked and returned as booleans,
16
16
  // any setting that has never been set is returned as null, and the virtual eventTypes key is
@@ -41,7 +41,6 @@ settingsOutputSchema.eventTypes = Joi.array()
41
41
  // the privileged keys to a narrowed credential, so the `write/settings` grant means the same thing
42
42
  // on both surfaces; test/settings-privileged-keys-test.js asserts the tool schema and the list
43
43
  // agree.
44
- const isHiddenSetting = key => (settingsSchema[key].describe().metas || []).some(meta => meta && meta.swaggerHidden);
45
44
  const MCP_SETTINGS_KEYS = Object.keys(settingsSchema).filter(key => !settings.privilegedKeys.includes(key) && !isHiddenSetting(key));
46
45
 
47
46
  async function init(args) {
@@ -392,7 +392,7 @@ async function init(args) {
392
392
  name: 'list_tokens',
393
393
  title: 'List access tokens',
394
394
  description:
395
- 'List the access tokens on this instance, paged: description, scopes, restrictions, the account each is bound to and when it was last used. Token values are never shown. Filter with query, or with account for the tokens bound to one account.',
395
+ "List the access tokens on this instance, paged: description, scopes, restrictions, the account each is bound to and when it was last used. Token values are never shown. Filter with query, or with account for the tokens bound to one account. A credential that is itself bound to an account sees only that account's tokens, not the instance.",
396
396
  bounds: { pageSize: MCP_MAX_PAGE_SIZE }
397
397
  },
398
398
  openapi: {
@@ -76,6 +76,11 @@ const MAX_AUTODISCOVERY_BODY = 256 * 1024;
76
76
  // re-render and only produces a cosmetic label, so it must not stall the page for the full RESOLV_TIMEOUT.
77
77
  const APP_PASSWORD_MX_TIMEOUT = 1500;
78
78
 
79
+ // How many times an autodiscovery response may name another endpoint instead of answering. Each hop
80
+ // is a request on the critical path of a resolver that shares a five second budget, and a loop
81
+ // between two endpoints that redirect to each other would otherwise spend all of it.
82
+ const MAX_AUTODISCOVER_REDIRECTS = 2;
83
+
79
84
  /**
80
85
  * Does a resolver result actually name a server? Asked by every branch that has to decide whether
81
86
  * a lookup answered, so they all decide it the same way.
@@ -854,6 +859,54 @@ function processAutodiscoverSoapResponse(text) {
854
859
  // lead to http (the anonymous lookup carries nothing worth protecting), so the host that ends up
855
860
  // issuing the challenge is not necessarily on https, and Basic over cleartext would hand the
856
861
  // mailbox password to anyone on the path.
862
+ /**
863
+ * The endpoint a POX response names instead of answering.
864
+ *
865
+ * Microsoft's sequence lets a server say "ask over there" rather than return settings:
866
+ * `<Action>redirectUrl</Action>` with a `<RedirectUrl>` names another endpoint for the same mailbox.
867
+ * processAutodiscoverResponse() reads `Account > Protocol` only, so such a response parsed as naming
868
+ * no server and the lookup stopped there.
869
+ *
870
+ * `<RedirectAddr>` is deliberately NOT followed. It names a different ADDRESS, so following it would
871
+ * restart the lookup for a mailbox the caller did not ask about. A response carrying only a
872
+ * RedirectAddr stays a loss.
873
+ *
874
+ * The endpoint this does name is asked anonymously - see the call site in runAutodiscovery().
875
+ *
876
+ * @param {String} text - The POX response body
877
+ * @returns {String|false} The URL the response names, or false
878
+ */
879
+ function poxRedirectUrl(text) {
880
+ let json;
881
+ try {
882
+ // Only reached after processAutodiscoverResponse() has already parsed the same body, so a
883
+ // document that does not parse cannot get here in production - guarded so the helper is still
884
+ // safe called on its own
885
+ json = parseXml(text);
886
+ } catch (err) {
887
+ return false;
888
+ }
889
+ const responses = json && json.autodiscover && Array.isArray(json.autodiscover.response) ? json.autodiscover.response : [];
890
+
891
+ for (const responseRow of responses) {
892
+ if (!responseRow || !Array.isArray(responseRow.account)) {
893
+ continue;
894
+ }
895
+ for (const accountRow of responseRow.account) {
896
+ const action = accountRow && Array.isArray(accountRow.action) ? accountRow.action[0] : null;
897
+ const redirectUrl = accountRow && Array.isArray(accountRow.redirecturl) ? accountRow.redirecturl[0] : null;
898
+
899
+ // The action is what makes it a redirect; a document that carries a stray RedirectUrl
900
+ // without saying so is not one
901
+ if (typeof action === 'string' && /^redirecturl$/i.test(action.trim()) && typeof redirectUrl === 'string' && redirectUrl.trim()) {
902
+ return redirectUrl.trim();
903
+ }
904
+ }
905
+ }
906
+
907
+ return false;
908
+ }
909
+
857
910
  function secureOriginOf(url) {
858
911
  try {
859
912
  const parsed = new URL(url);
@@ -872,6 +925,44 @@ async function resolveAutodiscoveryHost(domain, ctx) {
872
925
  return `autodiscover.${encodeURIComponent(domain)}`;
873
926
  }
874
927
 
928
+ /**
929
+ * The https endpoint that the subdomain's plain-http redirect names.
930
+ *
931
+ * Microsoft's sequence has a step before the POSTs: an unauthenticated GET to
932
+ * `http://autodiscover.<domain>/autodiscover/autodiscover.xml`, whose 302 names the endpoint that
933
+ * actually answers. It used to be skipped entirely, and for a provider that publishes nothing else
934
+ * the lookup then had nowhere to go: IONOS/1&1 hosted mail points `autodiscover.<domain>` at a
935
+ * redirector that listens on port 80 only, so the https POST could not connect and the whole
936
+ * Exchange branch failed for every domain on that provider.
937
+ *
938
+ * Anonymous, and it stays anonymous: no credential is attached to an http request, and only an https
939
+ * origin is returned, so a redirect that lands on http names nothing. The target is chosen by a
940
+ * server the address domain's DNS points at, so the hop goes through the same vetted-redirect fetch
941
+ * as every other request here and `fetchWithVettedRedirects` drops credentials on a cross-origin hop.
942
+ *
943
+ * @param {String} domain - The address domain, already punycoded
944
+ * @param {Object} ctx - `{ fetchResource, signal }`
945
+ * @returns {Promise<String|false>} An https origin, or false when the lookup names nothing new
946
+ */
947
+ async function autodiscoverRedirectOrigin(domain, ctx) {
948
+ const { fetchResource, signal } = withIo(ctx);
949
+ const subdomain = `autodiscover.${encodeURIComponent(domain)}`;
950
+
951
+ try {
952
+ const res = await fetchResource(`http://${subdomain}/autodiscover/autodiscover.xml`, { method: 'get', signal });
953
+ // Nothing reads the body - only where the request ended up - but it is drained so the
954
+ // keep-alive socket goes back to the pool
955
+ await readDocument(res).catch(() => false);
956
+
957
+ const origin = secureOriginOf(res.url || '');
958
+ // A plain http-to-https upgrade on the same host names nothing new: that origin is already
959
+ // one of the candidates raced below
960
+ return origin && origin !== `https://${subdomain}` ? origin : false;
961
+ } catch (err) {
962
+ return false;
963
+ }
964
+ }
965
+
875
966
  /**
876
967
  * Runs autodiscovery against one host.
877
968
  *
@@ -890,10 +981,12 @@ async function resolveAutodiscoveryHost(domain, ctx) {
890
981
  * @param {Object} [ctx] - `{ fetchResource, signal }`: the fetch to use, `(url, opts) =>
891
982
  * Promise<Response>`, and the signal that aborts every request of the lookup (the resolver's
892
983
  * time budget). Either may be left out, this is an entry point of its own for the tests
984
+ * @param {Number} [redirectsLeft] - How many more times a response may name another endpoint
985
+ * instead of answering; see MAX_AUTODISCOVER_REDIRECTS
893
986
  * @returns {Promise<Object>} `{ imap, smtp, _source }`
894
987
  * @throws {Error} When no endpoint returned anything usable
895
988
  */
896
- async function runAutodiscovery(baseUrl, email, credentials, ctx) {
989
+ async function runAutodiscovery(baseUrl, email, credentials, ctx, redirectsLeft = MAX_AUTODISCOVER_REDIRECTS) {
897
990
  const { fetchResource, signal } = withIo(ctx);
898
991
 
899
992
  const poxBody = buildAutodiscoverRequest(email);
@@ -908,10 +1001,24 @@ async function runAutodiscovery(baseUrl, email, credentials, ctx) {
908
1001
  // A server that answers without credentials is never asked for them
909
1002
  let res = await post(baseUrl, '/autodiscover/autodiscover.xml', poxBody);
910
1003
  if (res.ok) {
911
- let result = processAutodiscoverResponse(await readDocument(res));
1004
+ const body = await readDocument(res);
1005
+ let result = processAutodiscoverResponse(body);
912
1006
  if (hasResolvedHost(result)) {
913
1007
  return result;
914
1008
  }
1009
+
1010
+ // The response can name another endpoint for the same mailbox instead of answering, which read
1011
+ // as "no server" before. Asked ANONYMOUSLY, whatever credentials this lookup holds: the origin
1012
+ // is named by the body of a server that answered 200 without asking for anything, and an
1013
+ // anonymous 200 carrying no settings is exactly the case that must end the lookup rather than
1014
+ // escalate it. Passing the password on here would let any host the address domain points at
1015
+ // choose where that password goes, which is the one thing the rules around it prevent. https
1016
+ // only, for the same reason the 401 retry is.
1017
+ const redirectOrigin = redirectsLeft > 0 && secureOriginOf(poxRedirectUrl(body) || '');
1018
+ if (redirectOrigin) {
1019
+ return await runAutodiscovery(redirectOrigin, email, undefined, ctx, redirectsLeft - 1);
1020
+ }
1021
+
915
1022
  // It answered anonymously, just with nothing usable. It never asked for a password, so it
916
1023
  // is not given one.
917
1024
  throw new Error('Invalid response');
@@ -980,9 +1087,37 @@ async function resolveUsingAutodiscovery(email, ctx, credentials) {
980
1087
  //ignore
981
1088
  }
982
1089
 
983
- let discoveryDomain = await resolveAutodiscoveryHost(domain, ctx);
1090
+ // Microsoft's sequence names three places a provider may publish autodiscovery, and a provider
1091
+ // can publish only one of them: the root domain, the autodiscover subdomain (or whatever the
1092
+ // _autodiscover._tcp SRV record names instead), and the endpoint that the subdomain's plain-http
1093
+ // redirect names. Only the second was ever tried.
1094
+ //
1095
+ // Raced rather than walked in order, for the same reason the two endpoints of one host already
1096
+ // are: this resolver shares a five second budget with four others, and a domain that publishes
1097
+ // none of them fails slowly - a DNS name that does not exist, a port that refuses the connection
1098
+ // and a host that answers 404 are three waits, not three answers.
1099
+ const subdomainOrigin = `https://${await resolveAutodiscoveryHost(domain, ctx)}`;
1100
+ const rootOrigin = `https://${encodeURIComponent(domain)}`;
1101
+
1102
+ const attempts = [...new Set([subdomainOrigin, rootOrigin])].map(origin => runAutodiscovery(origin, email, credentials, ctx));
1103
+
1104
+ // One request behind the others, so it is started here rather than awaited first
1105
+ attempts.push(
1106
+ autodiscoverRedirectOrigin(domain, ctx).then(origin => {
1107
+ if (!origin) {
1108
+ throw new Error('Invalid response');
1109
+ }
1110
+ return runAutodiscovery(origin, email, credentials, ctx);
1111
+ })
1112
+ );
984
1113
 
985
- return await runAutodiscovery(`https://${discoveryDomain}`, email, credentials, ctx);
1114
+ try {
1115
+ // Every attempt rejects unless it has a usable configuration (runAutodiscovery throws on
1116
+ // anything else), so the first to resolve is the first real answer
1117
+ return await Promise.any(attempts);
1118
+ } catch (err) {
1119
+ throw new Error('Invalid response', { cause: err });
1120
+ }
986
1121
  }
987
1122
 
988
1123
  function processAutodiscoverResponse(text, source) {
@@ -1206,3 +1341,10 @@ module.exports.resolver = resolver;
1206
1341
  module.exports.resolveUsingSRV = resolveUsingSRV;
1207
1342
  module.exports.timedFunction = timedFunction;
1208
1343
  module.exports.MAX_AUTODISCOVERY_BODY = MAX_AUTODISCOVERY_BODY;
1344
+
1345
+ // Exposed so the two steps of Microsoft's sequence that used to be missing can be tested on their
1346
+ // own: the plain-http GET whose redirect names the real endpoint, and the in-response redirect
1347
+ module.exports.autodiscoverRedirectOrigin = autodiscoverRedirectOrigin;
1348
+ module.exports.poxRedirectUrl = poxRedirectUrl;
1349
+ module.exports.resolveUsingAutodiscovery = resolveUsingAutodiscovery;
1350
+ module.exports.MAX_AUTODISCOVER_REDIRECTS = MAX_AUTODISCOVER_REDIRECTS;
package/lib/consts.js CHANGED
@@ -358,6 +358,16 @@ module.exports = {
358
358
  // the path and delimiter after the pick.
359
359
  MAILBOX_RESPONSE_FIELDS: ['path', 'specialUse', 'name', 'listed', 'subscribed', 'delimiter', 'specialUseSource', 'noInferiors'],
360
360
 
361
+ // The special-use folders an account may override, each stored on the account as
362
+ // `imap.<type>MailPath`. EmailEngine detects these folders from the server's own flags; an
363
+ // override is for a server that flags none of them, or flags the wrong one.
364
+ //
365
+ // One list because four places have to agree on it: the IMAP client turns it into the
366
+ // specialUseHints it passes to LIST, lib/schemas.js declares a field per entry for the account
367
+ // create and update schemas, and the admin edit form offers an input per entry. Only the client
368
+ // and the form used to carry a copy, and the form's had four of the five missing.
369
+ SPECIAL_USE_PATH_TYPES: ['sent', 'drafts', 'junk', 'trash', 'archive'],
370
+
361
371
  // nanoseconds
362
372
  ALLOWED_REDIS_LATENCY: 5 * 1000000,
363
373
 
@@ -394,6 +404,8 @@ module.exports = {
394
404
  OUTLOOK_MISSED_LOOKBACK: 4 * 60 * 60 * 1000, // ms
395
405
  // How long announced new messages are remembered, so a recovery pass does not announce them again
396
406
  OUTLOOK_ANNOUNCED_RETENTION: 6 * 60 * 60 * 1000, // ms
407
+ // How far back a manual sync of a Graph account may be asked to look (PUT /v1/account/{account}/sync `since`)
408
+ OUTLOOK_SYNC_MAX_LOOKBACK: 30 * 24 * 60 * 60 * 1000, // ms
397
409
 
398
410
  // Google Pub/Sub subscription defaults
399
411
  GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL: '2678400s', // 31 days in seconds (Google's default)
package/lib/db.js CHANGED
@@ -11,6 +11,7 @@ const pathlib = require('path');
11
11
  const redisUrl = require('./redis-url');
12
12
  const { threadId } = require('worker_threads');
13
13
  const logger = require('./logger');
14
+ const { readEnvValue } = require('./read-env-value');
14
15
  const { REDIS_PREFIX } = require('./consts');
15
16
  const Path = require('path');
16
17
  const { isMainThread } = require('worker_threads');
@@ -22,25 +23,6 @@ config.dbs = config.dbs || {
22
23
  const { Queue } = require('bullmq');
23
24
  const Redis = require('ioredis');
24
25
 
25
- // duplicate function declaration to avoid requiring tools.js
26
- const readEnvValue = key => {
27
- if (key in process.env) {
28
- return process.env[key];
29
- }
30
-
31
- if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
32
- try {
33
- // try to load from file
34
- process.env[key] = fs.readFileSync(process.env[`${key}_FILE`], 'utf-8').replace(/\r?\n$/, '');
35
- logger.trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
36
- } catch (err) {
37
- logger.error({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
38
- process.env[key] = '';
39
- }
40
- return process.env[key];
41
- }
42
- };
43
-
44
26
  const redisConf = readEnvValue('EENGINE_REDIS') || readEnvValue('REDIS_URL') || config.dbs.redis;
45
27
  const REDIS_CONF = Object.assign(
46
28
  {
@@ -112,4 +112,71 @@ function isFinalFailedAttempt(job) {
112
112
  return !!job.finishedOn || job.attemptsMade >= (job.opts.attempts || 1);
113
113
  }
114
114
 
115
- module.exports = { NON_RETRYABLE_CODES, isPermanentDeliveryError, shouldDiscardJob, willBeFinalAttempt, isFinalFailedAttempt };
115
+ // The same phase difference decides the retry TIME reported as `nextAttempt`, and the two call sites
116
+ // read a job in the two different phases, so they used to carry exponents that differ by one and
117
+ // looked like one of them was wrong. BullMQ's exponential strategy delays retry number r by
118
+ // 2^(r-1) * backoff.delay (Backoffs.builtinStrategies.exponential), and Job#shouldRetryJob() calls it
119
+ // with attemptsMade + 1, so the wait after the attempt numbered k fails is 2^(k-1) * delay. Verified
120
+ // against bullmq 6.3.11. Jitter is deliberately not applied: submissions are queued with
121
+ // jitter: 0.2, which spreads the real wait over [0.8, 1.0) of this figure, so what is reported is
122
+ // the latest the retry can happen. The schema calls it approximate for that reason.
123
+
124
+ /**
125
+ * How long BullMQ waits before retrying, once the attempt numbered `attemptNumber` has failed.
126
+ *
127
+ * @param {Number} attemptNumber - 1-based number of the attempt that failed
128
+ * @param {Object} job - BullMQ job, for its backoff options
129
+ * @returns {Number} Delay in milliseconds (0 when the job has no exponential backoff)
130
+ */
131
+ function retryDelayAfterAttempt(attemptNumber, job) {
132
+ const backoffDelay = Number(job.opts.backoff && job.opts.backoff.delay) || 0;
133
+ return Math.pow(2, attemptNumber - 1) * backoffDelay;
134
+ }
135
+
136
+ /**
137
+ * Inside a job processor: when would a failure of the CURRENTLY RUNNING attempt be retried?
138
+ * attemptsMade is not yet incremented here, so the running attempt is attemptsMade + 1.
139
+ *
140
+ * @param {Object} job - BullMQ job (mid-processing)
141
+ * @returns {Number|false} Epoch milliseconds, or false when this attempt is the job's last
142
+ */
143
+ function nextAttemptWhileProcessing(job) {
144
+ if (willBeFinalAttempt(job)) {
145
+ return false;
146
+ }
147
+ return Math.round(job.processedOn + retryDelayAfterAttempt(job.attemptsMade + 1, job));
148
+ }
149
+
150
+ /**
151
+ * Reading a job back out of Redis (the outbox listing): when is its next attempt due? attemptsMade
152
+ * already counts the attempt that failed, so that attempt is attemptsMade itself.
153
+ *
154
+ * @param {Object} job - BullMQ job as stored
155
+ * @param {Number} scheduled - Epoch milliseconds the job was queued for, used while nothing has failed
156
+ * @returns {Number|false} Epoch milliseconds, or false when every attempt has been used up
157
+ */
158
+ function nextAttemptOfStoredJob(job, scheduled) {
159
+ // isFinalFailedAttempt() rather than the attempts bound alone, for its finishedOn clause: a job
160
+ // the submit worker ended early with UnrecoverableError (every permanent SMTP rejection) is listed
161
+ // by the outbox with attempts left over, and reporting a retry time for a delivery that is dead
162
+ // for good is exactly the figure this module exists to get right
163
+ if (isFinalFailedAttempt(job)) {
164
+ return false;
165
+ }
166
+ if (!job.attemptsMade) {
167
+ // Nothing has failed yet, so the job is still waiting for its scheduled time
168
+ return scheduled;
169
+ }
170
+ return Math.round(job.processedOn + retryDelayAfterAttempt(job.attemptsMade, job));
171
+ }
172
+
173
+ module.exports = {
174
+ NON_RETRYABLE_CODES,
175
+ isPermanentDeliveryError,
176
+ shouldDiscardJob,
177
+ willBeFinalAttempt,
178
+ isFinalFailedAttempt,
179
+ retryDelayAfterAttempt,
180
+ nextAttemptWhileProcessing,
181
+ nextAttemptOfStoredJob
182
+ };
@@ -30,6 +30,7 @@ const { oauth2Apps } = require('../oauth2-apps');
30
30
  const { Account } = require('../account');
31
31
  const { removeBcc } = require('../get-raw-email');
32
32
  const {
33
+ applyTemplate,
33
34
  SmtpConfigBuilder,
34
35
  NetworkRoutingBuilder,
35
36
  NotificationBuilder,
@@ -1766,17 +1767,7 @@ class BaseClient {
1766
1767
  throw err;
1767
1768
  }
1768
1769
 
1769
- if (templateData.content && templateData.content.html && templateData.format) {
1770
- data.render = data.render || {};
1771
- data.render.format = templateData.format;
1772
- }
1773
-
1774
- // Merge template content into message
1775
- for (let key of Object.keys(templateData.content || {})) {
1776
- data[key] = templateData.content[key];
1777
- }
1778
-
1779
- delete data.template;
1770
+ applyTemplate(data, templateData);
1780
1771
  }
1781
1772
 
1782
1773
  // Handle single message or mail merge
@@ -3864,8 +3855,10 @@ class BaseClient {
3864
3855
  async handleSubmitError(err, context) {
3865
3856
  const { smtpSettings, networkRouting, gatewayData, gatewayObject, data, jobData, queueId, envelope } = context;
3866
3857
 
3867
- // Build SMTP status from error
3868
- const smtpStatus = SmtpErrorBuilder.buildStatus(err, smtpSettings, networkRouting);
3858
+ // Build SMTP status from error. Only an SMTP attempt has one to report: a provider API send
3859
+ // (Gmail, Graph) reaches here with no smtpSettings, and recording a status for it would
3860
+ // describe an SMTP server the message never touched
3861
+ const smtpStatus = smtpSettings ? SmtpErrorBuilder.buildStatus(err, smtpSettings, networkRouting) : null;
3869
3862
 
3870
3863
  if (smtpStatus) {
3871
3864
  // Store SMTP error for the account
@@ -21,18 +21,34 @@ const { resolveCredentials } = require('../tools');
21
21
  const { AUTH_ERROR_NOTIFY, TRANSIENT_NETWORK_CODES } = require('../consts');
22
22
  const { ACCOUNT_STATES } = require('../account/account-state');
23
23
 
24
+ // How far down a cause chain the transient check looks. A chain is not guaranteed to be finite - an
25
+ // error may cite itself - so the walk is bounded rather than trusting it to end.
26
+ const MAX_CAUSE_DEPTH = 5;
27
+
24
28
  /**
25
29
  * Failing to reach a remote endpoint is a connection problem, not a rejected credential. Both
26
30
  * OAuth2 credential sources (EmailEngine's own token refresh and an external authentication
27
31
  * server) use this to avoid reporting an unreachable host as an authentication error, and the API
28
- * transports use it to decide which failed requests to repeat. undici reports a connection failure
29
- * as a generic TypeError ("fetch failed") with the real DNS/socket error attached as err.cause, so
30
- * the code is looked up there as well
32
+ * transports use it to decide which failed requests to repeat.
33
+ *
34
+ * The whole cause chain is searched, not one level. undici reports a connection failure as a generic
35
+ * TypeError ("fetch failed") with the real DNS/socket error on err.cause, and a caller that wraps THAT
36
+ * failure in an error of its own pushes it one level deeper: lib/oauth/external-account-signer.js does
37
+ * exactly that for its three Workload Identity Federation requests, so an unreachable Google STS
38
+ * endpoint used to be classified as a refused credential and park the account - the one outcome this
39
+ * check exists to prevent.
40
+ *
31
41
  * @param {Error} err - The error to check
32
- * @returns {boolean} True if the error is a transient network failure
42
+ * @returns {boolean} True if the error, or anything it was caused by, is a transient network failure
33
43
  */
34
44
  function isTransientNetworkError(err) {
35
- return !!err && (TRANSIENT_NETWORK_CODES.has(err.code) || (!!err.cause && TRANSIENT_NETWORK_CODES.has(err.cause.code)));
45
+ for (let cause = err, depth = 0; cause && typeof cause === 'object' && depth < MAX_CAUSE_DEPTH; cause = cause.cause, depth++) {
46
+ if (TRANSIENT_NETWORK_CODES.has(cause.code)) {
47
+ return true;
48
+ }
49
+ }
50
+
51
+ return false;
36
52
  }
37
53
 
38
54
  /**
@@ -11,7 +11,7 @@ const he = require('he');
11
11
  const { BaseClient, metricsMeta } = require('./base-client');
12
12
  const { isTransientCredentialError } = require('./credential-errors');
13
13
  const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
14
- const { emitChangeEvent, toCamelCase, collectCidReferences, embedCidImages, truncateTextContents } = require('../tools');
14
+ const { emitChangeEvent, toCamelCase, collectCidReferences, embedCidImages, truncateTextContents, readEnvValue } = require('../tools');
15
15
  const { Gateway } = require('../gateway');
16
16
 
17
17
  const {
@@ -100,7 +100,7 @@ const MIN_WATCH_TTL = 24 * 3600 * 1000; // 1day - minimum time before renewing w
100
100
  // 10min default - fallback polling if no Pub/Sub notifications. Overridable via
101
101
  // EENGINE_GMAIL_FALLBACK_POLL_INTERVAL (ms) so integration tests can exercise the poller
102
102
  // without waiting the full interval.
103
- const FALLBACK_POLLING_INTERVAL = Number((process.env.EENGINE_GMAIL_FALLBACK_POLL_INTERVAL || '').toString().trim()) || 10 * 60 * 1000;
103
+ const FALLBACK_POLLING_INTERVAL = Number((readEnvValue('EENGINE_GMAIL_FALLBACK_POLL_INTERVAL') || '').toString().trim()) || 10 * 60 * 1000;
104
104
 
105
105
  /*
106
106
  Gmail API implementation status:
@@ -50,6 +50,7 @@ const {
50
50
  CONNECTION_CLOSING_CODES,
51
51
  DEFAULT_DOWNLOAD_CHUNK_SIZE,
52
52
  MAX_BACKOFF_DELAY,
53
+ SPECIAL_USE_PATH_TYPES,
53
54
  STABLE_CONNECTION_TIME,
54
55
  TLS_DEFAULTS
55
56
  } = require('../consts');
@@ -686,7 +687,7 @@ class IMAPClient extends BaseClient {
686
687
 
687
688
  // Build hints for special-use folders from account configuration
688
689
  let specialUseHints = {};
689
- for (let type of ['sent', 'drafts', 'junk', 'trash', 'archive']) {
690
+ for (let type of SPECIAL_USE_PATH_TYPES) {
690
691
  if (accountData.imap && accountData.imap[`${type}MailPath`]) {
691
692
  specialUseHints[type] = accountData.imap[`${type}MailPath`];
692
693
  }
@@ -445,7 +445,9 @@ class ProviderMessageIdHandler {
445
445
  }
446
446
 
447
447
  /**
448
- * Error code to description mapping for SMTP errors
448
+ * Error code to description mapping for SMTP errors. A code that is absent here, or whose entry
449
+ * returns nothing, falls back to the error's own message in buildStatus() - the table turns a
450
+ * known failure into a sentence an operator can act on, it does not decide what gets recorded.
449
451
  */
450
452
  const SMTP_ERROR_DESCRIPTIONS = {
451
453
  ESOCKET: (settings, err) => {
@@ -472,22 +474,19 @@ const SMTP_ERROR_DESCRIPTIONS = {
472
474
  */
473
475
  class SmtpErrorBuilder {
474
476
  /**
475
- * Builds SMTP status object from error
477
+ * Builds SMTP status object from error. Always produces a status: it used to return null for
478
+ * any error SMTP_ERROR_DESCRIPTIONS could not describe (a 5xx rejection arriving without the
479
+ * EENVELOPE marker, a nodemailer code added since the table was written), and the caller then
480
+ * left the gateway's lastError and the account's smtpStatus showing the previous attempt. The
481
+ * caller decides whether there is an SMTP attempt to describe at all.
476
482
  * @param {Error} err - The error that occurred
477
483
  * @param {Object} smtpSettings - SMTP settings for context
478
484
  * @param {Object} networkRouting - Network routing info
479
- * @returns {Object|null} SMTP status object or null
485
+ * @returns {Object} SMTP status object
480
486
  */
481
487
  static buildStatus(err, smtpSettings, networkRouting) {
482
488
  const descriptionBuilder = SMTP_ERROR_DESCRIPTIONS[err.code];
483
- if (!descriptionBuilder) {
484
- return null;
485
- }
486
-
487
- const description = descriptionBuilder(smtpSettings, err);
488
- if (!description) {
489
- return null;
490
- }
489
+ const description = (descriptionBuilder && descriptionBuilder(smtpSettings, err)) || err.message || 'Failed to send email';
491
490
 
492
491
  return {
493
492
  created: Date.now(),
@@ -570,7 +569,38 @@ class SentMailCopyDecider {
570
569
  }
571
570
  }
572
571
 
572
+ /**
573
+ * Merges a stored template into the message being queued.
574
+ *
575
+ * `render: false` is the documented way to send a template as-is, and the format carried by the
576
+ * template used to be applied with `data.render = data.render || {}`, which turned that explicit false
577
+ * into an empty options object - and an options object renders. So the one value that asked for no
578
+ * rendering was the one value that could not be expressed. Extracted from queueMessageHandler(),
579
+ * which a test cannot reach without a connection, an account record and a license answer.
580
+ *
581
+ * Mutates `data`, as the caller's own merge did.
582
+ *
583
+ * @param {Object} data - the message being queued, carrying `template` and optionally `render`
584
+ * @param {Object} templateData - the stored template
585
+ * @returns {Object} the same `data`
586
+ */
587
+ function applyTemplate(data, templateData) {
588
+ if (data.render !== false && templateData.content && templateData.content.html && templateData.format) {
589
+ data.render = data.render || {};
590
+ data.render.format = templateData.format;
591
+ }
592
+
593
+ for (let key of Object.keys(templateData.content || {})) {
594
+ data[key] = templateData.content[key];
595
+ }
596
+
597
+ delete data.template;
598
+
599
+ return data;
600
+ }
601
+
573
602
  module.exports = {
603
+ applyTemplate,
574
604
  SmtpConfigBuilder,
575
605
  NetworkRoutingBuilder,
576
606
  NotificationBuilder,