emailengine-app 2.77.0 → 2.78.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 (94) hide show
  1. package/.github/workflows/test.yml +80 -0
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +31 -0
  4. package/bin/emailengine.js +1 -1
  5. package/data/google-crawlers.json +1 -1
  6. package/encrypt.js +1 -1
  7. package/lib/account/expected-identity.js +88 -0
  8. package/lib/account.js +75 -26
  9. package/lib/api-reference/format.js +14 -0
  10. package/lib/api-reference/index.js +24 -7
  11. package/lib/api-reference/model.js +4 -2
  12. package/lib/api-routes/account-routes.js +19 -2
  13. package/lib/api-routes/behavior-notes.js +3 -0
  14. package/lib/append-list.js +3 -14
  15. package/lib/arf-detect.js +23 -1
  16. package/lib/autodetect-imap-settings.js +40 -16
  17. package/lib/base32.js +30 -0
  18. package/lib/bounce-detect.js +182 -62
  19. package/lib/egress-filter.js +89 -8
  20. package/lib/email-client/base-client.js +8 -72
  21. package/lib/email-client/gmail-client.js +3 -3
  22. package/lib/email-client/imap/listing-diff.js +3 -3
  23. package/lib/email-client/imap/mailbox.js +5 -69
  24. package/lib/email-client/imap-client.js +3 -2
  25. package/lib/email-client/message-builder.js +13 -13
  26. package/lib/email-client/outlook-client.js +1 -1
  27. package/lib/export.js +1 -1
  28. package/lib/gateway.js +1 -1
  29. package/lib/get-raw-email.js +1 -1
  30. package/lib/imapproxy/imap-core/lib/imap-connection.js +2 -2
  31. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  32. package/lib/imapproxy/imap-server.js +13 -3
  33. package/lib/license-beacon.js +1 -1
  34. package/lib/llm-pre-process.js +1 -1
  35. package/lib/msgpack.js +62 -0
  36. package/lib/oauth/decode-jwt-payload.js +39 -0
  37. package/lib/oauth/outlook-identity.js +61 -0
  38. package/lib/oauth/retry-setup.js +38 -0
  39. package/lib/oauth2-apps.js +1 -1
  40. package/lib/outbox.js +66 -3
  41. package/lib/pre-process.js +1 -1
  42. package/lib/read-env-value.js +37 -0
  43. package/lib/schemas.js +12 -0
  44. package/lib/templates.js +1 -1
  45. package/lib/tokens.js +1 -1
  46. package/lib/tools.js +117 -48
  47. package/lib/totp.js +67 -0
  48. package/lib/ui-routes/account-routes.js +91 -15
  49. package/lib/ui-routes/admin-config-routes.js +2 -7
  50. package/lib/ui-routes/auth-routes.js +6 -24
  51. package/lib/ui-routes/reference-routes.js +8 -5
  52. package/lib/ui-routes/route-helpers.js +28 -0
  53. package/lib/utils/is-email.js +34 -0
  54. package/lib/utils/to-camel-case.js +17 -0
  55. package/lib/webhook-egress.js +37 -0
  56. package/lib/webhooks.js +1 -1
  57. package/package.json +22 -24
  58. package/sbom.json +1 -0
  59. package/server.js +1 -1
  60. package/static/css/flyonui.css +1 -1
  61. package/static/css/public.css +3 -0
  62. package/static/css/src/app.tailwind.css +23 -0
  63. package/static/js/app.js +69 -0
  64. package/static/js/reference.js +286 -1
  65. package/static/licenses.html +656 -1558
  66. package/translations/README.md +64 -0
  67. package/translations/de.mo +0 -0
  68. package/translations/de.po +164 -120
  69. package/translations/en.po +200 -161
  70. package/translations/et.mo +0 -0
  71. package/translations/et.po +163 -120
  72. package/translations/fr.mo +0 -0
  73. package/translations/fr.po +163 -120
  74. package/translations/ja.mo +0 -0
  75. package/translations/ja.po +163 -120
  76. package/translations/messages.pot +76 -46
  77. package/translations/nl.mo +0 -0
  78. package/translations/nl.po +164 -120
  79. package/translations/pl.mo +0 -0
  80. package/translations/pl.po +163 -120
  81. package/views/account-identity-error.hbs +34 -0
  82. package/views/accounts/edit.hbs +1 -0
  83. package/views/accounts/register/imap.hbs +12 -2
  84. package/views/layout/app.hbs +29 -5
  85. package/views/oauth-scope-error.hbs +1 -1
  86. package/views/partials/reference/nav.hbs +36 -9
  87. package/views/partials/reference/operation.hbs +1 -1
  88. package/views/partials/reference/schema-node.hbs +1 -1
  89. package/views/partials/reference/token-alert.hbs +35 -10
  90. package/views/reference/index.hbs +1 -1
  91. package/workers/api.js +157 -87
  92. package/workers/imap.js +1 -1
  93. package/workers/submit.js +1 -1
  94. package/workers/webhooks.js +2 -13
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const msgpack = require('msgpack5')();
3
+ const msgpack = require('./msgpack');
4
4
 
