emailengine-app 2.85.0 → 2.87.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 (137) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +97 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +16 -3
  6. package/ENVIRONMENT.md +139 -0
  7. package/README.md +5 -1
  8. package/config/default.toml +2 -0
  9. package/copy-static-files.sh +4 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +4 -3
  12. package/lib/account-assignment.js +19 -0
  13. package/lib/account.js +285 -195
  14. package/lib/api-error-codes.js +49 -0
  15. package/lib/api-reference/model.js +6 -1
  16. package/lib/api-routes/account-routes.js +91 -32
  17. package/lib/api-routes/blocklist-routes.js +68 -2
  18. package/lib/api-routes/delivery-test-routes.js +1 -1
  19. package/lib/api-routes/gateway-routes.js +82 -10
  20. package/lib/api-routes/index.js +4 -0
  21. package/lib/api-routes/license-routes.js +2 -2
  22. package/lib/api-routes/mailbox-routes.js +3 -3
  23. package/lib/api-routes/message-routes.js +15 -7
  24. package/lib/api-routes/oauth2-app-routes.js +15 -8
  25. package/lib/api-routes/outbox-routes.js +77 -66
  26. package/lib/api-routes/permission-map.js +55 -6
  27. package/lib/api-routes/scoped-routes.js +74 -0
  28. package/lib/api-routes/settings-routes.js +11 -4
  29. package/lib/api-routes/stats-routes.js +5 -1
  30. package/lib/api-routes/submit-routes.js +25 -5
  31. package/lib/api-routes/template-routes.js +7 -6
  32. package/lib/api-routes/token-routes.js +11 -5
  33. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  34. package/lib/api-routes/webhook-route-routes.js +119 -4
  35. package/lib/calendar-event.js +81 -1
  36. package/lib/consts.js +38 -46
  37. package/lib/db.js +14 -6
  38. package/lib/delivery-error.js +6 -0
  39. package/lib/deprecations.js +270 -0
  40. package/lib/email-client/base-client.js +134 -158
  41. package/lib/email-client/fallback-poll.js +62 -0
  42. package/lib/email-client/gmail-client.js +59 -11
  43. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  44. package/lib/email-client/imap/adaptive-idle.js +278 -0
  45. package/lib/email-client/imap/connection-errors.js +14 -1
  46. package/lib/email-client/imap/idle-settings.js +31 -5
  47. package/lib/email-client/imap/listing-diff.js +37 -0
  48. package/lib/email-client/imap/mailbox.js +380 -227
  49. package/lib/email-client/imap/subconnection.js +7 -29
  50. package/lib/email-client/imap/sync-operations.js +220 -127
  51. package/lib/email-client/imap-client.js +227 -163
  52. package/lib/email-client/message-builder.js +14 -79
  53. package/lib/email-client/outlook-client.js +378 -338
  54. package/lib/email-client/smtp-pool-manager.js +16 -13
  55. package/lib/email-client/sync-state-fields.js +19 -0
  56. package/lib/encrypt.js +157 -41
  57. package/lib/enum-descriptions.js +3 -1
  58. package/lib/env-setting-overrides.js +288 -0
  59. package/lib/export-worker.js +751 -0
  60. package/lib/export.js +64 -15
  61. package/lib/field-usage.js +1 -1
  62. package/lib/gateway.js +17 -1
  63. package/lib/get-raw-email.js +35 -108
  64. package/lib/health.js +75 -0
  65. package/lib/lock-run.js +119 -0
  66. package/lib/logger-consts.js +48 -0
  67. package/lib/logger.js +1 -1
  68. package/lib/lua/z-head-scores.lua +28 -0
  69. package/lib/network-errors.js +1 -1
  70. package/lib/node-version.js +24 -0
  71. package/lib/notify-attachments.js +20 -1
  72. package/lib/oauth/gmail.js +54 -29
  73. package/lib/oauth2-apps.js +630 -655
  74. package/lib/otp.js +66 -0
  75. package/lib/outbox.js +184 -54
  76. package/lib/parse-message.js +3 -3
  77. package/lib/privileged-settings.js +2 -2
  78. package/lib/queue-browser/definitions.js +11 -0
  79. package/lib/queue-browser/index.js +68 -19
  80. package/lib/queue-job-actions.js +18 -1
  81. package/lib/queue-retention.js +48 -12
  82. package/lib/queue-stats.js +11 -2
  83. package/lib/read-env-value.js +3 -0
  84. package/lib/redis-memory-warnings.js +99 -0
  85. package/lib/redis-reconnect.js +29 -0
  86. package/lib/request-timing.js +23 -0
  87. package/lib/respawn-backoff.js +35 -0
  88. package/lib/rewrite-text-nodes.js +19 -59
  89. package/lib/schemas.js +225 -41
  90. package/lib/settings.js +6 -2
  91. package/lib/smtp-auth.js +19 -1
  92. package/lib/swagger-options.js +2 -2
  93. package/lib/thread-diagnostics.js +18 -1
  94. package/lib/tls/provision.js +6 -3
  95. package/lib/token-audit-log.js +19 -20
  96. package/lib/token-permission-view.js +4 -3
  97. package/lib/tools.js +8 -41
  98. package/lib/ui-routes/admin-config-routes.js +64 -90
  99. package/lib/ui-routes/admin-entities-routes.js +2 -14
  100. package/lib/ui-routes/imap-idle-field.js +1 -1
  101. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  102. package/lib/ui-routes/overridable-fields.js +84 -0
  103. package/lib/ui-routes/queue-routes.js +8 -5
  104. package/lib/ui-routes/settings-page.js +6 -0
  105. package/lib/utils/decode-headers.js +3 -12
  106. package/lib/utils/filter-empty.js +20 -0
  107. package/lib/utils/int-setting.js +48 -0
  108. package/lib/utils/tracking-settings.js +35 -0
  109. package/lib/web-safe-html.js +18 -105
  110. package/lib/webhook-delivery.js +461 -0
  111. package/lib/webhook-failures.js +132 -0
  112. package/lib/webhook-request.js +29 -1
  113. package/lib/webhook-routing.js +30 -1
  114. package/lib/webhook-test.js +88 -0
  115. package/lib/webhooks.js +59 -41
  116. package/lib/worker-rpc-error.js +2 -1
  117. package/package.json +28 -26
  118. package/sbom.json +600 -678
  119. package/server.js +149 -76
  120. package/static/css/flyonui.css +1 -1
  121. package/static/js/ace/ace.js +1 -1
  122. package/static/js/ee-client.js +650 -196
  123. package/static/licenses.html +49 -59
  124. package/translations/messages.pot +26 -26
  125. package/views/config/security.hbs +22 -0
  126. package/views/config/service.hbs +44 -0
  127. package/views/config/webhooks.hbs +36 -0
  128. package/views/layout/app.hbs +9 -6
  129. package/views/legal.hbs +8 -0
  130. package/views/partials/queue_retention_note.hbs +12 -8
  131. package/views/partials/ui/env-managed-alert.hbs +16 -7
  132. package/workers/api.js +112 -37
  133. package/workers/export.js +16 -631
  134. package/workers/imap.js +13 -0
  135. package/workers/smtp.js +9 -11
  136. package/workers/webhooks.js +18 -432
  137. package/lib/email-client/outlook-fallback-poll.js +0 -30
