emailengine-app 2.81.1 → 2.82.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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. package/workers/documents.js +0 -1128
package/workers/imap.js CHANGED
@@ -18,17 +18,15 @@ const { OutlookClient } = require('../lib/email-client/outlook-client');
18
18
  const { BaseClient } = require('../lib/email-client/base-client');
19
19
  const { Account } = require('../lib/account');
20
20
  const { oauth2Apps, isApiBasedApp } = require('../lib/oauth2-apps');
21
- const { redis, notifyQueue, submitQueue, documentsQueue, getFlowProducer } = require('../lib/db');
21
+ const { redis, notifyQueue, submitQueue, watchRedisReconnect } = require('../lib/db');
22
22
  const { sendToMessagePort, MessagePortWritable } = require('../lib/message-port-stream');
23
- const { packRpcError, unpackRpcError } = require('../lib/worker-rpc-error');
24
- const { getESClient } = require('../lib/document-store');
23
+ const { packRpcError, unpackRpcError, describeRpcCommand } = require('../lib/worker-rpc-error');
24
+ const { ImapFlowErrorCode } = require('imapflow');
25
25
  const settings = require('../lib/settings');
26
26
  const msgpack = require('../lib/msgpack');
27
27
 
28
28
  const getSecret = require('../lib/get-secret');
29
29
 
30
- const flowProducer = getFlowProducer();
31
-
32
30
  config.service = config.service || {};
33
31
 
