emailengine-app 2.77.0 → 2.79.0

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 (189) hide show
  1. package/.github/workflows/test.yml +80 -0
  2. package/.ncurc.js +23 -13
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +60 -0
  5. package/bin/emailengine.js +1 -1
  6. package/config/e2e.toml +2 -1
  7. package/config/test.toml +2 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +1 -1
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +145 -61
  12. package/lib/api-reference/format.js +105 -4
  13. package/lib/api-reference/index.js +24 -7
  14. package/lib/api-reference/model.js +148 -21
  15. package/lib/api-reference/schema-tree.js +282 -28
  16. package/lib/api-routes/account-routes.js +99 -36
  17. package/lib/api-routes/behavior-notes.js +3 -0
  18. package/lib/api-routes/blocklist-routes.js +21 -47
  19. package/lib/api-routes/chat-routes.js +10 -12
  20. package/lib/api-routes/delivery-test-routes.js +6 -26
  21. package/lib/api-routes/export-routes.js +2 -0
  22. package/lib/api-routes/gateway-routes.js +52 -11
  23. package/lib/api-routes/license-routes.js +2 -0
  24. package/lib/api-routes/mailbox-routes.js +29 -26
  25. package/lib/api-routes/message-routes.js +27 -21
  26. package/lib/api-routes/oauth2-app-routes.js +11 -29
  27. package/lib/api-routes/operation-impact.js +80 -0
  28. package/lib/api-routes/outbox-routes.js +15 -5
  29. package/lib/api-routes/permission-map.js +397 -0
  30. package/lib/api-routes/route-helpers.js +223 -9
  31. package/lib/api-routes/route-metadata.js +28 -0
  32. package/lib/api-routes/settings-routes.js +30 -25
  33. package/lib/api-routes/stats-routes.js +2 -2
  34. package/lib/api-routes/submit-routes.js +53 -31
  35. package/lib/api-routes/template-routes.js +3 -0
  36. package/lib/api-routes/token-routes.js +319 -33
  37. package/lib/api-routes/webhook-route-routes.js +14 -4
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/auth-token.js +80 -8
  41. package/lib/autodetect-imap-settings.js +40 -16
  42. package/lib/base32.js +30 -0
  43. package/lib/bounce-detect.js +182 -62
  44. package/lib/consts.js +10 -0
  45. package/lib/db.js +20 -2
  46. package/lib/delivery-error.js +30 -1
  47. package/lib/egress-filter.js +89 -8
  48. package/lib/email-client/base-client.js +35 -113
  49. package/lib/email-client/gmail-client.js +22 -13
  50. package/lib/email-client/imap/listing-diff.js +3 -3
  51. package/lib/email-client/imap/mailbox.js +28 -93
  52. package/lib/email-client/imap/subconnection.js +10 -7
  53. package/lib/email-client/imap/sync-operations.js +46 -46
  54. package/lib/email-client/imap-client.js +39 -28
  55. package/lib/email-client/message-builder.js +15 -15
  56. package/lib/email-client/notification-handler.js +1 -1
  57. package/lib/email-client/outlook/graph-api.js +10 -4
  58. package/lib/email-client/outlook-client.js +54 -55
  59. package/lib/email-client/smtp-pool-manager.js +1 -1
  60. package/lib/enum-descriptions.js +92 -2
  61. package/lib/export.js +2 -2
  62. package/lib/field-usage.js +133 -0
  63. package/lib/gateway.js +2 -2
  64. package/lib/get-raw-email.js +1 -1
  65. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  66. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  67. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  68. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  69. package/lib/imapproxy/imap-core/lib/imap-connection.js +17 -7
  70. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  71. package/lib/imapproxy/imap-server.js +40 -10
  72. package/lib/license-beacon.js +5 -10
  73. package/lib/lists.js +49 -1
  74. package/lib/llm-pre-process.js +6 -6
  75. package/lib/logger.js +5 -1
  76. package/lib/metrics-collector.js +2 -2
  77. package/lib/msgpack.js +62 -0
  78. package/lib/oauth/decode-jwt-payload.js +39 -0
  79. package/lib/oauth/gmail.js +9 -12
  80. package/lib/oauth/mail-ru.js +5 -7
  81. package/lib/oauth/outlook-identity.js +61 -0
  82. package/lib/oauth/outlook.js +9 -9
  83. package/lib/oauth/pubsub/google.js +25 -10
  84. package/lib/oauth/retry-setup.js +38 -0
  85. package/lib/oauth/scope-checker.js +1 -1
  86. package/lib/oauth2-apps.js +224 -295
  87. package/lib/openapi/build-document.js +15 -7
  88. package/lib/openapi/joi-schema.js +20 -0
  89. package/lib/outbox.js +145 -14
  90. package/lib/pre-process.js +9 -9
  91. package/lib/queue-stats.js +49 -0
  92. package/lib/read-env-value.js +37 -0
  93. package/lib/reconnection-manager.js +2 -2
  94. package/lib/rewrite-text-nodes.js +4 -3
  95. package/lib/routes-ui.js +4 -0
  96. package/lib/schemas.js +223 -155
  97. package/lib/settings.js +84 -5
  98. package/lib/sub-script.js +2 -1
  99. package/lib/swagger-options.js +2 -1
  100. package/lib/templates.js +5 -5
  101. package/lib/threads.js +2 -2
  102. package/lib/token-audit-log.js +208 -0
  103. package/lib/token-permission-view.js +219 -0
  104. package/lib/token-permissions.js +172 -0
  105. package/lib/tokens.js +100 -16
  106. package/lib/tools.js +259 -85
  107. package/lib/totp.js +67 -0
  108. package/lib/ui-routes/account-routes.js +122 -26
  109. package/lib/ui-routes/admin-config-routes.js +20 -17
  110. package/lib/ui-routes/admin-entities-routes.js +66 -22
  111. package/lib/ui-routes/auth-routes.js +36 -48
  112. package/lib/ui-routes/export-routes.js +10 -4
  113. package/lib/ui-routes/oauth-config-routes.js +5 -5
  114. package/lib/ui-routes/reference-routes.js +11 -8
  115. package/lib/ui-routes/route-helpers.js +79 -2
  116. package/lib/ui-routes/settings-page.js +1 -1
  117. package/lib/ui-routes/smtp-test-routes.js +1 -1
  118. package/lib/ui-routes/suppression-list-routes.js +294 -0
  119. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  120. package/lib/utils/is-email.js +34 -0
  121. package/lib/utils/network.js +2 -2
  122. package/lib/utils/to-camel-case.js +17 -0
  123. package/lib/web-safe-html.js +1 -1
  124. package/lib/webhook-egress.js +37 -0
  125. package/lib/webhook-routing.js +80 -0
  126. package/lib/webhooks.js +21 -15
  127. package/package.json +26 -27
  128. package/sbom.json +1 -0
  129. package/server.js +81 -42
  130. package/static/css/flyonui.css +1 -1
  131. package/static/css/public.css +3 -0
  132. package/static/css/src/app.tailwind.css +159 -9
  133. package/static/js/app.js +69 -0
  134. package/static/js/reference.js +741 -10
  135. package/static/js/ui.js +43 -0
  136. package/static/licenses.html +698 -1590
  137. package/translations/README.md +64 -0
  138. package/translations/de.mo +0 -0
  139. package/translations/de.po +164 -120
  140. package/translations/en.po +200 -161
  141. package/translations/et.mo +0 -0
  142. package/translations/et.po +163 -120
  143. package/translations/fr.mo +0 -0
  144. package/translations/fr.po +163 -120
  145. package/translations/ja.mo +0 -0
  146. package/translations/ja.po +163 -120
  147. package/translations/messages.pot +94 -64
  148. package/translations/nl.mo +0 -0
  149. package/translations/nl.po +164 -120
  150. package/translations/pl.mo +0 -0
  151. package/translations/pl.po +163 -120
  152. package/views/account-identity-error.hbs +34 -0
  153. package/views/accounts/account.hbs +69 -7
  154. package/views/accounts/browse.hbs +18 -35
  155. package/views/accounts/edit.hbs +1 -0
  156. package/views/accounts/register/imap.hbs +12 -2
  157. package/views/config/logging.hbs +6 -0
  158. package/views/config/oauth/app.hbs +0 -2
  159. package/views/config/security.hbs +13 -0
  160. package/views/layout/app.hbs +29 -5
  161. package/views/oauth-scope-error.hbs +1 -1
  162. package/views/partials/oauth_form.hbs +0 -15
  163. package/views/partials/reference/disclosure.hbs +8 -2
  164. package/views/partials/reference/nav.hbs +36 -9
  165. package/views/partials/reference/operation.hbs +48 -14
  166. package/views/partials/reference/params.hbs +17 -1
  167. package/views/partials/reference/schema-node.hbs +112 -54
  168. package/views/partials/reference/schema-tools.hbs +25 -0
  169. package/views/partials/reference/token-alert.hbs +35 -10
  170. package/views/partials/reference/try-it.hbs +84 -11
  171. package/views/partials/side_menu.hbs +1 -0
  172. package/views/partials/ui/checkbox.hbs +2 -2
  173. package/views/partials/ui/tabs.hbs +7 -1
  174. package/views/reference/index.hbs +1 -1
  175. package/views/reference/token.hbs +4 -0
  176. package/views/suppression-lists/index.hbs +85 -0
  177. package/views/suppression-lists/list.hbs +87 -0
  178. package/views/templates/index.hbs +8 -2
  179. package/views/tokens/index.hbs +31 -4
  180. package/views/tokens/new.hbs +324 -2
  181. package/workers/api.js +299 -140
  182. package/workers/documents.js +46 -26
  183. package/workers/export.js +20 -8
  184. package/workers/imap-proxy.js +2 -2
  185. package/workers/imap.js +13 -7
  186. package/workers/smtp.js +13 -7
  187. package/workers/submit.js +41 -31
  188. package/workers/webhooks.js +60 -37
  189. package/lib/feature-flags.js +0 -48
