emailengine-app 2.87.0 → 2.87.2

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 (71) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -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/dbsc/index.js +292 -0
  17. package/lib/dbsc/jwt.js +157 -0
  18. package/lib/dbsc/protocol.js +132 -0
  19. package/lib/dbsc/store.js +136 -0
  20. package/lib/email-client/base-client.js +23 -107
  21. package/lib/email-client/gmail-client.js +7 -4
  22. package/lib/email-client/imap/mailbox.js +89 -96
  23. package/lib/email-client/imap/sync-operations.js +13 -6
  24. package/lib/email-client/imap-client.js +28 -7
  25. package/lib/email-client/new-message-steps.js +162 -0
  26. package/lib/email-client/outlook-client.js +4 -2
  27. package/lib/env-setting-overrides.js +6 -2
  28. package/lib/export-worker.js +3 -2
  29. package/lib/export.js +43 -4
  30. package/lib/get-boolean.js +38 -0
  31. package/lib/health-probe.js +71 -0
  32. package/lib/imapproxy/imap-server.js +4 -55
  33. package/lib/net-tos-guard.js +42 -0
  34. package/lib/oauth2-apps.js +2 -1
  35. package/lib/privileged-settings.js +6 -0
  36. package/lib/read-env-value.js +19 -7
  37. package/lib/redis-keys.js +19 -0
  38. package/lib/redis-operations.js +7 -3
  39. package/lib/routes-ui.js +4 -1
  40. package/lib/schemas.js +8 -0
  41. package/lib/security-headers.js +18 -0
  42. package/lib/session-default.js +60 -0
  43. package/lib/settings.js +2 -1
  44. package/lib/stream-encrypt.js +71 -20
  45. package/lib/sub-script.js +8 -2
  46. package/lib/submit-lock.js +84 -0
  47. package/lib/submit-processor.js +283 -0
  48. package/lib/templates.js +6 -3
  49. package/lib/tls/context.js +2 -16
  50. package/lib/tools.js +8 -30
  51. package/lib/ui-routes/admin-config-routes.js +27 -5
  52. package/lib/ui-routes/auth-routes.js +4 -0
  53. package/lib/ui-routes/dbsc-routes.js +43 -0
  54. package/lib/utils/redis-errors.js +44 -0
  55. package/lib/webhook-delivery.js +3 -4
  56. package/lib/worker-rpc-error.js +10 -5
  57. package/lib/worker-rpc.js +138 -0
  58. package/package.json +17 -19
  59. package/sbom.json +370 -1446
  60. package/server.js +6 -5
  61. package/static/css/flyonui.css +2 -2
  62. package/static/licenses.html +253 -1366
  63. package/translations/messages.pot +16 -16
  64. package/views/config/security.hbs +37 -0
  65. package/workers/api.js +61 -467
  66. package/workers/export.js +14 -55
  67. package/workers/imap-proxy.js +5 -18
  68. package/workers/imap.js +27 -49
  69. package/workers/smtp.js +7 -69
  70. package/workers/submit.js +21 -279
  71. package/workers/webhooks.js +7 -72
@@ -7,12 +7,21 @@ const { PBKDF2_ITERATIONS, PBKDF2_DIGEST } = require('./encrypt');
7
7
 
8
8
  const MAGIC = Buffer.from('EE01');
9
9
  // How the key is derived, by header version. Version 1 used scrypt, which an OpenSSL FIPS provider
10
- // does not offer; everything written is version 2 (PBKDF2-HMAC-SHA256, with the parameters of the
11
- // field encryption's wd02 scheme), and a version 1 file still decrypts
12
- const VERSION = 2;
10
+ // does not offer; versions 2 and 3 use PBKDF2-HMAC-SHA256 with the parameters of the field
11
+ // encryption's wd02 scheme.
12
+ //
13
+ // Versions 1 and 2 seal every chunk on its own, so a file could have its chunks reordered,
14
+ // duplicated or dropped, or be cut at a chunk boundary, and still decrypt. Version 3, the one
15
+ // written, follows the STREAM construction: each chunk carries a flags byte, and its additional
16
+ // authenticated data is the file header, the chunk's index and those flags, so a chunk only
17
+ // decrypts at its own position in its own file, and a file that ends without the chunk flagged
18
+ // final is refused. Files of the earlier versions still decrypt.
19
+ const VERSION = 3;
20
+ const PBKDF2 = (password, salt, callback) => crypto.pbkdf2(password, salt, PBKDF2_ITERATIONS, 32, PBKDF2_DIGEST, callback);
13
21
  const KDF = {
14
22
  1: (password, salt, callback) => crypto.scrypt(password, salt, 32, callback),
15
- 2: (password, salt, callback) => crypto.pbkdf2(password, salt, PBKDF2_ITERATIONS, 32, PBKDF2_DIGEST, callback)
23
+ 2: PBKDF2,
24
+ 3: PBKDF2
16
25
  };
