emailengine-app 2.81.2 → 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 (204) hide show
  1. package/.ncurc.js +12 -11
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/Dockerfile +2 -0
  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/expected-identity.js +1 -1
  13. package/lib/account-assignment.js +138 -1
  14. package/lib/account.js +254 -859
  15. package/lib/api-reference/index.js +2 -3
  16. package/lib/api-reference/schema-tree.js +53 -3
  17. package/lib/api-routes/account-routes.js +18 -29
  18. package/lib/api-routes/blocklist-routes.js +2 -2
  19. package/lib/api-routes/bull-board-routes.js +1 -6
  20. package/lib/api-routes/export-routes.js +2 -22
  21. package/lib/api-routes/gateway-routes.js +5 -14
  22. package/lib/api-routes/index.js +1 -13
  23. package/lib/api-routes/mailbox-routes.js +2 -7
  24. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  25. package/lib/api-routes/mcp-routes.js +7 -7
  26. package/lib/api-routes/message-routes.js +40 -235
  27. package/lib/api-routes/mint-bounds.js +110 -0
  28. package/lib/api-routes/oauth2-app-routes.js +23 -32
  29. package/lib/api-routes/operation-impact.js +1 -1
  30. package/lib/api-routes/outbox-routes.js +2 -2
  31. package/lib/api-routes/permission-map.js +1 -7
  32. package/lib/api-routes/route-helpers.js +11 -5
  33. package/lib/api-routes/settings-routes.js +19 -19
  34. package/lib/api-routes/stats-routes.js +1 -1
  35. package/lib/api-routes/submit-routes.js +17 -18
  36. package/lib/api-routes/template-routes.js +4 -9
  37. package/lib/api-routes/token-routes.js +27 -5
  38. package/lib/api-token-scheme.js +71 -0
  39. package/lib/arf-detect.js +33 -6
  40. package/lib/auth-token.js +44 -24
  41. package/lib/autodetect-imap-settings.js +163 -123
  42. package/lib/bounce-detect.js +25 -16
  43. package/lib/calendar-event.js +78 -0
  44. package/lib/consts.js +42 -5
  45. package/lib/create-imap-client.js +24 -0
  46. package/lib/db.js +76 -11
  47. package/lib/delivery-error.js +2 -1
  48. package/lib/egress-fetch.js +54 -3
  49. package/lib/egress-filter.js +11 -0
  50. package/lib/email-client/api-retry.js +147 -0
  51. package/lib/email-client/base-client.js +377 -523
  52. package/lib/email-client/gmail/gmail-api.js +38 -125
  53. package/lib/email-client/gmail/send-request.js +1 -1
  54. package/lib/email-client/gmail-client.js +76 -50
  55. package/lib/email-client/imap/mailbox.js +158 -324
  56. package/lib/email-client/imap/stale-view.js +109 -0
  57. package/lib/email-client/imap/subconnection.js +46 -9
  58. package/lib/email-client/imap/sync-operations.js +5 -37
  59. package/lib/email-client/imap-client.js +188 -64
  60. package/lib/email-client/message-builder.js +9 -14
  61. package/lib/email-client/notification-handler.js +5 -219
  62. package/lib/email-client/outlook/graph-api.js +147 -126
  63. package/lib/email-client/outlook/send-request.js +10 -4
  64. package/lib/email-client/outlook-client.js +194 -397
  65. package/lib/email-client/smtp-pool-manager.js +3 -2
  66. package/lib/encrypt.js +184 -19
  67. package/lib/enum-descriptions.js +1 -2
  68. package/lib/export.js +133 -39
  69. package/lib/gateway.js +20 -6
  70. package/lib/get-raw-email.js +26 -44
  71. package/lib/handlebars-helpers.js +31 -10
  72. package/lib/imap-proxy-auth.js +13 -29
  73. package/lib/imapproxy/imap-core/README.md +1 -0
  74. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  75. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  76. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  77. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  78. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  79. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  80. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  81. package/lib/imapproxy/imap-server.js +17 -177
  82. package/lib/imapproxy/proxy-handoff.js +235 -0
  83. package/lib/imapproxy/response-error.js +33 -0
  84. package/lib/imapproxy/upstream-client.js +2 -2
  85. package/lib/license-beacon.js +3 -9
  86. package/lib/llm-pre-process.js +182 -43
  87. package/lib/logger.js +1 -1
  88. package/lib/lua/ee-export-queue-add.lua +39 -0
  89. package/lib/lua/ee-get-idempotency.lua +15 -3
  90. package/lib/lua/ee-release-attempts.lua +23 -0
  91. package/lib/lua/ee-reserve-attempts.lua +42 -0
  92. package/lib/lua/h-set-bigger.lua +12 -2
  93. package/lib/lua/s-list-accounts.lua +6 -3
  94. package/lib/mcp/index.js +1 -2
  95. package/lib/mcp/listen.js +221 -18
  96. package/lib/mcp/oauth.js +44 -5
  97. package/lib/mcp/resources.js +8 -2
  98. package/lib/mcp/tools.js +13 -0
  99. package/lib/message-port-stream.js +64 -6
  100. package/lib/oauth/external-account-signer.js +16 -13
  101. package/lib/oauth/gmail.js +22 -20
  102. package/lib/oauth/outlook.js +19 -16
  103. package/lib/oauth/pubsub/google.js +38 -2
  104. package/lib/oauth/scope-checker.js +4 -7
  105. package/lib/oauth/verify-app.js +2 -2
  106. package/lib/oauth2-apps.js +139 -44
  107. package/lib/openapi/build-document.js +1 -1
  108. package/lib/openapi/joi-schema.js +78 -9
  109. package/lib/parse-message.js +21 -0
  110. package/lib/payload-examples-webhooks.json +4 -7
  111. package/lib/pbkdf2-phc.js +101 -0
  112. package/lib/privileged-settings.js +0 -14
  113. package/lib/rate-limit.js +54 -15
  114. package/lib/redis-scan-delete.js +56 -29
  115. package/lib/redis-url.js +3 -1
  116. package/lib/respawn-backoff.js +5 -4
  117. package/lib/response-stream.js +25 -4
  118. package/lib/rewrite-text-nodes.js +27 -40
  119. package/lib/routes-ui.js +0 -5
  120. package/lib/schemas.js +122 -242
  121. package/lib/sentry.js +21 -5
  122. package/lib/settings.js +58 -59
  123. package/lib/smtp-auth.js +6 -2
  124. package/lib/smtp-message-processor.js +28 -7
  125. package/lib/sso.js +7 -3
  126. package/lib/stream-encrypt.js +14 -13
  127. package/lib/swagger-options.js +3 -1
  128. package/lib/tls/provision.js +69 -3
  129. package/lib/tls/store.js +14 -1
  130. package/lib/tools.js +113 -52
  131. package/lib/totp.js +16 -1
  132. package/lib/ui-routes/account-routes.js +27 -63
  133. package/lib/ui-routes/admin-config-routes.js +111 -134
  134. package/lib/ui-routes/admin-entities-routes.js +101 -191
  135. package/lib/ui-routes/ai-options.js +104 -0
  136. package/lib/ui-routes/auth-routes.js +98 -18
  137. package/lib/ui-routes/export-routes.js +3 -23
  138. package/lib/ui-routes/internals-routes.js +12 -9
  139. package/lib/ui-routes/network-config-routes.js +8 -18
  140. package/lib/ui-routes/oauth-config-routes.js +80 -214
  141. package/lib/ui-routes/route-helpers.js +40 -44
  142. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  143. package/lib/utils/decode-headers.js +32 -5
  144. package/lib/utils/header-map.js +62 -1
  145. package/lib/utils/network.js +2 -0
  146. package/lib/web-safe-html.js +77 -4
  147. package/lib/webhook-request.js +9 -1
  148. package/lib/webhook-routing.js +27 -1
  149. package/lib/webhooks.js +120 -43
  150. package/lib/worker-rpc-error.js +43 -2
  151. package/list-generate.js +13 -2
  152. package/package.json +33 -41
  153. package/sbom.json +1 -1
  154. package/scripts/refresh-test-tokens.js +42 -14
  155. package/server.js +317 -289
  156. package/static/css/flyonui.css +1 -1
  157. package/static/css/src/app.tailwind.css +7 -8
  158. package/static/js/ee-client.js +145 -70
  159. package/static/js/ui.js +350 -154
  160. package/static/licenses.html +434 -1835
  161. package/translations/messages.pot +97 -97
  162. package/views/accounts/browse.hbs +10 -4
  163. package/views/config/ai.hbs +49 -41
  164. package/views/config/oauth/app.hbs +2 -1
  165. package/views/dashboard.hbs +18 -16
  166. package/views/layout/app.hbs +0 -22
  167. package/views/layout/login.hbs +2 -1
  168. package/views/partials/filter_editor_js.hbs +4 -3
  169. package/views/partials/side_menu.hbs +0 -4
  170. package/views/partials/ui/account-picker.hbs +6 -32
  171. package/views/partials/ui/model-picker.hbs +31 -0
  172. package/views/partials/ui/pagination.hbs +6 -1
  173. package/views/partials/ui/picker.hbs +47 -0
  174. package/views/unsubscribe.hbs +1 -1
  175. package/workers/api.js +20 -20
  176. package/workers/export.js +55 -60
  177. package/workers/imap.js +126 -46
  178. package/workers/submit.js +3 -1
  179. package/workers/webhooks.js +46 -27
  180. package/.githooks/pre-commit +0 -80
  181. package/.github/CODE_OF_CONDUCT.md +0 -76
  182. package/.github/contributing.md +0 -17
  183. package/.github/dependabot.yml +0 -22
  184. package/.github/docker-smoke-test.sh +0 -61
  185. package/.github/workflows/deploy.yml +0 -215
  186. package/.github/workflows/e2e.yml +0 -55
  187. package/.github/workflows/release.yaml +0 -217
  188. package/.github/workflows/test.yml +0 -307
  189. package/lib/api-routes/chat-routes.js +0 -535
  190. package/lib/document-store.js +0 -75
  191. package/lib/es.js +0 -757
  192. package/lib/generate-text-preview.js +0 -61
  193. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  194. package/lib/pre-process.js +0 -196
  195. package/lib/threads.js +0 -155
  196. package/lib/ui-routes/document-store-routes.js +0 -806
  197. package/playwright.config.js +0 -47
  198. package/views/config/document-store/chat.hbs +0 -286
  199. package/views/config/document-store/index.hbs +0 -146
  200. package/views/config/document-store/mappings/index.hbs +0 -108
  201. package/views/config/document-store/mappings/new.hbs +0 -68
  202. package/views/config/document-store/pre-processing/index.hbs +0 -103
  203. package/views/partials/document_store_header.hbs +0 -30
  204. package/workers/documents.js +0 -1128
