emailengine-app 2.89.0 → 2.91.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 (120) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +73 -0
  4. package/Dockerfile +7 -3
  5. package/ENVIRONMENT.md +24 -23
  6. package/README.md +1 -1
  7. package/bin/healthcheck.js +1 -1
  8. package/copy-static-files.sh +0 -8
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +1 -4
  11. package/lib/account/field-codec.js +396 -0
  12. package/lib/account-assignment.js +26 -9
  13. package/lib/account.js +196 -462
  14. package/lib/api-routes/account-routes.js +49 -6
  15. package/lib/api-routes/route-metadata.js +5 -2
  16. package/lib/api-routes/submit-routes.js +15 -2
  17. package/lib/api-token-auth.js +342 -274
  18. package/lib/arf-detect.js +174 -149
  19. package/lib/attachment-size.js +29 -0
  20. package/lib/autodetect-imap-settings.js +482 -296
  21. package/lib/consts.js +5 -5
  22. package/lib/db.js +1 -4
  23. package/lib/email-client/base-client.js +907 -780
  24. package/lib/email-client/gmail-client.js +557 -450
  25. package/lib/email-client/imap/cid-parts.js +61 -0
  26. package/lib/email-client/imap/mailbox.js +376 -422
  27. package/lib/email-client/imap/sync-operations.js +239 -178
  28. package/lib/email-client/imap-client.js +5 -5
  29. package/lib/email-client/message-builder.js +4 -5
  30. package/lib/email-client/new-message-steps.js +168 -2
  31. package/lib/email-client/outlook/graph-message.js +266 -0
  32. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  33. package/lib/email-client/outlook-client.js +652 -808
  34. package/lib/get-raw-email.js +338 -232
  35. package/lib/get-secret.js +1 -4
  36. package/lib/imapproxy/imap-server.js +5 -5
  37. package/lib/license-subscription.js +60 -0
  38. package/lib/load-env.js +48 -0
  39. package/lib/logger-consts.js +37 -1
  40. package/lib/logger.js +1 -4
  41. package/lib/mail-probe.js +157 -0
  42. package/lib/mcp/tools.js +244 -207
  43. package/lib/metric-values.js +76 -0
  44. package/lib/metrics.js +320 -0
  45. package/lib/oauth/gmail.js +39 -120
  46. package/lib/oauth/http-request.js +195 -0
  47. package/lib/oauth/mail-ru.js +33 -60
  48. package/lib/oauth/outlook.js +37 -137
  49. package/lib/oauth/pubsub/google.js +176 -117
  50. package/lib/oauth2-apps.js +440 -463
  51. package/lib/openapi/build-document.js +10 -10
  52. package/lib/read-env-value.js +31 -7
  53. package/lib/redis-backend-warnings.js +70 -0
  54. package/lib/route-descriptors.js +78 -0
  55. package/lib/schemas.js +10 -1
  56. package/lib/sentry-integrations.js +299 -0
  57. package/lib/sentry.js +75 -27
  58. package/lib/sso-routes.js +249 -0
  59. package/lib/sso.js +29 -6
  60. package/lib/tools.js +17 -28
  61. package/lib/ui-routes/account-edit-form.js +198 -0
  62. package/lib/ui-routes/account-page.js +241 -0
  63. package/lib/ui-routes/account-routes.js +46 -349
  64. package/lib/ui-routes/account-setup.js +1 -1
  65. package/lib/ui-routes/auth-routes.js +10 -10
  66. package/lib/ui-routes/provider-signin.js +187 -0
  67. package/lib/ui-routes/route-helpers.js +1 -1
  68. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  69. package/lib/ui-view-context.js +328 -0
  70. package/lib/utils/public-suffix.js +22 -101
  71. package/lib/web-safe-html.js +20 -7
  72. package/lib/worker-metrics.js +82 -0
  73. package/list-generate.js +2 -5
  74. package/package.json +28 -24
  75. package/sbom.json +360 -1030
  76. package/scripts/refresh-test-tokens.js +1 -1
  77. package/server.js +400 -677
  78. package/static/css/flyonui.css +1 -1
  79. package/static/css/public.css +55 -1
  80. package/static/css/src/app.tailwind.css +18 -0
  81. package/static/js/ee-client.js +2619 -645
  82. package/static/js/ui.js +12 -2
  83. package/static/licenses.html +224 -764
  84. package/translations/de.mo +0 -0
  85. package/translations/de.po +429 -390
  86. package/translations/en.mo +0 -0
  87. package/translations/en.po +342 -257
  88. package/translations/es.mo +0 -0
  89. package/translations/es.po +440 -395
  90. package/translations/et.mo +0 -0
  91. package/translations/et.po +425 -375
  92. package/translations/fr.mo +0 -0
  93. package/translations/fr.po +425 -383
  94. package/translations/it.mo +0 -0
  95. package/translations/it.po +441 -394
  96. package/translations/ja.mo +0 -0
  97. package/translations/ja.po +408 -335
  98. package/translations/messages.pot +188 -130
  99. package/translations/nl.mo +0 -0
  100. package/translations/nl.po +419 -382
  101. package/translations/pl.mo +0 -0
  102. package/translations/pl.po +425 -379
  103. package/translations/sv.mo +0 -0
  104. package/translations/sv.po +440 -388
  105. package/translations/tr.mo +0 -0
  106. package/translations/tr.po +441 -387
  107. package/views/account-identity-error.hbs +1 -1
  108. package/views/account-workspace-error.hbs +2 -2
  109. package/views/accounts/browse.hbs +19 -1
  110. package/views/accounts/register/imap-server.hbs +22 -7
  111. package/views/accounts/register/imap.hbs +3 -0
  112. package/views/accounts/register/index.hbs +1 -27
  113. package/views/accounts/register/provider-signin.hbs +58 -0
  114. package/views/oauth-scope-error.hbs +1 -1
  115. package/views/partials/provider_signin_button.hbs +30 -0
  116. package/views/queues/index.hbs +1 -1
  117. package/views/redirect.hbs +1 -1
  118. package/views/unsubscribe.hbs +6 -6
  119. package/workers/api.js +20 -451
  120. package/data/public_suffix_list.dat +0 -16698
