emailengine-app 2.78.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 (142) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +29 -0
  4. package/config/e2e.toml +2 -1
  5. package/config/test.toml +2 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +70 -35
  8. package/lib/api-reference/format.js +91 -4
  9. package/lib/api-reference/model.js +144 -19
  10. package/lib/api-reference/schema-tree.js +282 -28
  11. package/lib/api-routes/account-routes.js +80 -34
  12. package/lib/api-routes/blocklist-routes.js +21 -47
  13. package/lib/api-routes/chat-routes.js +10 -12
  14. package/lib/api-routes/delivery-test-routes.js +6 -26
  15. package/lib/api-routes/export-routes.js +2 -0
  16. package/lib/api-routes/gateway-routes.js +52 -11
  17. package/lib/api-routes/license-routes.js +2 -0
  18. package/lib/api-routes/mailbox-routes.js +29 -26
  19. package/lib/api-routes/message-routes.js +27 -21
  20. package/lib/api-routes/oauth2-app-routes.js +11 -29
  21. package/lib/api-routes/operation-impact.js +80 -0
  22. package/lib/api-routes/outbox-routes.js +15 -5
  23. package/lib/api-routes/permission-map.js +397 -0
  24. package/lib/api-routes/route-helpers.js +223 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +30 -25
  27. package/lib/api-routes/stats-routes.js +2 -2
  28. package/lib/api-routes/submit-routes.js +53 -31
  29. package/lib/api-routes/template-routes.js +3 -0
  30. package/lib/api-routes/token-routes.js +319 -33
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/auth-token.js +80 -8
  33. package/lib/consts.js +10 -0
  34. package/lib/db.js +20 -2
  35. package/lib/delivery-error.js +30 -1
  36. package/lib/email-client/base-client.js +27 -41
  37. package/lib/email-client/gmail-client.js +19 -10
  38. package/lib/email-client/imap/mailbox.js +23 -24
  39. package/lib/email-client/imap/subconnection.js +10 -7
  40. package/lib/email-client/imap/sync-operations.js +46 -46
  41. package/lib/email-client/imap-client.js +36 -26
  42. package/lib/email-client/message-builder.js +3 -3
  43. package/lib/email-client/notification-handler.js +1 -1
  44. package/lib/email-client/outlook/graph-api.js +10 -4
  45. package/lib/email-client/outlook-client.js +53 -54
  46. package/lib/email-client/smtp-pool-manager.js +1 -1
  47. package/lib/enum-descriptions.js +92 -2
  48. package/lib/export.js +1 -1
  49. package/lib/field-usage.js +133 -0
  50. package/lib/gateway.js +1 -1
  51. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  52. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  53. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  54. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  55. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  56. package/lib/imapproxy/imap-server.js +27 -7
  57. package/lib/license-beacon.js +4 -9
  58. package/lib/lists.js +49 -1
  59. package/lib/llm-pre-process.js +5 -5
  60. package/lib/logger.js +5 -1
  61. package/lib/metrics-collector.js +2 -2
  62. package/lib/oauth/gmail.js +9 -12
  63. package/lib/oauth/mail-ru.js +5 -7
  64. package/lib/oauth/outlook.js +9 -9
  65. package/lib/oauth/pubsub/google.js +25 -10
  66. package/lib/oauth/scope-checker.js +1 -1
  67. package/lib/oauth2-apps.js +223 -294
  68. package/lib/openapi/build-document.js +15 -7
  69. package/lib/openapi/joi-schema.js +20 -0
  70. package/lib/outbox.js +85 -17
  71. package/lib/pre-process.js +8 -8
  72. package/lib/queue-stats.js +49 -0
  73. package/lib/read-env-value.js +1 -1
  74. package/lib/reconnection-manager.js +2 -2
  75. package/lib/rewrite-text-nodes.js +4 -3
  76. package/lib/routes-ui.js +4 -0
  77. package/lib/schemas.js +216 -160
  78. package/lib/settings.js +84 -5
  79. package/lib/sub-script.js +2 -1
  80. package/lib/swagger-options.js +2 -1
  81. package/lib/templates.js +4 -4
  82. package/lib/threads.js +2 -2
  83. package/lib/token-audit-log.js +208 -0
  84. package/lib/token-permission-view.js +219 -0
  85. package/lib/token-permissions.js +172 -0
  86. package/lib/tokens.js +99 -15
  87. package/lib/tools.js +142 -37
  88. package/lib/ui-routes/account-routes.js +31 -11
  89. package/lib/ui-routes/admin-config-routes.js +18 -10
  90. package/lib/ui-routes/admin-entities-routes.js +66 -22
  91. package/lib/ui-routes/auth-routes.js +30 -24
  92. package/lib/ui-routes/export-routes.js +10 -4
  93. package/lib/ui-routes/oauth-config-routes.js +5 -5
  94. package/lib/ui-routes/reference-routes.js +3 -3
  95. package/lib/ui-routes/route-helpers.js +51 -2
  96. package/lib/ui-routes/settings-page.js +1 -1
  97. package/lib/ui-routes/smtp-test-routes.js +1 -1
  98. package/lib/ui-routes/suppression-list-routes.js +294 -0
  99. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  100. package/lib/utils/network.js +2 -2
  101. package/lib/web-safe-html.js +1 -1
  102. package/lib/webhook-routing.js +80 -0
  103. package/lib/webhooks.js +20 -14
  104. package/package.json +11 -10
  105. package/sbom.json +1 -1
  106. package/server.js +80 -41
  107. package/static/css/flyonui.css +1 -1
  108. package/static/css/src/app.tailwind.css +136 -9
  109. package/static/js/reference.js +456 -10
  110. package/static/js/ui.js +43 -0
  111. package/static/licenses.html +51 -41
  112. package/translations/messages.pot +59 -59
  113. package/views/accounts/account.hbs +69 -7
  114. package/views/accounts/browse.hbs +18 -35
  115. package/views/config/logging.hbs +6 -0
  116. package/views/config/oauth/app.hbs +0 -2
  117. package/views/config/security.hbs +13 -0
  118. package/views/partials/oauth_form.hbs +0 -15
  119. package/views/partials/reference/disclosure.hbs +8 -2
  120. package/views/partials/reference/operation.hbs +47 -13
  121. package/views/partials/reference/params.hbs +17 -1
  122. package/views/partials/reference/schema-node.hbs +110 -52
  123. package/views/partials/reference/schema-tools.hbs +25 -0
  124. package/views/partials/reference/try-it.hbs +84 -11
  125. package/views/partials/side_menu.hbs +1 -0
  126. package/views/partials/ui/checkbox.hbs +2 -2
  127. package/views/partials/ui/tabs.hbs +7 -1
  128. package/views/reference/token.hbs +4 -0
  129. package/views/suppression-lists/index.hbs +85 -0
  130. package/views/suppression-lists/list.hbs +87 -0
  131. package/views/templates/index.hbs +8 -2
  132. package/views/tokens/index.hbs +31 -4
  133. package/views/tokens/new.hbs +324 -2
  134. package/workers/api.js +146 -57
  135. package/workers/documents.js +46 -26
  136. package/workers/export.js +20 -8
  137. package/workers/imap-proxy.js +2 -2
  138. package/workers/imap.js +12 -6
  139. package/workers/smtp.js +13 -7
  140. package/workers/submit.js +40 -30
  141. package/workers/webhooks.js +59 -25
  142. package/lib/feature-flags.js +0 -48
