emailengine-app 2.87.0 → 2.87.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +19 -0
  4. package/Dockerfile +3 -4
  5. package/bin/emailengine.js +2 -4
  6. package/bin/healthcheck.js +20 -0
  7. package/data/google-crawlers.json +1 -1
  8. package/data/public_suffix_list.dat +3 -7
  9. package/lib/account/auth-failure-backfill.js +3 -2
  10. package/lib/account/expected-identity.js +2 -2
  11. package/lib/account.js +9 -8
  12. package/lib/api-listener.js +40 -0
  13. package/lib/api-token-auth.js +406 -0
  14. package/lib/autodetect-imap-settings.js +36 -3
  15. package/lib/consts.js +5 -0
  16. package/lib/email-client/base-client.js +23 -107
  17. package/lib/email-client/gmail-client.js +7 -4
  18. package/lib/email-client/imap/mailbox.js +89 -96
  19. package/lib/email-client/imap/sync-operations.js +13 -6
  20. package/lib/email-client/imap-client.js +28 -7
  21. package/lib/email-client/new-message-steps.js +162 -0
  22. package/lib/email-client/outlook-client.js +4 -2
  23. package/lib/env-setting-overrides.js +6 -2
  24. package/lib/export-worker.js +3 -2
  25. package/lib/export.js +43 -4
  26. package/lib/get-boolean.js +38 -0
  27. package/lib/health-probe.js +71 -0
  28. package/lib/imapproxy/imap-server.js +4 -55
  29. package/lib/net-tos-guard.js +42 -0
  30. package/lib/oauth2-apps.js +2 -1
  31. package/lib/read-env-value.js +19 -7
  32. package/lib/redis-keys.js +19 -0
  33. package/lib/redis-operations.js +7 -3
  34. package/lib/security-headers.js +18 -0
  35. package/lib/session-default.js +50 -0
  36. package/lib/settings.js +2 -1
  37. package/lib/stream-encrypt.js +71 -20
  38. package/lib/sub-script.js +8 -2
  39. package/lib/submit-lock.js +84 -0
  40. package/lib/submit-processor.js +283 -0
  41. package/lib/templates.js +6 -3
  42. package/lib/tls/context.js +2 -16
  43. package/lib/tools.js +8 -30
  44. package/lib/utils/redis-errors.js +44 -0
  45. package/lib/webhook-delivery.js +3 -4
  46. package/lib/worker-rpc-error.js +10 -5
  47. package/lib/worker-rpc.js +138 -0
  48. package/package.json +17 -19
  49. package/sbom.json +370 -1446
  50. package/server.js +6 -5
  51. package/static/css/flyonui.css +2 -2
  52. package/static/licenses.html +253 -1366
  53. package/translations/messages.pot +16 -16
  54. package/workers/api.js +41 -465
  55. package/workers/export.js +14 -55
  56. package/workers/imap-proxy.js +5 -18
  57. package/workers/imap.js +27 -49
  58. package/workers/smtp.js +7 -69
  59. package/workers/submit.js +21 -279
  60. package/workers/webhooks.js +7 -72
package/workers/submit.js CHANGED
@@ -6,7 +6,6 @@ const packageData = require('../package.json');
6
6
  const config = require('@zone-eu/wild-config');
7
7
  const logger = require('../lib/logger');
8
8
 
9
- const { REDIS_PREFIX } = require('../lib/consts');
10
9
  const { getDuration, readEnvValue, threadStats } = require('../lib/tools');
11
10
  const { webhooks: Webhooks } = require('../lib/webhooks');
12
11
  const settings = require('../lib/settings');
@@ -16,10 +15,10 @@ initSentry('submit');
16
15
 
17
16
  const util = require('util');
18
17
  const { redis, queueConf, submitQueue, logBullErrors } = require('../lib/db');
19
- const { Worker, UnrecoverableError } = require('bullmq');
18
+ const { Worker } = require('bullmq');
20
19
  const { Account } = require('../lib/account');
21
20
  const getSecret = require('../lib/get-secret');