@@ -42,177 +42,247 @@ function getKeyHeader(licenseInfo) {
42
42
  return msgpack.encode({ n: crypto.randomBytes(4), t: Date.now(), l: Buffer.from(licenseInfo.details.key, 'hex') }).toString('base64url');
43
43
  }
44
44
 
45
- async function processMessage(data, licenseInfo) {
46
- let raw = typeof data.raw === 'string' ? Buffer.from(data.raw, 'base64') : data.raw;
47
- let hasBcc = false;
45
+ /**
46
+ * Reads and removes the X-EE-* control headers of a raw message, and takes the subject from the
47
+ * message when the request gave none
48
+ * @param {Object} headers - mailsplit headers of the root node
49
+ * @param {Object} current - sendAt, deliveryAttempts, gateway, trackingEnabled and subject of the request
50
+ * @returns {Object} The same fields, updated from the headers
51
+ */
52
+ function extractControlHeaders(headers, current) {
53
+ const result = Object.assign({}, current);
54
+
55
+ let sendAtVal = headers.getFirst('x-ee-send-at');
56
+ headers.remove('x-ee-send-at');
57
+
58
+ let deliveryAttemptsVal = headers.getFirst('x-ee-delivery-attempts');
59
+ headers.remove('x-ee-delivery-attempts');
60
+
61
+ let gatewayVal = headers.getFirst('x-ee-gateway');
62
+ headers.remove('x-ee-gateway');
63
+
64
+ if (headers.hasHeader('x-ee-tracking-enabled')) {
65
+ result.trackingEnabled = getBoolean(headers.getFirst('x-ee-tracking-enabled'));
66
+ headers.remove('x-ee-tracking-enabled');
67
+ }
48
68
 
49
- let messageId, envelope;
50
- let sendAt = data.sendAt;
51
- let deliveryAttempts = data.deliveryAttempts;
52
- let subject = data.subject;
53
- let trackingEnabled = data.trackingEnabled;
69
+ if (!result.subject && headers.hasHeader('subject')) {
70
+ result.subject = headers.getFirst('subject');
71
+ }
54
72
 
55
- let gateway = data.gateway;
73
+ if (sendAtVal) {
74
+ if (!isNaN(sendAtVal)) {
75
+ sendAtVal = Number(sendAtVal);
76
+ }
77
+ sendAtVal = new Date(sendAtVal);
78
+ if (sendAtVal.toString() !== 'Invalid Date') {
79
+ result.sendAt = sendAtVal;
80
+ }
81
+ }
56
82
 
57
- const splitter = new Splitter();
58
- const joiner = new Joiner();
59
- const headersRewriter = new HeadersRewriter(async headers => {
60
- let sendAtVal = headers.getFirst('x-ee-send-at');
61
- headers.remove('x-ee-send-at');
83
+ if (deliveryAttemptsVal && !isNaN(deliveryAttemptsVal)) {
84
+ // within the bounds the API schema gives the same option; the header is what a stored
85
+ // draft or an SMTP submission carries, and nothing else validates it
86
+ result.deliveryAttempts = Math.min(Math.max(Math.round(Number(deliveryAttemptsVal)), 1), MAX_DELIVERY_ATTEMPTS);
87
+ }
62
88
 
63
- let deliveryAttemptsVal = headers.getFirst('x-ee-delivery-attempts');
64
- headers.remove('x-ee-delivery-attempts');
89
+ if (gatewayVal) {
90
+ result.gateway = gatewayVal;
91
+ }
65
92
 
66
- let gatewayVal = headers.getFirst('x-ee-gateway');
67
- headers.remove('x-ee-gateway');
93
+ return result;
94
+ }
68
95
 
69
- if (headers.hasHeader('x-ee-tracking-enabled')) {
70
- trackingEnabled = getBoolean(headers.getFirst('x-ee-tracking-enabled'));
71
- headers.remove('x-ee-tracking-enabled');
96
+ /**
97
+ * Replaces, adds or removes the From, To, Cc and Bcc headers the request names. A default sender
98
+ * does not replace the one the message already has
99
+ * @param {Object} headers - mailsplit headers of the root node
100
+ * @param {Object} data - Request data
101
+ */
102
+ function applyAddressHeaders(headers, data) {
103
+ for (let addrKey of ['from', 'to', 'cc', 'bcc']) {
104
+ if (!(addrKey in data)) {
105
+ continue;
72
106
  }
73
107
 
74
- if (!subject && headers.hasHeader('subject')) {
75
- subject = headers.getFirst('subject');
108
+ let addrValue = [].concat(data[addrKey] || []);
109
+ if (!addrValue.length) {
110
+ // remove existing
111
+ headers.remove(addrKey);
112
+ continue;
76
113
  }
77
114
 
78
- if (sendAtVal) {
79
- if (!isNaN(sendAtVal)) {
80
- sendAtVal = Number(sendAtVal);
81
- }
82
- sendAtVal = new Date(sendAtVal);
83
- if (sendAtVal.toString() !== 'Invalid Date') {
84
- sendAt = sendAtVal;
115
+ // update or add new
116
+ let headerLine = MimeNode.encodeHeaderValue(addrKey, addrValue);
117
+ if (headers.hasHeader(addrKey)) {
118
+ let addressEntries = addrValue.filter(entry => !entry._default);
119
+ if (!addressEntries.length) {
120
+ // Do not replace existing value with a default value
121
+ continue;
85
122
  }
123
+ headers.update(
124
+ addrKey.replace(/^./, c => c.toUpperCase()),
125
+ headerLine
126
+ );
127
+ } else {
128
+ // push to bottom
129
+ headers.add(
130
+ addrKey.replace(/^./, c => c.toUpperCase()),
131
+ headerLine,
132
+ Infinity
133
+ );
86
134
  }
135
+ }
136
+ }
87
137
 
88
- if (deliveryAttemptsVal && !isNaN(deliveryAttemptsVal)) {
89
- // within the bounds the API schema gives the same option; the header is what a stored
90
- // draft or an SMTP submission carries, and nothing else validates it
91
- deliveryAttempts = Math.min(Math.max(Math.round(Number(deliveryAttemptsVal)), 1), MAX_DELIVERY_ATTEMPTS);
92
- }
138
+ /**
139
+ * The SMTP envelope of a raw message: the one the request gave, else the addresses of the
140
+ * (already rewritten) address headers
141
+ * @param {Object} headers - mailsplit headers of the root node
142
+ * @param {Object} data - Request data
143
+ * @returns {Object} Envelope with a single `from` and a `to` list
144
+ */
145
+ function buildEnvelope(headers, data) {
146
+ // The addresses an envelope is built from: a punycode domain stays in the ASCII form every
147
+ // server accepts, and an entry left without an address (an encoded word hiding one is
148
+ // dropped by the parser) is no recipient. getDecoded() unfolds the value and drops the
149
+ // header name, and leaves encoded words for the parser to judge
150
+ const envelopeAddresses = key =>
151
+ parseAddressHeader(
152
+ headers.getDecoded(key).map(header => header.value),
153
+ { flatten: true, decodePunycode: false }
154
+ )
155
+ .value.map(addr => addr.address)
156
+ .filter(address => address);
157
+
158
+ let envelope = data.envelope || {
159
+ from: envelopeAddresses('from')[0] || '',
160
+ to: Array.from(new Set([...envelopeAddresses('to'), ...envelopeAddresses('cc'), ...envelopeAddresses('bcc')]))
161
+ };
93
162
 
94
- if (gatewayVal) {
95
- gateway = gatewayVal;
96
- }
163
+ envelope.from = [].concat(envelope.from || []).shift() || '';
164
+ envelope.to = [].concat(envelope.to || []);
97
165
 
98
- if (sendAt && sendAt > new Date()) {
99
- // update Date: header for delayed messages
100
- headers.update('Date', sendAt.toUTCString().replace(/GMT/, '+0000'));
101
- }
166
+ return envelope;
167
+ }
102
168
 
103
- if (licenseInfo) {
104
- headers.add('X-Ee-Sid', getKeyHeader(licenseInfo));
105
- }
169
+ /**
170
+ * Makes sure a raw message has a Message-ID (generated on the envelope sender domain, or the one
171
+ * the request gave), a Date and a MIME-Version header
172
+ * @param {Object} headers - mailsplit headers of the root node
173
+ * @param {Object} data - Request data
174
+ * @param {Object} envelope - SMTP envelope
175
+ * @returns {string} The Message-ID of the message
176
+ */
177
+ function ensureStandardHeaders(headers, data, envelope) {
178
+ let messageId;
106
179
 
107
- for (let addrKey of ['from', 'to', 'cc', 'bcc']) {
108
- if (!(addrKey in data)) {
109
- continue;
110
- }
180
+ // generate default message-id
181
+ if (!data.messageId && !headers.hasHeader('message-id')) {
182
+ let fromDomain = envelope.from ? envelope.from.split('@').pop().toLowerCase() : os.hostname();
183
+ messageId = `<${uuid()}@${fromDomain}>`;
184
+ headers.add('Message-ID', messageId, Infinity);
185
+ }
111
186
 
112
- let addrValue = [].concat(data[addrKey] || []);
113
- if (!addrValue.length) {
114
- // remove existing
115
- headers.remove(addrKey);
116
- continue;
117
- }
187
+ if (data.messageId) {
188
+ messageId = (data.messageId || '').toString().trim().replace(/^<*/, '<').replace(/>*$/, '>');
189
+ headers.update('Message-ID', messageId);
190
+ }
118
191
 
119
- // update or add new
120
- let headerLine = MimeNode.encodeHeaderValue(addrKey, addrValue);
121
- if (headers.hasHeader(addrKey)) {
122
- let addressEntries = addrValue.filter(entry => !entry._default);
123
- if (!addressEntries.length) {
124
- // Do not replace existing value with a default value
125
- continue;
126
- }
127
- headers.update(
128
- addrKey.replace(/^./, c => c.toUpperCase()),
129
- headerLine
130
- );
131
- } else {
132
- // push to bottom
133
- headers.add(
134
- addrKey.replace(/^./, c => c.toUpperCase()),
135
- headerLine,
136
- Infinity
137
- );
138
- }
139
- }
192
+ if (!messageId) {
193
+ messageId = headers.getFirst('message-id');
194
+ }
140
195
 
141
- hasBcc = headers.hasHeader('bcc');
196
+ // make sure that there is a Date header
197
+ if (!headers.hasHeader('date')) {
198
+ let dateVal = (data.date || new Date()).toUTCString().replace(/GMT/, '+0000');
199
+ headers.add('Date', dateVal, Infinity);
200
+ }
142
201
 
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);
154
-
155
- envelope = data.envelope || {
156
- from: envelopeAddresses('from')[0] || '',
157
- to: Array.from(new Set([...envelopeAddresses('to'), ...envelopeAddresses('cc'), ...envelopeAddresses('bcc')]))
158
- };
159
-
160
- envelope.from = [].concat(envelope.from || []).shift() || '';
161
- envelope.to = [].concat(envelope.to || []);
162
-
163
- // generate default message-id
164
- if (!data.messageId && !headers.hasHeader('message-id')) {
165
- let fromDomain = envelope.from ? envelope.from.split('@').pop().toLowerCase() : os.hostname();
166
- messageId = `<${uuid()}@${fromDomain}>`;
167
- headers.add('Message-ID', messageId, Infinity);
168
- }
202
+ // ... and MIME-Version
203
+ if (!headers.hasHeader('mime-version')) {
204
+ headers.add('MIME-Version', '1.0', Infinity);
205
+ }
169
206
 
170
- if (data.messageId) {
171
- messageId = (data.messageId || '').toString().trim().replace(/^<*/, '<').replace(/>*$/, '>');
172
- headers.update('Message-ID', messageId);
173
- }
207
+ return messageId;
208
+ }
174
209
 
175
- if (!messageId) {
176
- messageId = headers.getFirst('message-id');
210
+ /**
211
+ * Adds the custom headers of the request. In-Reply-To and References replace the message's own
212
+ * @param {Object} headers - mailsplit headers of the root node
213
+ * @param {Object} [customHeaders] - Custom headers of the request
214
+ */
215
+ function applyCustomHeaders(headers, customHeaders) {
216
+ if (!customHeaders) {
217
+ return;
218
+ }
219
+
220
+ for (let key of Object.keys(customHeaders)) {
221
+ let casedKey = key.replace(/^.|-./g, c => c.toUpperCase());
222
+ switch (key.toLowerCase()) {
223
+ case 'in-reply-to':
224
+ case 'references':
225
+ headers.update(casedKey, customHeaders[key]);
226
+ break;
227
+ default:
228
+ // Encoded like any other header: a non-ASCII value used to go out as raw 8-bit
229
+ headers.add(casedKey, typeof customHeaders[key] === 'string' ? MimeNode.encodeHeaderValue(casedKey, customHeaders[key]) : customHeaders[key]);
230
+ break;
177
231
  }
232
+ }
233
+ }
234
+
235
+ async function processMessage(data, licenseInfo) {
236
+ let raw = typeof data.raw === 'string' ? Buffer.from(data.raw, 'base64') : data.raw;
237
+ let hasBcc = false;
238
+
239
+ let messageId, envelope;
178
240
 
179
- // make sure that there is a Date header
180
- if (!headers.hasHeader('date')) {
181
- let dateVal = (data.date || new Date()).toUTCString().replace(/GMT/, '+0000');
182
- headers.add('Date', dateVal, Infinity);
241
+ // what the request gave, until the control headers of the message say otherwise
242
+ let control = {
243
+ sendAt: data.sendAt,
244
+ deliveryAttempts: data.deliveryAttempts,
245
+ subject: data.subject,
246
+ trackingEnabled: data.trackingEnabled,
247
+ gateway: data.gateway
248
+ };
249
+
250
+ const splitter = new Splitter();
251
+ const joiner = new Joiner();
252
+
253
+ // The steps depend on each other in this order: the envelope is built from the rewritten
254
+ // address headers, and a generated Message-ID uses the envelope sender's domain
255
+ const headersRewriter = new HeadersRewriter(async headers => {
256
+ control = extractControlHeaders(headers, control);
257
+
258
+ if (control.sendAt && control.sendAt > new Date()) {
259
+ // update Date: header for delayed messages
260
+ headers.update('Date', control.sendAt.toUTCString().replace(/GMT/, '+0000'));
183
261
  }
184
262
 
185
- // ... and MIME-Version
186
- if (!headers.hasHeader('mime-version')) {
187
- headers.add('MIME-Version', '1.0', Infinity);
263
+ if (licenseInfo) {
264
+ headers.add('X-Ee-Sid', getKeyHeader(licenseInfo));
188
265
  }
189
266
 
267
+ applyAddressHeaders(headers, data);
268
+
269
+ hasBcc = headers.hasHeader('bcc');
270
+
271
+ envelope = buildEnvelope(headers, data);
272
+
273
+ messageId = ensureStandardHeaders(headers, data, envelope);
274
+
190
275
  if (data.subject) {
191
276
  headers.update('Subject', mimeFuncs.encodeWords(data.subject, 'Q', 64, true));
192
277
  }
193
278
 
194
- if (data.headers) {
195
- for (let key of Object.keys(data.headers)) {
196
- let casedKey = key.replace(/^.|-./g, c => c.toUpperCase());
197
- switch (key.toLowerCase()) {
198
- case 'in-reply-to':
199
- case 'references':
200
- headers.update(casedKey, data.headers[key]);
201
- break;
202
- default:
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
- );
208
- break;
209
- }
210
- }
211
- }
279
+ applyCustomHeaders(headers, data.headers);
212
280
  });
213
281
 
214
282
  let message = await collectRewritten(splitter, headersRewriter, joiner, raw);
215
283
 
284
+ const { sendAt, deliveryAttempts, subject, trackingEnabled, gateway } = control;
285
+
216
286
  let trackClicks = typeof data.trackClicks === 'boolean' ? data.trackClicks : trackingEnabled;
217
287
  let trackOpens = typeof data.trackOpens === 'boolean' ? data.trackOpens : trackingEnabled;
218
288
 
@@ -285,73 +355,68 @@ ${html}`;
285
355
  return html;
286
356
  }
287
357
 
288
- async function getRawEmail(data, licenseInfo, options) {
289
- options = options || {};
290
-
291
- if (data.raw) {
292
- let response = await processMessage(data, licenseInfo);
293
-
294
- if (options.returnObject) {
295
- // parse email into a structured object
296
- const parsed = await parseMessage(response.raw, {
297
- skipHtmlToText: true,
298
- skipImageLinks: true,
299
- skipTextToHtml: true,
300
- skipTextLinks: true,
301
- keepDeliveryStatus: true,
302
- keepCidLinks: true,
303
- ignoreEmbedded: true,
304
- defaultInlineEmbedded: false,
305
- maxHeadSize: 2 * 1024 * 1024
306
- });
307
-
308
- if (parsed.from) {
309
- parsed.from = parsed.from.value?.[0];
310
- }
358
+ /**
359
+ * Parses a raw message into the structured object a structured (API) send takes
360
+ * @param {Buffer} raw - RFC822 message
361
+ * @returns {Object} Message object
362
+ */
363
+ async function parseRawToObject(raw) {
364
+ // parse email into a structured object
365
+ const parsed = await parseMessage(raw, {
366
+ skipHtmlToText: true,
367
+ skipImageLinks: true,
368
+ skipTextToHtml: true,
369
+ skipTextLinks: true,
370
+ keepDeliveryStatus: true,
371
+ keepCidLinks: true,
372
+ ignoreEmbedded: true,
373
+ defaultInlineEmbedded: false,
374
+ maxHeadSize: 2 * 1024 * 1024
375
+ });
311
376
 
312
- for (let key of ['to', 'cc', 'bcc', 'replyTo']) {
313
- if (parsed[key]) {
314
- parsed[key] = parsed[key].value;
315
- }
316
- }
377
+ if (parsed.from) {
378
+ parsed.from = parsed.from.value?.[0];
379
+ }
317
380
 
318
- delete parsed.headers; // conflicts
381
+ for (let key of ['to', 'cc', 'bcc', 'replyTo']) {
382
+ if (parsed[key]) {
383
+ parsed[key] = parsed[key].value;
384
+ }
385
+ }
319
386
 
320
- for (let attachment of parsed.attachments || []) {
321
- attachment.content = attachment.content.toString('base64');
322
- attachment.encoding = 'base64';
323
- if (attachment.contentId) {
324
- attachment.cid = attachment.contentId;
325
- }
326
- attachment.isInline = attachment.contentDisposition === 'inline';
327
- }
387
+ delete parsed.headers; // conflicts
328
388
 
329
- response.emailObject = parsed;
389
+ for (let attachment of parsed.attachments || []) {
390
+ attachment.content = attachment.content.toString('base64');
391
+ attachment.encoding = 'base64';
392
+ if (attachment.contentId) {
393
+ attachment.cid = attachment.contentId;
330
394
  }
331
-
332
- return response;
395
+ attachment.isInline = attachment.contentDisposition === 'inline';
333
396
  }
334
397
 
335
- let sendAt = data.sendAt;
336
- let deliveryAttempts = data.deliveryAttempts;
337
- let gateway = data.gateway;
338
- let trackingEnabled = data.trackingEnabled;
339
-
340
- let trackClicks = typeof data.trackClicks === 'boolean' ? data.trackClicks : trackingEnabled;
341
- let trackOpens = typeof data.trackOpens === 'boolean' ? data.trackOpens : trackingEnabled;
398
+ return parsed;
399
+ }
342
400
 
401
+ /**
402
+ * The MailComposer options of a structured message: the request with the preview text injected
403
+ * into the html, the license header added and the EmailEngine-only options unset. Takes the
404
+ * preview text out of `data`
405
+ * @param {Object} data - Request data
406
+ * @param {Object} licenseInfo - License information
407
+ * @returns {Object} MailComposer options
408
+ */
409
+ function buildComposerOptions(data, licenseInfo) {
343
410
  let html = data.html || null;
344
411
  if (data.previewText && html) {
345
412
  let previewText = data.previewText;
346
413
  delete data.previewText;
347
- if (html) {
348
- html = addPreviev(html, previewText);
349
- }
414
+ html = addPreviev(html, previewText);
350
415
  }
351
416
 
352
- const mailComposerOptions = Object.assign(
417
+ return Object.assign(
353
418
  {
354
- date: sendAt,
419
+ date: data.sendAt,
355
420
  disableUrlAccess: true,
356
421
  disableFileAccess: true,
357
422
  newline: '\r\n',
@@ -380,63 +445,104 @@ async function getRawEmail(data, licenseInfo, options) {
380
445
  previewText: null
381
446
  }
382
447
  );
448
+ }
383
449
 
384
- let emailBuffer;
385
- let emailObject;
450
+ /**
451
+ * Builds the MIME message of a structured submission
452
+ * @param {Object} mailComposerOptions - What buildComposerOptions() returned
453
+ * @returns {Object} raw, messageId and envelope
454
+ */
455
+ async function composeMime(mailComposerOptions) {
456
+ for (let attachment of mailComposerOptions.attachments || []) {
457
+ // Insert message/rfc822 attachments "as is" without any encoding. Handed over decoded,
458
+ // nodemailer (10.2.0) labels the part 7bit when it is plain ASCII and 8bit otherwise,
459
+ // which this used to work out itself by building the part's headers by hand
460
+ if (/^message\/rfc822\b/i.test(attachment.contentType) && typeof attachment.content === 'string' && attachment.encoding) {
461
+ attachment.content = Buffer.from(attachment.content, attachment.encoding);
462
+ delete attachment.encoding;
463
+ attachment.contentDisposition = attachment.contentDisposition || 'attachment';
464
+ }
465
+ }
386
466
 
387
- let messageId;
388
- let envelope;
467
+ const mail = new MailComposer(mailComposerOptions);
389
468
 
390
- if (!options.returnObject) {
391
- for (let attachment of mailComposerOptions.attachments || []) {
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
395
- if (/^message\/rfc822\b/i.test(attachment.contentType) && typeof attachment.content === 'string' && attachment.encoding) {
396
- attachment.content = Buffer.from(attachment.content, attachment.encoding);
397
- delete attachment.encoding;
398
- attachment.contentDisposition = attachment.contentDisposition || 'attachment';
399
- }
469
+ let compiled;
470
+ try {
471
+ compiled = mail.compile();
472
+ } catch (err) {
473
+ // an otp value the schema let through but the OTP-Token header can not carry
474
+ if (err.code === 'EOTP') {
475
+ err.statusCode = 400;
400
476
  }
477
+ throw err;
478
+ }
479
+ // do not strip Bcc header from the message (will be removed later)
480
+ compiled.keepBcc = true;
401
481
 
402
- const mail = new MailComposer(mailComposerOptions);
482
+ const messageId = compiled.messageId();
483
+ const raw = await compiled.build();
484
+ const envelope = compiled.getEnvelope();
403
485
 
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
- }
414
- // do not strip Bcc header from the message (will be removed later)
415
- compiled.keepBcc = true;
486
+ return { raw, messageId, envelope };
487
+ }
416
488
 
417
- messageId = compiled.messageId();
418
- emailBuffer = await compiled.build();
419
- envelope = compiled.getEnvelope();
420
- } else {
421
- emailObject = mailComposerOptions;
489
+ /**
490
+ * The SMTP envelope of a structured submission that is not built into MIME
491
+ * @param {Object} data - Request data
492
+ * @returns {Object} Envelope
493
+ */
494
+ function envelopeFromData(data) {
495
+ let envelopeTo = new Set();
496
+ for (let key of ['to', 'cc', 'bcc']) {
497
+ data[key]
498
+ ?.map(entry => entry.address)
499
+ .filter(address => address)
500
+ .forEach(address => {
501
+ envelopeTo.add(address);
502
+ });
503
+ }
422
504
 
423
- messageId = data.messageId;
505
+ return {
506
+ from: data.from?.address || null,
507
+ to: Array.from(envelopeTo)
508
+ };
509
+ }
424
510
 
425
- // generate envelope
426
- let envelopeTo = new Set();
427
- for (let key of ['to', 'cc', 'bcc']) {
428
- data[key]
429
- ?.map(entry => entry.address)
430
- .filter(address => address)
431
- .forEach(address => {
432
- envelopeTo.add(address);
433
- });
511
+ async function getRawEmail(data, licenseInfo, options) {
512
+ options = options || {};
513
+
514
+ if (data.raw) {
515
+ let response = await processMessage(data, licenseInfo);
516
+
517
+ if (options.returnObject) {
518
+ response.emailObject = await parseRawToObject(response.raw);
434
519
  }
435
520
 
436
- envelope = {
437
- from: data.from?.address || null,
438
- to: Array.from(envelopeTo)
439
- };
521
+ return response;
522
+ }
523
+
524
+ let sendAt = data.sendAt;
525
+ let deliveryAttempts = data.deliveryAttempts;
526
+ let gateway = data.gateway;
527
+ let trackingEnabled = data.trackingEnabled;
528
+
529
+ let trackClicks = typeof data.trackClicks === 'boolean' ? data.trackClicks : trackingEnabled;
530
+ let trackOpens = typeof data.trackOpens === 'boolean' ? data.trackOpens : trackingEnabled;
531
+
532
+ const mailComposerOptions = buildComposerOptions(data, licenseInfo);
533
+
534
+ let emailBuffer;
535
+ let emailObject;
536
+
537
+ let messageId;
538
+ let envelope;
539
+
540
+ if (!options.returnObject) {
541
+ ({ raw: emailBuffer, messageId, envelope } = await composeMime(mailComposerOptions));
542
+ } else {
543
+ emailObject = mailComposerOptions;
544
+ messageId = data.messageId;
545
+ envelope = envelopeFromData(data);
440
546
  }
441
547
 
442
548
  const bcc = [].concat(data.bcc || []);
package/lib/get-secret.js CHANGED
@@ -1,9 +1,6 @@
1
1
  'use strict';
2
2
 
3
- if (!process.env.EE_ENV_LOADED) {
4
- require('dotenv').config({ quiet: true });
5
- process.env.EE_ENV_LOADED = 'true';
6
- }
3
+ require('./load-env').loadEnvOnce();
7
4
 
8
5
  const config = require('@zone-eu/wild-config');
9
6
  const { readEnvValue } = require('./read-env-value');