17
26
  const CHUNK_SIZE = 64 * 1024;
18
27
  const IV_LENGTH = 12;
@@ -20,6 +29,19 @@ const AUTH_TAG_LENGTH = 16;
20
29
  const SALT_LENGTH = 16;
21
30
  const HEADER_SIZE = MAGIC.length + 4 + 4 + SALT_LENGTH;
22
31
  const MAX_CHUNK_SIZE = CHUNK_SIZE * 4;
32
+ const FLAG_FINAL = 0x01;
33
+
34
+ // Chunk header: the IV and the ciphertext length, and in version 3 the flags byte after them
35
+ const LEGACY_CHUNK_HEADER_SIZE = IV_LENGTH + 4;
36
+ const BOUND_CHUNK_HEADER_SIZE = LEGACY_CHUNK_HEADER_SIZE + 1;
37
+
38
+ // What a version 3 chunk is bound to: the file header, its index and its flags
39
+ function chunkAad(header, index, flags) {
40
+ const position = Buffer.alloc(9);
41
+ position.writeBigUInt64BE(BigInt(index), 0);
42
+ position.writeUInt8(flags, 8);
43
+ return Buffer.concat([header, position]);
44
+ }
23
45
 
24
46
  class EncryptStream extends Transform {
25
47
  constructor({ key, salt }) {
@@ -27,11 +49,12 @@ class EncryptStream extends Transform {
27
49
  this.key = key;
28
50
  this.salt = salt;
29
51
  this.buffer = Buffer.alloc(0);
30
- this.headerWritten = false;
52
+ this.header = null;
53
+ this.chunkIndex = 0;
31
54
  }
32
55
 
33
56
  _writeHeader() {
34
- if (this.headerWritten) return;
57
+ if (this.header) return;
35
58
 
36
59
  const versionBuf = Buffer.alloc(4);
37
60
  versionBuf.writeUInt32LE(VERSION);
@@ -39,20 +62,22 @@ class EncryptStream extends Transform {
39
62
  const chunkSizeBuf = Buffer.alloc(4);
40
63
  chunkSizeBuf.writeUInt32LE(CHUNK_SIZE);
41
64
 
42
- this.push(Buffer.concat([MAGIC, versionBuf, chunkSizeBuf, this.salt]));
43
- this.headerWritten = true;
65
+ this.header = Buffer.concat([MAGIC, versionBuf, chunkSizeBuf, this.salt]);
66
+ this.push(this.header);
44
67
  }
45
68
 
46
- _encryptChunk(chunk) {
69
+ _encryptChunk(chunk, flags) {
47
70
  const iv = crypto.randomBytes(IV_LENGTH);
48
71
  const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv, { authTagLength: AUTH_TAG_LENGTH });
72
+ cipher.setAAD(chunkAad(this.header, this.chunkIndex++, flags));
49
73
 
50
74
  const encrypted = Buffer.concat([cipher.update(chunk), cipher.final()]);
51
75
  const authTag = cipher.getAuthTag();
52
76
 
53
- const chunkHeader = Buffer.alloc(IV_LENGTH + 4);
77
+ const chunkHeader = Buffer.alloc(BOUND_CHUNK_HEADER_SIZE);
54
78
  iv.copy(chunkHeader, 0);
55
79
  chunkHeader.writeUInt32LE(encrypted.length, IV_LENGTH);
80
+ chunkHeader.writeUInt8(flags, IV_LENGTH + 4);
56
81
 
57
82
  return Buffer.concat([chunkHeader, encrypted, authTag]);
58
83
  }
@@ -63,10 +88,12 @@ class EncryptStream extends Transform {
63
88
 
64
89
  this.buffer = Buffer.concat([this.buffer, data]);
65
90
 
66
- while (this.buffer.length >= CHUNK_SIZE) {
91
+ // A full chunk is only sealed once more data follows it: the last chunk is flagged
92
+ // final, and until the stream ends any full chunk could be the last one
93
+ while (this.buffer.length > CHUNK_SIZE) {
67
94
  const chunk = this.buffer.subarray(0, CHUNK_SIZE);
68
95
  this.buffer = this.buffer.subarray(CHUNK_SIZE);
69
- this.push(this._encryptChunk(chunk));
96
+ this.push(this._encryptChunk(chunk, 0));
70
97
  }
71
98
 
72
99
  callback();
@@ -79,9 +106,10 @@ class EncryptStream extends Transform {
79
106
  try {
80
107
  this._writeHeader();
81
108
 
82
- if (this.buffer.length > 0) {
83
- this.push(this._encryptChunk(this.buffer));
84
- }
109
+ // Always written, even empty, so that a file cut right after a chunk boundary (or
110
+ // right after the header) is told apart from a complete one
111
+ this.push(this._encryptChunk(this.buffer, FLAG_FINAL));
112
+ this.buffer = Buffer.alloc(0);
85
113
 
86
114
  this.key = null;
87
115
  callback();
@@ -99,6 +127,8 @@ class DecryptStream extends Transform {
99
127
  this.headerParsed = false;
100
128
  this.key = null;
101
129
  this.chunkSize = CHUNK_SIZE;
130
+ this.chunkIndex = 0;
131
+ this.finalSeen = false;
102
132
  }
103
133
 
104
134
  _parseHeader() {
@@ -119,6 +149,8 @@ class DecryptStream extends Transform {
119
149
  throw new Error(`Unsupported encryption version: ${version}`);
120
150
  }
121
151
  this.version = version;
152
+ // Version 3 chunks carry a flags byte and are bound to their position (see VERSION)
153
+ this.boundChunks = version >= 3;
122
154
  offset += 4;
123
155
 
124
156
  this.chunkSize = this.buffer.readUInt32LE(offset);
@@ -128,6 +160,7 @@ class DecryptStream extends Transform {
128
160
  offset += 4;
129
161
 
130
162
  this.salt = this.buffer.subarray(offset, offset + SALT_LENGTH);
163
+ this.header = Buffer.from(this.buffer.subarray(0, HEADER_SIZE));
131
164
 
132
165
  this.buffer = this.buffer.subarray(HEADER_SIZE);
133
166
  this.headerParsed = true;
@@ -136,11 +169,15 @@ class DecryptStream extends Transform {
136
169
  }
137
170
 
138
171
  _decryptChunk() {
139
- const minChunkHeader = IV_LENGTH + 4;
172
+ const minChunkHeader = this.boundChunks ? BOUND_CHUNK_HEADER_SIZE : LEGACY_CHUNK_HEADER_SIZE;
140
173
  if (this.buffer.length < minChunkHeader) {
141
174
  return null;
142
175
  }
143
176
 
177
+ if (this.finalSeen) {
178
+ throw new Error('Invalid encrypted file: data after the final chunk');
179
+ }
180
+
144
181
  const iv = this.buffer.subarray(0, IV_LENGTH);
145
182
  const encryptedLength = this.buffer.readUInt32LE(IV_LENGTH);
146
183
  if (encryptedLength > this.chunkSize + 256) {
@@ -158,6 +195,12 @@ class DecryptStream extends Transform {
158
195
  const decipher = crypto.createDecipheriv('aes-256-gcm', this.key, iv, { authTagLength: AUTH_TAG_LENGTH });
159
196
  decipher.setAuthTag(authTag);
160
197
 
198
+ let flags = 0;
199
+ if (this.boundChunks) {
200
+ flags = this.buffer.readUInt8(IV_LENGTH + 4);
201
+ decipher.setAAD(chunkAad(this.header, this.chunkIndex, flags));
202
+ }
203
+
161
204
  let decrypted;
162
205
  try {
163
206
  decrypted = Buffer.concat([decipher.update(encryptedData), decipher.final()]);
@@ -169,6 +212,10 @@ class DecryptStream extends Transform {
169
212
  }
170
213
 
171
214
  this.buffer = this.buffer.subarray(totalChunkSize);
215
+ this.chunkIndex++;
216
+ if (flags & FLAG_FINAL) {
217
+ this.finalSeen = true;
218
+ }
172
219
 
173
220
  return decrypted;
174
221
  }
@@ -215,11 +262,11 @@ class DecryptStream extends Transform {
215
262
 
216
263
  _flush(callback) {
217
264
  try {
218
- if (this.buffer.length > 0) {
219
- if (!this.headerParsed) {
220
- throw new Error('Invalid encrypted file: incomplete header');
221
- }
265
+ if (!this.headerParsed) {
266
+ throw new Error('Invalid encrypted file: incomplete header');
267
+ }
222
268
 
269
+ if (this.buffer.length > 0) {
223
270
  const decrypted = this._decryptChunk();
224
271
  if (decrypted !== null) {
225
272
  this.push(decrypted);
@@ -230,6 +277,10 @@ class DecryptStream extends Transform {
230
277
  }
231
278
  }
232
279
 
280
+ if (this.boundChunks && !this.finalSeen) {
281
+ throw new Error('Invalid encrypted file: truncated, the final chunk is missing');
282
+ }
283
+
233
284
  this.key = null;
234
285
  callback();
235
286
  } catch (err) {
package/lib/sub-script.js CHANGED
@@ -5,8 +5,14 @@
5
5
  // host realm (e.g. via `someHostValue.constructor.constructor('return process')()`) and
6
6
  // therefore runs with full server privileges (process env/secrets, host modules, fs).
7
7
  // Only trusted operators may author these scripts; never expose script authoring to
8
- // untrusted principals. Replacing this with a real isolate (isolated-vm) or out-of-process
9
- // execution is a tracked follow-up (see security review finding C1).
8
+ // untrusted principals (see security review finding C1).
9
+ //
10
+ // There is no pure JavaScript isolate to move to. isolated-vm is a native addon and the QuickJS
11
+ // builds are WebAssembly, both ruled out by the no-compiled-dependencies rule (CLAUDE.md), and
12
+ // vm2 is abandoned with unfixed sandbox escapes, so it must never be adopted either. A hard time
13
+ // limit, which the `vm` timeout below gives only to synchronous code, would need a dedicated
14
+ // worker thread per run with `resourceLimits`, stopped with `worker.terminate()`. That bounds
15
+ // time and memory, not privilege: the trust rule above holds either way.
10
16
 
11
17
  const crypto = require('crypto');
12
18
  const vm = require('vm');
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+
3
+ // Sends a queued message under a lock, so a retry never runs next to a send that is still in
4
+ // progress. The submit worker retries when its call fails, and a call can fail while the send goes
5
+ // on: the command timed out while the SMTP server was still answering. Without the lock the retry
6
+ // would start a second SMTP transaction for the same message.
7
+
8
+ const { runLocked } = require('./lock-run');
9
+ const { statusError } = require('./utils/status-error');
10
+ const { REDIS_PREFIX } = require('./consts');
11
+ const { backOff } = require('./utils/back-off');
12
+ const { isTransientRedisError } = require('./utils/redis-errors');
13
+
14
+ // How long the lock lives without being extended. It is extended while the send runs, so this
15
+ // only has to outlast a stalled process
16
+ const SUBMIT_LOCK_TTL = 60 * 1000;
17
+
18
+ // How long a sent message is remembered when nothing clears it. The submit worker deletes it once
19
+ // the job completes, so only a send whose call failed leaves one behind, for its retries
20
+ const SENT_MARKER_TTL = 7 * 24 * 3600;
21
+
22
+ // The marker write is retried while Redis refuses it for now (OOM, LOADING, a failover), about
23
+ // twenty seconds in all and inside the lock, which is extended meanwhile: once the message went
24
+ // out, the marker is the only thing that keeps a retry of the job from sending it again
25
+ const MARKER_WRITE = { numOfAttempts: 8, startingDelay: 250, timeMultiple: 2, maxDelay: 5000, retry: err => isTransientRedisError(err) };
26
+
27
+ const sentKey = (account, queueId) => `${REDIS_PREFIX}submit:sent:${account}:${queueId}`;
28
+
29
+ /**
30
+ * @param {Object} opts
31
+ * @param {Object} opts.lock - ioredfour Lock (getSharedLock())
32
+ * @param {Object} opts.redis - ioredis client
33
+ * @param {string} opts.account
34
+ * @param {string} [opts.queueId] - The queue entry being sent; none for a direct send
35
+ * @param {Function} opts.send - () => the send itself
36
+ * @returns {Promise<*>} What send resolves with
37
+ */
38
+ async function sendQueuedOnce({ lock, redis, logger, account, queueId, send }) {
39
+ if (!queueId) {
40
+ return await send();
41
+ }
42
+ return await runLocked(
43
+ lock,
44
+ `submit:${account}:${queueId}`,
45
+ { ttl: SUBMIT_LOCK_TTL, wait: false, extend: true },
46
+ async () => {
47
+ // The attempt that held the lock before may have sent it. Its own record, not the job
48
+ // progress: a retry writes 'processing' over that before it gets here
49
+ if (await redis.exists(sentKey(account, queueId))) {
50
+ // The submit worker counts the job as sent
51
+ throw statusError('An earlier attempt already sent this message', 'AlreadySent', 409);
52
+ }
53
+ const result = await send();
54
+ // A send that resolved went out: the email clients swallow failures after the accept,
55
+ // and so does this, a lost marker must not turn a sent message into a failed one
56
+ try {
57
+ await backOff(() => redis.set(sentKey(account, queueId), '1', 'EX', SENT_MARKER_TTL), MARKER_WRITE);
58
+ } catch (err) {
59
+ logger?.error({ msg: 'Failed to record a sent message', account, queueId, err });
60
+ }
61
+ return result;
62
+ },
63
+ err => {
64
+ // Retried by the queue like any transient failure
65
+ const busy = statusError('An earlier attempt is still sending this message', 'SubmitInProgress', 409);
66
+ busy.cause = err;
67
+ throw busy;
68
+ }
69
+ );
70
+ }
71
+
72
+ /**
73
+ * Forgets that a message was sent, once its job completed and nothing will retry it
74
+ * @param {Object} redis
75
+ * @param {string} account
76
+ * @param {string} queueId
77
+ */
78
+ async function clearSent(redis, account, queueId) {
79
+ if (queueId) {
80
+ await redis.del(sentKey(account, queueId));
81
+ }
82
+ }
83
+
84
+ module.exports = { sendQueuedOnce, clearSent, sentKey };
@@ -0,0 +1,283 @@
1
+ 'use strict';
2
+
3
+ // The submit queue's job processor, moved out of workers/submit.js so a test can run the real thing
4
+ // against real BullMQ jobs: the worker cannot be loaded from a test (it starts consuming on
5
+ // require), and what has to be pinned here is the order of events around a crash, which only the
6
+ // real processor and a real queue show.
7
+ //
8
+ // What this does NOT do is forget that a message was sent. The marker sendQueuedOnce() writes
9
+ // (lib/submit-lock.js) is the only record that a retry must not send again, and it is needed until
10
+ // BullMQ has recorded the job as completed: a worker that dies after the send and before that
11
+ // record leaves a job that runs again. Clearing it here, before the processor returned, let that
12
+ // run send the message a second time. completeSubmission() clears it from the worker's
13
+ // 'completed' event, which BullMQ emits only once the completion is stored; a job that never
14
+ // completes keeps its marker until the marker expires.
15
+
16
+ const { UnrecoverableError } = require('bullmq');
17
+
18
+ const { decodeQueueEntry, outboxKey } = require('./outbox');
19
+ const { shouldDiscardJob, willBeFinalAttempt, nextAttemptWhileProcessing } = require('./delivery-error');
20
+ const { isAlreadySent } = require('./submit-progress');
21
+ const { clearSent } = require('./submit-lock');
22
+
23
+ /**
24
+ * Jobs queued by old versions carry the queue entry id as `qId`
25
+ * @param {Object} job - BullMQ job, its data updated in place
26
+ */
27
+ function normalizeQueueId(job) {
28
+ if (!job.data.queueId && job.data.qId) {
29
+ job.data.queueId = job.data.qId;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Builds the submit queue processor
35
+ * @param {Object} deps
36
+ * @param {Object} deps.redis - ioredis client
37
+ * @param {Object} deps.logger
38
+ * @param {Object} deps.submitQueue - the BullMQ queue the jobs belong to, read back for a job's stored progress
39
+ * @param {Function} deps.getAccount - async (accountId) => object with submitMessage(queueEntry)
40
+ * @returns {Function} async (job) => processes one queued message
41
+ */
42
+ function createSubmitProcessor({ redis, logger, submitQueue, getAccount }) {
43
+ return async job => {
44
+ normalizeQueueId(job);
45
+
46
+ // A job re-run after a stall (heartbeat kill, crash, a shutdown drain that could not cover
47
+ // a long SMTP transaction plus the Sent-folder upload) comes back with the progress its
48
+ // previous run stored. Once that says the MTA accepted the message, sending again would
49
+ // deliver a duplicate under the same queueId: the message is done, only the bookkeeping
50
+ // after the 250 was cut short. The catch below covers the same state for a run that got
51
+ // as far as throwing; this covers the run that never got to throw anything.
52
+ if (isAlreadySent(job.progress)) {
53
+ logger.info({
54
+ msg: 'Skipping re-run of an already sent message',
55
+ action: 'submit',
56
+ queue: job.queue.name,
57
+ code: 'result_success',
58
+ job: job.id,
59
+ event: job.name,
60
+ account: job.data.account,
61
+ queueId: job.data.queueId,
62
+ messageId: job.data.messageId,
63
+ progress: job.progress.status,
64
+ attemptsMade: job.attemptsMade
65
+ });
66
+ return;
67
+ }
68
+
69
+ let queueEntryBuf = await redis.hgetBuffer(outboxKey(job.data.account), job.data.queueId);
70
+ if (!queueEntryBuf) {
71
+ // nothing to do here
72
+ try {
73
+ await redis.hdel(outboxKey(job.data.account), job.data.queueId);
74
+ } catch (err) {
75
+ // ignore
76
+ }
77
+ return;
78
+ }
79
+
80
+ let queueEntry;
81
+ try {
82
+ // Rejects a value that decodes to something other than a map as well, otherwise the
83
+ // job metadata assignment below throws a TypeError against it and the entry is retried
84
+ // as a failed delivery instead of being dropped as the corrupt entry it is
85
+ queueEntry = decodeQueueEntry(queueEntryBuf);
86
+ } catch (err) {
87
+ logger.error({ msg: 'Failed to parse queued email entry', job: job.id, account: job.data.account, queueId: job.data.queueId, err });
88
+ try {
89
+ await redis.hdel(outboxKey(job.data.account), job.data.queueId);
90
+ } catch (err) {
91
+ // ignore
92
+ }
93
+ return;
94
+ }
95
+
96
+ let accountObject = await getAccount(job.data.account);
97
+
98
+ logger.trace({
99
+ msg: 'Processing message',
100
+ action: 'submit',
101
+ queue: job.queue.name,
102
+ code: 'processing',
103
+ job: job.id,
104
+ event: job.name,
105
+ data: job.data,
106
+ account: job.data.account
107
+ });
108
+
109
+ try {
110
+ try {
111
+ // try to update
112
+ await job.updateProgress({
113
+ status: 'processing'
114
+ });
115
+ } catch (err) {
116
+ // ignore
117
+ }
118
+
119
+ let nextAttempt = nextAttemptWhileProcessing(job);
120
+
121
+ queueEntry.job = {
122
+ id: job.id,
123
+ attemptsMade: job.attemptsMade,
124
+ attempts: job.opts.attempts,
125
+ nextAttempt: nextAttempt ? new Date(nextAttempt).toISOString() : false
126
+ };
127
+
128
+ let res = await accountObject.submitMessage(queueEntry);
129
+
130
+ logger.trace({
131
+ msg: 'Submitted queued message for delivery',
132
+ action: 'submit',
133
+ queue: job.queue.name,
134
+ code: 'result_success',
135
+ job: job.id,
136
+ event: job.name,
137
+ data: job.data,
138
+ account: job.data.account
139
+ });
140
+
141
+ try {
142
+ // try to update
143
+ await job.updateProgress({
144
+ status: 'submitted',
145
+ response: res.response
146
+ });
147
+ } catch (err) {
148
+ // ignore
149
+ }
150
+ } catch (err) {
151
+ // The message went out even though this run failed: an earlier attempt sent it and its
152
+ // call failed after the fact (AlreadySent, lib/submit-lock.js), or this run failed after
153
+ // the accept
154
+ let alreadySent = err.code === 'AlreadySent';
155
+ if (!alreadySent) {
156
+ try {
157
+ const submitJobEntry = await submitQueue.getJob(job.id);
158
+ alreadySent = !!submitJobEntry && isAlreadySent(submitJobEntry.progress);
159
+ } catch (err) {
160
+ logger.error({
161
+ msg: 'Failed to fetch job status',
162
+ job: job.id,
163
+ account: job.data.account,
164
+ err
165
+ });
166
+ }
167
+ }
168
+ if (alreadySent) {
169
+ logger.info({
170
+ msg: 'Message was already sent, counting the job as sent',
171
+ action: 'submit',
172
+ queue: job.queue.name,
173
+ code: 'result_success',
174
+ job: job.id,
175
+ event: job.name,
176
+ account: job.data.account,
177
+ queueId: job.data.queueId,
178
+ err
179
+ });
180
+ try {
181
+ // The retry wrote 'processing' over the sent state
182
+ await job.updateProgress({ status: 'submitted' });
183
+ } catch (err) {
184
+ // ignore
185
+ }
186
+ return;
187
+ }
188
+
189
+ const discardJob = shouldDiscardJob(err, job);
190
+ const isFinalAttempt = discardJob || willBeFinalAttempt(job);
191
+
192
+ logger[isFinalAttempt ? 'error' : 'warn']({
193
+ msg: 'Message submission failed',
194
+ action: 'submit',
195
+ queue: job.queue.name,
196
+ code: 'result_fail',
197
+ job: job.id,
198
+ event: job.name,
199
+ data: job.data,
200
+ account: job.data.account,
201
+ err
202
+ });
203
+
204
+ try {
205
+ // try to update
206
+ await job.updateProgress({
207
+ status: 'error',
208
+ error: {
209
+ message: err.message,
210
+ code: err.code,
211
+ statusCode: err.statusCode,
212
+ // the SMTP reply code, when there was a reply: what decides whether the
213
+ // failure is permanent (lib/delivery-error.js), kept so the queue browser
214
+ // can say so without a rule of its own
215
+ responseCode: err.responseCode
216
+ },
217
+ networkRouting: err.info?.networkRouting
218
+ });
219
+ } catch (err) {
220
+ // ignore
221
+ }
222
+
223
+ if (discardJob) {
224
+ // Do not retry after a permanent rejection (5xx except 503, which is transient).
225
+ // BullMQ 6 removed Job#discard(), so the way to end a job before its attempts are
226
+ // spent is to throw UnrecoverableError. The stack is carried over because the
227
+ // 'failed' handler reports job.stacktrace[0] as the error in the failure webhook -
228
+ // constructing a bare UnrecoverableError would replace the SMTP reason with
229
+ // "UnrecoverableError" there.
230
+ let unrecoverableErr = new UnrecoverableError(err.message);
231
+ unrecoverableErr.stack = err.stack;
232
+ unrecoverableErr.code = err.code;
233
+ unrecoverableErr.responseCode = err.responseCode;
234
+ unrecoverableErr.statusCode = err.statusCode;
235
+
236
+ logger.info({
237
+ msg: 'Job discarded',
238
+ job: job.id,
239
+ account: queueEntry.account,
240
+ queueId: job.data.queueId,
241
+ messageId: job.data.messageId,
242
+ errorCode: err.code,
243
+ responseCode: err.responseCode
244
+ });
245
+
246
+ throw unrecoverableErr;
247
+ }
248
+
249
+ throw err;
250
+ }
251
+ };
252
+ }
253
+
254
+ /**
255
+ * The bookkeeping of a job BullMQ has recorded as completed: the stored message content and the
256
+ * sent marker both go. Called from the worker's 'completed' event, never from the processor
257
+ * @param {Object} job - the completed BullMQ job
258
+ * @param {Object} deps
259
+ * @param {Object} deps.redis - ioredis client
260
+ * @param {Object} deps.logger
261
+ */
262
+ async function completeSubmission(job, { redis, logger }) {
263
+ normalizeQueueId(job);
264
+
265
+ if (!job.data.account || !job.data.queueId) {
266
+ return;
267
+ }
268
+
269
+ // Independent writes, sent together: a failure of one must not keep the other from running
270
+ const { account, queueId } = job.data;
271
+ await Promise.all([
272
+ redis.hdel(outboxKey(account), queueId).catch(err => {
273
+ logger.error({ msg: 'Failed to remove queue entry', account, queueId, messageId: job.data.messageId, err });
274
+ }),
275
+ // A marker that could not be cleared expires on its own, and until then it only stops a job
276
+ // that is already done from running again
277
+ clearSent(redis, account, queueId).catch(err => {
278
+ logger.warn({ msg: 'Failed to clear the sent marker of a completed message', job: job.id, account, err });
279
+ })
280
+ ]);
281
+ }
282
+
283
+ module.exports = { createSubmitProcessor, completeSubmission, normalizeQueueId };
package/lib/templates.js CHANGED
@@ -87,10 +87,13 @@ class TemplateHandler {
87
87
  // The inverse of generateId(): an 8-byte timestamp, a 4-byte counter, then the account id.
88
88
  // Anything shorter than the fixed 12-byte header cannot be an id this module issued, and the
89
89
  // routes accept any string up to 256 characters, so a malformed id is refused as "not found"
90
- // here rather than failing on the header read.
90
+ // here rather than failing on the header read. The same goes for a header whose timestamp is no
91
+ // time a Date can hold (a template name typed in place of an id decodes to one), which made
92
+ // toISOString() throw a RangeError.
91
93
  unpackId(id) {
92
94
  let idBuf = Buffer.from(id, 'base64');
93
- if (idBuf.length < 4 + 8) {
95
+ let created = idBuf.length >= 4 + 8 ? new Date(Number(idBuf.readBigUInt64BE(0))) : null;
96
+ if (!created || isNaN(created.getTime())) {
94
97
  let err = new Error('Document was not found');
95
98
  err.code = 'NotFound';
96
99
  err.statusCode = 404;
@@ -99,7 +102,7 @@ class TemplateHandler {
99
102
 
100
103
  return {
101
104
  counter: idBuf.readUInt32BE(8),
102
- created: new Date(Number(idBuf.readBigUInt64BE(0))).toISOString(),
105
+ created: created.toISOString(),
103
106
  account: idBuf.subarray(4 + 8).toString()
104
107
  };
105
108
  }
@@ -21,12 +21,12 @@
21
21
  // and the API's HTTPS listener, so anything it does is done once per client.
22
22
 
23
23
  const tls = require('tls');
24
- const config = require('@zone-eu/wild-config');
25
24
 
26
25
  const settings = require('../settings');
27
- const { hasEnvValue, readEnvValue, getBoolean } = require('../tools');
28
26
  const { hostnamesFrom, getSelfSignedCertificate, parseCertificate, describeX509 } = require('./store');
29
27
  const { TLS_CERTIFICATE_SETTINGS, SELF_SIGNED_ID, listenerByKey } = require('./listeners');
28
+ // Whether the API listener serves TLS; resolved in a leaf module the Docker health check shares
29
+ const { apiTlsConfig } = require('../api-listener');
30
30
  const { sourcesFor, listCertificates, entryForName, listenerView } = require('./catalog');
31
31
 
32
32
  /**
@@ -39,20 +39,6 @@ function fullChain(material) {
39
39
  return material.ca && material.ca.length ? [material.cert].concat(material.ca).join('\n') : material.cert;
40
40
  }
41
41
 
42
- /**
43
- * Whether, and how, the API listener serves TLS: EENGINE_API_TLS and `[api.tls]`.
44
- *
45
- * Read from the environment and the config file, which every process shares, so the API worker
46
- * (which builds its listener from it) and the certificate reconciler (which asks whether any
47
- * listener would serve a certificate) cannot answer differently.
48
- *
49
- * @returns {Object|false} The `[api.tls]` options to build the listener from, or false when the
50
- * API serves plain HTTP
51
- */
52
- function apiTlsConfig() {
53
- return hasEnvValue('EENGINE_API_TLS') ? getBoolean(readEnvValue('EENGINE_API_TLS')) && (config.api.tls || {}) : config.api.tls || false;
54
- }
55
-
56
42
  // How a listener negotiates, as opposed to what it serves. These belong to the listener rather
57
43
  // than to any one certificate, and they travel with the resolved options because installing a
58
44
  // context replaces it whole: tls.Server.setSecureContext() reverts everything absent from its