22
- const { decodeQueueEntry, retainFailedContent } = require('../lib/outbox');
21
+ const { retainFailedContent } = require('../lib/outbox');
23
22
 
24
23
  const { EMAIL_FAILED_NOTIFY } = require('../lib/consts');
25
24
 
@@ -42,45 +41,12 @@ const SUBMIT_QC = (readEnvValue('EENGINE_SUBMIT_QC') && Number(readEnvValue('EEN
42
41
 
43
42
  const SUBMIT_DELAY = getDuration(readEnvValue('EENGINE_SUBMIT_DELAY') || config.submitDelay) || null;
44
43
 
45
- const { shouldDiscardJob, willBeFinalAttempt, isFinalFailedAttempt, nextAttemptWhileProcessing } = require('../lib/delivery-error');
46
- const { isAlreadySent } = require('../lib/submit-progress');
47
- const { packRpcError, unpackRpcError } = require('../lib/worker-rpc-error');
48
-
49
- let callQueue = new Map();
50
- let mids = 0;
51
-
52
- async function call(message, transferList) {
53
- return new Promise((resolve, reject) => {
54
- let mid = `${Date.now()}:${++mids}`;
55
-
56
- let ttl = Math.max(message.timeout || 0, EENGINE_TIMEOUT || 0);
57
- let timer = setTimeout(() => {
58
- let err = new Error('Timeout waiting for command response [T5]');
59
- err.statusCode = 504;
60
- err.code = 'Timeout';
61
- err.ttl = ttl;
62
- callQueue.delete(mid);
63
- reject(err);
64
- }, ttl);
65
-
66
- callQueue.set(mid, { resolve, reject, timer });
67
-
68
- try {
69
- parentPort.postMessage(
70
- {
71
- cmd: 'call',
72
- mid,
73
- message
74
- },
75
- transferList
76
- );
77
- } catch (err) {
78
- clearTimeout(timer);
79
- callQueue.delete(mid);
80
- return reject(err);
81
- }
82
- });
83
- }
44
+ const { isFinalFailedAttempt } = require('../lib/delivery-error');
45
+ const { createSubmitProcessor, completeSubmission, normalizeQueueId } = require('../lib/submit-processor');
46
+
47
+ const { createRpcClient, respond, isCall } = require('../lib/worker-rpc');
48
+ const rpc = createRpcClient({ port: parentPort, defaultTimeout: EENGINE_TIMEOUT, timeoutTag: 'T5' });
49
+ const call = rpc.call;
84
50
 
85
51
  async function metrics(logger, key, method, ...args) {
86
52
  try {
@@ -137,206 +103,12 @@ for (let level of ['trace', 'debug', 'info', 'warn', 'error', 'fatal']) {
137
103
 
138
104
  const submitWorker = new Worker(
139
105
  'submit',
140
- async job => {
141
- if (!job.data.queueId && job.data.qId) {
142
- // this value was used to be called qId
143
- job.data.queueId = job.data.qId;
144
- }
145
-
146
- // A job re-run after a stall (heartbeat kill, crash, a shutdown drain that could not cover
147
- // a long SMTP transaction plus the Sent-folder upload) comes back with the progress its
148
- // previous run stored. Once that says the MTA accepted the message, sending again would
149
- // deliver a duplicate under the same queueId: the message is done, only the bookkeeping
150
- // after the 250 was cut short. The catch below covers the same state for a run that got
151
- // as far as throwing; this covers the run that never got to throw anything.
152
- if (isAlreadySent(job.progress)) {
153
- logger.info({
154
- msg: 'Skipping re-run of an already sent message',
155
- action: 'submit',
156
- queue: job.queue.name,
157
- code: 'result_success',
158
- job: job.id,
159
- event: job.name,
160
- account: job.data.account,
161
- queueId: job.data.queueId,
162
- messageId: job.data.messageId,
163
- progress: job.progress.status,
164
- attemptsMade: job.attemptsMade
165
- });
166
- return;
167
- }
168
-
169
- let queueEntryBuf = await redis.hgetBuffer(`${REDIS_PREFIX}iaq:${job.data.account}`, job.data.queueId);
170
- if (!queueEntryBuf) {
171
- // nothing to do here
172
- try {
173
- await redis.hdel(`${REDIS_PREFIX}iaq:${job.data.account}`, job.data.queueId);
174
- } catch (err) {
175
- // ignore
176
- }
177
- return;
178
- }
179
-
180
- let queueEntry;
181
- try {
182
- // Rejects a value that decodes to something other than a map as well, otherwise the
183
- // job metadata assignment below throws a TypeError against it and the entry is retried
184
- // as a failed delivery instead of being dropped as the corrupt entry it is
185
- queueEntry = decodeQueueEntry(queueEntryBuf);
186
- } catch (err) {
187
- logger.error({ msg: 'Failed to parse queued email entry', job: job.id, account: job.data.account, queueId: job.data.queueId, err });
188
- try {
189
- await redis.hdel(`${REDIS_PREFIX}iaq:${job.data.account}`, job.data.queueId);
190
- } catch (err) {
191
- // ignore
192
- }
193
- return;
194
- }
195
-
196
- let accountObject = new Account({ account: job.data.account, redis, call, secret: await getSecret() });
197
-
198
- logger.trace({
199
- msg: 'Processing message',
200
- action: 'submit',
201
- queue: job.queue.name,
202
- code: 'processing',
203
- job: job.id,
204
- event: job.name,
205
- data: job.data,
206
- account: job.data.account
207
- });
208
-
209
- try {
210
- try {
211
- // try to update
212
- await job.updateProgress({
213
- status: 'processing'
214
- });
215
- } catch (err) {
216
- // ignore
217
- }
218
-
219
- let nextAttempt = nextAttemptWhileProcessing(job);
220
-
221
- queueEntry.job = {
222
- id: job.id,
223
- attemptsMade: job.attemptsMade,
224
- attempts: job.opts.attempts,
225
- nextAttempt: nextAttempt ? new Date(nextAttempt).toISOString() : false
226
- };
227
-
228
- let res = await accountObject.submitMessage(queueEntry);
229
-
230
- logger.trace({
231
- msg: 'Submitted queued message for delivery',
232
- action: 'submit',
233
- queue: job.queue.name,
234
- code: 'result_success',
235
- job: job.id,
236
- event: job.name,
237
- data: job.data,
238
- account: job.data.account
239
- });
240
-
241
- try {
242
- // try to update
243
- await job.updateProgress({
244
- status: 'submitted',
245
- response: res.response
246
- });
247
- } catch (err) {
248
- // ignore
249
- }
250
- } catch (err) {
251
- try {
252
- const submitJobEntry = await submitQueue.getJob(job.id);
253
- if (submitJobEntry && isAlreadySent(submitJobEntry.progress)) {
254
- // SMTP transition succeeded, can accept even if the process yielded in error
255
- logger.trace({
256
- msg: 'Submitted queued message for delivery',
257
- action: 'submit',
258
- queue: job.queue.name,
259
- code: 'result_success',
260
- job: job.id,
261
- event: job.name,
262
- data: job.data,
263
- account: job.data.account,
264
- err
265
- });
266
- return;
267
- }
268
- } catch (err) {
269
- logger.error({
270
- msg: 'Failed to fetch job status',
271
- job: job.id,
272
- account: job.data.account,
273
- err
274
- });
275
- }
276
-
277
- const discardJob = shouldDiscardJob(err, job);
278
- const isFinalAttempt = discardJob || willBeFinalAttempt(job);
279
-
280
- logger[isFinalAttempt ? 'error' : 'warn']({
281
- msg: 'Message submission failed',
282
- action: 'submit',
283
- queue: job.queue.name,
284
- code: 'result_fail',
285
- job: job.id,
286
- event: job.name,
287
- data: job.data,
288
- account: job.data.account,
289
- err
290
- });
291
-
292
- try {
293
- // try to update
294
- await job.updateProgress({
295
- status: 'error',
296
- error: {
297
- message: err.message,
298
- code: err.code,
299
- statusCode: err.statusCode,
300
- // the SMTP reply code, when there was a reply: what decides whether the
301
- // failure is permanent (lib/delivery-error.js), kept so the queue browser
302
- // can say so without a rule of its own
303
- responseCode: err.responseCode
304
- },
305
- networkRouting: err.info?.networkRouting
306
- });
307
- } catch (err) {
308
- // ignore
309
- }
310
-
311
- if (discardJob) {
312
- // Do not retry after a permanent rejection (5xx except 503, which is transient).
313
- // BullMQ 6 removed Job#discard(), so the way to end a job before its attempts are
314
- // spent is to throw UnrecoverableError. The stack is carried over because the
315
- // 'failed' handler reports job.stacktrace[0] as the error in the failure webhook -
316
- // constructing a bare UnrecoverableError would replace the SMTP reason with
317
- // "UnrecoverableError" there.
318
- let unrecoverableErr = new UnrecoverableError(err.message);
319
- unrecoverableErr.stack = err.stack;
320
- unrecoverableErr.code = err.code;
321
- unrecoverableErr.responseCode = err.responseCode;
322
- unrecoverableErr.statusCode = err.statusCode;
323
-
324
- logger.info({
325
- msg: 'Job discarded',
326
- job: job.id,
327
- account: queueEntry.account,
328
- queueId: job.data.queueId,
329
- messageId: job.data.messageId,
330
- errorCode: err.code,
331
- responseCode: err.responseCode
332
- });
333
-
334
- throw unrecoverableErr;
335
- }
336
-
337
- throw err;
338
- }
339
- },
106
+ createSubmitProcessor({
107
+ redis,
108
+ logger,
109
+ submitQueue,
110
+ getAccount: async account => new Account({ account, redis, call, secret: await getSecret() })
111
+ }),
340
112
  Object.assign(
341
113
  {
342
114
  concurrency: SUBMIT_QC,
@@ -371,18 +143,8 @@ submitWorker.on('completed', async job => {
371
143
  status: 'completed'
372
144
  });
373
145
 
374
- if (!job.data.queueId && job.data.qId) {
375
- // this value was used to be called qId
376
- job.data.queueId = job.data.qId;
377
- }
378
-
379
- if (job.data && job.data.account && job.data.queueId) {
380
- try {
381
- await redis.hdel(`${REDIS_PREFIX}iaq:${job.data.account}`, job.data.queueId);
382
- } catch (err) {
383
- logger.error({ msg: 'Failed to remove queue entry', account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId, err });
384
- }
385
- }
146
+ // BullMQ emits this only once the completion is stored, which is what lets the sent marker go
147
+ await completeSubmission(job, { redis, logger });
386
148
 
387
149
  logger.info({
388
150
  msg: 'Submission queue entry completed',
@@ -404,10 +166,7 @@ submitWorker.on('failed', async job => {
404
166
  // attempts and being ended early by the UnrecoverableError thrown for a permanent rejection.
405
167
  if (job.finishedOn) {
406
168
  // this was the final attempt
407
- if (!job.data.queueId && job.data.qId) {
408
- // this value was used to be called qId
409
- job.data.queueId = job.data.qId;
410
- }
169
+ normalizeQueueId(job);
411
170
  if (job.data && job.data.account && job.data.queueId) {
412
171
  // The content stays stored, within the failed-content bounds, so the message can be
413
172
  // retried from the queue browser or the outbox API. It used to be deleted here, which
@@ -495,29 +254,12 @@ setInterval(() => {
495
254
  parentPort.postMessage({ cmd: 'ready' });
496
255
 
497
256
  parentPort.on('message', message => {
498
- if (message && message.cmd === 'resp' && message.mid && callQueue.has(message.mid)) {
499
- let { resolve, reject, timer } = callQueue.get(message.mid);
500
- clearTimeout(timer);
501
- callQueue.delete(message.mid);
502
- if (message.error) {
503
- return reject(unpackRpcError(message));
504
- } else {
505
- return resolve(message.response);
506
- }
257
+ if (rpc.handleResponse(message)) {
258
+ return;
507
259
  }
508
260
 
509
- if (message && message.cmd === 'call' && message.mid) {
510
- return onCommand(message.message)
511
- .then(response => {
512
- parentPort.postMessage({
513
- cmd: 'resp',
514
- mid: message.mid,
515
- response
516
- });
517
- })
518
- .catch(err => {
519
- parentPort.postMessage(Object.assign({ cmd: 'resp', mid: message.mid }, packRpcError(err)));
520
- });
261
+ if (isCall(message)) {
262
+ return respond(parentPort, message, onCommand, { logger });
521
263
  }
522
264
  });
523
265
 
@@ -39,41 +39,9 @@ const NOTIFY_QC = (readEnvValue('EENGINE_NOTIFY_QC') && Number(readEnvValue('EEN
39
39
  // DEFAULT_WEBHOOK_REQUEST_TIMEOUT baked into sendWebhookRequest when unset
40
40
  const WEBHOOK_TIMEOUT = getDuration(readEnvValue('EENGINE_WEBHOOK_TIMEOUT')) || false;
41
41
 
42
- let callQueue = new Map();
43
- let mids = 0;
44
-
45
- async function call(message, transferList) {
46
- return new Promise((resolve, reject) => {
47
- let mid = `${Date.now()}:${++mids}`;
48
-
49
- let ttl = Math.max(message.timeout || 0, EENGINE_TIMEOUT || 0);
50
- let timer = setTimeout(() => {
51
- let err = new Error('Timeout waiting for command response [T6]');
52
- err.statusCode = 504;
53
- err.code = 'Timeout';
54
- err.ttl = ttl;
55
- callQueue.delete(mid);
56
- reject(err);
57
- }, ttl);
58
-
59
- callQueue.set(mid, { resolve, reject, timer });
60
-
61
- try {
62
- parentPort.postMessage(
63
- {
64
- cmd: 'call',
65
- mid,
66
- message
67
- },
68
- transferList
69
- );
70
- } catch (err) {
71
- clearTimeout(timer);
72
- callQueue.delete(mid);
73
- return reject(err);
74
- }
75
- });
76
- }
42
+ const { createRpcClient, respond, isCall } = require('../lib/worker-rpc');
43
+ const rpc = createRpcClient({ port: parentPort, defaultTimeout: EENGINE_TIMEOUT, timeoutTag: 'T6' });
44
+ const call = rpc.call;
77
45
 
78
46
  const googlePubSub = new GooglePubSub({
79
47
  call
@@ -150,45 +118,12 @@ parentPort.on('close', () => {
150
118
  parentPort.postMessage({ cmd: 'ready' });
151
119
 
152
120
  parentPort.on('message', message => {
153
- if (message && message.cmd === 'resp' && message.mid && callQueue.has(message.mid)) {
154
- let { resolve, reject, timer } = callQueue.get(message.mid);
155
- clearTimeout(timer);
156
- callQueue.delete(message.mid);
157
- if (message.error) {
158
- let err = new Error(message.error);
159
- if (message.code) {
160
- err.code = message.code;
161
- }
162
- if (message.statusCode) {
163
- err.statusCode = message.statusCode;
164
- }
165
- if (message.info) {
166
- err.info = message.info;
167
- }
168
- return reject(err);
169
- } else {
170
- return resolve(message.response);
171
- }
121
+ if (rpc.handleResponse(message)) {
122
+ return;
172
123
  }
173
124
 
174
- if (message && message.cmd === 'call' && message.mid) {
175
- return onCommand(message.message)
176
- .then(response => {
177
- parentPort.postMessage({
178
- cmd: 'resp',
179
- mid: message.mid,
180
- response
181
- });
182
- })
183
- .catch(err => {
184
- parentPort.postMessage({
185
- cmd: 'resp',
186
- mid: message.mid,
187
- error: err.message,
188
- code: err.code,
189
- statusCode: err.statusCode
190
- });
191
- });
125
+ if (isCall(message)) {
126
+ return respond(parentPort, message, onCommand, { logger });
192
127
  }
193
128
  });
194
129