emailengine-app 2.74.1 → 2.75.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 (60) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/data/google-crawlers.json +1 -1
  3. package/lib/account.js +117 -63
  4. package/lib/api-routes/changes-routes.js +51 -0
  5. package/lib/api-routes/index.js +160 -0
  6. package/lib/api-routes/message-routes.js +3 -1
  7. package/lib/consts.js +21 -0
  8. package/lib/db.js +4 -1
  9. package/lib/egress-filter.js +220 -0
  10. package/lib/email-client/base-client.js +5 -8
  11. package/lib/email-client/gmail/send-request.js +69 -0
  12. package/lib/email-client/gmail-client.js +6 -46
  13. package/lib/email-client/imap/detach-client.js +27 -0
  14. package/lib/email-client/imap/listing-diff.js +165 -0
  15. package/lib/email-client/imap/mailbox.js +35 -22
  16. package/lib/email-client/imap/subconnection.js +2 -4
  17. package/lib/email-client/imap/sync-operations.js +5 -3
  18. package/lib/email-client/imap-client.js +50 -84
  19. package/lib/email-client/notification-handler.js +11 -12
  20. package/lib/email-client/outlook/send-request.js +48 -0
  21. package/lib/email-client/outlook-client.js +7 -19
  22. package/lib/export.js +97 -21
  23. package/lib/imapproxy/imap-core/README.md +69 -0
  24. package/lib/imapproxy/imap-core/lib/imap-connection.js +1 -1
  25. package/lib/logger.js +14 -6
  26. package/lib/oauth/external-account-config.js +41 -1
  27. package/lib/oauth/external-account-signer.js +7 -2
  28. package/lib/oauth/verify-app.js +18 -3
  29. package/lib/queue-retention.js +56 -0
  30. package/lib/rate-limit.js +33 -11
  31. package/lib/respawn-backoff.js +95 -0
  32. package/lib/response-stream.js +138 -0
  33. package/lib/schemas.js +9 -2
  34. package/lib/sentry.js +8 -0
  35. package/lib/settings.js +4 -1
  36. package/lib/smtp-message-processor.js +131 -0
  37. package/lib/tools.js +48 -5
  38. package/lib/ui-routes/admin-config-routes.js +22 -18
  39. package/lib/ui-routes/internals-routes.js +32 -0
  40. package/lib/utils/network.js +122 -3
  41. package/lib/web-safe-html.js +401 -0
  42. package/lib/webhook-request.js +40 -2
  43. package/lib/webhooks.js +2 -3
  44. package/package.json +15 -13
  45. package/sbom.json +1 -1
  46. package/server.js +33 -8
  47. package/static/js/ee-client.js +55 -6
  48. package/static/js/ui.js +13 -0
  49. package/static/licenses.html +336 -286
  50. package/translations/messages.pot +12 -12
  51. package/views/config/webhooks.hbs +2 -2
  52. package/views/internals/index.hbs +8 -0
  53. package/views/partials/webhooks_editor_functions.hbs +1 -1
  54. package/workers/api.js +52 -233
  55. package/workers/documents.js +6 -0
  56. package/workers/export.js +37 -16
  57. package/workers/imap.js +64 -29
  58. package/workers/smtp.js +50 -91
  59. package/workers/submit.js +10 -0
  60. package/workers/webhooks.js +23 -2
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ // Server-Sent Events response stream used by the admin UI change feed (`/admin/changes`)
4
+ // and the API `/v1/changes` endpoint.
5
+ //
6
+ // Lives in its own module (rather than inline in workers/api.js) so the lifecycle
7
+ // guarantees below can be unit tested against the real implementation. Importing
8
+ // workers/api.js from a test is not an option: it boots a Hapi server on require.
9
+ //
10
+ // `registeredPublishers` is the set of live streams the API worker fans change events
11
+ // out to. Every stream adds itself on construction and removes itself in finalize(),
12
+ // so a dropped browser tab can not leak a timer or keep receiving writes.
13
+
14
+ const { Transform, finished } = require('stream');
15
+
16
+ const packageData = require('../package.json');
17
+
18
+ // Every live SSE stream. publishChangeEvent() in workers/api.js iterates this set.
19
+ const registeredPublishers = new Set();
20
+
21
+ // How long a stream may stay silent before a comment frame is written to keep
22
+ // intermediate proxies from timing the connection out.
23
+ const KEEP_ALIVE_INTERVAL = 90 * 1000;
24
+
25
+ class ResponseStream extends Transform {
26
+ constructor() {
27
+ super();
28
+ registeredPublishers.add(this);
29
+ this.periodicKeepAliveTimer = false;
30
+ this.updateTimer();
31
+
32
+ this._finalized = false;
33
+
34
+ // Ensure cleanup on all stream end scenarios. 'error' uses on() rather than once():
35
+ // a destroyed stream can emit more than one error, and a second unhandled 'error'
36
+ // would take the worker down.
37
+ this.on('error', () => this.finalize());
38
+ this.once('close', () => this.finalize());
39
+ this.once('end', () => this.finalize());
40
+ }
41
+
42
+ updateTimer() {
43
+ clearTimeout(this.periodicKeepAliveTimer);
44
+ this.periodicKeepAliveTimer = setTimeout(() => {
45
+ if (this._finalized || this.destroyed) {
46
+ return;
47
+ }
48
+ this.write(': still here\n\n');
49
+ if (this._compressor) {
50
+ this._compressor.flush();
51
+ }
52
+ this.updateTimer();
53
+ }, KEEP_ALIVE_INTERVAL);
54
+ this.periodicKeepAliveTimer.unref();
55
+ }
56
+
57
+ setCompressor(compressor) {
58
+ this._compressor = compressor;
59
+ }
60
+
61
+ sendMessage(payload) {
62
+ if (this._finalized || this.destroyed) {
63
+ return;
64
+ }
65
+ let sendData = JSON.stringify(payload);
66
+ this.write('event: message\ndata:' + sendData + '\n\n');
67
+ if (this._compressor) {
68
+ this._compressor.flush();
69
+ }
70
+ this.updateTimer();
71
+ }
72
+
73
+ finalize() {
74
+ if (this._finalized) {
75
+ // Prevent double cleanup
76
+ return;
77
+ }
78
+ this._finalized = true;
79
+
80
+ clearTimeout(this.periodicKeepAliveTimer);
81
+ registeredPublishers.delete(this);
82
+
83
+ if (!this.destroyed) {
84
+ this.destroy();
85
+ }
86
+ }
87
+
88
+ _transform(data, encoding, done) {
89
+ this.push(data);
90
+ done();
91
+ }
92
+
93
+ _flush(done) {
94
+ // done() first: finalize() destroys the stream, and destroying before the flush callback
95
+ // has returned cuts the readable side short - end() then emits 'close' and never 'end',
96
+ // so anything waiting for end-of-data (a consumer, stream.finished, a pipeline) waits
97
+ // forever. Finalizing straight after is still safe: push(null) has already happened, so
98
+ // the queued 'end' is delivered either way, and an ended stream that nobody reads is
99
+ // still cleaned up rather than leaking its keep-alive timer and its publisher entry.
100
+ done();
101
+ this.finalize();
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Opens an SSE change feed on a Hapi request.
107
+ *
108
+ * Both feeds - the admin UI one (/admin/changes) and the API one (/v1/changes) - are the same
109
+ * stream with the same framing, so the wiring lives here next to the stream it wires up rather
110
+ * than being written out twice. The parts that matter and are easy to get subtly different:
111
+ * finalize() has to run when the response is finished (a dropped tab must not keep its stream in
112
+ * registeredPublishers), the greeting has to be deferred so it is written after the response
113
+ * headers, and X-Accel-Buffering: no is what keeps an intermediate proxy from holding events
114
+ * back until the connection closes.
115
+ *
116
+ * @param {Object} request - Hapi request; the stream is parked on request.app.stream
117
+ * @param {Object} h - Hapi response toolkit
118
+ * @returns {Object} Hapi response
119
+ */
120
+ function openChangeStream(request, h) {
121
+ request.app.stream = new ResponseStream();
122
+ finished(request.app.stream, err => request.app.stream.finalize(err));
123
+ setImmediate(() => {
124
+ try {
125
+ request.app.stream.write(`: EmailEngine v${packageData.version}\n\n`);
126
+ } catch (err) {
127
+ // ignore
128
+ }
129
+ });
130
+ return h
131
+ .response(request.app.stream)
132
+ .header('X-Accel-Buffering', 'no')
133
+ .header('Connection', 'keep-alive')
134
+ .header('Cache-Control', 'no-cache')
135
+ .type('text/event-stream');
136
+ }
137
+
138
+ module.exports = { ResponseStream, registeredPublishers, openChangeStream };
package/lib/schemas.js CHANGED
@@ -3,6 +3,7 @@
3
3
  const Joi = require('joi');
4
4
  const config = require('@zone-eu/wild-config');
5
5
  const { getByteSize } = require('./tools');
6
+ const { COLLAPSE_CLASS } = require('./consts');
6
7
  const { locales } = require('./translations');
7
8
  const { LEGACY_KEYS, OAUTH_PROVIDERS } = require('./oauth2-apps');
8
9
  const { ACCOUNT_STATES } = require('./account/account-state');
@@ -282,7 +283,9 @@ const settingsSchema = {
282
283
  notifyWebSafeHtml: Joi.boolean()
283
284
  .truthy('Y', 'true', '1', 'on')
284
285
  .falsy('N', 'false', 0, '')
285
- .description('Sanitize HTML content to remove potentially dangerous elements before including in webhooks'),
286
+ .description(
287
+ 'Sanitize HTML content to remove potentially dangerous elements before including in webhooks, and fold quoted thread history into a collapsed block'
288
+ ),
286
289
  notifyTextSize: Joi.number().integer().min(0).description('Maximum size (in bytes) of text content to include in webhook payloads'),
287
290
  notifyAttachments: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').description('Include attachment data in webhook payloads'),
288
291
  notifyAttachmentSize: Joi.number().integer().min(0).description('Maximum size (in bytes) per attachment to include in webhook payloads'),
@@ -1142,7 +1145,11 @@ const messageDetailsSchema = Joi.object({
1142
1145
  .description('Whether the message content was truncated (true if more content is available via separate API call)'),
1143
1146
  webSafe: Joi.boolean()
1144
1147
  .example(true)
1145
- .description('Whether the HTML content has been processed into a web-safe version (set when webSafeHtml was requested)')
1148
+ .description(
1149
+ 'Whether the HTML content has been processed into a web-safe version (set when webSafeHtml was requested). ' +
1150
+ `Web-safe HTML for a reply also carries the quoted thread in a single collapsed <details class="${COLLAPSE_CLASS}"> ` +
1151
+ 'element, so renderers can hide it behind one control. Its <summary> is deliberately empty - supply your own label.'
1152
+ )
1146
1153
  }).label('TextInfoDetails'),
1147
1154
 
1148
1155
  bounces: bounceListSchema,
package/lib/sentry.js CHANGED
@@ -49,6 +49,14 @@ function startSentry(dsn) {
49
49
  if (opts?.meta && Object.keys(opts.meta).length) {
50
50
  captureContext.contexts = { ee: opts.meta };
51
51
  }
52
+ // Tags are indexed and searchable, contexts are display-only, so anything
53
+ // worth filtering or alerting on belongs here rather than in `meta`
54
+ if (opts?.tags) {
55
+ captureContext.tags = opts.tags;
56
+ }
57
+ if (opts?.level) {
58
+ captureContext.level = opts.level;
59
+ }
52
60
  Sentry.captureException(err, captureContext);
53
61
  };
54
62
 
package/lib/settings.js CHANGED
@@ -56,7 +56,10 @@ module.exports = {
56
56
 
57
57
  value = JSON.parse(value);
58
58
  } catch (err) {
59
- logger.debug({ key, value, err });
59
+ // NB! never log `value` here. By this point a value for an encrypted key has
60
+ // already been decrypted, so on a parse failure this would write the plaintext
61
+ // secret (OAuth2 client secrets, the SMTP/IMAP proxy passwords) into the log.
62
+ logger.debug({ msg: 'Failed to parse stored setting', key, encrypted: ENCRYPTED_KEYS.includes(key), err });
60
63
  return null;
61
64
  }
62
65
  }
@@ -0,0 +1,131 @@
1
+ 'use strict';
2
+
3
+ // Inbound message processing for the built-in SMTP submission server (workers/smtp.js).
4
+ //
5
+ // Lives here rather than inline in the worker for the same reason the auth handler does
6
+ // (lib/smtp-auth.js): the worker requires worker_threads and boots an SMTPServer on load, so
7
+ // nothing inside it can be unit tested. This piece is worth testing on its own because it is
8
+ // the only place the EmailEngine-specific control headers are consumed, and every one of them
9
+ // MUST be stripped before the message goes out - a leaked X-EE-Account header discloses the
10
+ // internal account id to the recipient.
11
+
12
+ const { Splitter, Joiner } = require('@zone-eu/mailsplit');
13
+ const { HeadersRewriter } = require('./headers-rewriter');
14
+
15
+ // Control headers a client may set on a submitted message. Each is read into `meta` and then
16
+ // removed from the message. Header lookups are case-insensitive (mailsplit lowercases keys).
17
+ const ACCOUNT_HEADER = 'x-ee-account';
18
+ const IDEMPOTENCY_HEADER = 'x-ee-idempotency-key';
19
+
20
+ // SMTP reply code for a message the MIME splitter refuses to parse. Permanent, because the
21
+ // splitter is a pure parser over the message bytes: every failure it can raise (today a 1MB
22
+ // per-MIME-node header cap and a child-node cap, both 'EMAXLEN') is a property of the message
23
+ // itself, so redelivering the same bytes can only fail the same way. Without a responseCode
24
+ // smtp-server answers 450 and a conforming client keeps retrying the message until its own
25
+ // queue lifetime runs out. 552 rather than a generic 554 to match the size rejection in
26
+ // workers/smtp.js - both are "this message is too big in some dimension".
27
+ const PARSE_FAILURE_RESPONSE_CODE = 552;
28
+
29
+ /**
30
+ * Pipes a submitted message through the MIME splitter, strips the EmailEngine control headers
31
+ * into `meta`, and rejoins it.
32
+ *
33
+ * @param {Stream} stream - Raw message stream from the SMTP server
34
+ * @param {Object} [meta] - Collector object; receives requestedAccount / idempotencyKey
35
+ * @returns {Stream} Stream of the rewritten message
36
+ */
37
+ function processMessage(stream, meta) {
38
+ meta = meta || {};
39
+ const splitter = new Splitter();
40
+ const joiner = new Joiner();
41
+
42
+ const headersRewriter = new HeadersRewriter(async headers => {
43
+ let requestedAccount = headers.getFirst(ACCOUNT_HEADER);
44
+ headers.remove(ACCOUNT_HEADER);
45
+ if (requestedAccount) {
46
+ meta.requestedAccount = requestedAccount;
47
+ }
48
+
49
+ let idempotencyKey = headers.getFirst(IDEMPOTENCY_HEADER);
50
+ headers.remove(IDEMPOTENCY_HEADER);
51
+ if (idempotencyKey) {
52
+ meta.idempotencyKey = idempotencyKey;
53
+ }
54
+ });
55
+
56
+ // Forward the errors of every stage to the joiner, which is the only stream the caller ever
57
+ // sees. Readable.pipe() attaches an 'error' listener to the destination only, so an error
58
+ // raised anywhere upstream has no listener at all and takes the worker down as an uncaught
59
+ // exception. The splitter must be on this list too: it enforces a 1MB per-MIME-node header
60
+ // cap and a child-node limit (both 'EMAXLEN'), so any client that can reach the submission
61
+ // port can trigger one with a single oversized message.
62
+ //
63
+ // Only the splitter's failures are marked permanent. A raw-stream error is usually the client
64
+ // dropping the connection mid-DATA, and a headers-rewriter error can only come from the
65
+ // callback above, i.e. a bug on our side - neither is a verdict on the message, so both keep
66
+ // the retryable default.
67
+ for (let source of [stream, headersRewriter]) {
68
+ source.once('error', err => joiner.emit('error', err));
69
+ }
70
+
71
+ splitter.once('error', err => {
72
+ if (!err.responseCode) {
73
+ err.responseCode = PARSE_FAILURE_RESPONSE_CODE;
74
+ }
75
+ joiner.emit('error', err);
76
+ });
77
+
78
+ return stream.pipe(splitter).pipe(headersRewriter).pipe(joiner);
79
+ }
80
+
81
+ /**
82
+ * Buffers a submitted message: runs it through processMessage() and collects the result.
83
+ *
84
+ * The size verdict is read from the RAW stream. smtp-server keeps byteLength/sizeExceeded on the
85
+ * DATA stream it hands to onData, not on the rewritten stream returned by processMessage(), and
86
+ * it only refuses an oversized message on its own when the client volunteered a SIZE= parameter
87
+ * with MAIL FROM. Without a SIZE= it truncates the DATA stream and leaves the rejection to the
88
+ * application, so reading the flag off the wrong object means truncated messages get queued and
89
+ * delivered instead of being answered with a 552.
90
+ *
91
+ * @param {Stream} rawStream - Raw DATA stream from the SMTP server
92
+ * @param {Object} [meta] - Collector object; receives requestedAccount / idempotencyKey
93
+ * @returns {Promise<{message: Buffer, sizeExceeded: Boolean}>} Rewritten message and size verdict
94
+ */
95
+ function collectMessage(rawStream, meta) {
96
+ return new Promise((resolve, reject) => {
97
+ const stream = processMessage(rawStream, meta);
98
+
99
+ let chunks = [];
100
+ let chunklen = 0;
101
+
102
+ // Covers the source stream, the MIME splitter and the headers rewriter - processMessage()
103
+ // forwards all three here. A promise settles once, so a stream error arriving after the
104
+ // message was already collected can not produce a second SMTP response.
105
+ stream.on('error', reject);
106
+
107
+ stream.on('readable', () => {
108
+ let chunk;
109
+ while ((chunk = stream.read()) !== null) {
110
+ // Stop buffering once the limit is blown; the message is rejected either way and
111
+ // there is no reason to hold the rest of it in memory.
112
+ if (!rawStream.sizeExceeded) {
113
+ chunks.push(chunk);
114
+ chunklen += chunk.length;
115
+ }
116
+ }
117
+ });
118
+
119
+ stream.on('end', () => {
120
+ const message = Buffer.concat(chunks, chunklen);
121
+ // Release the per-chunk copies right away. The listeners above close over `chunks`
122
+ // and stay attached to the joiner until the submission finishes, so without this the
123
+ // account lookup and the queueing that follow run with two full copies of the message
124
+ // live - up to 2x EENGINE_MAX_SMTP_MESSAGE_SIZE per concurrent submission.
125
+ chunks = null;
126
+ resolve({ message, sizeExceeded: !!rawStream.sizeExceeded });
127
+ });
128
+ });
129
+ }
130
+
131
+ module.exports = { processMessage, collectMessage, ACCOUNT_HEADER, IDEMPOTENCY_HEADER, PARSE_FAILURE_RESPONSE_CODE };
package/lib/tools.js CHANGED
@@ -37,7 +37,9 @@ const {
37
37
  FETCH_RETRY_EXPONENTIAL,
38
38
  FETCH_RETRY_MAX,
39
39
  URL_FETCH_RETRY_MAX,
40
- MAX_DAYS_STATS
40
+ MAX_DAYS_STATS,
41
+ MAILBOX_RESPONSE_FIELDS,
42
+ MAILBOX_HASH
41
43
  } = require('./consts');
42
44
  const bullmqPackage = require('bullmq/package.json');
43
45
 
@@ -531,6 +533,20 @@ module.exports = {
531
533
  return path;
532
534
  },
533
535
 
536
+ // Hashed component of a mailbox's per-folder Redis keys: a hash of the normalized path, so an
537
+ // arbitrarily long (or delimiter-heavy) folder name maps to a compact, stable key.
538
+ mailboxPathHash(path) {
539
+ return BigInt('0x' + createHash(MAILBOX_HASH).update(module.exports.normalizePath(path)).digest('hex')).toString(36);
540
+ },
541
+
542
+ // Redis key of a mailbox's status hash (message count, uidNext, ...). Defined here once
543
+ // because the writer (lib/email-client/imap/mailbox.js) and the reader
544
+ // (Account.getMailboxListing) must agree byte for byte or the counters silently go missing.
545
+ // NB: distinct from Account.getMailboxHashKey(), which is the account-wide message-id index.
546
+ getMailboxStatusKey(account, path) {
547
+ return `${REDIS_PREFIX}iam:${account}:h:${module.exports.mailboxPathHash(path)}`;
548
+ },
549
+
534
550
  async resolveCredentials(account, proto) {
535
551
  let authServer = await settings.get('authServer');
536
552
  if (!authServer) {
@@ -1134,11 +1150,11 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1134
1150
  let mailboxList = [];
1135
1151
  for (let entry of mailboxes) {
1136
1152
  let mailbox = {};
1137
- Object.keys(entry).forEach(key => {
1138
- if (['path', 'specialUse', 'name', 'listed', 'subscribed', 'delimiter', 'specialUseSource', 'noInferiors'].includes(key)) {
1153
+ for (let key of MAILBOX_RESPONSE_FIELDS) {
1154
+ if (key in entry) {
1139
1155
  mailbox[key] = entry[key];
1140
1156
  }
1141
- });
1157
+ }
1142
1158
  if (mailbox.delimiter && mailbox.path.indexOf(mailbox.delimiter) >= 0) {
1143
1159
  mailbox.parentPath = mailbox.path.substr(0, mailbox.path.lastIndexOf(mailbox.delimiter));
1144
1160
  }
@@ -2024,6 +2040,26 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2024
2040
  return key in process.env || `${key}_FILE` in process.env;
2025
2041
  },
2026
2042
 
2043
+ /**
2044
+ * Reads a comma-separated environment value as a trimmed, blank-free array.
2045
+ *
2046
+ * Returns `null` when the variable is not set at all, which callers rely on to distinguish
2047
+ * "no allowlist configured" (feature off) from "an allowlist that happens to be empty".
2048
+ *
2049
+ * @param {string} key - Environment variable name
2050
+ * @returns {string[]|null} Parsed entries, or null when unset
2051
+ */
2052
+ readEnvList(key) {
2053
+ if (!module.exports.hasEnvValue(key)) {
2054
+ return null;
2055
+ }
2056
+
2057
+ return (module.exports.readEnvValue(key) || '')
2058
+ .split(',')
2059
+ .map(v => v.trim())
2060
+ .filter(v => v);
2061
+ },
2062
+
2027
2063
  readEnvValue(key) {
2028
2064
  if (key in process.env) {
2029
2065
  return process.env[key];
@@ -2258,6 +2294,7 @@ oPpCZh28fyCPv2TZ
2258
2294
  t0xCngRgaIZRuD3T
2259
2295
  dBb0Tc1IggSKY8dD
2260
2296
  exRqrporGRl2rjBf
2297
+ /3wJNVxD2zYMP0pk
2261
2298
  r+p1xHpDF4Ct0jfn
2262
2299
  QeunHH85jTFcsR7e
2263
2300
  kBFI6x6tfC8K1C8E
@@ -2373,6 +2410,12 @@ mF3GOI+Ev7mJODtG
2373
2410
  nQNwPlZ+tyx24XVo
2374
2411
  olObiSmdzVaMp7lH
2375
2412
  SruXHv6plKL9YuAW
2413
+ WVyvxP7wyEaQ/hzD
2414
+ YkdM9t/TzipfB13O
2415
+ LVvUBJQhWMOmq/mt
2416
+ +SJ8ylImwdExbw/8
2417
+ KvUe4HhYDNDXDouN
2418
+ jYfRjAsQtmeJcUTk
2376
2419
  cyp1GKV4Cl+eC8G/
2377
2420
  Q1y/TzbtUQCqnotR
2378
2421
  59Q2qOkuyTLzQDhd
@@ -2399,7 +2442,7 @@ QodzxvoJ6NPGhCgW
2399
2442
  b85BMAFRHn10uX8y
2400
2443
  vV2RgfFH2YFTYsly
2401
2444
  zcmIO3obSzUVHGtF
2402
- tzsA68uFVAffHmec
2445
+ Qm55I3Y1yUsDhHBU
2403
2446
  DkCU3OpaSa+rIVfU
2404
2447
  dcDjqpxVxivT46Rl
2405
2448
  QSgNcpNukC9CBNfe
@@ -21,7 +21,9 @@ const consts = require('../consts');
21
21
  const getSecret = require('../get-secret');
22
22
  const timezonesList = require('timezones-list').default;
23
23
  const { redis, submitQueue, notifyQueue, documentsQueue } = require('../db');
24
- const { getByteSize, formatByteSize, getDuration, failAction, hasEnvValue, readEnvValue, httpAgent } = require('../tools');
24
+ const { getByteSize, formatByteSize, getDuration, failAction, readEnvValue, readEnvList, httpAgent } = require('../tools');
25
+ const { assertAllowedUrl, normalizePolicy, POLICY_OFF } = require('../egress-filter');
26
+ const { sendWebhookRequest } = require('../webhook-request');
25
27
  const { llmPreProcess } = require('../llm-pre-process');
26
28
  const { documentStoreFeatureEnabled } = require('../document-store');
27
29
  const { locales } = require('../translations');
@@ -51,12 +53,12 @@ config.api = config.api || {
51
53
  const MAX_BODY_SIZE = getByteSize(readEnvValue('EENGINE_MAX_BODY_SIZE') || config.api.maxBodySize) || DEFAULT_MAX_BODY_SIZE;
52
54
  const MAX_PAYLOAD_TIMEOUT = getDuration(readEnvValue('EENGINE_MAX_PAYLOAD_TIMEOUT') || config.api.maxPayloadTimeout) || DEFAULT_MAX_PAYLOAD_TIMEOUT;
53
55
 
54
- const ADMIN_ACCESS_ADDRESSES = hasEnvValue('EENGINE_ADMIN_ACCESS_ADDRESSES')
55
- ? readEnvValue('EENGINE_ADMIN_ACCESS_ADDRESSES')
56
- .split(',')
57
- .map(v => v.trim())
58
- .filter(v => v)
59
- : null;
56
+ const ADMIN_ACCESS_ADDRESSES = readEnvList('EENGINE_ADMIN_ACCESS_ADDRESSES');
57
+
58
+ // Must match the policy the webhooks worker enforces on real deliveries, including the null that
59
+ // tells sendWebhookRequest to keep following redirects when the policy is off
60
+ const WEBHOOK_EGRESS_POLICY = normalizePolicy(readEnvValue('EENGINE_WEBHOOK_EGRESS_POLICY'));
61
+ const validateWebhookTarget = WEBHOOK_EGRESS_POLICY === POLICY_OFF ? null : target => assertAllowedUrl(target, { policy: WEBHOOK_EGRESS_POLICY });
60
62
 
61
63
  const IMAP_INDEXERS = [
62
64
  {
@@ -1065,12 +1067,14 @@ return true;`
1065
1067
  let start = Date.now();
1066
1068
  let duration;
1067
1069
  try {
1068
- let res;
1069
-
1070
1070
  let serviceUrl = await settings.get('serviceUrl');
1071
1071
 
1072
+ // The same call the notify worker makes, rather than a lookalike: a probe that
1073
+ // reimplements delivery can only prove that the reimplementation works. It also
1074
+ // inherits the delivery timeout and the response drain, both of which this route
1075
+ // used to do without while running on the same keep-alive retry dispatcher.
1072
1076
  try {
1073
- res = await fetchCmd(parsed.toString(), {
1077
+ await sendWebhookRequest(fetchCmd, parsed.toString(), {
1074
1078
  method: 'post',
1075
1079
  body:
1076
1080
  request.payload.payload ||
@@ -1084,20 +1088,17 @@ return true;`
1084
1088
  }
1085
1089
  }),
1086
1090
  headers,
1087
- dispatcher: httpAgent.retry
1091
+ dispatcher: httpAgent.retry,
1092
+ validateTarget: validateWebhookTarget
1088
1093
  });
1089
1094
  duration = Date.now() - start;
1090
1095
  } catch (err) {
1091
1096
  duration = Date.now() - start;
1097
+ // undici wraps a connection failure in a generic "fetch failed"; the cause is
1098
+ // the part worth reporting back to the operator
1092
1099
  throw err.cause || err;
1093
1100
  }
1094
1101
 
1095
- if (!res.ok) {
1096
- let err = new Error(res.statusText || `Invalid response: ${res.status} ${res.statusText}`);
1097
- err.statusCode = res.status;
1098
- throw err;
1099
- }
1100
-
1101
1102
  return {
1102
1103
  success: true,
1103
1104
  target: webhooks,
@@ -1110,7 +1111,10 @@ return true;`
1110
1111
  target: webhooks,
1111
1112
  duration,
1112
1113
  error: err.message,
1113
- code: err.code
1114
+ code: err.code,
1115
+ // Same field the stored webhookErrorFlag carries, so the probe and the error
1116
+ // block on this page describe a failed delivery the same way
1117
+ statusCode: err.statusCode
1114
1118
  };
1115
1119
  }
1116
1120
  },
@@ -20,6 +20,14 @@ const THREAD_TYPE_ORDER = ['main', 'api', 'imap', 'webhooks', 'submit', 'export'
20
20
  // Severity ranking for the per-group health roll-up (higher wins).
21
21
  const STATUS_RANK = { success: 0, neutral: 1, warning: 2, error: 3 };
22
22
 
23
+ // "Recently restarted" detection. Workers normally come online within seconds of the main
24
+ // process; one that came online much later was respawned after a crash (uncaught exception).
25
+ // A worker is flagged only when it started well after main (RESTART_GRACE, beyond any normal
26
+ // staggered-boot spread) AND that restart is still recent (RECENT_WINDOW), so a long-since
27
+ // recovered worker fades back to healthy while a flapping one stays flagged.
28
+ const WORKER_RESTART_GRACE = 3 * 60 * 1000; // 3 min after main = a restart, not normal boot
29
+ const WORKER_RESTART_RECENT_WINDOW = 30 * 60 * 1000; // keep flagging for 30 min after the restart
30
+
23
31
  // Short description of what each worker kind does, shown on the group card header.
24
32
  const THREAD_PURPOSE = {
25
33
  main: 'Orchestrates everything else: spawns and monitors the other worker threads, assigns email accounts to the sync workers, routes inter-thread calls, and manages the Redis connection and licensing.',
@@ -67,6 +75,13 @@ function init(args) {
67
75
  bytesFormatter = new Intl.NumberFormat('en-US', bytesFormatterOpts);
68
76
  }
69
77
 
78
+ // Reference point for "recently restarted" detection: the main thread's online
79
+ // time is the process start, so any worker that came online well after it was
80
+ // respawned after boot rather than started with the fleet.
81
+ let now = Date.now();
82
+ let mainThread = threads.find(threadInfo => threadInfo.isMain || threadInfo.type === 'main');
83
+ let mainOnline = mainThread && typeof mainThread.online === 'number' ? mainThread.online : null;
84
+
70
85
  // Process each thread into row data. The per-thread config (expected worker
71
86
  // count) is intentionally NOT surfaced per row here - it is a pool-level fact
72
87
  // and is shown once on the group header below.
@@ -105,6 +120,23 @@ function init(args) {
105
120
  }
106
121
  }
107
122
 
123
+ // A worker that came online well after the main process, recently, was most
124
+ // likely respawned after an uncaught exception. Surface it as a warning even
125
+ // when its health checks are otherwise passing; a real error/warning health
126
+ // status is more specific and takes precedence.
127
+ if (
128
+ !threadInfo.isMain &&
129
+ mainOnline !== null &&
130
+ typeof threadInfo.online === 'number' &&
131
+ threadInfo.online - mainOnline > WORKER_RESTART_GRACE &&
132
+ now - threadInfo.online < WORKER_RESTART_RECENT_WINDOW &&
133
+ STATUS_RANK[threadInfo.statusVariant] < STATUS_RANK.warning
134
+ ) {
135
+ threadInfo.statusVariant = 'warning';
136
+ threadInfo.statusLabel = 'Recently restarted';
137
+ threadInfo.recentlyRestarted = true;
138
+ }
139
+
108
140
  if (threadInfo.online) {
109
141
  threadInfo.timeStr = new Date(threadInfo.online).toISOString();
110
142
  }