34
32
  config.log = config.log || {
@@ -62,35 +60,29 @@ class ConnectionHandler {
62
60
  this.mids = 0;
63
61
 
64
62
  this.accounts = new Map();
63
+
64
+ // account -> token of the latest assign. An unassign or a newer assign replaces or drops it,
65
+ // which is how an assign still awaiting its setup learns it has been superseded. The one
66
+ // supersession check there is: the identity of the this.accounts entry cannot serve, because
67
+ // nothing is registered there until the Account object exists, so an unassign that lands
68
+ // during the loads before that leaves nothing to compare against. Entry identity is only
69
+ // consulted to decide whether a cleanup or an init retry still concerns the entry this
70
+ // assign registered.
71
+ this.assignTokens = new Map();
65
72
  }
66
73
 
67
74
  async init() {
68
- // Track Redis connection state for reconnection detection
69
- let hasSeenStableConnection = false;
70
- let redisWasDisconnected = false;
71
-
72
- // Check initial Redis state
73
- if (redis.status === 'ready') {
74
- hasSeenStableConnection = true;
75
- }
76
-
77
- redis.on('ready', () => {
78
- if (redisWasDisconnected && hasSeenStableConnection) {
79
- // Redis reconnected after being disconnected during our lifetime
75
+ // Redis reconnected after being disconnected during our lifetime. In-memory account state
76
+ // may no longer match Redis (a restart or a flush), so exit cleanly: the main thread
77
+ // treats exit code 0 as this case, respawns the worker and reassigns its accounts.
78
+ watchRedisReconnect(
79
+ redis,
80
+ () => {
80
81
  logger.info({ msg: 'Redis reconnected after disconnection, exiting worker for clean restart', worker: 'imap' });
81
- // Exit gracefully - the main process will restart this worker
82
82
  process.exit(0);
83
- }
84
- // Mark that we've seen a stable connection
85
- hasSeenStableConnection = true;
86
- });
87
-
88
- redis.on('end', () => {
89
- if (hasSeenStableConnection) {
90
- logger.warn({ msg: 'Redis connection lost', worker: 'imap' });
91
- redisWasDisconnected = true;
92
- }
93
- });
83
+ },
84
+ () => logger.warn({ msg: 'Redis connection lost', worker: 'imap' })
85
+ );
94
86
 
95
87
  // indicate that we are ready to process connections
96
88
  parentPort.postMessage({ cmd: 'ready' });
@@ -186,6 +178,34 @@ class ConnectionHandler {
186
178
  return accountLogger;
187
179
  }
188
180
 
181
+ /**
182
+ * Closes an account connection this worker no longer tracks. Nothing is deleted, the account
183
+ * is only moving to another worker or being assigned here again
184
+ * @param {string} account - Account ID
185
+ * @param {Object} accountObject - The entry that was removed from this.accounts
186
+ */
187
+ async closeReleasedConnection(account, accountObject) {
188
+ if (!accountObject || !accountObject.connection) {
189
+ return;
190
+ }
191
+ try {
192
+ await accountObject.connection.close();
193
+ } catch (err) {
194
+ logger.error({ msg: 'Failed to close released account connection', account, err });
195
+ }
196
+ }
197
+
198
+ // The main thread takes an account back after an `assign` it gave up waiting for, or to move
199
+ // it onto another worker. An assignment still being set up notices the missing entry and stops.
200
+ async unassignConnection(account) {
201
+ logger.info({ msg: 'Account unassign requested', account });
202
+ this.assignTokens.delete(account);
203
+ let accountObject = this.accounts.get(account);
204
+ this.accounts.delete(account);
205
+ await this.closeReleasedConnection(account, accountObject);
206
+ return true;
207
+ }
208
+
189
209
  async assignConnection(account, runIndex, initOpts) {
190
210
  logger.debug({ msg: 'Assigned account to worker', account });
191
211
 
@@ -197,6 +217,10 @@ class ConnectionHandler {
197
217
  runIndex = this.runIndex;
198
218
  }
199
219
 
220
+ const token = Symbol(account);
221
+ this.assignTokens.set(account, token);
222
+ const isCurrent = () => this.assignTokens.get(account) === token;
223
+
200
224
  let accountLogger = await this.getAccountLogger(account);
201
225
  let secret = await getSecret();
202
226
  let accountObject = new Account({
@@ -205,12 +229,65 @@ class ConnectionHandler {
205
229
  secret,
206
230
  // Needed so Account.update() can dispatch reconnect/update commands back to
207
231
  // this worker (e.g. auto-reconnect after OAuth re-auth in an error state).
208
- call: msg => this.call(msg),
209
- esClient: await getESClient(logger)
232
+ call: msg => this.call(msg)
210
233
  });
211
234
 
235
+ if (!isCurrent()) {
236
+ logger.info({ msg: 'Dropped superseded account assignment', account });
237
+ return false;
238
+ }
239
+
240
+ // Assigning an account this worker already runs replaces the connection. A retried assign
241
+ // (the main thread timed out on the first one) used to overwrite the map entry and leave the
242
+ // first connection running with nothing able to reach it. Swapped without an await in
243
+ // between, so two overlapping assigns cannot both keep a connection.
244
+ let previous = this.accounts.get(account);
212
245
  this.accounts.set(account, accountObject);
246
+ await this.closeReleasedConnection(account, previous);
213
247
 
248
+ let current;
249
+ try {
250
+ current = await this.setupConnection(account, accountObject, { runIndex, accountLogger, secret, isCurrent });
251
+ } catch (err) {
252
+ // Leave no connection-less entry behind: it answered commands with "no active handler"
253
+ // and counted as a disconnected account for as long as the worker lived. Only the entry
254
+ // this assign registered is its to remove, a newer assign may have replaced it
255
+ if (this.accounts.get(account) === accountObject) {
256
+ this.accounts.delete(account);
257
+ }
258
+ if (isCurrent()) {
259
+ this.assignTokens.delete(account);
260
+ }
261
+ if (err.isBoom && !err.statusCode && err.output) {
262
+ // Lets the main thread tell an account that is gone (404) from a transient failure
263
+ err.statusCode = err.output.statusCode;
264
+ }
265
+ throw err;
266
+ }
267
+
268
+ if (!current) {
269
+ // Unassigned or assigned again while this was being set up; the client was never
270
+ // started, so there is nothing to close
271
+ if (this.accounts.get(account) === accountObject) {
272
+ this.accounts.delete(account);
273
+ }
274
+ logger.info({ msg: 'Dropped superseded account assignment', account });
275
+ return false;
276
+ }
277
+
278
+ // do not wait before returning as it may take forever
279
+ this.startConnection(account, accountObject, initOpts);
280
+ }
281
+
282
+ /**
283
+ * Loads the account and builds its client, without starting it
284
+ * @param {string} account - Account ID
285
+ * @param {Object} accountObject - The entry assignConnection() registered
286
+ * @param {Object} opts - runIndex, accountLogger, secret and isCurrent, the assign's own
287
+ * supersession check (see the assignTokens comment in the constructor)
288
+ * @returns {Promise<boolean>} false when the assign was superseded in the meantime
289
+ */
290
+ async setupConnection(account, accountObject, { runIndex, accountLogger, secret, isCurrent }) {
214
291
  const accountData = await accountObject.loadAccountData();
215
292
 
216
293
  if (accountData.oauth2 && accountData.oauth2.auth) {
@@ -244,8 +321,6 @@ class ConnectionHandler {
244
321
 
245
322
  notifyQueue,
246
323
  submitQueue,
247
- documentsQueue,
248
- flowProducer,
249
324
 
250
325
  call: msg => this.call(msg)
251
326
  });
@@ -264,8 +339,6 @@ class ConnectionHandler {
264
339
 
265
340
  notifyQueue,
266
341
  submitQueue,
267
- documentsQueue,
268
- flowProducer,
269
342
 
270
343
  call: msg => this.call(msg)
271
344
  });
@@ -290,8 +363,6 @@ class ConnectionHandler {
290
363
 
291
364
  notifyQueue,
292
365
  submitQueue,
293
- documentsQueue,
294
- flowProducer,
295
366
 
296
367
  call: msg => this.call(msg),
297
368
  logRaw: EENGINE_LOG_RAW
@@ -299,13 +370,16 @@ class ConnectionHandler {
299
370
  accountObject.logger = accountObject.connection.logger;
300
371
  }
301
372
 
373
+ if (!isCurrent()) {
374
+ return false;
375
+ }
376
+
302
377
  if (accountData.state) {
303
378
  await redis.hSetExists(accountObject.connection.getAccountKey(), 'state', accountData.state);
304
379
  await emitChangeEvent(logger, account, 'state', accountData.state);
305
380
  }
306
381
 
307
- // do not wait before returning as it may take forever
308
- this.startConnection(account, accountObject, initOpts);
382
+ return isCurrent();
309
383
  }
310
384
 
311
385
  /**
@@ -341,6 +415,7 @@ class ConnectionHandler {
341
415
 
342
416
  async deleteConnection(account) {
343
417
  logger.info({ msg: 'Deleting connection', account });
418
+ this.assignTokens.delete(account);
344
419
  if (this.accounts.has(account)) {
345
420
  let accountObject = this.accounts.get(account);
346
421
  if (accountObject.connection) {
@@ -440,7 +515,12 @@ class ConnectionHandler {
440
515
  msg: 'Account reconnection requested'
441
516
  });
442
517
 
443
- await accountObject.connection.close();
518
+ try {
519
+ await accountObject.connection.close();
520
+ } catch (err) {
521
+ // a failed state write during close must not stop the reconnect
522
+ logger.error({ msg: 'Failed to close connection', account, err });
523
+ }
444
524
  }
445
525
 
446
526
  await this.assignConnection(account, false, { forceWatchRenewal: true });
@@ -709,8 +789,9 @@ class ConnectionHandler {
709
789
  return true;
710
790
 
711
791
  case 'missed':
792
+ // the API worker already stored the recovery request, see Account.queueMissedRecovery()
712
793
  logger.info({ msg: 'Handling missed notification lifecycle event', account: message.account });
713
- return await connection.syncMissedMessages();
794
+ return connection.recoverMissedNotifications();
714
795
 
715
796
  default:
716
797
  logger.warn({ msg: 'Unknown subscription lifecycle event', event: message.event, account: message.account });
@@ -858,9 +939,12 @@ class ConnectionHandler {
858
939
  logger.info({ msg: 'Closing account connections', accounts: this.accounts.size });
859
940
  this.connectionsClosed = true;
860
941
 
861
- this.accounts.forEach(accountObject => {
942
+ this.accounts.forEach((accountObject, account) => {
862
943
  if (accountObject && accountObject.connection) {
863
- accountObject.connection.close();
944
+ // Gmail and Graph close() write state to Redis; a rejection here is only worth a log line
945
+ Promise.resolve()
946
+ .then(() => accountObject.connection.close())
947
+ .catch(err => logger.error({ msg: 'Failed to close connection', account, err }));
864
948
  }
865
949
  });
866
950
  }
@@ -911,6 +995,7 @@ class ConnectionHandler {
911
995
  return true;
912
996
 
913
997
  case 'delete':
998
+ case 'unassign':
914
999
  case 'update':
915
1000
  case 'sync':
916
1001
  case 'pause':
@@ -1048,16 +1133,18 @@ parentPort.on('message', message => {
1048
1133
  });
1049
1134
  })
1050
1135
  .catch(err => {
1051
- if (message.message && message.message.data && message.message.data.raw) {
1052
- message.message.data.raw = message.message.data.raw.length;
1053
- }
1054
1136
  // Anything with a client-facing status (404 not found, 503 no active handler) is
1055
1137
  // reported back to the caller as the command response, so it is not a server fault.
1056
1138
  // 503 is excluded from the error branch on purpose: both "no active handler" and
1057
1139
  // IMAPConnectionClosing carry it, and a worker taking over accounts answers every
1058
1140
  // in-flight command with one until the reassignment settles.
1141
+ if (err.code === ImapFlowErrorCode.ETHROTTLE && !err.statusCode) {
1142
+ // ImapFlow gave up after the server throttled every retry: the caller should
1143
+ // back off, the same answer a throttled Gmail or Graph request gets
1144
+ err.statusCode = 429;
1145
+ }
1059
1146
  let isServerFault = !err.statusCode || (err.statusCode >= 500 && err.statusCode !== 503);
1060
- logger[isServerFault ? 'error' : 'debug'](Object.assign({ msg: 'Command failed' }, message, { err }));
1147
+ logger[isServerFault ? 'error' : 'debug'](Object.assign(describeRpcCommand(message), { msg: 'Command failed', err }));
1061
1148
  parentPort.postMessage(Object.assign({ cmd: 'resp', mid: message.mid }, packRpcError(err)));
1062
1149
  });
1063
1150
  }
package/workers/submit.js CHANGED
@@ -15,7 +15,7 @@ const { initSentry } = require('../lib/sentry');
15
15
  initSentry('submit');
16
16
 
17
17
  const util = require('util');
18
- const { redis, queueConf, submitQueue } = require('../lib/db');
18
+ const { redis, queueConf, submitQueue, logBullErrors } = require('../lib/db');
19
19
  const { Worker, UnrecoverableError } = require('bullmq');
20
20
  const { Account } = require('../lib/account');
21
21
  const getSecret = require('../lib/get-secret');
@@ -362,6 +362,8 @@ const submitWorker = new Worker(
362
362
  )
363
363
  );
364
364
 
365
+ logBullErrors(submitWorker, 'worker:submit');
366
+
365
367
  submitWorker.on('completed', async job => {
366
368
  metrics(logger, 'queuesProcessed', 'inc', {
367
369
  queue: 'submit',
@@ -11,17 +11,19 @@ const { webhooks: Webhooks } = require('../lib/webhooks');
11
11
  const { GooglePubSub } = require('../lib/oauth/pubsub/google');
12
12
 
13
13
  const { readEnvValue, threadStats, getDuration, httpAgent, getServiceSecret, redactUrlCredentials, splitUrlCredentials } = require('../lib/tools');
14
- const { sendWebhookRequest } = require('../lib/webhook-request');
14
+ const { sendWebhookRequest, isUnrecoverableWebhookError } = require('../lib/webhook-request');
15
15
  const { willBeFinalAttempt, isFinalFailedAttempt } = require('../lib/delivery-error');
16
16
  const { validateWebhookTarget } = require('../lib/webhook-egress');
17
- const { resolveTargetUrl, isDeliverableRoute, eventAllowed } = require('../lib/webhook-routing');
17
+ const { resolveTargetUrl, isDeliverableRoute, eventAllowed, deliveryCustomHeaders, isRouteMappingMissing } = require('../lib/webhook-routing');
18
18
 
19
19
  const { initSentry } = require('../lib/sentry');
20
20
  initSentry('webhooks');
21
21
 
22
- const { redis, queueConf } = require('../lib/db');
22
+ const { redis, queueConf, logBullErrors } = require('../lib/db');
23
23
  const { Worker, UnrecoverableError } = require('bullmq');
24
24
  const settings = require('../lib/settings');
25
+ const { decryptField } = require('../lib/encrypt');
26
+ const getSecret = require('../lib/get-secret');
25
27
 
26
28
  const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, MESSAGE_NEW_NOTIFY } = require('../lib/consts');
27
29
 
@@ -41,11 +43,6 @@ const NOTIFY_QC = (readEnvValue('EENGINE_NOTIFY_QC') && Number(readEnvValue('EEN
41
43
  // DEFAULT_WEBHOOK_REQUEST_TIMEOUT baked into sendWebhookRequest when unset
42
44
  const WEBHOOK_TIMEOUT = getDuration(readEnvValue('EENGINE_WEBHOOK_TIMEOUT')) || false;
43
45
 
44
- // Neither of these changes on a retry: the egress policy rejects the same destination every time,
45
- // and an endpoint configured to redirect keeps redirecting. Such a delivery is final on its first
46
- // failure, which decides both the log level and whether the remaining attempts are spent.
47
- const isUnrecoverableWebhookError = err => !!err && (err.code === 'EEGRESSBLOCKED' || err.code === 'EREDIRECTNOTFOLLOWED');
48
-
49
46
  let callQueue = new Map();
50
47
  let mids = 0;
51
48
 
@@ -90,6 +87,15 @@ function getAccountKey(account) {
90
87
  return `${REDIS_PREFIX}iad:${account}`;
91
88
  }
92
89
 
90
+ // The account `webhooks` and `webhooksCustomHeaders` fields are encrypted at rest (see
91
+ // ENCRYPTED_ACCOUNT_FIELDS in lib/account.js); a value stored before that is cleartext, which
92
+ // decrypt() passes through. One that no longer decrypts reads as unset, as it does for the account.
93
+ async function openAccountField(field, value, account) {
94
+ return decryptField(value, await getSecret(), err =>
95
+ logger.error({ msg: 'Failed to decrypt account webhook setting', action: 'webhook', account, field, err })
96
+ );
97
+ }
98
+
93
99
  async function metrics(logger, key, method, ...args) {
94
100
  try {
95
101
  parentPort.postMessage({
@@ -116,7 +122,10 @@ async function onCommand(command) {
116
122
  case 'close':
117
123
  clearTimeout(startRetryTimer);
118
124
  googlePubSub.stopAll();
119
- await notifyWorker.close(true);
125
+ // Not forced: a forced close abandons the delivery in flight, which BullMQ then
126
+ // re-runs as stalled after the lock expires, so the receiver got the event twice
127
+ // with the same X-EE-Wh-Id. The main thread bounds this wait with its own drain timeout.
128
+ await notifyWorker.close();
120
129
  return true;
121
130
  default:
122
131
  logger.debug({ msg: 'Unhandled command', command });
@@ -205,8 +214,9 @@ const notifyWorker = new Worker(
205
214
  job.__routeId = job.data._route.id;
206
215
  }
207
216
 
208
- // validate if we should even process this webhook
209
- let accountExists = await redis.hexists(accountKey, 'account');
217
+ // One round trip for the existence check and the two account fields a delivery may need
218
+ // (used to be three, one per job). The fields are opened where they are used, below.
219
+ let [accountExists, storedWebhooks, storedCustomHeaders] = await redis.hmget(accountKey, 'account', 'webhooks', 'webhooksCustomHeaders');
210
220
  if (!accountExists && job.name !== ACCOUNT_DELETED_NOTIFY) {
211
221
  logger.debug({
212
222
  msg: 'Account not found',
@@ -239,13 +249,27 @@ const notifyWorker = new Worker(
239
249
  if (job.data._route && job.data._route.id) {
240
250
  customRoute = await Webhooks.getMeta(job.data._route.id);
241
251
  customMapping = job.data._route.mapping;
252
+ let mappingMissing = isRouteMappingMissing(job.data._route);
242
253
  delete job.data._route;
243
254
  if (!isDeliverableRoute(customRoute)) {
244
255
  return;
245
256
  }
257
+ if (mappingMissing) {
258
+ logger.warn({
259
+ msg: 'Custom webhook route has no mapped payload, not sending',
260
+ action: 'webhook',
261
+ queue: job.queue.name,
262
+ code: 'missing_mapping',
263
+ job: job.id,
264
+ event: job.name,
265
+ account: job.data.account,
266
+ route: customRoute.id
267
+ });
268
+ return;
269
+ }
246
270
  }
247
271
 
248
- let accountWebhooks = await redis.hget(accountKey, 'webhooks');
272
+ let accountWebhooks = await openAccountField('webhooks', storedWebhooks, job.data.account);
249
273
 
250
274
  // the global setting is only fetched when neither a custom route nor the account override decides the target
251
275
  let webhooks = resolveTargetUrl(customRoute && customRoute.targetUrl, accountWebhooks, null).url || (await settings.get('webhooks'));
@@ -266,7 +290,10 @@ const notifyWorker = new Worker(
266
290
  }
267
291
 
268
292
  let accountWebhooksCustomHeaders;
269
- let accountWebhooksCustomHeadersJson = await redis.hget(accountKey, 'webhooksCustomHeaders');
293
+ // The account's headers belong to the account's (or the global) target. A custom route is
294
+ // an operator-defined endpoint with headers of its own: the account's secrets must not
295
+ // travel there, nor override the route's own Authorization.
296
+ let accountWebhooksCustomHeadersJson = customRoute ? null : await openAccountField('webhooksCustomHeaders', storedCustomHeaders, job.data.account);
270
297
  if (accountWebhooksCustomHeadersJson) {
271
298
  try {
272
299
  accountWebhooksCustomHeaders = JSON.parse(accountWebhooksCustomHeadersJson);
@@ -395,21 +422,11 @@ const notifyWorker = new Worker(
395
422
 
396
423
  if (customRoute) {
397
424
  headers['X-EE-Wh-Custom-Route'] = customRoute.id;
398
- for (let header of customRoute.customHeaders || []) {
399
- headers[header.key] = header.value;
400
- }
401
- } else {
402
- let webhookCustomHeaders = await settings.get('webhooksCustomHeaders');
403
- for (let header of webhookCustomHeaders || []) {
404
- headers[header.key] = header.value;
405
- }
406
- }
407
-
408
- if (accountWebhooksCustomHeaders) {
409
- for (let header of accountWebhooksCustomHeaders || []) {
410
- headers[header.key] = header.value;
411
- }
412
425
  }
426
+ Object.assign(
427
+ headers,
428
+ deliveryCustomHeaders(customRoute, customRoute ? null : await settings.get('webhooksCustomHeaders'), accountWebhooksCustomHeaders)
429
+ );
413
430
 
414
431
  let start = Date.now();
415
432
  let duration;
@@ -580,6 +597,8 @@ const notifyWorker = new Worker(
580
597
  )
581
598
  );
582
599
 
600
+ logBullErrors(notifyWorker, 'worker:webhooks');
601
+
583
602
  notifyWorker.on('completed', async job => {
584
603
  metrics(logger, 'queuesProcessed', 'inc', {
585
604
  queue: 'notify',
@@ -1,80 +0,0 @@
1
- #!/usr/bin/env bash
2
- #
3
- # Pre-commit hook: auto-format staged JavaScript with Prettier.
4
- #
5
- # Mirrors the file set covered by `npm run format` (lib/, workers/, test/, and
6
- # top-level *.js); Prettier additionally applies .prettierignore. Installed via the
7
- # "prepare" npm script, which points core.hooksPath at .githooks on `npm install`.
8
- #
9
- # Behavior:
10
- # - Fully-staged files are formatted in place and re-added to the index, so the
11
- # commit records the formatted result.
12
- # - Files that are staged AND still have unstaged changes are only *checked*,
13
- # never rewritten: formatting and re-adding them would sweep unrelated unstaged
14
- # hunks into the commit. If such a file is unformatted, the commit is aborted.
15
-
16
- set -u
17
-
18
- repo_root=$(git rev-parse --show-toplevel) || exit 0
19
- cd "$repo_root" || exit 0
20
-
21
- prettier="./node_modules/.bin/prettier"
22
- if [ ! -x "$prettier" ]; then
23
- echo "pre-commit: Prettier not found ($prettier) - skipping format (run 'npm install')." >&2
24
- exit 0
25
- fi
26
-
27
- # True for paths inside the format-covered set, matching *.js. Case patterns match
28
- # '/' with '*', so lib/*.js also covers nested files; the */* arm excludes anything
29
- # outside the covered directories, leaving top-level *.js to the last arm.
30
- is_covered() {
31
- case "$1" in
32
- lib/*.js | workers/*.js | test/*.js) return 0 ;;
33
- */*) return 1 ;;
34
- *.js) return 0 ;;
35
- *) return 1 ;;
36
- esac
37
- }
38
-
39
- to_format=()
40
- to_check=()
41
- while IFS= read -r -d '' f; do
42
- is_covered "$f" || continue
43
- # `git diff --quiet` compares the working tree to the index for this path:
44
- # exit 0 => no unstaged changes (safe to format+re-add), non-zero => partial.
45
- if git diff --quiet -- "$f"; then
46
- to_format+=("$f")
47
- else
48
- to_check+=("$f")
49
- fi
50
- done < <(git diff --cached --name-only --diff-filter=ACMR -z -- '*.js')
51
-
52
- if [ ${#to_format[@]} -eq 0 ] && [ ${#to_check[@]} -eq 0 ]; then
53
- exit 0
54
- fi
55
-
56
- status=0
57
-
58
- if [ ${#to_check[@]} -gt 0 ]; then
59
- if ! "$prettier" --check "${to_check[@]}"; then
60
- {
61
- echo ""
62
- echo "pre-commit: the staged file(s) above have additional unstaged changes and are not formatted."
63
- echo "They were left untouched to avoid committing unstaged hunks. Run:"
64
- echo " npm run format"
65
- echo "then re-stage and commit."
66
- } >&2
67
- status=1
68
- fi
69
- fi
70
-
71
- if [ ${#to_format[@]} -gt 0 ]; then
72
- if "$prettier" --write "${to_format[@]}"; then
73
- git add -- "${to_format[@]}"
74
- else
75
- echo "pre-commit: Prettier failed on staged files." >&2
76
- status=1
77
- fi
78
- fi
79
-
80
- exit $status
@@ -1,76 +0,0 @@
1
- # Contributor Covenant Code of Conduct
2
-
3
- ## Our Pledge
4
-
5
- In the interest of fostering an open and welcoming environment, we as
6
- contributors and maintainers pledge to making participation in our project and
7
- our community a harassment-free experience for everyone, regardless of age, body
8
- size, disability, ethnicity, sex characteristics, gender identity and expression,
9
- level of experience, education, socio-economic status, nationality, personal
10
- appearance, race, religion, or sexual identity and orientation.
11
-
12
- ## Our Standards
13
-
14
- Examples of behavior that contributes to creating a positive environment
15
- include:
16
-
17
- - Using welcoming and inclusive language
18
- - Being respectful of differing viewpoints and experiences
19
- - Gracefully accepting constructive criticism
20
- - Focusing on what is best for the community
21
- - Showing empathy towards other community members
22
-
23
- Examples of unacceptable behavior by participants include:
24
-
25
- - The use of sexualized language or imagery and unwelcome sexual attention or
26
- advances
27
- - Trolling, insulting/derogatory comments, and personal or political attacks
28
- - Public or private harassment
29
- - Publishing others' private information, such as a physical or electronic
30
- address, without explicit permission
31
- - Other conduct which could reasonably be considered inappropriate in a
32
- professional setting
33
-
34
- ## Our Responsibilities
35
-
36
- Project maintainers are responsible for clarifying the standards of acceptable
37
- behavior and are expected to take appropriate and fair corrective action in
38
- response to any instances of unacceptable behavior.
39
-
40
- Project maintainers have the right and responsibility to remove, edit, or
41
- reject comments, commits, code, wiki edits, issues, and other contributions
42
- that are not aligned to this Code of Conduct, or to ban temporarily or
43
- permanently any contributor for other behaviors that they deem inappropriate,
44
- threatening, offensive, or harmful.
45
-
46
- ## Scope
47
-
48
- This Code of Conduct applies both within project spaces and in public spaces
49
- when an individual is representing the project or its community. Examples of
50
- representing a project or community include using an official project e-mail
51
- address, posting via an official social media account, or acting as an appointed
52
- representative at an online or offline event. Representation of a project may be
53
- further defined and clarified by project maintainers.
54
-
55
- ## Enforcement
56
-
57
- Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
- reported by contacting the project team at andris@emailengine.app. All
59
- complaints will be reviewed and investigated and will result in a response that
60
- is deemed necessary and appropriate to the circumstances. The project team is
61
- obligated to maintain confidentiality with regard to the reporter of an incident.
62
- Further details of specific enforcement policies may be posted separately.
63
-
64
- Project maintainers who do not follow or enforce the Code of Conduct in good
65
- faith may face temporary or permanent repercussions as determined by other
66
- members of the project's leadership.
67
-
68
- ## Attribution
69
-
70
- This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
- available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72
-
73
- [homepage]: https://www.contributor-covenant.org
74
-
75
- For answers to common questions about this code of conduct, see
76
- https://www.contributor-covenant.org/faq
@@ -1,17 +0,0 @@
1
- # Contributing
2
-
3
- ## Legal
4
-
5
- (agreement below borrowed from [Sidekiq Legal](https://github.com/mperham/sidekiq/blob/master/.github/contributing.md))
6
-
7
- By submitting a Pull Request, you disavow any rights or claims to any changes
8
- submitted to the EmailEngine project and assign the copyright of
9
- those changes to Postal Systems OÜ.
10
-
11
- If you cannot or do not want to reassign those rights (your employment
12
- contract for your employer may not allow this), you should not submit a PR.
13
- Open an issue and someone else can do the work.
14
-
15
- This is a legal way of saying "If you submit a PR to us, that code becomes ours".
16
- 99.9% of the time that's what you intend anyways; we hope it doesn't scare you
17
- away from contributing.