5
5
  /**
6
6
  * Pushes an object to the end of a list where that list is stored in a hash field
@@ -43,19 +43,8 @@ async function list(redis, list, key) {
43
43
  return [];
44
44
  }
45
45
 
46
- return new Promise((resolve, reject) => {
47
- let decoder = msgpack.decoder({});
48
- let list = [];
49
- decoder.on('readable', () => {
50
- let data;
51
- while ((data = decoder.read()) !== null) {
52
- list.push(data);
53
- }
54
- });
55
- decoder.on('end', () => resolve(list));
56
- decoder.on('error', err => reject(err));
57
- decoder.end(contents);
58
- });
46
+ // the hash field holds a byte stream of concatenated msgpack values
47
+ return msgpack.decodeMulti(contents);
59
48
  }
60
49
 
61
50
  /**
package/lib/arf-detect.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  const libmime = require('libmime');
4
4
  const addressparser = require('nodemailer/lib/addressparser');
5
+ const { toCamelCase } = require('./utils/to-camel-case');
5
6
 
6
7
  const ARF_SINGLE = [
7
8
  'feedback-type',
@@ -199,4 +200,25 @@ const arfDetect = async messageInfo => {
199
200
  return report;
200
201
  };
201
202
 
202
- module.exports = { arfDetect };
203
+ /**
204
+ * Turns an ARF report into the camelCased shape published in a complaint notification
205
+ *
206
+ * @param {Object} report - Report from arfDetect()
207
+ * @returns {Object} The arf and headers sections with camelCased keys
208
+ */
209
+ function camelCaseComplaint(report) {
210
+ let complaint = {};
211
+
212
+ for (let subKey of ['arf', 'headers']) {
213
+ for (let key of Object.keys(report[subKey])) {
214
+ if (!complaint[subKey]) {
215
+ complaint[subKey] = {};
216
+ }
217
+ complaint[subKey][toCamelCase(key)] = report[subKey][key];
218
+ }
219
+ }
220
+
221
+ return complaint;
222
+ }
223
+
224
+ module.exports = { arfDetect, camelCaseComplaint };
@@ -2,23 +2,42 @@
2
2
 
3
3
  const punycode = require('punycode.js');
4
4
  const dns = require('dns').promises;
5
- const { parseString: parseXmlCb } = require('xml2js');
6
- const util = require('util');
5
+ const { XMLParser, XMLValidator } = require('fast-xml-parser');
7
6
  const packageData = require('../package.json');