@@ -82,4 +82,33 @@ function shouldDiscardJob(err, job) {
82
82
  return isPermanentDeliveryError(err) && job.attemptsMade < job.opts.attempts;
83
83
  }
84
84
 
85
- module.exports = { NON_RETRYABLE_CODES, isPermanentDeliveryError, shouldDiscardJob };
85
+ // BullMQ increments job.attemptsMade when an attempt FAILS, not when it starts. The two helpers
86
+ // below encode that phase difference once, because getting it wrong by one is a recurring trap:
87
+ // inside a processor the ongoing attempt is attemptsMade + 1, while inside a worker 'failed' event
88
+ // handler the failed attempt is already counted. Used by the queue workers to decide whether a
89
+ // failure log is the final, operator-actionable record or a routine retryable attempt.
90
+
91
+ /**
92
+ * Inside a job processor: is the CURRENTLY RUNNING attempt the job's last one?
93
+ *
94
+ * @param {Object} job - BullMQ job (mid-processing, attemptsMade not yet incremented)
95
+ * @returns {Boolean} True when a failure of this attempt will not be retried
96
+ */
97
+ function willBeFinalAttempt(job) {
98
+ return job.attemptsMade + 1 >= (job.opts.attempts || 1);
99
+ }
100
+
101
+ /**
102
+ * Inside a worker 'failed' event handler: was the failure that just happened the job's last
103
+ * attempt? finishedOn covers a job ended by UnrecoverableError regardless of remaining attempts.
104
+ * (It used to also check `discarded`, for jobs ended by Job#discard(); BullMQ 6 removed both the
105
+ * method and the property, and UnrecoverableError is the replacement.)
106
+ *
107
+ * @param {Object} job - BullMQ job (attemptsMade already incremented for the failed attempt)
108
+ * @returns {Boolean} True when nothing will be retried and the job is finished for good
109
+ */
110
+ function isFinalFailedAttempt(job) {
111
+ return !!job.finishedOn || job.attemptsMade >= (job.opts.attempts || 1);
112
+ }
113
+
114
+ module.exports = { NON_RETRYABLE_CODES, isPermanentDeliveryError, shouldDiscardJob, willBeFinalAttempt, isFinalFailedAttempt };
@@ -9,6 +9,11 @@ const ipaddr = require('ipaddr.js');
9
9
  // blocking private ranges outright would break ordinary deployments - the default therefore only