package/workers/imap.js CHANGED
@@ -18,18 +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');
23
+ const { packRpcError, unpackRpcError, describeRpcCommand } = require('../lib/worker-rpc-error');
24
24
  const { ImapFlowErrorCode } = require('imapflow');
25
- const { getESClient } = require('../lib/document-store');
26
25
  const settings = require('../lib/settings');
27
26
  const msgpack = require('../lib/msgpack');
28
27
 
29
28
  const getSecret = require('../lib/get-secret');
30
29
 
31
- const flowProducer = getFlowProducer();
32
-
33
30
  config.service = config.service || {};
34
31
 
35
32
  config.log = config.log || {
@@ -63,35 +60,29 @@ class ConnectionHandler {
63
60
  this.mids = 0;
64
61
 
65
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();
66
72
  }
67
73
 
68
74
  async init() {
69
- // Track Redis connection state for reconnection detection
70
- let hasSeenStableConnection = false;
71
- let redisWasDisconnected = false;
72
-
73
- // Check initial Redis state
74
- if (redis.status === 'ready') {
75
- hasSeenStableConnection = true;
76
- }
77
-
78
- redis.on('ready', () => {
79
- if (redisWasDisconnected && hasSeenStableConnection) {
80
- // 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
+ () => {
81
81
  logger.info({ msg: 'Redis reconnected after disconnection, exiting worker for clean restart', worker: 'imap' });
82
- // Exit gracefully - the main process will restart this worker
83
82
  process.exit(0);
84
- }
85
- // Mark that we've seen a stable connection
86
- hasSeenStableConnection = true;
87
- });
88
-
89
- redis.on('end', () => {
90
- if (hasSeenStableConnection) {
91
- logger.warn({ msg: 'Redis connection lost', worker: 'imap' });
92
- redisWasDisconnected = true;
93
- }
94
- });
83
+ },
84
+ () => logger.warn({ msg: 'Redis connection lost', worker: 'imap' })
85
+ );
95
86
 
96
87
  // indicate that we are ready to process connections
97
88
  parentPort.postMessage({ cmd: 'ready' });
@@ -187,6 +178,34 @@ class ConnectionHandler {
187
178
  return accountLogger;
188
179
  }
189
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
+
190
209
  async assignConnection(account, runIndex, initOpts) {
191
210
  logger.debug({ msg: 'Assigned account to worker', account });
192
211
 
@@ -198,6 +217,10 @@ class ConnectionHandler {
198
217
  runIndex = this.runIndex;
199
218
  }
200
219
 
220
+ const token = Symbol(account);
221
+ this.assignTokens.set(account, token);
222
+ const isCurrent = () => this.assignTokens.get(account) === token;
223
+
201
224
  let accountLogger = await this.getAccountLogger(account);
202
225
  let secret = await getSecret();
203
226
  let accountObject = new Account({
@@ -206,12 +229,65 @@ class ConnectionHandler {
206
229
  secret,
207
230
  // Needed so Account.update() can dispatch reconnect/update commands back to
208
231
  // this worker (e.g. auto-reconnect after OAuth re-auth in an error state).
209
- call: msg => this.call(msg),
210
- esClient: await getESClient(logger)
232
+ call: msg => this.call(msg)
211
233
  });
212
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);
213
245
  this.accounts.set(account, accountObject);
246
+ await this.closeReleasedConnection(account, previous);
214
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 }) {
215
291
  const accountData = await accountObject.loadAccountData();
216
292
 
217
293
  if (accountData.oauth2 && accountData.oauth2.auth) {
@@ -245,8 +321,6 @@ class ConnectionHandler {
245
321
 
246
322
  notifyQueue,
247
323
  submitQueue,
248
- documentsQueue,
249
- flowProducer,
250
324
 
251
325
  call: msg => this.call(msg)
252
326
  });
@@ -265,8 +339,6 @@ class ConnectionHandler {
265
339
 
266
340
  notifyQueue,
267
341
  submitQueue,
268
- documentsQueue,
269
- flowProducer,
270
342
 
271
343
  call: msg => this.call(msg)
272
344
  });