8
- const parseXml = util.promisify((xml, cb) => {
9
- parseXmlCb(
10
- xml,
11
- {
12
- explicitArray: true,
13
- normalize: true,
14
- normalizeTags: true,
15
- xmlMode: true,
16
- strict: true
17
- },
18
- cb
19
- );
7
+
8
+ // Configured to produce the same tree shape as the xml2js options this module was written
9
+ // against: lowercased tag names, child elements always as arrays (but not the root), attributes
10
+ // grouped under `$`, text of an attributed element under `_`, and entity references decoded.
11
+ // The `isArray` jpath check is what keeps the root an object: only the root's jpath has no dot.
12
+ const xmlParser = new XMLParser({
13
+ ignoreDeclaration: true,
14
+ ignoreAttributes: false,
15
+ attributesGroupName: '$',
16
+ attributeNamePrefix: '',
17
+ textNodeName: '_',
18
+ isArray: (name, jpath, isLeafNode, isAttribute) => !isAttribute && jpath.includes('.'),
19
+ transformTagName: tag => tag.toLowerCase(),
20
+ parseTagValue: false,
21
+ trimValues: true,
22
+ htmlEntities: true
20
23
  });
21
24
 
25
+ function parseXml(text) {
26
+ if (!text || !text.trim()) {
27
+ // xml2js resolved an empty document to null instead of erroring, callers check for it
28
+ return null;
29
+ }
30
+
31
+ const validation = XMLValidator.validate(text);
32
+ if (validation !== true) {
33
+ let err = new Error(`Failed to parse XML: ${validation.err.msg}`);
34
+ err.code = 'EXmlParseError';
35
+ throw err;
36
+ }
37
+
38
+ return xmlParser.parse(text);
39
+ }
40
+
22
41
  const { fetch: fetchCmd } = require('undici');
23
42
  const { httpAgent } = require('./tools');
24
43
 
@@ -178,7 +197,7 @@ async function processAutoconfigFile(email, domain, text, source) {
178
197
  } catch (err) {
179
198
  //ignore
180
199
  }
181
- let json = await parseXml(text);
200
+ let json = parseXml(text);
182
201
 
183
202
  let emailProviders = json && json.clientconfig && Array.isArray(json.clientconfig.emailprovider) ? json.clientconfig.emailprovider : [];
184
203
  let incomingServer = emailProviders
@@ -697,7 +716,11 @@ async function resolveUsingAutodiscovery(email, domain, source) {
697
716
 
698
717
  let text = await res.text();
699
718
 
700
- let json = await parseXml(text);
719
+ return await processAutodiscoverResponse(text, source);
720
+ }
721
+
722
+ async function processAutodiscoverResponse(text, source) {
723
+ let json = parseXml(text);
701
724
 
702
725
  let imap = false;
703
726
  let smtp = false;
@@ -829,6 +852,7 @@ module.exports.autodetectImapSettings = autodetectImapSettings;
829
852
  // Exposed for unit testing of the pure parsing/matching helpers. These have no
830
853
  // network side effects, so they can be exercised directly without mocking DNS or HTTP.
831
854
  module.exports.processAutoconfigFile = processAutoconfigFile;
855
+ module.exports.processAutodiscoverResponse = processAutodiscoverResponse;
832
856
  module.exports.getAppPassword = getAppPassword;
833
857
  module.exports.resolveAppPassword = resolveAppPassword;
834
858
  module.exports.escapeXml = escapeXml;
package/lib/base32.js ADDED
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+
3
+ // RFC 4648 base32 without padding. Replaces the unmaintained base32.js package; output is
4
+ // byte-identical to its encoder for the two uses in this codebase (otpauth: URL secrets and
5
+ // IMAP proxy connection ids), which never need padding or decoding.
6
+
7
+ const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
8
+
9
+ function base32Encode(buf) {
10
+ let bits = 0;
11
+ let value = 0;
12
+ let output = '';
13
+
14
+ for (let octet of buf) {
15
+ value = (value << 8) | octet;
16
+ bits += 8;
17
+ while (bits >= 5) {
18
+ output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
19
+ bits -= 5;
20
+ }
21
+ }
22
+
23
+ if (bits > 0) {
24
+ output += BASE32_ALPHABET[(value << (5 - bits)) & 31];
25
+ }
26
+
27
+ return output;
28
+ }
29
+
30
+ module.exports = { base32Encode };
@@ -24,6 +24,136 @@
24
24
 
25
25
  const libmime = require('libmime');
26
26
  const simpleParser = require('mailparser').simpleParser;
27
+ const { toCamelCase } = require('./utils/to-camel-case');
28
+
29
+ /**
30
+ * Splits the address type off a DSN value, eg. "rfc822; user@example.com"
31
+ *
32
+ * @param {string} value - Raw field value
33
+ * @returns {Object} { label, value }, with label absent when the value carries no type
34
+ */
35
+ function splitAddressType(value) {
36
+ let splitPos = value.indexOf(';');
37
+ if (splitPos < 0) {
38
+ return { value: value.trim() };
39
+ }
40
+ return { label: value.substring(0, splitPos).trim(), value: value.substring(splitPos + 1).trim() };
41
+ }
42
+
43
+ /**
44
+ * Splits the body of a message/delivery-status part into its header blocks
45
+ *
46
+ * A DSN body is not a single header block. RFC 3464 splits it into a per-message block and a
47
+ * separate per-recipient block for every reported address, with an empty line between them.
48
+ * libmime.decodeHeaders() stops at the first empty line, as that is where a header block ends,
49
+ * so each block is decoded on its own.
50
+ *
51
+ * @param {string|Buffer} content - Raw message/delivery-status body
52
+ * @returns {Object[]} One header entries object per non-empty block, in source order
53
+ */
54
+ function decodeDeliveryStatusBlocks(content) {
55
+ return (
56
+ (content || '')
57
+ .toString()
58
+ .replace(/\r\n|\r/g, '\n')
59
+ .split(/\n{2,}/)
60
+ .map(block => libmime.decodeHeaders(block))
61
+ // A block of nothing but a continuation line decodes to a single empty key, which is
62
+ // not a header and would otherwise be merged into the result
63
+ .filter(entries => Object.keys(entries).some(key => key))
64
+ );
65
+ }
66
+
67
+ /**
68
+ * Tells whether a decoded DSN block describes a recipient rather than the message
69
+ *
70
+ * @param {Object} entries - Header entries of one block
71
+ * @returns {Boolean} True for a per-recipient block
72
+ */
73
+ function isRecipientBlock(entries) {
74
+ return !!(entries['final-recipient'] || entries['original-recipient']);
75
+ }
76
+
77
+ /**
78
+ * Decodes a message/delivery-status body into the header entries of a single reported recipient
79
+ *
80
+ * A DSN may report on several recipients, but everything downstream of this describes one
81
+ * delivery. Merging every block together would mix them: a recipient that failed without a
82
+ * Diagnostic-Code would be paired with the diagnostic code of the next recipient. So the
83
+ * per-message fields are merged with exactly one per-recipient block, and a body that reports
84
+ * no recipient at all is merged whole.
85
+ *
86
+ * @param {string|Buffer} content - Raw message/delivery-status body
87
+ * @returns {Object} Header keys mapped to arrays of values, in source order
88
+ */
89
+ function decodeDeliveryStatus(content) {
90
+ let blocks = decodeDeliveryStatusBlocks(content);
91
+
92
+ // The first reported recipient is the one described, the same one the bounce path has
93
+ // always read off the merged bag
94
+ let reported = blocks.find(isRecipientBlock);
95
+
96
+ // Prototype-less, the keys come straight from the message: with a plain object a
97
+ // "__proto__:" header would make entries[key] the inherited prototype rather than an array
98
+ let entries = Object.create(null);
99
+ for (let block of blocks) {
100
+ if (block !== reported && isRecipientBlock(block)) {
101
+ continue;
102
+ }
103
+
104
+ for (let key of Object.keys(block)) {
105
+ entries[key] = (entries[key] || []).concat(block[key]);
106
+ }
107
+ }
108
+
109
+ return entries;
110
+ }
111
+
112
+ /**
113
+ * Builds the camelCased delivery report exposed for a message/delivery-status part
114
+ *
115
+ * Where decodeDeliveryStatus() returns the raw header entries, this turns them into the shape
116
+ * published on messageData.deliveryReport: keys camelCased, Arrival-Date normalized to an ISO
117
+ * timestamp, and a field that carries an address type reported as { label, value } - so
118
+ * "Final-Recipient: rfc822; user@example.com" becomes
119
+ * finalRecipient: { label: 'rfc822', value: 'user@example.com' }.
120
+ *
121
+ * @param {string|Buffer} content - Raw message/delivery-status body
122
+ * @returns {Object} Delivery report keyed by camelCased field name
123
+ */
124
+ function parseDeliveryReport(content) {
125
+ let entries = decodeDeliveryStatus(content);
126
+ let structured = {};
127
+
128
+ for (let key of Object.keys(entries)) {
129
+ // The field names come from the message. "__proto__" names no DSN field, while assigning
130
+ // it would hand the value to the Object.prototype setter and swap the report's prototype,
131
+ // and defining it as an own property instead leaves a key msgpack refuses to decode
132
+ if (!key || key === '__proto__') {
133
+ continue;
134
+ }
135
+
136
+ let displayKey = toCamelCase(key);
137
+ let value = entries[key].at(-1);
138
+
139
+ if (typeof value !== 'string') {
140
+ structured[displayKey] = value;
141
+ continue;
142
+ }
143
+
144
+ // Only a leading token counts as an address type, a semicolon inside prose does not
145
+ if (/^[^\s;]+;/.test(value)) {
146
+ structured[displayKey] = splitAddressType(value);
147
+ } else if (key === 'arrival-date') {
148
+ let date = new Date(value.trim());
149
+ structured[displayKey] = date.toString() !== 'Invalid Date' ? date.toISOString() : value;
150
+ } else {
151
+ structured[displayKey] = value.trim();
152
+ }
153
+ }
154
+
155
+ return structured;
156
+ }
27
157
 
28
158
  /**
29
159
  * Parses a message/delivery-status attachment to extract bounce information
@@ -41,38 +171,21 @@ const simpleParser = require('mailparser').simpleParser;
41
171
  * @returns {string} [returns.messageId] - The original message ID
42
172
  */
43
173
  function parseDeliveryStatus(content) {
44
- // Ensure content is a trimmed string
45
- content = (content || '').toString().trim();
46
-
47
174
  // Parse RFC 3464 formatted headers
48
- let entries = libmime.decodeHeaders(content);
175
+ let entries = decodeDeliveryStatus(content);
49
176
 
50
177
  let result = {};
51
178
 
52
179
  // Extract recipient address from Final-Recipient header (preferred)
53
180
  // Format: "Final-Recipient: rfc822; user@example.com"
54
181
  if (entries['final-recipient'] && entries['final-recipient'].length) {
55
- let rcpt = entries['final-recipient'][0];
56
- let splitPos = rcpt.indexOf(';');
57
- if (splitPos >= 0) {
58
- // Extract address after the address-type (usually 'rfc822;')
59
- result.recipient = rcpt.substr(splitPos + 1).trim();
60
- } else {
61
- // No address-type specified, use the whole value
62
- result.recipient = rcpt.trim();
63
- }
182
+ result.recipient = splitAddressType(entries['final-recipient'][0]).value;
64
183
  }
65
184
 
66
185
  // Fallback to Original-Recipient if Final-Recipient not found
67
186
  // This might contain the intended recipient before aliasing/forwarding
68
187
  if (!result.recipient && entries['original-recipient'] && entries['original-recipient'].length) {
69
- let rcpt = entries['original-recipient'][0];
70
- let splitPos = rcpt.indexOf(';');
71
- if (splitPos >= 0) {
72
- result.recipient = rcpt.substr(splitPos + 1).trim();
73
- } else {
74
- result.recipient = rcpt.trim();
75
- }
188
+ result.recipient = splitAddressType(entries['original-recipient'][0]).value;
76
189
  }
77
190
 
78
191
  // Extract delivery action (e.g., 'failed', 'delayed', 'delivered', 'relayed', 'expanded')
@@ -83,18 +196,8 @@ function parseDeliveryStatus(content) {
83
196
  // Parse Diagnostic-Code header for detailed error information
84
197
  // Format: "Diagnostic-Code: smtp; 550 5.1.1 User unknown"
85
198
  if (entries['diagnostic-code'] && entries['diagnostic-code'].length) {
86
- let code = entries['diagnostic-code'][0];
87
- let splitPos = code.indexOf(';');
88
- let respSource, respMessage;
89
-
90
- if (splitPos >= 0) {
91
- // Extract diagnostic-type (e.g., 'smtp')
92
- respSource = code.substr(0, splitPos).trim();
93
- respMessage = code.substr(splitPos + 1).trim();
94
- } else {
95
- // No diagnostic-type specified
96
- respMessage = code.trim();
97
- }
199
+ // label is the diagnostic type, eg. 'smtp'
200
+ let { label: respSource, value: respMessage } = splitAddressType(entries['diagnostic-code'][0]);
98
201
 
99
202
  result.response = {};
100
203
  if (respSource) {
@@ -116,31 +219,13 @@ function parseDeliveryStatus(content) {
116
219
  // Extract Remote-MTA (the MTA that reported the failure)
117
220
  // Format: "Remote-MTA: dns; mx.example.com"
118
221
  if (entries['remote-mta'] && entries['remote-mta'].length) {
119
- let mta = entries['remote-mta'][0];
120
- let splitPos = mta.indexOf(';');
121
- if (splitPos >= 0) {
122
- result.mta = mta
123
- .substr(splitPos + 1)
124
- .trim()
125
- .toLowerCase();
126
- } else {
127
- result.mta = mta.trim().toLowerCase();
128
- }
222
+ result.mta = splitAddressType(entries['remote-mta'][0]).value.toLowerCase();
129
223
  }
130
224
 
131
225
  // Fallback to Reporting-MTA if Remote-MTA not found
132
226
  // This is the MTA generating the bounce report
133
227
  if (!result.mta && entries['reporting-mta'] && entries['reporting-mta'].length) {
134
- let mta = entries['reporting-mta'][0];
135
- let splitPos = mta.indexOf(';');
136
- if (splitPos >= 0) {
137
- result.mta = mta
138
- .substr(splitPos + 1)
139
- .trim()
140
- .toLowerCase();
141
- } else {
142
- result.mta = mta.trim().toLowerCase();
143
- }
228
+ result.mta = splitAddressType(entries['reporting-mta'][0]).value.toLowerCase();
144
229
  }
145
230
 
146
231
  // Postfix-specific headers
@@ -157,16 +242,16 @@ function parseDeliveryStatus(content) {
157
242
  }
158
243
 
159
244
  /**
160
- * Parses text/rfc822-headers attachment to extract message headers
245
+ * Extracts the bounced message's identity from its already decoded headers
246
+ *
247
+ * Takes decoded entries rather than the raw attachment, as every caller has just decoded the
248
+ * same content, most of them to keep as the reported message headers.
161
249
  *
162
- * @param {string|Buffer} content - The headers content
250
+ * @param {Object} entries - Header entries from libmime.decodeHeaders()
163
251
  * @returns {Object} Parsed header information
164
252
  * @returns {string} [returns.messageId] - The Message-ID header value
165
253
  */
166
- function parseDeliveryHeaders(content) {
167
- content = (content || '').toString().trim();
168
- let entries = libmime.decodeHeaders(content);
169
-
254
+ function parseDeliveryHeaders(entries) {
170
255
  let result = {};
171
256
 
172
257
  // Extract Message-ID from the original message headers
@@ -275,7 +360,7 @@ async function bounceDetect(sourceStream) {
275
360
  // Process RFC822 headers attachment (contains headers of the original message)
276
361
  if (messageHeaders) {
277
362
  parsedMessageHeaders = libmime.decodeHeaders((messageHeaders.content || '').toString().trim());
278
- result = Object.assign(result, parseDeliveryHeaders(messageHeaders.content) || {});
363
+ result = Object.assign(result, parseDeliveryHeaders(parsedMessageHeaders));
279
364
  }
280
365
 
281
366
  // Process complete original message attachment
@@ -317,7 +402,8 @@ async function bounceDetect(sourceStream) {
317
402
  if (!messageHeaders) {
318
403
  messageHeaders = originalAttachments.find(attachment => attachment.contentType?.toLowerCase() === 'text/rfc822-headers');
319
404
  if (messageHeaders) {
320
- result = Object.assign(result, parseDeliveryHeaders(messageHeaders.content) || {});
405
+ let headerEntries = libmime.decodeHeaders((messageHeaders.content || '').toString().trim());
406
+ result = Object.assign(result, parseDeliveryHeaders(headerEntries));
321
407
  }
322
408
  }
323
409
  }
@@ -376,7 +462,7 @@ async function bounceDetect(sourceStream) {
376
462
  let headers = libmime.decodeHeaders(headerContent);
377
463
  if (headers && headers['message-id']) {
378
464
  parsedMessageHeaders = headers;
379
- result = Object.assign(result, parseDeliveryHeaders(headerContent) || {});
465
+ result = Object.assign(result, parseDeliveryHeaders(headers));
380
466
  }
381
467
  }
382
468
  }
@@ -838,4 +924,38 @@ async function bounceDetect(sourceStream) {
838
924
  }
839
925
 
840
926
  // Export the main function
841
- module.exports = { bounceDetect };
927
+ /**
928
+ * Sets messageInfo.deliveryReport when a parsed DSN reports a delivery or a delay
929
+ *
930
+ * A bounce is handled by bounceDetect() instead, so only these two actions are reported here.
931
+ * Both the IMAP and the API paths call this with their own already parsed message.
932
+ *
933
+ * @param {Object} parsed - Message parsed with { keepDeliveryStatus: true }
934
+ * @param {Object} messageInfo - Message object to annotate
935
+ * @param {Object} logger - Logger to report a detected report on
936
+ * @returns {Boolean} True if a delivery report was set
937
+ */
938
+ function applyDeliveryReport(parsed, messageInfo, logger) {
939
+ let deliveryStatus = parsed.attachments.find(attachment => attachment.contentType === 'message/delivery-status');
940
+ if (!deliveryStatus) {
941
+ return false;
942
+ }
943
+
944
+ let structured = parseDeliveryReport(deliveryStatus.content);
945
+ if (!/^delivered|^delayed/i.test(structured.action)) {
946
+ return false;
947
+ }
948
+
949
+ logger.debug({
950
+ msg: 'Detected delivery report',
951
+ id: messageInfo.id,
952
+ uid: messageInfo.uid,
953
+ messageId: messageInfo.messageId,
954
+ report: structured
955
+ });
956
+
957
+ messageInfo.deliveryReport = structured;
958
+ return true;
959
+ }
960
+
961
+ module.exports = { bounceDetect, decodeDeliveryStatus, parseDeliveryReport, applyDeliveryReport };
@@ -9,6 +9,11 @@ const ipaddr = require('ipaddr.js');
9
9
  // blocking private ranges outright would break ordinary deployments - the default therefore only
10
10
  // blocks the link-local range, which is where every cloud provider parks its instance metadata
11
11
  // service and which no real webhook receiver lives on.
12
+ //
13
+ // Scope: this is a guardrail against misconfiguration and mistakes, not a boundary against a
14
+ // hostile operator. Anyone who can set a webhook target can generally also author fn/map scripts,
15
+ // which lib/sub-script.js runs with full server privileges and hands an unfiltered fetch. Do not
16
+ // treat the policy as tenant isolation.
12
17
  const POLICY_OFF = 'off';
13
18
  const POLICY_LINK_LOCAL = 'link-local';
14
19
  const POLICY_PRIVATE = 'private';
@@ -108,9 +113,10 @@ const policyBlockedError = reason => blockedError(`${reason}. ${POLICY_HINT}`);
108
113
  // and the notify worker runs at concurrency 1 by default, so that cost is fully serialized ahead
109
114
  // of each POST. Caching the verdict rather than the addresses keeps entries tiny.
110
115
  //
111
- // This gives up nothing: undici resolves the name again independently when it connects, so the
112
- // check is inherently time-of-check/time-of-use racy and a short TTL introduces no hole that was
113
- // not already there. Distinct webhook targets are few, so the hit rate is effectively total.
116
+ // A stale verdict opens no hole. This pre-check exists to refuse a bad destination early and with
117
+ // an error worth reading; the binding decision is made by createEgressLookup() at connect time,
118
+ // against the very addresses the socket is opened to. Distinct webhook targets are few, so the hit
119
+ // rate is effectively total.
114
120
  const VERDICT_TTL = 60 * 1000;
115
121
  const VERDICT_CACHE_LIMIT = 1000;
116
122
  const verdictCache = new Map();
@@ -138,12 +144,36 @@ function cacheVerdict(key, blockedBy) {
138
144
  verdictCache.set(key, { blockedBy, expires: Date.now() + VERDICT_TTL });
139
145
  }
140
146
 
147
+ /**
148
+ * Finds the first address in a resolver answer that the policy refuses.
149
+ *
150
+ * A name is judged by its whole answer, not by whichever record the resolver happened to order
151
+ * first: one that hands back a mix of permitted and blocked addresses is not one to reach under
152
+ * any of them.
153
+ *
154
+ * @param {Array} addresses - Resolver answer, in the shape dns.lookup(host, {all: true}) returns
155
+ * @param {string} policy - One of the POLICY_* constants
156
+ * @returns {string|null} The offending address, or null when every address is permitted
157
+ */
158
+ function findBlockedAddress(addresses, policy) {
159
+ for (let { address } of addresses || []) {
160
+ if (isBlockedAddress(address, policy)) {
161
+ return address;
162
+ }
163
+ }
164
+ return null;
165
+ }
166
+
141
167
  /**
142
168
  * Verifies that a URL may be contacted under the given egress policy.
143
169
  *
144
170
  * Hostnames are resolved and every returned address is checked, so a name that points at a
145
171
  * blocked address is rejected just like a literal would be.
146
172
  *
173
+ * This is the early, human-facing half of the guard: it fails a bad destination before the request
174
+ * is built and names the reason. It is not the half that binds - see createEgressLookup(), which
175
+ * enforces the same policy against the addresses actually connected to.
176
+ *
147
177
  * @param {string} url - Destination URL
148
178
  * @param {Object} [opts]
149
179
  * @param {string} [opts.policy] - One of the POLICY_* constants, defaults to the link-local policy
@@ -197,18 +227,69 @@ async function assertAllowedUrl(url, opts) {
197
227
  return;
198
228
  }
199
229
 
200
- for (let { address } of addresses) {
201
- if (isBlockedAddress(address, policy)) {
202
- cacheVerdict(cacheKey, address);
203
- throw policyBlockedError(`Refusing to deliver to ${hostname}, it resolves to a blocked address (${address})`);
204
- }
230
+ // Compared against null, not for truthiness: isBlockedAddress fails closed on a value it
231
+ // cannot parse, including an empty string, and that verdict has to survive the return trip.
232
+ const blocked = findBlockedAddress(addresses, policy);
233
+ if (blocked !== null) {
234
+ cacheVerdict(cacheKey, blocked);
235
+ throw policyBlockedError(`Refusing to deliver to ${hostname}, it resolves to a blocked address (${blocked})`);
205
236
  }
206
237
 
207
238
  cacheVerdict(cacheKey, null);
208
239
  }
209
240
 
241
+ /**
242
+ * Builds a Node-compatible `lookup` implementation that applies an egress policy at the moment of
243
+ * connection.
244
+ *
245
+ * `assertAllowedUrl()` can only vet the addresses it resolved itself, and undici resolves the
246
+ * hostname again when it connects. A name that answers differently between the two lookups is
247
+ * therefore checked as one address and connected to as another - deliberately, in a DNS rebinding
248
+ * setup, but equally by accident behind a short TTL or a round-robin record. Handing this function
249
+ * to an undici Agent as `connect: { lookup }` collapses check and use into a single step: the
250
+ * addresses returned here are the addresses the socket is opened to, so no window remains between
251
+ * the two.
252
+ *
253
+ * Only names reach this: net.connect skips the lookup when the host is already an IP. That is the
254
+ * whole story for literals anyway, since an address cannot change between being checked by
255
+ * assertAllowedUrl() and being connected to.
256
+ *
257
+ * @param {string} [policy] - One of the POLICY_* constants, defaults to the link-local policy
258
+ * @param {Object} [opts]
259
+ * @param {Function} [opts.resolve] - Injectable resolver returning [{address, family}], defaults to dns.lookup
260
+ * @returns {Function} lookup(hostname, options, callback), in the shape net.connect expects
261
+ */
262
+ function createEgressLookup(policy, opts) {
263
+ const resolvedPolicy = normalizePolicy(policy);
264
+ const { resolve = dns.lookup } = opts || {};
265
+
266
+ return (hostname, options, callback) => {
267
+ // Forwarded as given, plus `all`, which autoSelectFamily (Happy Eyeballs, on by default
268
+ // since Node 20) already asks for anyway. Forcing it means every address gets classified,
269
+ // not just the one the resolver happened to order first.
270
+ resolve(hostname, Object.assign({}, options, { all: true })).then(addresses => {
271
+ if (!addresses || !addresses.length) {
272
+ let err = new Error(`Could not resolve ${hostname}`);
273
+ err.code = 'ENOTFOUND';
274
+ return callback(err);
275
+ }
276
+
277
+ const blocked = findBlockedAddress(addresses, resolvedPolicy);
278
+ if (blocked !== null) {
279
+ return callback(policyBlockedError(`Refusing to connect to ${hostname}, it resolves to a blocked address (${blocked})`));
280
+ }
281
+
282
+ if (options.all) {
283
+ return callback(null, addresses);
284
+ }
285
+ callback(null, addresses[0].address, addresses[0].family);
286
+ }, callback);
287
+ };
288
+ }
289
+
210
290
  module.exports = {
211
291
  assertAllowedUrl,
292
+ createEgressLookup,
212
293
  isBlockedAddress,
213
294
  normalizePolicy,
214
295
  // Exported so tests can start from a known state; nothing in production clears the cache,