package/lib/export.js CHANGED
@@ -631,25 +631,51 @@ class Export {
631
631
  }
632
632
 
633
633
  static async queueMessage(account, exportId, messageInfo) {
634
+ return (await Export.queueMessages(account, exportId, [messageInfo])) === 1;
635
+ }
636
+
637
+ /**
638
+ * Queues messages of an export: per message the ZADD, the count of a new member and the queue's
639
+ * expiry (copied from the record's), all of them sent as one pipeline. Indexing used to send one
640
+ * call per message. A retried folder queues the messages its failed attempt already queued, and
641
+ * only a new member counts, see the script
642
+ * @param {string} account
643
+ * @param {string} exportId
644
+ * @param {Object[]} messages - { folder, messageId, uid, size, date }
645
+ * @returns {Promise<number>} How many were new
646
+ */
647
+ static async queueMessages(account, exportId, messages) {
648
+ if (!messages.length) {
649
+ return 0;
650
+ }
651
+
634
652
  const queueKey = getExportQueueKey(account, exportId);
635
653
  const exportKey = getExportKey(account, exportId);
636
654
 
637
- const score = calculateScore(messageInfo.date, messageInfo.folder, messageInfo.messageId, messageInfo.uid);
638
-
639
- const value = msgpack
640
- .encode({
641
- folder: messageInfo.folder,
642
- messageId: messageInfo.messageId,
643
- uid: messageInfo.uid,
644
- size: messageInfo.size || 0
645
- })
646
- .toString('base64url');
655
+ const pipeline = redis.pipeline();
656
+ for (const messageInfo of messages) {
657
+ const score = calculateScore(messageInfo.date, messageInfo.folder, messageInfo.messageId, messageInfo.uid);
658
+ const value = msgpack
659
+ .encode({
660
+ folder: messageInfo.folder,
661
+ messageId: messageInfo.messageId,
662
+ uid: messageInfo.uid,
663
+ size: messageInfo.size || 0
664
+ })
665
+ .toString('base64url');
666
+ pipeline.eeExportQueueAdd(exportKey, queueKey, score, value, 'messagesQueued');
667
+ }
647
668
 
648
- // ZADD, the count of a new member and the queue's expiry (copied from the record's) in one
649
- // round trip; this runs once per message of an export. A retried folder queues the
650
- // messages its failed attempt already queued, and only a new member counts, see the script.
651
- const added = await redis.eeExportQueueAdd(exportKey, queueKey, score, value, 'messagesQueued');
652
- return !!added;
669
+ let added = 0;
670
+ for (const [err, result] of await pipeline.exec()) {
671
+ if (err) {
672
+ throw err;
673
+ }
674
+ if (result) {
675
+ added++;
676
+ }
677
+ }
678
+ return added;
653
679
  }