@@ -291,8 +363,6 @@ class ConnectionHandler {
291
363
 
292
364
  notifyQueue,
293
365
  submitQueue,
294
- documentsQueue,
295
- flowProducer,
296
366
 
297
367
  call: msg => this.call(msg),
298
368
  logRaw: EENGINE_LOG_RAW
@@ -300,13 +370,16 @@ class ConnectionHandler {
300
370
  accountObject.logger = accountObject.connection.logger;
301
371
  }
302
372
 
373
+ if (!isCurrent()) {
374
+ return false;
375
+ }
376
+
303
377
  if (accountData.state) {
304
378
  await redis.hSetExists(accountObject.connection.getAccountKey(), 'state', accountData.state);
305
379
  await emitChangeEvent(logger, account, 'state', accountData.state);
306
380
  }
307
381
 
308
- // do not wait before returning as it may take forever
309
- this.startConnection(account, accountObject, initOpts);
382
+ return isCurrent();
310
383
  }
311
384
 
312
385
  /**
@@ -342,6 +415,7 @@ class ConnectionHandler {
342
415
 
343
416
  async deleteConnection(account) {
344
417
  logger.info({ msg: 'Deleting connection', account });
418
+ this.assignTokens.delete(account);
345
419
  if (this.accounts.has(account)) {
346
420
  let accountObject = this.accounts.get(account);
347
421
  if (accountObject.connection) {
@@ -441,7 +515,12 @@ class ConnectionHandler {
441
515
  msg: 'Account reconnection requested'
442
516
  });
443
517
 
444
- 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
+ }
445
524
  }
446
525
 
447
526
  await this.assignConnection(account, false, { forceWatchRenewal: true });
@@ -860,9 +939,12 @@ class ConnectionHandler {
860
939
  logger.info({ msg: 'Closing account connections', accounts: this.accounts.size });
861
940
  this.connectionsClosed = true;
862
941
 
863
- this.accounts.forEach(accountObject => {
942
+ this.accounts.forEach((accountObject, account) => {
864
943
  if (accountObject && accountObject.connection) {
865
- 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 }));
866
948
  }
867
949
  });
868
950
  }
@@ -913,6 +995,7 @@ class ConnectionHandler {
913
995
  return true;
914
996
 
915
997
  case 'delete':
998
+ case 'unassign':
916
999
  case 'update':
917
1000
  case 'sync':
918
1001
  case 'pause':
@@ -1050,9 +1133,6 @@ parentPort.on('message', message => {
1050
1133
  });
1051
1134
  })
1052
1135
  .catch(err => {
1053
- if (message.message && message.message.data && message.message.data.raw) {
1054
- message.message.data.raw = message.message.data.raw.length;
1055
- }
1056
1136
  // Anything with a client-facing status (404 not found, 503 no active handler) is
1057
1137
  // reported back to the caller as the command response, so it is not a server fault.
1058
1138
  // 503 is excluded from the error branch on purpose: both "no active handler" and
@@ -1064,7 +1144,7 @@ parentPort.on('message', message => {
1064
1144
  err.statusCode = 429;
1065
1145
  }
1066
1146
  let isServerFault = !err.statusCode || (err.statusCode >= 500 && err.statusCode !== 503);
1067
- logger[isServerFault ? 'error' : 'debug'](Object.assign({ msg: 'Command failed' }, message, { err }));
1147
+ logger[isServerFault ? 'error' : 'debug'](Object.assign(describeRpcCommand(message), { msg: 'Command failed', err }));
1068
1148
  parentPort.postMessage(Object.assign({ cmd: 'resp', mid: message.mid }, packRpcError(err)));
1069
1149
  });
1070
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.
@@ -1,22 +0,0 @@
1
- version: 2
2
-
3
- updates:
4
- # The Node base image is the one dependency that goes stale without any diff to review, which is
5
- # how it ended up 19 months behind. This entry exists to keep the digest current, nothing else.
6
- - package-ecosystem: docker
7
- directory: /
8
- schedule:
9
- interval: weekly
10
- commit-message:
11
- # `fix:` rather than `chore:`, so a base image bump reaches users through the release notes
12
- # instead of being filtered out of them
13
- prefix: fix
14
- # Digest updates only. The Node major is a deliberate choice that has to stay in step with the
15
- # CI matrix, the pkg targets and the deploy workflow, and it tracks Active LTS rather than
16
- # Current - left unignored, the first run proposed 24-alpine to 26-alpine, which is exactly the
17
- # drift this entry is meant to prevent. Moving the major is a manual decision.
18
- ignore:
19
- - dependency-name: node
20
- update-types:
21
- - version-update:semver-major
22
- - version-update:semver-minor