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
@@ -24,6 +24,46 @@ for (let prefixEntry of googleCrawlerRanges.prefixes) {
24
24
  }
25
25
  }
26
26
 
27
+ /**
28
+ * Parses an address, unwrapping the IPv4-mapped IPv6 form to the plain IPv4 it carries.
29
+ *
30
+ * A dual-stack listener reports an IPv4 peer as `::ffff:10.0.0.5`, while operators write the
31
+ * allowlist as `10.0.0.5`. Without this the two never compare equal, so a proxy declared in
32
+ * `EENGINE_API_PROXY_ADDRESSES` is not recognized and its X-Forwarded-For is discarded - which
33
+ * then denies the admin allowlist the very address it is configured to match.
34
+ *
35
+ * @param {string} address - IP address in any textual form
36
+ * @returns {Object} ipaddr.js address object, IPv4 whenever the input describes an IPv4 address
37
+ */
38
+ function parseComparableIp(address) {
39
+ let parsed = ipaddr.parse(address);
40
+
41
+ if (parsed.kind() === 'ipv6' && parsed.isIPv4MappedAddress()) {
42
+ return parsed.toIPv4Address();
43
+ }
44
+
45
+ return parsed;
46
+ }
47
+
48
+ /**
49
+ * Parses a CIDR range the same way, so an IPv4-mapped range matches plain IPv4 subjects.
50
+ *
51
+ * The mapped prefix occupies the first 96 bits, so the remaining bits are the IPv4 prefix length:
52
+ * `::ffff:10.0.0.0/104` describes exactly `10.0.0.0/8`.
53
+ *
54
+ * @param {string} range - CIDR range
55
+ * @returns {Array} `[address, bits]` as ipaddr.js reports it, unwrapped where applicable
56
+ */
57
+ function parseComparableCidr(range) {
58
+ let [parsed, bits] = ipaddr.parseCIDR(range);
59
+
60
+ if (parsed.kind() === 'ipv6' && parsed.isIPv4MappedAddress()) {
61
+ return [parsed.toIPv4Address(), Math.max(bits - 96, 0)];
62
+ }
63
+
64
+ return [parsed, bits];
65
+ }
66
+
27
67
  /**
28
68
  * Matches an IP address against a list of addresses or CIDR ranges
29
69
  * @param {string} ip - IP address to check
@@ -31,14 +71,32 @@ for (let prefixEntry of googleCrawlerRanges.prefixes) {
31
71
  * @returns {boolean} True if IP matches any address in the list
32
72
  */