654
680
 
655
681
  static async getNextBatch(account, exportId, limit) {
@@ -684,6 +710,29 @@ class Export {
684
710
  await redis.hincrby(getExportKey(account, exportId), 'messagesSkipped', 1);
685
711
  }
686
712
 
713
+ /**
714
+ * Adds a batch worth of progress to the export record in one round trip
715
+ * @param {string} account
716
+ * @param {string} exportId
717
+ * @param {{exported?: number, bytesWritten?: number, skipped?: number}} counts
718
+ */
719
+ static async incrementCounters(account, exportId, counts) {
720
+ const exportKey = getExportKey(account, exportId);
721
+ const fields = [
722
+ ['messagesExported', counts.exported],
723
+ ['bytesWritten', counts.bytesWritten],
724
+ ['messagesSkipped', counts.skipped]
725
+ ].filter(([, value]) => value);
726
+ if (!fields.length) {
727
+ return;
728
+ }
729
+ const multi = redis.multi();
730
+ for (const [field, value] of fields) {
731
+ multi.hincrby(exportKey, field, value);
732
+ }
733
+ await multi.exec();
734
+ }
735
+
687
736
  static async complete(account, exportId) {
688
737
  const exportKey = getExportKey(account, exportId);
689
738
  const queueKey = getExportQueueKey(account, exportId);
@@ -122,7 +122,7 @@ const FIELD_USAGE = {
122
122
 
123
123
  revokeGrant:
124
124
  'Set this when deleting an account should also cut EmailEngine off at the provider, for example because a user asked for their data to be disconnected rather than just removed here.\n\n' +
125
- 'It currently works for individual Gmail OAuth2 grants. Gmail Workspace service-account integrations, Outlook and non-OAuth2 accounts ignore it. A failed revocation is logged and never blocks the deletion.',
125
+ 'It currently works for individual Gmail OAuth2 grants. Gmail Workspace service-account integrations, Outlook and non-OAuth2 accounts ignore it. The response reports the outcome under `revocation`. With `true` a failed revocation never blocks the deletion; use `required` when the account must stay until the grant is gone, so a failure can be retried without reading the token out of EmailEngine.',
126
126
 
127
127
  webSafeHtml:
128
128
  'Turn this on when you are rendering the message in your own UI and want EmailEngine to do the sanitising. It is a shorthand that overrides `textType`, `preProcessHtml` and `embedAttachedImages`.\n\n' +
package/lib/gateway.js CHANGED
@@ -292,4 +292,20 @@ class Gateway {
292
292
  }
293
293
  }
294
294
 
295
- module.exports = { Gateway };
295
+ /**
296
+ * The SMTP connection config of a gateway: what a message sent through it connects with, and what
297
+ * verifyAccountInfo() checks it with, from its stored settings or from the same fields on the admin
298
+ * form
299
+ * @param {Object} data - `{ host, port, secure, requireTLS, user, pass }`
300
+ * @returns {Object} SMTP configuration
301
+ */
302
+ function gatewaySmtpConfig(data) {
303
+ const { host, port, secure, requireTLS, user, pass } = data;
304
+ const config = { host, port, secure, requireTLS };
305
+ if (user || pass) {
306
+ config.auth = { user: user || '', pass: pass || '' };
307
+ }
308
+ return config;
309
+ }
310
+
311
+ module.exports = { Gateway, gatewaySmtpConfig };
@@ -7,10 +7,9 @@ const { HeadersRewriter } = require('./headers-rewriter');
7
7
  const { markParseFailure } = require('./smtp-message-processor');
8
8
  const mimeFuncs = require('nodemailer/lib/mime-funcs');
9
9
  const MimeNode = require('nodemailer/lib/mime-node');
10
- const addressparser = require('nodemailer/lib/addressparser');
10
+ const { parseAddressHeader } = require('mailparser');
11
11
  const { randomUUID: uuid } = require('crypto');
12
12
  const os = require('os');
13
- const libmime = require('libmime');
14
13
  const { getBoolean, genBaseBoundary, download } = require('./tools');
15
14
  const msgpack = require('./msgpack');
16
15
  const crypto = require('crypto');
@@ -58,8 +57,6 @@ async function processMessage(data, licenseInfo) {
58
57
  const splitter = new Splitter();
59
58
  const joiner = new Joiner();
60
59
  const headersRewriter = new HeadersRewriter(async headers => {
61
- let mn = new MimeNode();
62
-
63
60
  let sendAtVal = headers.getFirst('x-ee-send-at');
64
61
  headers.remove('x-ee-send-at');
65
62
 
@@ -120,7 +117,7 @@ async function processMessage(data, licenseInfo) {
120
117
  }
121
118
 
122
119
  // update or add new
123
- let headerLine = mn._encodeHeaderValue(addrKey, addrValue);
120
+ let headerLine = MimeNode.encodeHeaderValue(addrKey, addrValue);
124
121
  if (headers.hasHeader(addrKey)) {
125
122
  let addressEntries = addrValue.filter(entry => !entry._default);
126
123
  if (!addressEntries.length) {
@@ -143,77 +140,21 @@ async function processMessage(data, licenseInfo) {
143
140
 
144
141
  hasBcc = headers.hasHeader('bcc');
145
142
 
146
- let addresses = {
147
- from: headers
148
- .get('from')
149
- .flatMap(line => addressparser(line, { flatten: true }))
150
- .filter(a => a)
151
- .map(addr => {
152
- if (addr.name) {
153
- try {
154
- addr.name = libmime.decodeWords(addr.name);
155
- } catch (err) {
156
- // ignore
157
- }
158
- }
159
- return addr;
160
- })
161
- .find(addr => addr && addr.address),
162
- to: headers
163
- .get('to')
164
- .flatMap(line => addressparser(line, { flatten: true }))
165
- .filter(a => a)
166
- .map(addr => {
167
- if (addr.name) {
168
- try {
169
- addr.name = libmime.decodeWords(addr.name);
170
- } catch (err) {
171
- // ignore
172
- }
173
- }
174
- return addr;
175
- }),
176
- cc: headers
177
- .get('cc')
178
- .flatMap(line => addressparser(line, { flatten: true }))
179
- .filter(a => a)
180
- .map(addr => {
181
- if (addr.name) {
182
- try {
183
- addr.name = libmime.decodeWords(addr.name);
184
- } catch (err) {
185
- // ignore
186
- }
187
- }
188
- return addr;
189
- }),
190
- bcc: headers
191
- .get('bcc')
192
- .flatMap(line => addressparser(line, { flatten: true }))
193
- .filter(a => a)
194
- .map(addr => {
195
- if (addr.name) {
196
- try {
197
- addr.name = libmime.decodeWords(addr.name);
198
- } catch (err) {
199
- // ignore
200
- }
201
- }
202
- return addr;
203
- })
204
- };
143
+ // The addresses an envelope is built from: a punycode domain stays in the ASCII form every
144
+ // server accepts, and an entry left without an address (an encoded word hiding one is
145
+ // dropped by the parser) is no recipient. getDecoded() unfolds the value and drops the
146
+ // header name, and leaves encoded words for the parser to judge
147
+ const envelopeAddresses = key =>
148
+ parseAddressHeader(
149
+ headers.getDecoded(key).map(header => header.value),
150
+ { flatten: true, decodePunycode: false }
151
+ )
152
+ .value.map(addr => addr.address)
153
+ .filter(address => address);
205
154
 
206
155
  envelope = data.envelope || {
207
- from: (addresses.from && addresses.from.address) || '',
208
- to: Array.from(
209
- new Set(
210
- []
211
- .concat(addresses.to)
212
- .concat(addresses.cc)
213
- .concat(addresses.bcc)
214
- .map(addr => addr.address)
215
- )
216
- )
156
+ from: envelopeAddresses('from')[0] || '',
157
+ to: Array.from(new Set([...envelopeAddresses('to'), ...envelopeAddresses('cc'), ...envelopeAddresses('bcc')]))
217
158
  };
218
159
 
219
160
  envelope.from = [].concat(envelope.from || []).shift() || '';
@@ -259,7 +200,11 @@ async function processMessage(data, licenseInfo) {
259
200
  headers.update(casedKey, data.headers[key]);
260
201
  break;
261
202
  default:
262
- headers.add(casedKey, data.headers[key]);
203
+ // Encoded like any other header: a non-ASCII value used to go out as raw 8-bit
204
+ headers.add(
205
+ casedKey,
206
+ typeof data.headers[key] === 'string' ? MimeNode.encodeHeaderValue(casedKey, data.headers[key]) : data.headers[key]
207
+ );
263
208
  break;
264
209
  }
265
210
  }
@@ -444,46 +389,28 @@ async function getRawEmail(data, licenseInfo, options) {
444
389
 
445
390
  if (!options.returnObject) {
446
391
  for (let attachment of mailComposerOptions.attachments || []) {
447
- // Insert message/rfc822 attachments "as is" without any encoding
392
+ // Insert message/rfc822 attachments "as is" without any encoding. Handed over decoded,
393
+ // nodemailer (10.2.0) labels the part 7bit when it is plain ASCII and 8bit otherwise,
394
+ // which this used to work out itself by building the part's headers by hand
448
395
  if (/^message\/rfc822\b/i.test(attachment.contentType) && typeof attachment.content === 'string' && attachment.encoding) {
449
- let raw = Buffer.from(attachment.content, attachment.encoding);
450
-
451
- delete attachment.content;
396
+ attachment.content = Buffer.from(attachment.content, attachment.encoding);
452
397
  delete attachment.encoding;
453
-
454
- let isAscii = true;
455
- for (let i = 0, len = raw.length; i < len; i++) {
456
- if (raw[i] > 0x7f) {
457
- // 8bit byte encountered, so the contents are not purely ascii (7bit)
458
- isAscii = false;
459
- break;
460
- }
461
- }
462
-
463
- // we need to generate a valid message header with correct filename encoding (if needed)
464
- const mimeNode = new MimeNode('message/rfc822', {
465
- filename: attachment.filename,
466
- // Use empty root node, otherwise MimeNode will set default Date and Message-ID headers which we do not need
467
- rootNode: new MimeNode()
468
- });
469
- mimeNode.setHeader('Content-Disposition', attachment.contentDisposition || 'attachment');
470
- mimeNode.setHeader('Content-Transfer-Encoding', isAscii ? '7bit' : '8bit');
471
- const nodeHeaders = mimeNode.buildHeaders();
472
-
473
- attachment.raw = Buffer.concat([
474
- // Generated message/rfc822 headers
475
- Buffer.from(nodeHeaders),
476
- // Linebreak between headers and content
477
- Buffer.from('\r\n\r\n'),
478
- // Unencoded message/rfc822 contents
479
- raw
480
- ]);
398
+ attachment.contentDisposition = attachment.contentDisposition || 'attachment';
481
399
  }
482
400
  }
483
401
 
484
402
  const mail = new MailComposer(mailComposerOptions);
485
403
 
486
- const compiled = mail.compile();
404
+ let compiled;
405
+ try {
406
+ compiled = mail.compile();
407
+ } catch (err) {
408
+ // an otp value the schema let through but the OTP-Token header can not carry
409
+ if (err.code === 'EOTP') {
410
+ err.statusCode = 400;
411
+ }
412
+ throw err;
413
+ }
487
414
  // do not strip Bcc header from the message (will be removed later)
488
415
  compiled.keepBcc = true;
489
416
 
package/lib/health.js ADDED
@@ -0,0 +1,75 @@
1
+ 'use strict';
2
+
3
+ // The checks behind the health endpoints, kept free of Hapi and of the worker's own globals so each
4
+ // failure branch can be tested without booting the API.
5
+ //
6
+ // Two questions with different consequences. Liveness asks whether this process should be
7
+ // restarted, so it only depends on the process itself: answering it with a Redis check would make
8
+ // an orchestrator restart every pod whenever Redis has a hiccup. Readiness asks whether this process
9
+ // should get traffic, and that needs the IMAP workers and Redis, and is false while the API worker is
10
+ // draining on shutdown.
11
+
12
+ const crypto = require('crypto');
13
+ const { statusError } = require('./utils/status-error');
14
+
15
+ const notReady = (message, code) => statusError(message, code, 503);
16
+
17
+ /**
18
+ * @param {Object} deps
19
+ * @param {Function} deps.call - RPC to the main thread, resolves with the command's answer
20
+ * @param {Object} deps.redis - ioredis client
21
+ * @param {string} deps.prefix - Redis key prefix
22
+ * @param {number} deps.expectedImapWorkers - IMAP worker threads the instance is configured for
23
+ * @param {Function} deps.isDraining - True once the worker has started shutting down
24
+ * @returns {{ live: Function, ready: Function }}
25
+ */
26
+ function createHealthChecks(deps) {
27
+ const { call, redis, prefix, expectedImapWorkers, isDraining } = deps;
28
+
29
+ function live() {
30
+ if (isDraining()) {
31
+ // Still alive while it drains; reporting otherwise would get it killed mid-request
32
+ return { success: true, draining: true };
33
+ }
34
+ return { success: true };
35
+ }
36
+
37
+ /**
38
+ * @param {number} [timeout] - RPC timeout, already validated by the caller
39
+ */
40
+ async function ready(timeout) {
41
+ if (isDraining()) {
42
+ throw notReady('Shutting down', 'ShuttingDown');
43
+ }
44
+
45
+ let workers;
46
+ try {
47
+ ({ workers } = (await call({ cmd: 'imapWorkerCount', timeout })) || {});
48
+ } catch (err) {
49
+ throw notReady(`Worker check failed: ${err.message}`, 'WorkerCheckFailed');
50
+ }
51
+ // The answer used to be compared as a whole object, which is never less than a number, so
52
+ // missing workers were never reported
53
+ if (!(workers >= expectedImapWorkers)) {
54
+ throw notReady('Not all IMAP workers available', 'WorkersUnavailable');
55
+ }
56
+
57
+ const checkKey = `${prefix}test:${Date.now()}:${crypto.randomBytes(4).toString('hex')}`;
58
+ const expected = crypto.randomBytes(8).toString('hex');
59
+ let res;
60
+ try {
61
+ res = await redis.multi().set(checkKey, expected).get(checkKey).del(checkKey).exec();
62
+ } catch (err) {
63
+ throw notReady(`Database check failed: ${err.message}`, 'DatabaseCheckFailed');
64
+ }
65
+ if (!(res?.[1]?.[1] === expected && res?.[2]?.[1] === 1)) {
66
+ throw notReady('Database check failed', 'DatabaseCheckFailed');
67
+ }
68
+
69
+ return { success: true };
70
+ }
71
+
72
+ return { live, ready };
73
+ }
74
+
75
+ module.exports = { createHealthChecks };
@@ -0,0 +1,119 @@
1
+ 'use strict';
2
+
3
+ const Boom = require('@hapi/boom');
4
+
5
+ // Runs a critical section under an ioredfour lock through its withLock(), which owns the acquire,
6
+ // the release in every case, and a failed release (the lock expires on its own). What a caller
7
+ // does when the lock is not there to take differs per site: refuse with an error of its own, or go
8
+ // ahead unserialized, so that is the one thing left to it.
9
+
10
+ let sharedLock = null;
11
+
12
+ /**
13
+ * The lock instance every EmailEngine lock is taken from: one namespace, one subscriber connection
14
+ * per worker, and the one place a failed release (which withLock() reports as an 'error' event and
15
+ * never as the result) is logged. Built on first use, so requiring this module opens nothing
16
+ * @returns {Object} ioredfour Lock
17
+ */
18
+ function getSharedLock() {
19
+ if (!sharedLock) {
20
+ const Lock = require('ioredfour');
21
+ const { redis } = require('./db');
22
+ const logger = require('./logger');
23
+ sharedLock = new Lock({ redis, namespace: 'ee' });
24
+ sharedLock.on('error', err => logger.warn({ msg: 'Lock operation failed, the lock expires on its own', err }));
25
+ }
26
+ return sharedLock;
27
+ }
28
+
29
+ /**
30
+ * @param {Object} lock - ioredfour Lock instance
31
+ * @param {string} id - Lock id
32
+ * @param {Object} opts
33
+ * @param {number} opts.ttl - Lock TTL in ms
34
+ * @param {number|false} opts.wait - How long to wait for the lock in ms, false for one try
35
+ * @param {boolean} [opts.extend] - Keep extending the lock while fn runs, so ttl only has to cover a
36
+ * stalled process rather than the whole job
37
+ * @param {Function} fn - The critical section
38
+ * @param {Function} onUnavailable - (err) => value or throw, when the lock was not obtained (err is
39
+ * ioredfour's ELOCKNOTACQUIRED LockError, or the Redis error that kept it from being taken)
40
+ * @returns {Promise<*>} What fn resolves with, or what onUnavailable returns
41
+ */
42
+ async function runLocked(lock, id, { ttl, wait, extend }, fn, onUnavailable) {
43
+ // withLock() rejects the same way whether the lock was not taken or fn failed; only the first
44
+ // goes to onUnavailable
45
+ let entered = false;
46
+ try {
47
+ return await lock.withLock(
48
+ id,
49
+ ttl,
50
+ wait === false ? 0 : wait,
51
+ async (...args) => {
52
+ entered = true;
53
+ return await fn(...args);
54
+ },
55
+ { wait: wait !== false, extend: !!extend }
56
+ );
57
+ } catch (err) {
58
+ if (entered) {
59
+ throw err;
60
+ }
61
+ return await onUnavailable(err);
62
+ }
63
+ }
64
+
65
+ const isContention = err => !!err && err.code === 'ELOCKNOTACQUIRED';
66
+
67
+ /**
68
+ * An onUnavailable for runLocked() that refuses with a Boom error: contention (someone else held the
69
+ * lock for the whole wait) is logged as a warning and answered with `contention` (a 500 with no code
70
+ * of its own by default), a lock that could not be taken at all as an error and a 500 carrying the
71
+ * Redis error's code
72
+ * @param {Object} logger
73
+ * @param {string} message - What failed, e.g. 'Failed to get renewal lock'
74
+ * @param {Object} fields - Fields for the log entry
75
+ * @param {Object} [contention] - `{ statusCode, code, message, logMessage }` for the contention answer
76
+ * @returns {Function}
77
+ */
78
+ function refuseUnavailableLock(logger, message, fields, contention = {}) {
79
+ return err => {
80
+ let error;
81
+ if (isContention(err)) {
82
+ logger.warn(Object.assign({ msg: contention.logMessage || `${message}, timed out waiting for the current holder` }, fields));
83
+ error = Boom.boomify(new Error(contention.message || message), { statusCode: contention.statusCode || 500 });
84
+ if (contention.code) {
85
+ error.output.payload.code = contention.code;
86
+ }
87
+ } else {
88
+ logger.error(Object.assign({ msg: message }, fields, { err }));
89
+ error = Boom.boomify(new Error(contention.failureMessage || message), { statusCode: 500 });
90
+ if (err && err.code) {
91
+ error.output.payload.code = err.code;
92
+ }
93
+ }
94
+ throw error;
95
+ };
96
+ }
97
+
98
+ /**
99
+ * An onUnavailable for runLocked() outside the API: contention becomes an Error of its own (code
100
+ * LockNotAcquired) after a warning, any other failure is logged and rethrown as it is
101
+ * @param {Object} logger
102
+ * @param {string} message - What failed, e.g. 'Failed to get connection lock'
103
+ * @param {Object} fields - Fields for the log entry
104
+ * @returns {Function}
105
+ */
106
+ function rethrowUnavailableLock(logger, message, fields) {
107
+ return err => {
108
+ if (isContention(err)) {
109
+ logger.warn(Object.assign({ msg: `${message}, timed out waiting for the current holder` }, fields));
110
+ const error = new Error(message);
111
+ error.code = 'LockNotAcquired';
112
+ throw error;
113
+ }
114
+ logger.error(Object.assign({ msg: message }, fields, { err }));
115
+ throw err;
116
+ };
117
+ }
118
+
119
+ module.exports = { runLocked, refuseUnavailableLock, rethrowUnavailableLock, getSharedLock, isContention };
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ // The constants lib/logger.js needs, in a module that requires nothing. lib/consts.js reads its
4
+ // own environment variables through lib/read-env-value.js, which logs through lib/logger.js, so a
5
+ // logger that required lib/consts.js was a require cycle, and read-env-value had to defer every
6
+ // log line by a tick to get around it. lib/consts.js re-exports both, so other callers are unchanged.
7
+
8
+ // Transient network error codes that indicate a retry-worthy connection failure
9
+ const TRANSIENT_NETWORK_CODES = new Set([
10
+ 'ENOTFOUND',
11
+ 'EAI_AGAIN',
12
+ 'ETIMEDOUT',
13
+ 'ECONNRESET',
14
+ 'ECONNREFUSED',
15
+ // no route to the host, such as an IPv6 address on a host without IPv6 connectivity
16
+ 'ENETUNREACH',
17
+ 'EHOSTUNREACH',
18
+ 'UND_ERR_SOCKET',
19
+ 'UND_ERR_CONNECT_TIMEOUT',
20
+ 'UND_ERR_HEADERS_TIMEOUT',
21
+ // a response body that stalled mid-transfer
22
+ 'UND_ERR_BODY_TIMEOUT'
23
+ ]);
24
+
25
+ // Applied by lib/logger.js to the root logger, so every worker inherits it. A logged joi
26
+ // ValidationError carries the full submitted payload in `_original` and the offending value in
27
+ // each detail context, and `rawPacket` is a TLS-error field that can carry an unparsed
28
+ // credential frame - without these a failed validation writes plaintext passwords, OAuth2
29
+ // client secrets and access tokens into the log, the per-account log store and Sentry.
30
+ // `req.query.access_token` is here because the api-token scheme accepts the credential as a
31
+ // query argument, and the request logger (lib/hapi-request-logger.js) logs the parsed query
32
+ // object with every request - so a client using that form wrote a live token into this
33
+ // instance's own request log. The serialized `req.url` is the pathname only
34
+ // (pino-std-serializers reports `req.path`), so the credential reaches the log through the
35
+ // query object and nowhere else.
36
+ const REDACTED_LOG_KEYS = [
37
+ 'req.headers.authorization',
38
+ 'req.headers.cookie',
39
+ 'req.query.access_token',
40
+ 'err.rawPacket',
41
+ 'err._original',
42
+ 'err.details[*].context.value',
43
+ // the WHATWG URL parser attaches the string it rejected, and a stored proxy or webhook URL
44
+ // carries its credentials inline
45
+ 'err.input'
46
+ ];
47
+
48
+ module.exports = { REDACTED_LOG_KEYS, TRANSIENT_NETWORK_CODES };
package/lib/logger.js CHANGED
@@ -7,7 +7,7 @@ if (!process.env.EE_ENV_LOADED) {
7
7
 
8
8
  const config = require('@zone-eu/wild-config');
9
9
  const pino = require('pino');
10
- const { REDACTED_LOG_KEYS } = require('./consts');
10
+ const { REDACTED_LOG_KEYS } = require('./logger-consts');
11
11
  const { isTransientNetworkError } = require('./network-errors');
12
12
 
13
13
  config.log = config.log || {
@@ -0,0 +1,28 @@
1
+ --[[
2
+ Script: z-head-scores.lua
3
+ Purpose: Returns the scores of the lowest-scored entries of a sorted set, without the members.
4
+ For a queue scored by UID whose members are full JSON payloads, the UIDs are all a caller wants,
5
+ and ZRANGE WITHSCORES would send every payload along with them
6
+
7
+ KEYS:
8
+ [1] key - Sorted set key
9
+
10
+ ARGV:
11
+ [1] count - How many entries to read from the head of the set
12
+
13
+ Returns:
14
+ Array of scores (as strings), lowest first; empty when the set does not exist
15
+ --]]
16
+
17
+ local count = tonumber(ARGV[1]) or 0;
18
+ if count < 1 then
19
+ return {};
20
+ end;
21
+
22
+ local list = redis.call("ZRANGE", KEYS[1], 0, count - 1, "WITHSCORES");
23
+ local scores = {};
24
+ for i = 2, #list, 2 do
25
+ scores[#scores + 1] = list[i];
26
+ end;
27
+
28
+ return scores;
@@ -6,7 +6,7 @@
6
6
  //
7
7
  // Dependency-free apart from consts, so lib/logger.js can use it without a require cycle.
8
8
 
9
- const { TRANSIENT_NETWORK_CODES } = require('./consts');
9
+ const { TRANSIENT_NETWORK_CODES } = require('./logger-consts');
10
10
 
11
11
  // How far down a cause chain the transient check looks. A chain is not guaranteed to be finite - an
12
12
  // error may cite itself - so the walk is bounded rather than trusting it to end.
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ // The oldest Node.js release the dependency tree supports, matching `engines.node` in package.json
4
+ // (test/node-version-test.js keeps the two in step). Requires nothing but the dependency-free
5
+ // lib/utils/version.js, because server.js checks it before it requires anything else.
6
+
7
+ const MIN_SUPPORTED_NODE = '20.19.0';
8
+
9
+ const { compareVersions } = require('./utils/version');
10
+
11
+ /**
12
+ * Whether a Node.js version is older than MIN_SUPPORTED_NODE
13
+ * @param {string} version - A version such as process.versions.node ("20.18.1")
14
+ * @returns {boolean} True when the version is older, false for one that can not be read
15
+ */
16
+ function isBelowSupportedNode(version) {
17
+ try {
18
+ return compareVersions(String(version || '').replace(/^v/, ''), MIN_SUPPORTED_NODE) < 0;
19
+ } catch (err) {
20
+ return false;
21
+ }
22
+ }
23
+
24
+ module.exports = { MIN_SUPPORTED_NODE, isBelowSupportedNode };