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
@@ -0,0 +1,19 @@
1
+ 'use strict';
2
+
3
+ // Names of the Redis keys that more than one module builds. A key name is a storage contract: a
4
+ // module that spells one differently reads an empty key rather than failing, so a key used across
5
+ // layers (the API, the workers, the main thread) is named here once. test/redis-keys-test.js fails
6
+ // when one of the keys below is spelled out by hand anywhere else.
7
+ //
8
+ // lib/lua/s-list-accounts.lua builds the account data key itself; Lua cannot share this module.
9
+
10
+ const { REDIS_PREFIX } = require('./consts');
11
+
12
+ /**
13
+ * The account data hash: the account record, its connection state and counters
14
+ * @param {String} account - account id
15
+ * @returns {String}
16
+ */
17
+ const accountDataKey = account => `${REDIS_PREFIX}iad:${account}`;
18
+
19
+ module.exports = { accountDataKey };
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const logger = require('./logger');
4
+ const { isTransientRedisError } = require('./utils/redis-errors');
4
5
 
5
6
  /**
6
7
  * Default retry configuration for Redis operations
@@ -31,8 +32,8 @@ function isTransientError(err) {
31
32
  return true;
32
33
  }
33
34
 
34
- // Check for Redis connection errors
35
- if (err.name === 'ReplyError' && /LOADING|BUSY|READONLY|CLUSTERDOWN/.test(err.message)) {
35
+ // Redis replies that clear up on their own
36
+ if (isTransientRedisError(err)) {
36
37
  return true;
37
38
  }
38
39
 
@@ -185,7 +186,10 @@ class RedisTransaction {
185
186
  const results = await multi.exec();
186
187
  const error = extractMultiError(results);
187
188
 
188
- if (error && isTransientError(error) && attempt < maxAttempts) {
189
+ // Only when nothing of it was applied: a transaction runs every command whatever the
190
+ // others answer, so retrying one where some went through would apply those twice
191
+ // (an increment, a push). A refused EXEC (EXECABORT) throws and is retried below
192
+ if (error && isTransientError(error) && results.every(result => Array.isArray(result) && result[0]) && attempt < maxAttempts) {
189
193
  const delay = calculateBackoffDelay(attempt, baseDelay, maxDelay);
190
194
  this.logger.warn({
191
195
  msg: 'Redis transaction encountered transient error, retrying',
@@ -195,6 +195,23 @@ function isMachineRoute(tags = []) {
195
195
  return tags.some(tag => MACHINE_TAGS.includes(tag));
196
196
  }
197
197
 
198
+ /**
199
+ * Whether a route's auth setting admits the admin session cookie. An undeclared setting inherits
200
+ * the server default, which is the session strategy once an admin password is set.
201
+ *
202
+ * @param {(Object|Boolean|undefined)} auth - the route's auth setting
203
+ * @returns {boolean}
204
+ */
205
+ function acceptsSession(auth) {
206
+ if (auth === undefined) {
207
+ return true;
208
+ }
209
+ if (!auth || typeof auth !== 'object') {
210
+ return false;
211
+ }
212
+ return auth.strategy === 'session' || (Array.isArray(auth.strategies) && auth.strategies.includes('session'));
213
+ }
214
+
198
215
  /**
199
216
  * Tells whether the instance declares itself served over https - the same signal that gives the
200
217
  * session and CSRF cookies their Secure flag, and the one that decides whether HSTS is sent.
@@ -382,6 +399,7 @@ module.exports = {
382
399
  profileNameFor,
383
400
  isAdminPath,
384
401
  isMachineRoute,
402
+ acceptsSession,
385
403
  isSecureOrigin,
386
404
  CSP_MODES,
387
405
  CSP_HEADER,
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ // Makes an API worker ask for an admin login as soon as an admin password exists.
4
+ //
5
+ // workers/api.js sets the session strategy as the server default at startup when a password is
6
+ // already stored, and the worker that serves the "set password" form sets it in-process and
7
+ // broadcasts the change to the other API workers. The CLI (`emailengine password`) writes the
8
+ // password straight into Redis, with no broadcast, so a running worker kept serving /admin with no
9
+ // login until it was restarted. Checking before authentication closes that gap from the first
10
+ // request that would have got through. Setting the default rebuilds every route's lifecycle, but the
11
+ // request already running keeps the one it started with, which has no authentication step, so that
12
+ // one request is sent back to its own URL (307, which a browser repeats with the same method and
13
+ // body) and runs again with authentication.
14
+
15
+ /**
16
+ * Registers an onPreAuth extension that sets the session strategy as the default once a password is
17
+ * stored. Only a request that would use the default asks Redis, and only until the default is set
18
+ * @param {Object} opts
19
+ * @param {Object} opts.server - hapi server, with the session strategy registered
20
+ * @param {Function} opts.isInstanceSecured - Resolves true once an admin password is set
21
+ * @param {Object} opts.logger
22
+ */
23
+ function requireSessionOnceSecured({ server, isInstanceSecured, logger }) {
24
+ server.ext('onPreAuth', async (request, h) => {
25
+ if (server.auth.settings.default || request.route.settings.auth !== undefined) {
26
+ return h.continue;
27
+ }
28
+ if (!(await isInstanceSecured())) {
29
+ return h.continue;
30
+ }
31
+ // hapi refuses a second default, and a concurrent request may have set it meanwhile
32
+ if (!server.auth.settings.default) {
33
+ server.auth.default('session');
34
+ logger.info({ msg: 'Admin session authentication enabled after a password was set' });
35
+ }
36
+ // Leading slashes collapsed, so a path like //host cannot become a protocol-relative Location
37
+ const location = '/' + request.url.pathname.replace(/^\/+/, '') + request.url.search;
38
+ return h.redirect(location).code(307).takeover();
39
+ });
40
+ }
41
+
42
+ // Route paths a session that has passed the password step but not yet the second factor may reach.
43
+ // Every other route sends such a session to the TOTP prompt (registerTotpExtension() in
44
+ // workers/api.js). The login and TOTP pages have to be here or the prompt could never be answered,
45
+ // the passkey login endpoints because a passkey is a factor of its own, and the catch-all 404 so a
46
+ // mistyped URL does not bounce. test/admin-auth-guardrail-test.js checks every entry against the
47
+ // route table, so a renamed route cannot leave a stale entry that silently drops the exemption.
48
+ const TOTP_EXEMPT_PATHS = Object.freeze(['/{any*}', '/admin/totp', '/admin/login', '/admin/passkey/auth/options', '/admin/passkey/auth/verify']);
49
+
50
+ module.exports = { requireSessionOnceSecured, TOTP_EXEMPT_PATHS };
package/lib/settings.js CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { accountDataKey } = require('./redis-keys');
3
4
  const { redis } = require('./db');
4
5
  const logger = require('./logger');
5
6
  const { encrypt, decryptField } = require('./encrypt');
@@ -365,7 +366,7 @@ module.exports = {
365
366
  }
366
367
 
367
368
  if (account) {
368
- let accountLoggingEnabled = (await redis.hget(`${REDIS_PREFIX}iad:${account}`, 'logs')) === 'true' ? true : false;
369
+ let accountLoggingEnabled = (await redis.hget(accountDataKey(account), 'logs')) === 'true' ? true : false;
369
370
  return {
370
371
  enabled: accountLoggingEnabled,
371
372
  maxLogLines
@@ -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 };