10
10
  // blocks the link-local range, which is where every cloud provider parks its instance metadata
11
11
  // service and which no real webhook receiver lives on.
12
+ //
13
+ // Scope: this is a guardrail against misconfiguration and mistakes, not a boundary against a
14
+ // hostile operator. Anyone who can set a webhook target can generally also author fn/map scripts,
15
+ // which lib/sub-script.js runs with full server privileges and hands an unfiltered fetch. Do not
16
+ // treat the policy as tenant isolation.
12
17
  const POLICY_OFF = 'off';
13
18
  const POLICY_LINK_LOCAL = 'link-local';
14
19
  const POLICY_PRIVATE = 'private';
@@ -108,9 +113,10 @@ const policyBlockedError = reason => blockedError(`${reason}. ${POLICY_HINT}`);
108
113
  // and the notify worker runs at concurrency 1 by default, so that cost is fully serialized ahead
109
114
  // of each POST. Caching the verdict rather than the addresses keeps entries tiny.
110
115
  //
111
- // This gives up nothing: undici resolves the name again independently when it connects, so the
112
- // check is inherently time-of-check/time-of-use racy and a short TTL introduces no hole that was
113
- // not already there. Distinct webhook targets are few, so the hit rate is effectively total.
116
+ // A stale verdict opens no hole. This pre-check exists to refuse a bad destination early and with
117
+ // an error worth reading; the binding decision is made by createEgressLookup() at connect time,
118
+ // against the very addresses the socket is opened to. Distinct webhook targets are few, so the hit
119
+ // rate is effectively total.
114
120
  const VERDICT_TTL = 60 * 1000;
115
121
  const VERDICT_CACHE_LIMIT = 1000;
116
122
  const verdictCache = new Map();
@@ -138,12 +144,36 @@ function cacheVerdict(key, blockedBy) {
138
144
  verdictCache.set(key, { blockedBy, expires: Date.now() + VERDICT_TTL });
139
145
  }
140
146
 