package/lib/auth-token.js CHANGED
@@ -2,12 +2,15 @@
2
2
 
3
3
  // Shared token validation for the SMTP and IMAP-proxy submission servers. Both
4
4
  // servers accept a 64-char hex API token as the password and apply the same
5
- // checks (account binding, scope, IP allowlist). The logic lives here so the two
5
+ // checks (account binding, scope, permissions, IP allowlist). The logic lives here so the two
6
6
  // auth handlers (lib/smtp-auth.js, lib/imap-proxy-auth.js) cannot drift apart -
7
7
  // a token security-policy change is made once and applies to both surfaces.
8
8
 
9
9
  const logger = require('./logger');
10
10
  const tokens = require('./tokens');
11
+ const tokenPermissions = require('./token-permissions');
12
+ const tokenAuditLog = require('./token-audit-log');
13
+ const { SURFACE_GRANTS } = require('./api-routes/permission-map');
11
14
  const { matchIp } = require('./utils/network');
12
15
 
13
16
  // Reason-specific denial messages, shared verbatim by both auth handlers. The
@@ -16,22 +19,23 @@ const { matchIp } = require('./utils/network');
16
19
  const REASON_MESSAGES = {
17
20
  username: 'Access denied, invalid username',
18
21
  scope: 'Access denied, invalid scope',
19
- ip: 'Access denied, traffic not accepted from this IP'
22
+ ip: 'Access denied, traffic not accepted from this IP',
23
+ permissions: 'Access denied, token permissions do not allow this'
20
24
  };