33
73
  function matchIp(ip, addresses) {
34
- let parsed = ipaddr.parse(ip);
74
+ let parsed;
75
+ try {
76
+ parsed = parseComparableIp(ip);
77
+ } catch (err) {
78
+ // Every caller uses this for an allowlist decision, so an address we can not parse must
79
+ // match nothing. Throwing here used to surface as a 500 for any request that carried a
80
+ // non-IP value in a trusted X-Forwarded-For header.
81
+ //
82
+ // Logged at debug, not error: the subject address is client-supplied (it can come from an
83
+ // X-Forwarded-For chain entry), so junk here is expected input rather than a fault. Bad
84
+ // entries in the allowlist itself are a config problem and still log at error below.
85
+ logger.debug({ msg: 'Failed to parse IP address', ip, err });
86
+ return false;
87
+ }
88
+
35
89
  for (let addr of addresses) {
36
90
  try {
37
91
  let match;
38
92
  if (/\/\d+$/.test(addr)) {
39
- match = parsed.match(ipaddr.parseCIDR(addr));
93
+ let [range, bits] = parseComparableCidr(addr);
94
+ // ipaddr.js throws when the families differ, and a list that mixes IPv4 and IPv6
95
+ // entries is ordinary rather than a misconfiguration, so a mismatch is simply not
96
+ // a match instead of an error log on every request
97
+ match = range.kind() === parsed.kind() && parsed.match(range, bits);
40
98
  } else {
41
- match = parsed.toNormalizedString() === ipaddr.parse(addr).toNormalizedString();
99
+ match = parsed.toNormalizedString() === parseComparableIp(addr).toNormalizedString();
42
100
  }
43
101
  if (match) {
44
102
  return true;
@@ -51,6 +109,66 @@ function matchIp(ip, addresses) {
51
109
  return false;
52
110
  }
53
111
 
112
+ /**
113
+ * Resolves the effective client IP address for an incoming HTTP request.
114
+ *
115
+ * `X-Forwarded-For` is a list that each proxy APPENDS to, so the left-most entry is whatever the
116
+ * original caller sent and is never trustworthy on its own - nginx's canonical
117
+ * `$proxy_add_x_forwarded_for`, Apache's mod_proxy and HAProxy's `option forwardfor` all preserve
118
+ * a client-supplied value and add the peer after it. Two security controls key off the resolved
119
+ * address (the `EENGINE_ADMIN_ACCESS_ADDRESSES` admin allowlist and per-token
120
+ * `restrictions.addresses`), so taking the left-most entry lets any caller present the address the
121
+ * allowlist expects and walk through both.
122
+ *
123
+ * With `trustedProxies` (`EENGINE_API_PROXY_ADDRESSES`) configured the chain is therefore walked
124
+ * from the right, discarding entries contributed by declared proxies; the first entry that is not
125
+ * one of our proxies is the closest address they actually observed. Both the peer and the chain
126
+ * are checked, so a caller that is not behind a declared proxy gets no say at all.
127
+ *
128
+ * With no `trustedProxies` there is no way to know how many hops to believe, so the historical
129
+ * left-most behavior is kept for compatibility. That mode is fine for logging but must not be
130
+ * relied on for allowlists - which is what the startup warning in the API worker is about.
131
+ *
132
+ * @param {Object} opts
133
+ * @param {string} opts.remoteAddress - Peer address of the socket the request arrived on
134
+ * @param {string} [opts.forwardedFor] - Raw `X-Forwarded-For` header value, if any
135
+ * @param {boolean} [opts.enableApiProxy] - Whether the deployment is configured to sit behind a proxy
136
+ * @param {string[]} [opts.trustedProxies] - Addresses or CIDR ranges of our own proxies
137
+ * @returns {string} Address to treat as the client for logging and allowlist checks
138
+ */
139
+ function resolveClientIp({ remoteAddress, forwardedFor, enableApiProxy, trustedProxies }) {
140
+ if (!enableApiProxy || !forwardedFor) {
141
+ return remoteAddress;
142
+ }
143
+
144
+ // Anything that is not a bare IP (a port suffix, an obfuscated identifier, junk) can not be
145
+ // matched against an allowlist, so it is treated as no claim at all
146
+ const asClientAddress = value => (net.isIP(value) ? value : remoteAddress);
147
+
148
+ if (!trustedProxies || !trustedProxies.length) {
149
+ return asClientAddress(forwardedFor.split(',')[0].trim());
150
+ }
151
+
152
+ if (!matchIp(remoteAddress, trustedProxies)) {
153
+ // Request did not come from a declared proxy, so its forwarding header means nothing
154
+ return remoteAddress;
155
+ }
156
+
157
+ const chain = forwardedFor
158
+ .split(',')
159
+ .map(entry => entry.trim())
160
+ .filter(entry => entry);
161
+
162
+ for (let i = chain.length - 1; i >= 0; i--) {
163
+ if (!matchIp(chain[i], trustedProxies)) {
164
+ return asClientAddress(chain[i]);
165
+ }
166
+ }
167
+
168
+ // Every hop was one of ours, so nothing in the chain describes an external caller
169
+ return remoteAddress;
170
+ }
171
+
54
172
  /**
55
173
  * Detects if a request is from an automated scanner (Google, Barracuda, etc.)
56
174
  * @param {string} ip - IP address to check
@@ -232,6 +350,7 @@ module.exports = {
232
350
  updatePublicInterfaces,
233
351
  getLocalAddress,
234
352
  matchIp,
353
+ resolveClientIp,
235
354
  detectAutomatedRequest,
236
355
  googleCrawlerMap
237
356
  };
@@ -0,0 +1,401 @@
1
+ 'use strict';
2
+
3
+ const { analyze } = require('@postalsys/email-content');
4
+ const { mimeHtml, textToHtml } = require('@postalsys/email-text-tools');
5
+ const { getBoolean, readEnvValue } = require('./tools');
6
+ const { COLLAPSE_CLASS, COLLAPSE_TOGGLE_CLASS } = require('./consts');
7
+ const logger = require('./logger');
8
+
9
+ /**
10
+ * Web-safe HTML generation for message bodies.
11
+ *
12
+ * On top of the sanitization mimeHtml() performs, a reply that quotes the whole thread gets a
13
+ * single collapse marker: everything from the point where the sender stopped writing to the end
14
+ * of the body is wrapped in one <details> element.
15
+ *
16
+ * The marker carries structure and class names, and nothing else - no label text, no styling. A
17
+ * renderer that knows about it puts its own label into the <summary> and styles the block; a
18
+ * renderer that strips unknown elements is left with the body it would have got anyway.
19
+ */
20
+
21
+ const COLLAPSE_OPEN_MARKUP = `<details class="${COLLAPSE_CLASS}"><summary class="${COLLAPSE_TOGGLE_CLASS}"></summary>`;
22
+ const COLLAPSE_CLOSE_MARKUP = '</details>';
23
+
24
+ /**
25
+ * Segment labels that may be folded away.
26
+ *
27
+ * Every segment also carries the extractor's own `visibility`, and folding on that alone was
28
+ * rejected: it marks signatures as collapsible, and a signature sits inside the content block for
29
+ * Gmail-style replies, which moves the cut point somewhere the marker can only fold a fraction of
30
+ * the thread. The label set decides what kind of content may be folded, and `visibility` is still
31
+ * consulted, so a segment the extractor was not confident enough to collapse is never folded here
32
+ * either.
33
+ */
34
+ const COLLAPSIBLE_TYPES = new Set(['REPLY_HISTORY', 'FORWARDED_CONTENT', 'DISCLAIMER']);
35
+
36
+ // A shorter tail is not worth a control: hiding two lines behind a click adds noise instead of
37
+ // removing it.
38
+ const MIN_COLLAPSE_CHARS = 120;
39
+
40
+ /**
41
+ * Largest body the extractor is run over.
42
+ *
43
+ * Extraction is synchronous and roughly linear in body size, and two of the callers run on the
44
+ * IMAP worker for every newly seen message, so this is a bound on how long a single message may
45
+ * block that event loop - around 25 ms at this size. Larger bodies are passed through unfolded
46
+ * rather than analysed in part: a cut point derived from a truncated body says nothing about the
47
+ * content past the truncation, which is exactly where new content would have to be looked for.
48
+ */
49
+ const MAX_ANALYZE_CHARS = 256 * 1024;
50
+
51
+ // Opt-out for operators who need the previous output shape, or who do not want to pay for
52
+ // extraction on every notified message.
53
+ const DISABLE_THREAD_COLLAPSE = getBoolean(readEnvValue('EENGINE_DISABLE_THREAD_COLLAPSE'));
54
+
55
+ /**
56
+ * Base styles for messages that only have a plain text body.
57
+ *
58
+ * mimeHtml() applies its own copy of these whenever it converts text to HTML itself. Once a
59
+ * collapse marker is involved the conversion happens here instead, so the styling has to travel
60
+ * with it, otherwise a plain text reply would lose its quote colouring the moment it became
61
+ * collapsible. juice inlines the block and the sanitizer then drops the tag.
62
+ *
63
+ * Kept byte for byte identical to INLINE_STYLE_BLOCK in @postalsys/email-text-tools, so the two
64
+ * can be diffed when that package restyles quoted text.
65
+ */
66
+ const PLAINTEXT_STYLE_BLOCK = `<style>
67
+
68
+ body, td, th, p {
69
+ font-family: sans-serif;
70
+ font-size: 12px;
71
+ }
72
+
73
+ blockquote {
74
+ border-left-width: 2px;
75
+ border-left-style: solid;
76
+
77
+ border-left-color: darkblue;
78
+ color: darkblue;
79
+
80
+ margin: 1rem 0;
81
+ padding-left: 1rem;
82
+ }
83
+
84
+ blockquote blockquote{
85
+ border-left-color: royalblue;
86
+ color: royalblue;
87
+ }
88
+
89
+ blockquote blockquote blockquote{
90
+ border-left-color: dodgerblue;
91
+ color: dodgerblue;
92
+ }
93
+
94
+ blockquote blockquote blockquote blockquote{
95
+ border-left-color: darkblue;
96
+ color: darkblue;
97
+ }
98
+
99
+ </style>`;
100
+
101
+ // Table internals can not host a wrapper element. A <details> opened between table cells is
102
+ // foster-parented out of the table by the HTML parser, which would leave the content behind and
103
+ // move an empty control above the table, so such cut points are skipped.
104
+ const TABLE_INTERNAL_TAG = /^<(?:table|thead|tbody|tfoot|tr|td|th|col|colgroup|caption)[\s/>]/i;
105
+
106
+ // Longest tag name the check above can match, plus the angle bracket and the delimiter.
107
+ const TABLE_INTERNAL_TAG_MAX = 12;
108
+
109
+ // The document end tags are within a few bytes of the end of any real body, so only the tail is
110
+ // searched for them rather than lowercasing a body that can be a quarter of a megabyte.
111
+ const DOCUMENT_END_TAIL = 4096;
112
+ const DOCUMENT_END_TAG = /<\/(?:body|html)[\s>]/gi;
113
+
114
+ /**
115
+ * Formats an address object the way the extractor expects it, as signature evidence.
116
+ *
117
+ * @param {Object} [from] - Address object carrying `name` and/or `address`
118
+ * @returns {string|null} "Name <address>" style string, or null when there is nothing to format
119
+ */
120
+ function formatSender(from) {
121
+ if (!from) {
122
+ return null;
123
+ }
124
+
125
+ let name = (from.name || '').trim();
126
+ let address = (from.address || '').trim();
127
+
128
+ if (name && address) {
129
+ return `${name} <${address}>`;
130
+ }
131
+
132
+ return address || name || null;
133
+ }
134
+
135
+ /**
136
+ * Normalizes text the same way the extractor does, so the offsets it reports index this string.
137
+ *
138
+ * Mirrors canonicaliseText() in @postalsys/email-content: BOM removal, LF line endings, NUL
139
+ * removal and NFC normalization. Anything else would shift the offsets.
140
+ *
141
+ * There is no HTML counterpart on purpose. HTML offsets come from source ranges over the string
142
+ * exactly as it was handed to the extractor, so HTML must not be normalized before slicing it.
143
+ *
144
+ * @param {string} text - Decoded plain text body
145
+ * @returns {string} Canonical text
146
+ */
147
+ function canonicaliseText(text) {
148
+ let canonical = text;
149
+
150
+ if (canonical.charCodeAt(0) === 0xfeff) {
151
+ canonical = canonical.slice(1);
152
+ }
153
+
154
+ canonical = canonical.replace(/\r\n?/g, '\n').replace(/\0/g, '');
155
+
156
+ try {
157
+ canonical = canonical.normalize('NFC');
158
+ } catch (_err) {
159
+ // Extremely long or malformed input can defeat NFC. Unnormalized text still slices.
160
+ }
161
+
162
+ return canonical;
163
+ }
164
+
165
+ /**
166
+ * Finds the offset where the quoted tail of a message starts.
167
+ *
168
+ * Both bodies are handed to the extractor even though only one of them can be spliced. The one it
169
+ * does not pick is what tells it that the other is a stub or failed to parse, and that decision is
170
+ * what the caller reads to know whether folding is safe at all.
171
+ *
172
+ * @param {Object} content - Message content passed to the extractor
173
+ * @returns {Promise<{representation: string, offset: number}|null>} Cut point, or null when the
174
+ * message has no tail worth folding
175
+ */
176
+ async function findCollapseCut(content) {
177
+ let result = await analyze(content);
178
+
179
+ let representation = result.primaryRepresentation;
180
+ if (representation !== 'html' && representation !== 'text') {
181
+ return null;
182
+ }
183
+
184
+ // Hidden segments are held back from `segments`, so both lists are needed to see the body in
185
+ // document order. Only the representation that drove the classification can be spliced.
186
+ let segments = result.segments
187
+ .concat(result.hiddenSegments)
188
+ .filter(segment => segment.source.kind === 'mime-part' && segment.source.representation === representation)
189
+ .sort((a, b) => a.source.start - b.source.start);
190
+
191
+ let cutIndex = segments.length;
192
+ let collapsedChars = 0;
193
+ let seenContent = false;
194
+
195
+ while (cutIndex > 0) {
196
+ let segment = segments[cutIndex - 1];
197
+ // `visibility` is the extractor's confidence gate. A quote it left visible is one it was
198
+ // not sure about, and folding it anyway would override the one judgement it publishes.
199
+ if (!COLLAPSIBLE_TYPES.has(segment.type) || segment.visibility === 'show') {
200
+ break;
201
+ }
202
+ collapsedChars += segment.text.trim().length;
203
+ cutIndex--;
204
+ }
205
+
206
+ if (!cutIndex || cutIndex === segments.length || collapsedChars < MIN_COLLAPSE_CHARS) {
207
+ // Nothing to fold, nothing left over once it is folded, or a tail too short to be worth a
208
+ // control. Folding a message into nothing but a button is worse than showing it.
209
+ return null;
210
+ }
211
+
212
+ for (let index = 0; index < cutIndex && !seenContent; index++) {
213
+ seenContent = !!segments[index].text.trim();
214
+ }
215
+
216
+ return seenContent ? { representation, offset: segments[cutIndex].source.start } : null;
217
+ }
218
+
219
+ /**
220
+ * Locates the next element start at or after an offset, stepping over comments.
221
+ *
222
+ * The offset reported by the extractor sits on the boundary between two blocks, which may still
223
+ * have closing tags of the preceding content in front of it. Opening the marker on the next
224
+ * element start keeps it out of the middle of markup.
225
+ *
226
+ * @returns {number} Offset of the element start, or -1 when there is none
227
+ */
228
+ function nextElementStart(html, from) {
229
+ let pos = from;
230
+
231
+ while (pos < html.length) {
232
+ let next = html.indexOf('<', pos);
233
+ if (next < 0) {
234
+ return -1;
235
+ }
236
+
237
+ if (html.startsWith('<!--', next)) {
238
+ let commentEnd = html.indexOf('-->', next + 4);
239
+ if (commentEnd < 0) {
240
+ return -1;
241
+ }
242
+ pos = commentEnd + 3;
243
+ continue;
244
+ }
245
+
246
+ if (/^<[a-z]/i.test(html.slice(next, next + 2))) {
247
+ return next;
248
+ }
249
+
250
+ pos = next + 1;
251
+ }
252
+
253
+ return -1;
254
+ }
255
+
256
+ /**
257
+ * Offset the marker has to be closed at, so it does not wrap the document epilogue.
258
+ *
259
+ * @returns {number} Offset to close at
260
+ */
261
+ function collapseCloseOffset(html) {
262
+ let tailStart = Math.max(html.length - DOCUMENT_END_TAIL, 0);
263
+ let tail = html.slice(tailStart);
264
+
265
+ DOCUMENT_END_TAG.lastIndex = 0;
266
+ let match = DOCUMENT_END_TAG.exec(tail);
267
+
268
+ return match ? tailStart + match.index : html.length;
269
+ }
270
+
271
+ /**
272
+ * Splices the collapse marker into an HTML body.
273
+ *
274
+ * The marker is opened at the cut point and closed at the end of the body. Tags stay balanced
275
+ * because exactly one element is opened and one closed, so an unclosed ancestor between the two
276
+ * ends the marker early - the fold then covers less of the tail than it could, which is a worse
277
+ * fold rather than broken markup.
278
+ *
279
+ * @returns {string|null} HTML carrying the marker, or null when there is no safe place for it
280
+ */
281
+ function collapseHtml(html, offset) {
282
+ if (offset <= 0 || offset >= html.length) {
283
+ return null;
284
+ }
285
+
286
+ let start = nextElementStart(html, offset);
287
+ if (start < 0 || TABLE_INTERNAL_TAG.test(html.slice(start, start + TABLE_INTERNAL_TAG_MAX))) {
288
+ return null;
289
+ }
290
+
291
+ let closeOffset = collapseCloseOffset(html);
292
+ if (closeOffset <= start) {
293
+ return null;
294
+ }
295
+
296
+ return html.slice(0, start) + COLLAPSE_OPEN_MARKUP + html.slice(start, closeOffset) + COLLAPSE_CLOSE_MARKUP + html.slice(closeOffset);
297
+ }
298
+
299
+ /**
300
+ * Builds HTML with a collapse marker from a plain text body.
301
+ *
302
+ * Messages without an HTML part are analysed as text - the HTML mimeHtml() would generate from
303
+ * them carries no quote structure the extractor could read, only the structure it inferred from
304
+ * the text in the first place. The two halves are therefore converted separately here.
305
+ *
306
+ * @returns {string|null} Generated HTML, or null when the cut point is out of range
307
+ */
308
+ function collapseText(text, offset) {
309
+ if (offset <= 0 || offset >= text.length) {
310
+ return null;
311
+ }
312
+
313
+ return PLAINTEXT_STYLE_BLOCK + textToHtml(text.slice(0, offset)) + COLLAPSE_OPEN_MARKUP + textToHtml(text.slice(offset)) + COLLAPSE_CLOSE_MARKUP;
314
+ }
315
+
316
+ /**
317
+ * Folds the quoted thread of a message into a single collapsible block.
318
+ *
319
+ * @param {Object} messageData - Message object
320
+ * @param {Object} messageData.text - Decoded bodies, as `text.html` and `text.plain`
321
+ * @param {string} [messageData.subject] - Subject line
322
+ * @param {Object} [messageData.from] - Sender address
323
+ * @param {string} [messageData.inReplyTo] - In-Reply-To header value
324
+ * @returns {Promise<{html: string}|null>} Replacement content for mimeHtml(), or null when the
325
+ * message has no tail worth folding
326
+ */
327
+ async function collapseThreadHistory(messageData) {
328
+ let bodies = messageData.text || {};
329
+ let html = (bodies.html || '').toString();
330
+ let text = (bodies.plain || '').toString();
331
+
332
+ if (html.length + text.length > MAX_ANALYZE_CHARS) {
333
+ return null;
334
+ }
335
+
336
+ html = html.trim() ? html : '';
337
+ text = text.trim() ? text : '';
338
+
339
+ if (!html && !text) {
340
+ return null;
341
+ }
342
+
343
+ let cut = await findCollapseCut({
344
+ html: html || null,
345
+ text: text || null,
346
+ subject: messageData.subject || null,
347
+ from: formatSender(messageData.from),
348
+ inReplyTo: messageData.inReplyTo || null
349
+ });
350
+
351
+ if (!cut) {
352
+ return null;
353
+ }
354
+
355
+ let collapsed;
356
+ if (cut.representation === 'html') {
357
+ collapsed = collapseHtml(html, cut.offset);
358
+ } else if (html) {
359
+ // The extractor can pick the text representation over an HTML one it could not read - a
360
+ // stub HTML part, or markup that failed to parse. Generating the body from the text there
361
+ // would fold the thread at the cost of throwing the sender's real HTML away, which is a
362
+ // far bigger change than the fold is worth, so those messages are rendered whole.
363
+ return null;
364
+ } else {
365
+ // Text offsets index the extractor's canonical form, so the same normalization has to be
366
+ // applied before slicing. It is done here rather than up front because the HTML path,
367
+ // which is the common one, has no use for it.
368
+ collapsed = collapseText(canonicaliseText(text), cut.offset);
369
+ }
370
+
371
+ return collapsed ? { html: collapsed } : null;
372
+ }
373
+
374
+ /**
375
+ * Converts the bodies of a message object into sanitized, web-safe HTML.
376
+ *
377
+ * @param {Object} messageData - Message object, as described on collapseThreadHistory()
378
+ * @returns {Promise<string>} Sanitized HTML
379
+ */
380
+ async function messageWebSafeHtml(messageData) {
381
+ let source = { html: messageData.text.html, text: messageData.text.plain };
382
+
383
+ if (!DISABLE_THREAD_COLLAPSE) {
384
+ try {
385
+ let collapsed = await collapseThreadHistory(messageData);
386
+ if (collapsed) {
387
+ source = collapsed;
388
+ }
389
+ } catch (err) {
390
+ // A message that can not be folded is still a message. Render all of it.
391
+ logger.error({ msg: 'Failed to mark quoted thread content', err });
392
+ }
393
+ }
394
+
395
+ return mimeHtml(source);
396
+ }
397
+
398
+ module.exports = {
399
+ messageWebSafeHtml,
400
+ collapseThreadHistory
401
+ };
@@ -2,6 +2,23 @@
2
2
 
3
3
  const { DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('./consts');
4
4
 
5
+ /**
6
+ * Builds the error for a redirect that was deliberately not followed.
7
+ *
8
+ * Carries `statusCode` like every other non-2xx failure, because that is the field the admin UI
9
+ * webhook error block prints as "HTTP response"; without it the operator is told a redirect
10
+ * happened but not which one.
11
+ *
12
+ * @param {number} status - The 3xx status the endpoint answered with
13
+ * @returns {Error} Error tagged with code EREDIRECTNOTFOLLOWED
14
+ */
15
+ function redirectNotFollowedError(status) {
16
+ let err = new Error('Webhook endpoint returned a redirect, which is not followed. Configure the webhook to use the final URL.');
17
+ err.code = 'EREDIRECTNOTFOLLOWED';
18
+ err.statusCode = status;
19
+ return err;
20
+ }
21
+
5
22
  /**
6
23
  * Performs a single webhook HTTP delivery and always drains the response body.
7
24
  *
@@ -21,11 +38,25 @@ const { DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('./consts');
21
38
  * an optional `timeout` in milliseconds
22
39
  * @returns {Promise<number>} Resolves with the HTTP status code on success
23
40
  * @throws {Error} On a non-2xx response the error carries a `statusCode` property;
24
- * on timeout the error carries code 'ETIMEDOUT'
41
+ * on timeout the error carries code 'ETIMEDOUT'; on an unfollowed redirect both,
42
+ * see redirectNotFollowedError()
25
43
  */
26
44
  async function sendWebhookRequest(fetchImpl, url, options) {
27
- let { timeout, ...fetchOptions } = options || {};
45
+ let { timeout, validateTarget, ...fetchOptions } = options || {};
28
46
  timeout = timeout || DEFAULT_WEBHOOK_REQUEST_TIMEOUT;
47
+
48
+ if (validateTarget) {
49
+ // fetch() follows redirects on its own, which would let a permitted destination hand us a
50
+ // Location pointing at one the policy rejects. There is no hook to vet the intermediate
51
+ // hops, so redirects are surfaced to the operator instead of followed. Deliveries are
52
+ // machine-to-machine POSTs; a receiver that redirects should be reconfigured to publish
53
+ // its final URL. Setting the egress policy to `off` restores the previous behavior.
54
+ fetchOptions.redirect = 'manual';
55
+ await validateTarget(url);
56
+ }
57
+
58
+ // Armed after the target check so a slow DNS resolution is not charged against the delivery's
59
+ // own timeout budget
29
60
  fetchOptions.signal = AbortSignal.timeout(timeout);
30
61
 
31
62
  const isTimeoutError = err => err && (err.name === 'TimeoutError' || (err.cause && err.cause.name === 'TimeoutError'));
@@ -58,6 +89,13 @@ async function sendWebhookRequest(fetchImpl, url, options) {
58
89
  // ignore other drain errors
59
90
  }
60
91
 
92
+ // With redirect:'manual' undici hands back the 3xx itself (deliberately, unlike the browser
93
+ // spec's opaque redirect), which would otherwise be reported as a generic non-2xx failure
94
+ // carrying only the status. Name the actual problem instead.
95
+ if (validateTarget && res.status >= 300 && res.status < 400) {
96
+ throw redirectNotFollowedError(res.status);
97
+ }
98
+
61
99
  if (!res.ok) {
62
100
  let err = new Error(res.statusText || `Invalid response: ${res.status} ${res.statusText}`);
63
101
  err.statusCode = res.status;
package/lib/webhooks.js CHANGED
@@ -8,6 +8,7 @@ const { REDIS_PREFIX, MESSAGE_NEW_NOTIFY } = require('./consts');
8
8
  const { SubScript } = require('./sub-script');
9
9
  const settings = require('./settings');
10
10
  const { filterListPage } = require('./tools');
11
+ const { buildRetentionPolicy } = require('./queue-retention');
11
12
 
12
13
  class WebhooksHandler {
13
14
  constructor(options) {
@@ -531,10 +532,8 @@ class WebhooksHandler {
531
532
  let webhookRoutes = await this.getWebhookHandlers();
532
533
  let queueKeep = (await settings.get('queueKeep')) ?? true;
533
534
 
534
- let removePolicy = typeof queueKeep === 'number' ? { age: 24 * 3600, count: queueKeep } : queueKeep;
535
535
  let jobOpts = {
536
- removeOnComplete: removePolicy,
537
- removeOnFail: removePolicy,
536
+ ...buildRetentionPolicy(queueKeep),
538
537
  attempts: 10,
539
538
  backoff: {
540
539
  type: 'exponential',