147
+ /**
148
+ * Finds the first address in a resolver answer that the policy refuses.
149
+ *
150
+ * A name is judged by its whole answer, not by whichever record the resolver happened to order
151
+ * first: one that hands back a mix of permitted and blocked addresses is not one to reach under
152
+ * any of them.
153
+ *
154
+ * @param {Array} addresses - Resolver answer, in the shape dns.lookup(host, {all: true}) returns
155
+ * @param {string} policy - One of the POLICY_* constants
156
+ * @returns {string|null} The offending address, or null when every address is permitted
157
+ */
158
+ function findBlockedAddress(addresses, policy) {
159
+ for (let { address } of addresses || []) {
160
+ if (isBlockedAddress(address, policy)) {
161
+ return address;
162
+ }
163
+ }
164
+ return null;
165
+ }
166
+
141
167
  /**
142
168
  * Verifies that a URL may be contacted under the given egress policy.
143
169
  *
144
170
  * Hostnames are resolved and every returned address is checked, so a name that points at a
145
171
  * blocked address is rejected just like a literal would be.
146
172
  *
173
+ * This is the early, human-facing half of the guard: it fails a bad destination before the request
174
+ * is built and names the reason. It is not the half that binds - see createEgressLookup(), which
175
+ * enforces the same policy against the addresses actually connected to.
176
+ *
147
177
  * @param {string} url - Destination URL
148
178
  * @param {Object} [opts]
149
179
  * @param {string} [opts.policy] - One of the POLICY_* constants, defaults to the link-local policy
@@ -197,18 +227,69 @@ async function assertAllowedUrl(url, opts) {
197
227
  return;
198
228
  }
199
229
 
200
- for (let { address } of addresses) {
201
- if (isBlockedAddress(address, policy)) {
202
- cacheVerdict(cacheKey, address);
203
- throw policyBlockedError(`Refusing to deliver to ${hostname}, it resolves to a blocked address (${address})`);
204
- }
230
+ // Compared against null, not for truthiness: isBlockedAddress fails closed on a value it
231
+ // cannot parse, including an empty string, and that verdict has to survive the return trip.
232
+ const blocked = findBlockedAddress(addresses, policy);
233
+ if (blocked !== null) {
234
+ cacheVerdict(cacheKey, blocked);
235
+ throw policyBlockedError(`Refusing to deliver to ${hostname}, it resolves to a blocked address (${blocked})`);
205
236
  }
206
237
 
207
238
  cacheVerdict(cacheKey, null);
208
239
  }
209
240
 
241
+ /**
242
+ * Builds a Node-compatible `lookup` implementation that applies an egress policy at the moment of
243
+ * connection.
244
+ *
245
+ * `assertAllowedUrl()` can only vet the addresses it resolved itself, and undici resolves the
246
+ * hostname again when it connects. A name that answers differently between the two lookups is
247
+ * therefore checked as one address and connected to as another - deliberately, in a DNS rebinding
248
+ * setup, but equally by accident behind a short TTL or a round-robin record. Handing this function
249
+ * to an undici Agent as `connect: { lookup }` collapses check and use into a single step: the
250
+ * addresses returned here are the addresses the socket is opened to, so no window remains between
251
+ * the two.
252
+ *
253
+ * Only names reach this: net.connect skips the lookup when the host is already an IP. That is the
254
+ * whole story for literals anyway, since an address cannot change between being checked by
255
+ * assertAllowedUrl() and being connected to.
256
+ *
257
+ * @param {string} [policy] - One of the POLICY_* constants, defaults to the link-local policy
258
+ * @param {Object} [opts]
259
+ * @param {Function} [opts.resolve] - Injectable resolver returning [{address, family}], defaults to dns.lookup
260
+ * @returns {Function} lookup(hostname, options, callback), in the shape net.connect expects
261
+ */
262
+ function createEgressLookup(policy, opts) {
263
+ const resolvedPolicy = normalizePolicy(policy);
264
+ const { resolve = dns.lookup } = opts || {};
265
+
266
+ return (hostname, options, callback) => {
267
+ // Forwarded as given, plus `all`, which autoSelectFamily (Happy Eyeballs, on by default
268
+ // since Node 20) already asks for anyway. Forcing it means every address gets classified,
269
+ // not just the one the resolver happened to order first.
270
+ resolve(hostname, Object.assign({}, options, { all: true })).then(addresses => {
271
+ if (!addresses || !addresses.length) {
272
+ let err = new Error(`Could not resolve ${hostname}`);
273
+ err.code = 'ENOTFOUND';
274
+ return callback(err);
275
+ }
276
+
277
+ const blocked = findBlockedAddress(addresses, resolvedPolicy);
278
+ if (blocked !== null) {
279
+ return callback(policyBlockedError(`Refusing to connect to ${hostname}, it resolves to a blocked address (${blocked})`));
280
+ }
281
+
282
+ if (options.all) {
283
+ return callback(null, addresses);
284
+ }
285
+ callback(null, addresses[0].address, addresses[0].family);
286
+ }, callback);
287
+ };
288
+ }
289
+
210
290
  module.exports = {
211
291
  assertAllowedUrl,
292
+ createEgressLookup,
212
293
  isBlockedAddress,
213
294
  normalizePolicy,
214
295
  // Exported so tests can start from a known state; nothing in production clears the cache,
@@ -5,7 +5,7 @@ const crypto = require('crypto');
5
5
  const logger = require('../logger');
6
6
  const settings = require('../settings');
7
7
  const { isDocumentStoreEnabled } = require('../document-store');
8
- const msgpack = require('msgpack5')();
8
+ const msgpack = require('../msgpack');
9
9
  const { templates } = require('../templates');
10
10
  const { Gateway } = require('../gateway');
11
11
  const os = require('os');
@@ -17,11 +17,11 @@ const { addTrackers } = require('../add-trackers');
17
17
  const { getRawEmail } = require('../get-raw-email');
18
18
  const { getTemplate } = require('@postalsys/templates');
19
19
  const { deepEqual } = require('assert');
20
- const { arfDetect } = require('../arf-detect');
20
+ const { arfDetect, camelCaseComplaint } = require('../arf-detect');
21
21
  const { createTransaction } = require('../redis-operations');
22
22
  const simpleParser = require('mailparser').simpleParser;
23
23
  const libmime = require('libmime');
24
- const { bounceDetect } = require('../bounce-detect');
24
+ const { bounceDetect, applyDeliveryReport } = require('../bounce-detect');
25
25
  const ical = require('ical.js');
26
26
  const { llmPreProcess } = require('../llm-pre-process');
27
27
  const { oauth2Apps } = require('../oauth2-apps');
@@ -40,7 +40,7 @@ const { getMailTransport } = require('./smtp-pool-manager');
40
40
 
41
41
  // Import various utility functions and constants
42
42
  const {
43
- getSignedFormDataSync,
43
+ buildUnsubscribeUrl,
44
44
  getServiceSecret,
45
45
  convertDataUrisToAttachments,
46
46
  genBaseBoundary,
@@ -50,7 +50,8 @@ const {
50
50
  emitChangeEvent,
51
51
  filterEmptyObjectValues,
52
52
  getDateBuckets,
53
- resolveCredentials
53
+ resolveCredentials,
54
+ useAuthServerForOAuth2
54
55
  } = require('../tools');
55
56
 
56
57
  // Import application constants
@@ -157,7 +158,7 @@ async function retryOnTransientError(fn, options = {}) {
157
158
  attempt,
158
159
  maxAttempts,
159
160
  delay,
160
- err: err.message,
161
+ err,
161
162
  statusCode: err.statusCode || err.oauthRequest?.status
162
163
  });
163
164
  }