21
25
 
22
26
  /**
23
27
  * Validates a 64-char hex API token supplied as a server password.
24
28
  *
25
- * Performs the token lookup plus the account-binding, scope and IP-allowlist
26
- * checks. Does NOT throw - the caller maps the returned reason to its own
27
- * protocol-specific error (SMTP and IMAP use different response shapes).
29
+ * Performs the token lookup plus the account-binding, scope, permission and
30
+ * IP-allowlist checks. Does NOT throw - the caller maps the returned reason to
31
+ * its own protocol-specific error (SMTP and IMAP use different response shapes).
28
32
  *
29
33
  * @param {Object} opts
30
34
  * @param {String} opts.password - supplied password (candidate token)
31
35
  * @param {String} opts.account - username the client authenticated as
32
36
  * @param {String} opts.requiredScope - scope the token must hold ('smtp' | 'imap-proxy')
33
37
  * @param {String} opts.remoteAddress - client IP, checked against token restrictions
34
- * @returns {Promise<{authenticated: Boolean, reason: (null|'username'|'scope'|'ip')}>}
38
+ * @returns {Promise<{authenticated: Boolean, reason: (null|'username'|'scope'|'permissions'|'ip')}>}
35
39
  */
36
40
  async function validateAuthToken({ password, account, requiredScope, remoteAddress }) {
37
41
  if (!/^[0-9a-f]{64}$/i.test(password)) {
@@ -49,12 +53,33 @@ async function validateAuthToken({ password, account, requiredScope, remoteAddre
49
53
  return { authenticated: false, reason: null };
50
54
  }
51
55
 
56
+ // Built before the first check that can refuse, for the same reason as the HTTP surface: a
57
+ // trail that only held accepted logins would be silent about exactly the ones worth looking at.
58
+ const auditEntry = {
59
+ tokenId: tokenData.id,
60
+ ip: remoteAddress || null,
61
+ method: requiredScope,
62
+ path: requiredScope,
63
+ account
64
+ };
65
+
52
66
  if (tokenData.account && tokenData.account !== account) {
67
+ // Logged like the refusals below it, rather than only into the per-token trail: a credential
68
+ // presented for someone else's account is the same class of event as a bad scope, and the
69
+ // application log is the record that leaves the instance.
70
+ logger.warn({
71
+ msg: 'Trying to use a token bound to another account',
72
+ tokenAccount: tokenData.account,
73
+ tokenId: tokenData.id,
74
+ account,
75
+ requestedScope: requiredScope
76
+ });
77
+ tokenAuditLog.denied(auditEntry, 'username');
53
78
  return { authenticated: false, reason: 'username' };
54
79
  }
55
80
 
56
81
  if (tokenData.scopes && !tokenData.scopes.includes(requiredScope) && !tokenData.scopes.includes('*')) {
57
- logger.error({
82
+ logger.warn({
58
83
  msg: 'Trying to use invalid scope for a token',
59
84
  tokenAccount: tokenData.account,
60
85
  tokenId: tokenData.id,
@@ -62,11 +87,55 @@ async function validateAuthToken({ password, account, requiredScope, remoteAddre
62
87
  requestedScope: requiredScope,
63
88
  scopes: tokenData.scopes
64
89
  });
90
+ tokenAuditLog.denied(auditEntry, 'scope');
65
91
  return { authenticated: false, reason: 'scope' };
66
92
  }
67
93
 
94
+ // Narrowing below the scope. Checked here rather than in each handler so a policy change cannot
95
+ // land on one submission surface and miss the other, which is why this module exists.
96
+ //
97
+ // An unknown scope resolves to no operation, which denies: a surface this function does not know
98
+ // how to describe must not be reachable by a narrowed token just because nobody mapped it.
99
+ // Object.hasOwn rather than a bare lookup: SCOPE_OPERATIONS['__proto__'] would otherwise return
100
+ // Object.prototype, and Object.values of that is an empty list - which would pass a
101
+ // "does it hold every grant" loop vacuously. A surface nobody mapped must be refused, not waved
102
+ // through, so an unknown scope resolves to no grants at all and denies below.
103
+ const requiredGrants = Object.hasOwn(SURFACE_GRANTS, requiredScope) ? SURFACE_GRANTS[requiredScope] : null;
104
+
105
+ // First refusal wins, so the reported reason names a grant the token actually lacks. An unmapped
106
+ // surface has no grants to check, and check() with no operation denies a narrowed token on
107
+ // UNCLASSIFIED - which is why this passes `null` through rather than skipping the loop.
108
+ //
109
+ // `action`/`group` land on the audit entry only in the refusal branch, and the accept path
110
+ // leaves them null on purpose. These surfaces do not perform an operation: they admit a session
111
+ // that may then exercise every grant the surface carries - five of them for the IMAP proxy - so
112
+ // naming one of the five on an accepted login would report a request that was never made. A
113
+ // refusal is the opposite case: exactly one grant decided it, and that one is worth recording.
114
+ let permissionCheck = { allowed: true, reason: null, required: null };
115
+ for (const operation of requiredGrants || [null]) {
116
+ permissionCheck = tokenPermissions.check({ tokenData, operation });
117
+ if (!permissionCheck.allowed) {
118
+ Object.assign(auditEntry, { action: operation && operation.action, group: operation && operation.group });
119
+ break;
120
+ }
121
+ }
122
+
123
+ if (!permissionCheck.allowed) {
124
+ logger.warn({
125
+ msg: 'Token permissions do not allow this operation',
126
+ tokenAccount: tokenData.account,
127
+ tokenId: tokenData.id,
128
+ account,
129
+ requestedScope: requiredScope,
130
+ reason: permissionCheck.reason,
131
+ required: permissionCheck.required
132
+ });
133
+ tokenAuditLog.denied(auditEntry, permissionCheck.reason);
134
+ return { authenticated: false, reason: 'permissions' };
135
+ }
136
+
68
137
  if (tokenData.restrictions && tokenData.restrictions.addresses && !matchIp(remoteAddress, tokenData.restrictions.addresses)) {
69
- logger.error({
138
+ logger.warn({
70
139
  msg: 'Trying to use invalid IP for a token',
71
140
  tokenAccount: tokenData.account,
72
141
  tokenId: tokenData.id,
@@ -74,9 +143,12 @@ async function validateAuthToken({ password, account, requiredScope, remoteAddre
74
143
  remoteAddress,
75
144
  addressAllowlist: tokenData.restrictions.addresses
76
145
  });
146
+ tokenAuditLog.denied(auditEntry, 'ip');
77
147
  return { authenticated: false, reason: 'ip' };
78
148
  }
79
149
 
150
+ tokenAuditLog.allowed(auditEntry);
151
+
80
152
  return { authenticated: true, reason: null };
81
153
  }
82
154
 
package/lib/consts.js CHANGED
@@ -273,6 +273,16 @@ module.exports = {
273
273
  'UND_ERR_HEADERS_TIMEOUT'
274
274
  ]),
275
275
 
276
+ // Error codes meaning "the IMAP connection is gone", as opposed to the command itself failing
277
+ CONNECTION_CLOSING_CODES: new Set(['IMAPConnectionClosing', 'EConnectionClosed', 'NoConnection']),
278
+
279
+ // Applied by lib/logger.js to the root logger, so every worker inherits it. A logged joi
280
+ // ValidationError carries the full submitted payload in `_original` and the offending value in
281
+ // each detail context, and `rawPacket` is a TLS-error field that can carry an unparsed
282
+ // credential frame - without these a failed validation writes plaintext passwords, OAuth2
283
+ // client secrets and access tokens into the log, the per-account log store and Sentry.
284
+ REDACTED_LOG_KEYS: ['req.headers.authorization', 'req.headers.cookie', 'err.rawPacket', 'err._original', 'err.details[*].context.value'],
285
+
276
286
  generateWebhookTable() {
277
287
  let entries = [];
278
288
 
package/lib/db.js CHANGED
@@ -108,9 +108,11 @@ const redis = new Redis(REDIS_CONF);
108
108
 
109
109
  const reqisQueue = new Redis(REDIS_CONF);
110
110
 
111
+ // Passing an ioredis instance as `connection` (rather than connection options) is what keeps BullMQ
112
+ // from closing the client on its own: it marks the connection shared via isRedisInstance() and only
113
+ // disconnects the ones it created itself.
111
114
  module.exports.queueConf = {
112
115
  connection: reqisQueue,
113
- sharedConnection: true, // Prevent BullMQ from closing shared connection
114
116
  prefix: `${REDIS_PREFIX}bull`
115
117
  };
116
118
 
@@ -222,6 +224,15 @@ module.exports.submitQueue = submitQueue;
222
224
  module.exports.documentsQueue = documentsQueue;
223
225
  module.exports.exportQueue = exportQueue;
224
226
 
227
+ // Queues addressable by the name the API and the stats payload use for them. `export` is
228
+ // deliberately absent: neither surface exposes it, and the {queue} route parameter is validated
229
+ // against this same set of names.
230
+ module.exports.QUEUES_BY_NAME = {
231
+ notify: notifyQueue,
232
+ submit: submitQueue,
233
+ documents: documentsQueue
234
+ };
235
+
225
236
  // do not set up the flow producer by default
226
237
  module.exports.getFlowProducer = () => new FlowProducer(module.exports.queueConf /*, Redis*/);
227
238
 
@@ -248,7 +259,14 @@ To run EmailEngine provide valid Redis configuration
248
259
  process.exit(1);
249
260
  }
250
261
 
251
- logger.fatal({ msg, err });
262
+ // Only reached when the process stays up (the exit path above never returns), so this must
263
+ // not log at fatal. A post-connection error is retried by ioredis on its own, so it is a
264
+ // warning; config-class errors (forceClose) that did not trigger an exit are logged at error.
265
+ if (forceClose) {
266
+ logger.error({ msg: msg || 'Redis connection error', err });
267
+ } else {
268
+ logger.warn({ msg: msg || 'Redis connection error', err });
269
+ }
252
270
  };
253
271
 
254
272
  redis.on('connect', () => {
@@ -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 };
@@ -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,
@@ -158,7 +158,7 @@ async function retryOnTransientError(fn, options = {}) {
158
158
  attempt,
159
159
  maxAttempts,
160
160
  delay,
161
- err: err.message,
161
+ err,
162
162
  statusCode: err.statusCode || err.oauthRequest?.status
163
163
  });
164
164
  }
@@ -501,7 +501,7 @@ class BaseClient {
501
501
  );
502
502
  await disableTxn.exec();
503
503
 
504
- this.logger.info({
504
+ this.logger.warn({
505
505
  msg: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
506
506
  errorEvent: event,
507
507
  firstError: firstError.toISOString(),
@@ -597,7 +597,7 @@ class BaseClient {
597
597
  // rejected credential. Reporting it as an authentication error would webhook every
598
598
  // account on the instance and park them in an error state over a brief blip.
599
599
  if (isTransientNetworkError(err)) {
600
- ctx.logger.error({
600
+ ctx.logger.warn({
601
601
  msg: 'Network error while resolving credentials from the authentication server',
602
602
  account: accountObject.account,
603
603
  target,
@@ -635,7 +635,7 @@ class BaseClient {
635
635
  } catch (err) {
636
636
  // Transient network errors are not authentication failures
637
637
  if (isTransientNetworkError(err)) {
638
- ctx.logger.error({
638
+ ctx.logger.warn({
639
639
  msg: 'Network error during OAuth2 token refresh',
640
640
  account: accountObject.account,
641
641
  code: err.code,
@@ -654,7 +654,8 @@ class BaseClient {
654
654
  notifyData.tokenRequest = err.tokenRequest;
655
655
  }
656
656
  await ctx.notify(false, AUTH_ERROR_NOTIFY, notifyData);
657
- ctx.logger.error({
657
+ ctx.logger.warn({
658
+ msg: 'Failed to renew OAuth2 access token',
658
659
  account: accountObject.account,
659
660
  err
660
661
  });
@@ -663,11 +664,10 @@ class BaseClient {
663
664
  }
664
665
  } else {
665
666
  // Use cached token
666
- this.logger.info({
667
+ this.logger.debug({
667
668
  msg: 'Using cached OAuth2 access token',
668
669
  action: 'ensureAccessToken',
669
670
  target,
670
- error: null,
671
671
  user: accountData.oauth2.auth.user,
672
672
  expires: accountData.oauth2.expires,
673
673
  scopes: accountData.oauth2.scope,
@@ -952,7 +952,7 @@ class BaseClient {
952
952
  try {
953
953
  gatewayData = await gatewayObject.loadGatewayData();
954
954
  } catch (err) {
955
- 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 });
956
956
  }
957
957
  }
958
958
 
@@ -1201,7 +1201,7 @@ class BaseClient {
1201
1201
  this.logger.warn({
1202
1202
  msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
1203
1203
  messageId: data.reference.message,
1204
- err: err.message,
1204
+ err,
1205
1205
  statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
1206
1206
  });
1207
1207
  referencedMessage = null;
@@ -1403,7 +1403,7 @@ class BaseClient {
1403
1403
  if (attachmentsToDownload && attachmentsToDownload.length) {
1404
1404
  this.checkIMAPConnection(connectionOptions);
1405
1405
 
1406
- this.logger.info({
1406
+ this.logger.debug({
1407
1407
  msg: 'Fetching attachments from the referenced email',
1408
1408
  attachments: attachmentsToDownload.map(a => ({ id: a.id, hasContent: !!a.content }))
1409
1409
  });
@@ -1567,8 +1567,6 @@ class BaseClient {
1567
1567
  baseDomain = baseDomain || (os.hostname() || '').toLowerCase().trim() || 'localhost';
1568
1568
 
1569
1569
  if (baseDomain) {
1570
- let unsubscribeUrlObj = new URL('/unsubscribe', baseUrl);
1571
-
1572
1570
  const serviceSecret = await getServiceSecret();
1573
1571
 
1574
1572
  let fromDomain = ((data.from && data.from.address) || '').split('@').pop().trim().toLowerCase() || baseDomain;
@@ -1585,24 +1583,14 @@ class BaseClient {
1585
1583
  }
1586
1584
 
1587
1585
  // Create signed unsubscribe URL
1588
- let { data: signedData, signature } = getSignedFormDataSync(
1589
- serviceSecret,
1590
- {
1591
- act: 'unsub',
1592
- acc: accountData.account,
1593
- list: data.listId,
1594
- rcpt: data.to[0].address,
1595
- msg: data.messageId
1596
- },
1597
- true
1598
- );
1599
-
1600
- unsubscribeUrlObj.searchParams.append('data', signedData);
1601
- if (signature) {
1602
- unsubscribeUrlObj.searchParams.append('sig', signature);
1603
- }
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
+ });
1604
1592
 
1605
- context.rcpt = Object.assign({}, data.to[0], { unsubscribeUrl: unsubscribeUrlObj.href });
1593
+ context.rcpt = Object.assign({}, data.to[0], { unsubscribeUrl });
1606
1594
 
1607
1595
  // Add RFC 8058 compliant unsubscribe headers
1608
1596
  data.headers['List-Unsubscribe'] = `<${context.rcpt.unsubscribeUrl}>`;
@@ -1633,7 +1621,7 @@ class BaseClient {
1633
1621
  try {
1634
1622
  data.text = htmlToText(data.html);
1635
1623
  } catch (err) {
1636
- 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 });
1637
1625
  }
1638
1626
  }
1639
1627
 
@@ -1705,7 +1693,7 @@ class BaseClient {
1705
1693
  this.logger.warn({
1706
1694
  msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
1707
1695
  messageId: data.reference.message,
1708
- err: err.message,
1696
+ err,
1709
1697
  statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
1710
1698
  });
1711
1699
  referencedMessage = null;
@@ -1918,7 +1906,7 @@ class BaseClient {
1918
1906
  if (attachmentsToDownload && attachmentsToDownload.length) {
1919
1907
  this.checkIMAPConnection(connectionOptions);
1920
1908
 
1921
- this.logger.info({
1909
+ this.logger.debug({
1922
1910
  msg: 'Fetching attachments from the referenced email',
1923
1911
  attachments: attachmentsToDownload.map(a => ({ id: a.id, hasContent: !!a.content }))
1924
1912
  });
@@ -2025,7 +2013,7 @@ class BaseClient {
2025
2013
  try {
2026
2014
  gatewayData = await gatewayObject.loadGatewayData();
2027
2015
  } catch (err) {
2028
- 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 });
2029
2017
  }
2030
2018
  }
2031
2019
 
@@ -2250,7 +2238,7 @@ class BaseClient {
2250
2238
  try {
2251
2239
  gatewayData = await gatewayObject.loadGatewayData();
2252
2240
  } catch (err) {
2253
- 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 });
2254
2242
  }
2255
2243
  }
2256
2244
 
@@ -2321,7 +2309,7 @@ class BaseClient {
2321
2309
 
2322
2310
  return compiledTemplate(data);
2323
2311
  } catch (err) {
2324
- logger.error({ msg: `Failed rendering ${key} template`, err });
2312
+ this.logger.error({ msg: 'Failed to render template', templateKey: key, err });
2325
2313
  let error = new Error(`Failed rendering ${key} template`);
2326
2314
  error.code = err.code || 'SubmitFail';
2327
2315
  error.statusCode = 422;
@@ -2535,7 +2523,7 @@ class BaseClient {
2535
2523
  }
2536
2524
  } catch (err) {
2537
2525
  // ignore, just do not include this information
2538
- this.logger.error({
2526
+ this.logger.warn({
2539
2527
  msg: 'Failed to classify bounce response',
2540
2528
  bounceResponse: bounce?.response?.message,
2541
2529
  err
@@ -2543,7 +2531,6 @@ class BaseClient {
2543
2531
  }
2544
2532
  }
2545
2533
 
2546
- let stored = 0;
2547
2534
  if (bounce.action && bounce.recipient && bounce.messageId) {
2548
2535
  bounceNotifyInfo = Object.assign({ bounceMessage: messageData.id }, bounce);
2549
2536
 
@@ -2556,8 +2543,7 @@ class BaseClient {
2556
2543
  id: messageData.id,
2557
2544
  uid: messageData.uid,
2558
2545
  messageId: messageData.messageId,
2559
- bounce,
2560
- stored
2546
+ bounce
2561
2547
  });
2562
2548
  }
2563
2549
  } catch (err) {
@@ -2825,7 +2811,7 @@ class BaseClient {
2825
2811
  time: Date.now()
2826
2812
  })
2827
2813
  );
2828
- this.logger.error({ msg: 'Failed to fetch embeddings OpenAI', err });
2814
+ this.logger.error({ msg: 'Failed to fetch embeddings from OpenAI', err });
2829
2815
  }
2830
2816
  }
2831
2817
  }
@@ -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
@@ -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