@@ -500,7 +501,7 @@ class BaseClient {
500
501
  );
501
502
  await disableTxn.exec();
502
503
 
503
- this.logger.info({
504
+ this.logger.warn({
504
505
  msg: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
505
506
  errorEvent: event,
506
507
  firstError: firstError.toISOString(),
@@ -581,7 +582,7 @@ class BaseClient {
581
582
  // An external authentication server owns this account's tokens, so EmailEngine must ask for
582
583
  // one instead of renewing from a stored refresh token (it has none). The app is still
583
584
  // resolved above, because the caller needs it for the provider's host and port.
584
- if (accountData.oauth2.useAuthServer) {
585
+ if (await useAuthServerForOAuth2(accountData.oauth2, ctx.logger, { account: accountObject.account, target })) {
585
586
  try {
586
587
  let authData = await resolveCredentials(accountObject.account, target);
587
588
  // The auth server owns the credentials, but a shared mailbox is still addressed by
@@ -596,7 +597,7 @@ class BaseClient {
596
597
  // rejected credential. Reporting it as an authentication error would webhook every
597
598
  // account on the instance and park them in an error state over a brief blip.
598
599
  if (isTransientNetworkError(err)) {
599
- ctx.logger.error({
600
+ ctx.logger.warn({
600
601
  msg: 'Network error while resolving credentials from the authentication server',
601
602
  account: accountObject.account,
602
603
  target,
@@ -634,7 +635,7 @@ class BaseClient {
634
635
  } catch (err) {
635
636
  // Transient network errors are not authentication failures
636
637
  if (isTransientNetworkError(err)) {
637
- ctx.logger.error({
638
+ ctx.logger.warn({
638
639
  msg: 'Network error during OAuth2 token refresh',
639
640
  account: accountObject.account,
640
641
  code: err.code,
@@ -653,7 +654,8 @@ class BaseClient {
653
654
  notifyData.tokenRequest = err.tokenRequest;
654
655
  }
655
656
  await ctx.notify(false, AUTH_ERROR_NOTIFY, notifyData);
656
- ctx.logger.error({
657
+ ctx.logger.warn({
658
+ msg: 'Failed to renew OAuth2 access token',
657
659
  account: accountObject.account,
658
660
  err
659
661
  });
@@ -662,11 +664,10 @@ class BaseClient {
662
664
  }
663
665
  } else {
664
666
  // Use cached token
665
- this.logger.info({
667
+ this.logger.debug({
666
668
  msg: 'Using cached OAuth2 access token',
667
669
  action: 'ensureAccessToken',
668
670
  target,
669
- error: null,
670
671
  user: accountData.oauth2.auth.user,
671
672
  expires: accountData.oauth2.expires,
672
673
  scopes: accountData.oauth2.scope,
@@ -951,7 +952,7 @@ class BaseClient {
951
952
  try {
952
953
  gatewayData = await gatewayObject.loadGatewayData();
953
954
  } catch (err) {
954
- this.logger.info({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
955
+ this.logger.warn({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
955
956
  }
956
957
  }
957
958
 
@@ -1200,7 +1201,7 @@ class BaseClient {
1200
1201
  this.logger.warn({
1201
1202
  msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
1202
1203
  messageId: data.reference.message,
1203
- err: err.message,
1204
+ err,
1204
1205
  statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
1205
1206
  });
1206
1207
  referencedMessage = null;
@@ -1402,7 +1403,7 @@ class BaseClient {
1402
1403
  if (attachmentsToDownload && attachmentsToDownload.length) {
1403
1404
  this.checkIMAPConnection(connectionOptions);
1404
1405
 
1405
- this.logger.info({
1406
+ this.logger.debug({
1406
1407
  msg: 'Fetching attachments from the referenced email',
1407
1408
  attachments: attachmentsToDownload.map(a => ({ id: a.id, hasContent: !!a.content }))
1408
1409
  });
@@ -1566,8 +1567,6 @@ class BaseClient {
1566
1567
  baseDomain = baseDomain || (os.hostname() || '').toLowerCase().trim() || 'localhost';
1567
1568
 
1568
1569
  if (baseDomain) {
1569
- let unsubscribeUrlObj = new URL('/unsubscribe', baseUrl);
1570
-
1571
1570
  const serviceSecret = await getServiceSecret();
1572
1571
 
1573
1572
  let fromDomain = ((data.from && data.from.address) || '').split('@').pop().trim().toLowerCase() || baseDomain;
@@ -1584,24 +1583,14 @@ class BaseClient {
1584
1583
  }
1585
1584
 
1586
1585
  // Create signed unsubscribe URL
1587
- let { data: signedData, signature } = getSignedFormDataSync(
1588
- serviceSecret,
1589
- {
1590
- act: 'unsub',
1591
- acc: accountData.account,
1592
- list: data.listId,
1593
- rcpt: data.to[0].address,
1594
- msg: data.messageId
1595
- },
1596
- true
1597
- );
1598
-
1599
- unsubscribeUrlObj.searchParams.append('data', signedData);
1600
- if (signature) {
1601
- unsubscribeUrlObj.searchParams.append('sig', signature);
1602
- }
1586
+ let unsubscribeUrl = buildUnsubscribeUrl(serviceSecret, baseUrl, {
1587
+ account: accountData.account,
1588
+ list: data.listId,
1589
+ recipient: data.to[0].address,
1590
+ messageId: data.messageId
1591
+ });
1603
1592
 
1604
- context.rcpt = Object.assign({}, data.to[0], { unsubscribeUrl: unsubscribeUrlObj.href });
1593
+ context.rcpt = Object.assign({}, data.to[0], { unsubscribeUrl });
1605
1594
 
1606
1595
  // Add RFC 8058 compliant unsubscribe headers
1607
1596
  data.headers['List-Unsubscribe'] = `<${context.rcpt.unsubscribeUrl}>`;
@@ -1632,7 +1621,7 @@ class BaseClient {
1632
1621
  try {
1633
1622
  data.text = htmlToText(data.html);
1634
1623
  } catch (err) {
1635
- this.logger.error({ msg: 'Failed to generate plaintext content from html', err });
1624
+ this.logger.warn({ msg: 'Failed to generate plaintext content from html', err });
1636
1625
  }
1637
1626
  }
1638
1627
 
@@ -1704,7 +1693,7 @@ class BaseClient {
1704
1693
  this.logger.warn({
1705
1694
  msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
1706
1695
  messageId: data.reference.message,
1707
- err: err.message,
1696
+ err,
1708
1697
  statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
1709
1698
  });
1710
1699
  referencedMessage = null;
@@ -1917,7 +1906,7 @@ class BaseClient {
1917
1906
  if (attachmentsToDownload && attachmentsToDownload.length) {
1918
1907
  this.checkIMAPConnection(connectionOptions);
1919
1908
 
1920
- this.logger.info({
1909
+ this.logger.debug({
1921
1910
  msg: 'Fetching attachments from the referenced email',
1922
1911
  attachments: attachmentsToDownload.map(a => ({ id: a.id, hasContent: !!a.content }))
1923
1912
  });
@@ -2024,7 +2013,7 @@ class BaseClient {
2024
2013
  try {
2025
2014
  gatewayData = await gatewayObject.loadGatewayData();
2026
2015
  } catch (err) {
2027
- this.logger.info({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
2016
+ this.logger.warn({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
2028
2017
  }
2029
2018
  }
2030
2019
 
@@ -2249,7 +2238,7 @@ class BaseClient {
2249
2238
  try {
2250
2239
  gatewayData = await gatewayObject.loadGatewayData();
2251
2240
  } catch (err) {
2252
- this.logger.info({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
2241
+ this.logger.warn({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
2253
2242
  }
2254
2243
  }
2255
2244
 
@@ -2320,7 +2309,7 @@ class BaseClient {
2320
2309
 
2321
2310
  return compiledTemplate(data);
2322
2311
  } catch (err) {
2323
- logger.error({ msg: `Failed rendering ${key} template`, err });
2312
+ this.logger.error({ msg: 'Failed to render template', templateKey: key, err });
2324
2313
  let error = new Error(`Failed rendering ${key} template`);
2325
2314
  error.code = err.code || 'SubmitFail';
2326
2315
  error.statusCode = 422;
@@ -2457,17 +2446,7 @@ class BaseClient {
2457
2446
 
2458
2447
  if (report && report.arf && report.arf['original-rcpt-to'] && report.arf['original-rcpt-to'].length) {
2459
2448
  // can send report
2460
- let complaint = {};
2461
-
2462
- // Convert headers to camelCase
2463
- for (let subKey of ['arf', 'headers']) {
2464
- for (let key of Object.keys(report[subKey])) {
2465
- if (!complaint[subKey]) {
2466
- complaint[subKey] = {};
2467
- }
2468
- complaint[subKey][key.replace(/-(.)/g, (o, c) => c.toUpperCase())] = report[subKey][key];
2469
- }
2470
- }
2449
+ let complaint = camelCaseComplaint(report);
2471
2450
 
2472
2451
  complaintNotifyInfo = Object.assign({ complaintMessage: messageData.id }, complaint);
2473
2452
 
@@ -2497,62 +2476,7 @@ class BaseClient {
2497
2476
  let parsed = await simpleParser(raw, { keepDeliveryStatus: true });
2498
2477
  if (parsed) {
2499
2478
  content = { parsed };
2500
-
2501
- // Extract delivery status attachment
2502
- let deliveryStatus = parsed.attachments.find(attachment => attachment.contentType === 'message/delivery-status');
2503
- if (deliveryStatus) {
2504
- let deliveryEntries = libmime.decodeHeaders((deliveryStatus.content || '').toString().trim());
2505
- let structured = {};
2506
-
2507
- // Parse delivery status fields
2508
- for (let key of Object.keys(deliveryEntries)) {
2509
- if (!key) {
2510
- continue;
2511
- }
2512
- let displayKey = key.replace(/-(.)/g, (m, c) => c.toUpperCase());
2513
- let value = deliveryEntries[key].at(-1);
2514
- if (typeof value === 'string') {
2515
- // Parse structured fields
2516
- let m = value.match(/^([^\s;]+);/);
2517
- if (m) {
2518
- value = {
2519
- label: m[1],
2520
- value: value.substring(m[0].length).trim()
2521
- };
2522
- } else {
2523
- switch (key) {
2524
- case 'arrival-date': {
2525
- value.trim();
2526
- let date = new Date(value);
2527
- if (date.toString() !== 'Invalid Date') {
2528
- value = date.toISOString();
2529
- }
2530
- structured[displayKey] = value;
2531
- break;
2532
- }
2533
- default:
2534
- structured[displayKey] = value.trim();
2535
- }
2536
- }
2537
- } else {
2538
- // ???
2539
- structured[displayKey] = value;
2540
- }
2541
- }
2542
-
2543
- // Check if this is a delivery or delay notification
2544
- if (/^delivered|^delayed/i.test(structured.action)) {
2545
- this.logger.debug({
2546
- msg: 'Detected delivery report',
2547
- id: messageData.id,
2548
- uid: messageData.uid,
2549
- messageId: messageData.messageId,
2550
- report: structured
2551
- });
2552
-
2553
- messageData.deliveryReport = structured;
2554
- }
2555
- }
2479
+ applyDeliveryReport(parsed, messageData, this.logger);
2556
2480
  }
2557
2481
  } catch (err) {
2558
2482
  this.logger.error({
@@ -2599,7 +2523,7 @@ class BaseClient {
2599
2523
  }
2600
2524
  } catch (err) {
2601
2525
  // ignore, just do not include this information
2602
- this.logger.error({
2526
+ this.logger.warn({
2603
2527
  msg: 'Failed to classify bounce response',
2604
2528
  bounceResponse: bounce?.response?.message,
2605
2529
  err
@@ -2607,7 +2531,6 @@ class BaseClient {
2607
2531
  }
2608
2532
  }
2609
2533
 
2610
- let stored = 0;
2611
2534
  if (bounce.action && bounce.recipient && bounce.messageId) {
2612
2535
  bounceNotifyInfo = Object.assign({ bounceMessage: messageData.id }, bounce);
2613
2536
 
@@ -2620,8 +2543,7 @@ class BaseClient {
2620
2543
  id: messageData.id,
2621
2544
  uid: messageData.uid,
2622
2545
  messageId: messageData.messageId,
2623
- bounce,
2624
- stored
2546
+ bounce
2625
2547
  });
2626
2548
  }
2627
2549
  } catch (err) {
@@ -2889,7 +2811,7 @@ class BaseClient {
2889
2811
  time: Date.now()
2890
2812
  })
2891
2813
  );
2892
- this.logger.error({ msg: 'Failed to fetch embeddings OpenAI', err });
2814
+ this.logger.error({ msg: 'Failed to fetch embeddings from OpenAI', err });
2893
2815
  }
2894
2816
  }
2895
2817
  }
@@ -4,13 +4,13 @@ const { Account } = require('../account');
4
4
  const { oauth2Apps } = require('../oauth2-apps');
5
5
  const { checkAccountScopes, isSendOnlyByScopes } = require('../oauth/scope-checker');
6
6
  const getSecret = require('../get-secret');
7
- const msgpack = require('msgpack5')();
7
+ const msgpack = require('../msgpack');
8
8
  const addressparser = require('nodemailer/lib/addressparser');
9
9
  const libmime = require('libmime');
10
10
  const he = require('he');
11
11
  const { BaseClient, metricsMeta } = require('./base-client');
12
12
  const { messageWebSafeHtml } = require('../web-safe-html');
13
- const { emitChangeEvent } = require('../tools');
13
+ const { emitChangeEvent, toCamelCase } = require('../tools');
14
14
  const { Gateway } = require('../gateway');
15
15
 
16
16
  const {
@@ -320,7 +320,7 @@ class GmailClient extends BaseClient {
320
320
  // Reload account data after getting access token to ensure we have the latest OAuth2 scopes
321
321
  accountData = await this.accountObject.loadAccountData(this.account);
322
322
  } catch (err) {
323
- this.logger.error({
323
+ this.logger.warn({
324
324
  msg: 'Failed to get token or reload account data during init',
325
325
  account: this.account,
326
326
  err
@@ -333,7 +333,7 @@ class GmailClient extends BaseClient {
333
333
  const { hasSendScope, hasReadScope } = checkAccountScopes('gmail', scopes);
334
334
  const isSendOnly = hasSendScope && !hasReadScope;
335
335
 
336
- this.logger.info({
336
+ this.logger.debug({
337
337
  msg: 'Account scopes loaded',
338
338
  account: this.account,
339
339
  scopes,
@@ -412,7 +412,7 @@ class GmailClient extends BaseClient {
412
412
  }
413
413
  } catch (err) {
414
414
  // not very important if succeeds or not
415
- this.logger.error({
415
+ this.logger.warn({
416
416
  msg: 'Failed to resolve locale for account',
417
417
  err
418
418
  });
@@ -470,7 +470,7 @@ class GmailClient extends BaseClient {
470
470
  this.state = 'connected';
471
471
  await this.setStateVal();
472
472
 
473
- let isiInitial = !!isFirstSuccessfulConnection;
473
+ let isInitial = !!isFirstSuccessfulConnection;
474
474
 
475
475
  if (!isFirstSuccessfulConnection) {
476
476
  // check if the connection was previously in an errored state
@@ -491,12 +491,12 @@ class GmailClient extends BaseClient {
491
491
 
492
492
  // Send appropriate authentication success notification
493
493
  if (isFirstSuccessfulConnection) {
494
- this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isiInitial, prevActive: false });
494
+ this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isInitial, prevActive: false });
495
495
  await this.notify(false, AUTH_SUCCESS_NOTIFY, {
496
496
  user: accountData.oauth2?.auth?.user
497
497
  });
498
498
  } else {
499
- this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, isiInitial, prevActive: true });
499
+ this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, isInitial, prevActive: true });
500
500
  }
501
501
 
502
502
  // Clear any previous error state
@@ -1603,7 +1603,7 @@ class GmailClient extends BaseClient {
1603
1603
  draftId = listing?.drafts?.find(draftEntry => draftEntry?.message?.id === emailId)?.id || null;
1604
1604
  } catch (err) {
1605
1605
  // draft id resolution is best effort - fall back to sending the raw copy
1606
- this.logger.info({ msg: 'Failed to resolve Gmail draft id', emailId, err });
1606
+ this.logger.warn({ msg: 'Failed to resolve Gmail draft id', emailId, err });
1607
1607
  }
1608
1608
  }
1609
1609
 
@@ -1642,7 +1642,7 @@ class GmailClient extends BaseClient {
1642
1642
  try {
1643
1643
  gatewayData = await gatewayObject.loadGatewayData();
1644
1644
  } catch (err) {
1645
- this.logger.info({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
1645
+ this.logger.warn({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
1646
1646
  }
1647
1647
  }
1648
1648
 
@@ -2074,7 +2074,7 @@ class GmailClient extends BaseClient {
2074
2074
  const timeSinceNotification = Date.now() - (this.lastNotificationTime || 0);
2075
2075
  if (timeSinceNotification >= FALLBACK_POLLING_INTERVAL) {
2076
2076
  // No notifications received within the interval, do a proactive sync
2077
- this.logger.info({
2077
+ this.logger.debug({
2078
2078
  msg: 'No Pub/Sub notifications received, triggering fallback sync',
2079
2079
  account: this.account,
2080
2080
  timeSinceNotification
@@ -2292,7 +2292,7 @@ class GmailClient extends BaseClient {
2292
2292
  for (let header of messageData.payload.headers.filter(header => header.name.toLowerCase() === key)) {
2293
2293
  let parsed = addressparser(header.value, { flatten: true });
2294
2294
 
2295
- let envelopekey = key.toLowerCase().replace(/-(.)/g, (o, c) => c.toUpperCase());
2295
+ let envelopekey = toCamelCase(key.toLowerCase());
2296
2296
 
2297
2297
  envelope[envelopekey] = [].concat(envelope[envelopekey] || []).concat(parsed || []);
2298
2298
  }
@@ -3085,7 +3085,16 @@ class GmailClient extends BaseClient {
3085
3085
  lastHistoryId = historyEntryId;
3086
3086
  }
3087
3087
  } catch (err) {
3088
- this.logger.error({ msg: 'Failed to process history entry', account: this.account, entry, err });
3088
+ this.logger.error({
3089
+ msg: 'Failed to process history entry',
3090
+ account: this.account,
3091
+ entryId: entry?.id,
3092
+ messagesAdded: entry?.messagesAdded?.length,
3093
+ messagesDeleted: entry?.messagesDeleted?.length,
3094
+ labelsAdded: entry?.labelsAdded?.length,
3095
+ labelsRemoved: entry?.labelsRemoved?.length,
3096
+ err
3097
+ });
3089
3098
  }
3090
3099
  }
3091
3100
 
@@ -12,7 +12,7 @@
12
12
  // Folder paths are compared through normalizePath(), which case-folds INBOX so a server that
13
13
  // reports "Inbox" one pass and "INBOX" the next does not look like a delete plus an add.
14
14
 
15
- const msgpack = require('msgpack5')();
15
+ const msgpack = require('../../msgpack');
16
16
  const { normalizePath } = require('../../tools');
17
17
  const { STORED_MAILBOX_FIELDS } = require('../../consts');
18
18
 
@@ -26,8 +26,8 @@ const COMPARED_MAILBOX_FIELDS = STORED_MAILBOX_FIELDS.filter(field => field !==
26
26
  * value is unusable. Callers drop a false entry rather than failing: a single corrupt value must
27
27
  * not take down the sync (or the mailboxes API response) for every other folder in the account.
28
28
  *
29
- * The shape check is not redundant with the try/catch. msgpack5 only throws on input it can not
30
- * parse at all - a corrupt buffer whose first byte happens to be a valid type marker decodes to
29
+ * The shape check is not redundant with the try/catch. The msgpack decoder only throws on input
30
+ * it can not parse at all - a corrupt buffer whose first byte is a valid type marker decodes to
31
31
  * a plain number or string instead. Such an entry has no `path`, so downstream it would register
32
32
  * as a phantom mailbox keyed `undefined` and (via Object.assign onto a primitive) surface as a
33
33
  * boxed Number in the mailboxes API response.