emailengine-app 2.74.2 → 2.76.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.
- package/.github/workflows/test.yml +0 -10
- package/CHANGELOG.md +40 -0
- package/config/e2e.toml +1 -1
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +94 -18
- package/lib/api-routes/message-routes.js +3 -1
- package/lib/api-routes/route-helpers.js +3 -0
- package/lib/api-routes/submit-routes.js +159 -52
- package/lib/consts.js +6 -0
- package/lib/db.js +4 -1
- package/lib/egress-filter.js +220 -0
- package/lib/email-client/base-client.js +169 -27
- package/lib/email-client/gmail/send-request.js +16 -1
- package/lib/email-client/gmail-client.js +91 -10
- package/lib/email-client/imap/mailbox.js +3 -9
- package/lib/email-client/imap-client.js +103 -1
- package/lib/email-client/message-builder.js +24 -7
- package/lib/email-client/notification-handler.js +11 -12
- package/lib/email-client/outlook/send-request.js +18 -1
- package/lib/email-client/outlook-client.js +81 -9
- package/lib/imapproxy/imap-core/README.md +69 -0
- package/lib/oauth/external-account-config.js +41 -1
- package/lib/oauth/external-account-signer.js +7 -2
- package/lib/oauth/verify-app.js +18 -3
- package/lib/queue-retention.js +56 -0
- package/lib/respawn-backoff.js +95 -0
- package/lib/schemas.js +9 -2
- package/lib/settings.js +4 -1
- package/lib/tools.js +20 -0
- package/lib/ui-routes/admin-config-routes.js +22 -18
- package/lib/utils/network.js +122 -3
- package/lib/web-safe-html.js +401 -0
- package/lib/webhook-request.js +40 -2
- package/lib/webhooks.js +2 -3
- package/package.json +17 -20
- package/playwright.config.js +1 -1
- package/sbom.json +1 -1
- package/server.js +45 -8
- package/static/js/ee-client.js +55 -6
- package/static/js/ui.js +13 -0
- package/static/licenses.html +332 -292
- package/translations/messages.pot +52 -52
- package/views/config/webhooks.hbs +2 -2
- package/views/partials/webhooks_editor_functions.hbs +1 -1
- package/workers/api.js +32 -17
- package/workers/documents.js +6 -0
- package/workers/export.js +8 -1
- package/workers/imap.js +17 -19
- package/workers/submit.js +10 -0
- package/workers/webhooks.js +23 -2
- package/Gruntfile.js +0 -58
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const net = require('net');
|
|
4
|
+
const dns = require('dns').promises;
|
|
5
|
+
const ipaddr = require('ipaddr.js');
|
|
6
|
+
|
|
7
|
+
// Egress policies for operator-supplied outbound URLs (webhook targets), least to most
|
|
8
|
+
// restrictive. EmailEngine is usually self-hosted alongside the services it notifies, so
|
|
9
|
+
// blocking private ranges outright would break ordinary deployments - the default therefore only
|
|
10
|
+
// blocks the link-local range, which is where every cloud provider parks its instance metadata
|
|
11
|
+
// service and which no real webhook receiver lives on.
|
|
12
|
+
const POLICY_OFF = 'off';
|
|
13
|
+
const POLICY_LINK_LOCAL = 'link-local';
|
|
14
|
+
const POLICY_PRIVATE = 'private';
|
|
15
|
+
|
|
16
|
+
const VALID_POLICIES = new Set([POLICY_OFF, POLICY_LINK_LOCAL, POLICY_PRIVATE]);
|
|
17
|
+
|
|
18
|
+
// Range names come from ipaddr.js `range()`
|
|
19
|
+
const LINK_LOCAL_BLOCKED_RANGES = new Set(['linkLocal']);
|
|
20
|
+
|
|
21
|
+
const PRIVATE_BLOCKED_RANGES = new Set([
|
|
22
|
+
'linkLocal',
|
|
23
|
+
'loopback',
|
|
24
|
+
'private',
|
|
25
|
+
'uniqueLocal',
|
|
26
|
+
'carrierGradeNat',
|
|
27
|
+
'reserved',
|
|
28
|
+
'unspecified',
|
|
29
|
+
'broadcast',
|
|
30
|
+
'multicast'
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
// Metadata endpoints that range classification alone does not catch under the default policy:
|
|
34
|
+
// AWS serves IMDS over IPv6 from a unique-local address, and Alibaba Cloud parks its IMDS in the
|
|
35
|
+
// carrier-grade NAT range. Normalized forms, compared against a normalized subject.
|
|
36
|
+
const ALWAYS_BLOCKED_ADDRESSES = new Set(['fd00:ec2:0:0:0:0:0:254', '100.100.100.200']);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Resolves the configured egress policy, falling back to the default for unknown values.
|
|
40
|
+
* @param {string} [value] - Raw configured value
|
|
41
|
+
* @returns {string} One of the POLICY_* constants
|
|
42
|
+
*/
|
|
43
|
+
function normalizePolicy(value) {
|
|
44
|
+
let policy = (value || '').toString().trim().toLowerCase();
|
|
45
|
+
return VALID_POLICIES.has(policy) ? policy : POLICY_LINK_LOCAL;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Checks a single IP address against an egress policy.
|
|
50
|
+
*
|
|
51
|
+
* IPv4-mapped IPv6 addresses are unwrapped first, otherwise `::ffff:169.254.169.254` would be
|
|
52
|
+
* classified as a plain IPv6 unicast address and sail through.
|
|
53
|
+
*
|
|
54
|
+
* @param {string} ip - IP address to classify
|
|
55
|
+
* @param {string} policy - One of the POLICY_* constants
|
|
56
|
+
* @returns {boolean} True when the address must not be contacted
|
|
57
|
+
*/
|
|
58
|
+
function isBlockedAddress(ip, policy) {
|
|
59
|
+
if (policy === POLICY_OFF) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
let parsed;
|
|
64
|
+
try {
|
|
65
|
+
parsed = ipaddr.parse(ip);
|
|
66
|
+
} catch (err) {
|
|
67
|
+
// Fail closed: an address we can not classify is not one we should connect to
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (parsed.kind() === 'ipv6' && parsed.isIPv4MappedAddress()) {
|
|
72
|
+
parsed = parsed.toIPv4Address();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (ALWAYS_BLOCKED_ADDRESSES.has(parsed.toNormalizedString())) {
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const blockedRanges = policy === POLICY_PRIVATE ? PRIVATE_BLOCKED_RANGES : LINK_LOCAL_BLOCKED_RANGES;
|
|
80
|
+
|
|
81
|
+
return blockedRanges.has(parsed.range());
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Builds the error thrown for a blocked destination. Carries `code` so callers can recognize a
|
|
86
|
+
* policy rejection and stop retrying: a blocked target is a configuration problem, and burning
|
|
87
|
+
* ten attempts on it only delays the operator seeing the real reason.
|
|
88
|
+
* @param {string} reason - Human readable explanation
|
|
89
|
+
* @returns {Error} Error tagged with code EEGRESSBLOCKED
|
|
90
|
+
*/
|
|
91
|
+
function blockedError(reason) {
|
|
92
|
+
let err = new Error(reason);
|
|
93
|
+
err.code = 'EEGRESSBLOCKED';
|
|
94
|
+
return err;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// An operator who does not know this policy exists otherwise has nothing to search for: the
|
|
98
|
+
// message would describe a refusal without naming what is refusing. It also reaches operators who
|
|
99
|
+
// only ever see the log line, which no amount of UI help would.
|
|
100
|
+
const POLICY_HINT = 'See EENGINE_WEBHOOK_EGRESS_POLICY if this destination is intended.';
|
|
101
|
+
|
|
102
|
+
// A destination the policy refuses, as opposed to one we could not parse - the hint belongs on the
|
|
103
|
+
// former only, since the setting cannot help with a malformed URL
|
|
104
|
+
const policyBlockedError = reason => blockedError(`${reason}. ${POLICY_HINT}`);
|
|
105
|
+
|
|
106
|
+
// Verdict cache for resolved hostnames. Node's dns.lookup has no cache of its own and glibc has
|
|
107
|
+
// none either without nscd, so without this every webhook delivery pays a resolver round trip -
|
|
108
|
+
// and the notify worker runs at concurrency 1 by default, so that cost is fully serialized ahead
|
|
109
|
+
// of each POST. Caching the verdict rather than the addresses keeps entries tiny.
|
|
110
|
+
//
|
|
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.
|
|
114
|
+
const VERDICT_TTL = 60 * 1000;
|
|
115
|
+
const VERDICT_CACHE_LIMIT = 1000;
|
|
116
|
+
const verdictCache = new Map();
|
|
117
|
+
|
|
118
|
+
function readCachedVerdict(key) {
|
|
119
|
+
const hit = verdictCache.get(key);
|
|
120
|
+
if (!hit) {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (hit.expires <= Date.now()) {
|
|
125
|
+
verdictCache.delete(key);
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return hit;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function cacheVerdict(key, blockedBy) {
|
|
133
|
+
// Bounded: drop the oldest entry once full. Map preserves insertion order.
|
|
134
|
+
if (verdictCache.size >= VERDICT_CACHE_LIMIT) {
|
|
135
|
+
verdictCache.delete(verdictCache.keys().next().value);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
verdictCache.set(key, { blockedBy, expires: Date.now() + VERDICT_TTL });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Verifies that a URL may be contacted under the given egress policy.
|
|
143
|
+
*
|
|
144
|
+
* Hostnames are resolved and every returned address is checked, so a name that points at a
|
|
145
|
+
* blocked address is rejected just like a literal would be.
|
|
146
|
+
*
|
|
147
|
+
* @param {string} url - Destination URL
|
|
148
|
+
* @param {Object} [opts]
|
|
149
|
+
* @param {string} [opts.policy] - One of the POLICY_* constants, defaults to the link-local policy
|
|
150
|
+
* @param {Function} [opts.resolve] - Injectable resolver returning [{address}], defaults to dns.lookup
|
|
151
|
+
* @returns {Promise<void>} Resolves when the destination is allowed
|
|
152
|
+
* @throws {Error} Tagged with code EEGRESSBLOCKED when the destination is not allowed
|
|
153
|
+
*/
|
|
154
|
+
async function assertAllowedUrl(url, opts) {
|
|
155
|
+
const { policy = POLICY_LINK_LOCAL, resolve } = opts || {};
|
|
156
|
+
|
|
157
|
+
if (policy === POLICY_OFF) {
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
let hostname;
|
|
162
|
+
try {
|
|
163
|
+
hostname = new URL(url).hostname;
|
|
164
|
+
} catch (err) {
|
|
165
|
+
throw blockedError(`Invalid webhook URL: ${url}`);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// URL keeps IPv6 literals in brackets, ipaddr.js does not want them
|
|
169
|
+
if (hostname.startsWith('[') && hostname.endsWith(']')) {
|
|
170
|
+
hostname = hostname.slice(1, -1);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// A literal needs no resolution, so it is both the cheapest path and never cached
|
|
174
|
+
if (net.isIP(hostname)) {
|
|
175
|
+
if (isBlockedAddress(hostname, policy)) {
|
|
176
|
+
throw policyBlockedError(`Refusing to deliver to a blocked address (${hostname})`);
|
|
177
|
+
}
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const cacheKey = `${policy}:${hostname}`;
|
|
182
|
+
const cached = readCachedVerdict(cacheKey);
|
|
183
|
+
if (cached) {
|
|
184
|
+
if (cached.blockedBy) {
|
|
185
|
+
throw policyBlockedError(`Refusing to deliver to ${hostname}, it resolves to a blocked address (${cached.blockedBy})`);
|
|
186
|
+
}
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
let addresses;
|
|
191
|
+
try {
|
|
192
|
+
addresses = resolve ? await resolve(hostname) : await dns.lookup(hostname, { all: true });
|
|
193
|
+
} catch (err) {
|
|
194
|
+
// A name that does not resolve is a delivery problem, not a policy one. Let the request
|
|
195
|
+
// proceed and fail with the transport's own error so it retries like any other DNS blip.
|
|
196
|
+
// Deliberately not cached, so a resolver blip cannot pin a verdict for a whole minute.
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
|
|
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
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
cacheVerdict(cacheKey, null);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
module.exports = {
|
|
211
|
+
assertAllowedUrl,
|
|
212
|
+
isBlockedAddress,
|
|
213
|
+
normalizePolicy,
|
|
214
|
+
// Exported so tests can start from a known state; nothing in production clears the cache,
|
|
215
|
+
// entries simply expire.
|
|
216
|
+
clearVerdictCache: () => verdictCache.clear(),
|
|
217
|
+
POLICY_OFF,
|
|
218
|
+
POLICY_LINK_LOCAL,
|
|
219
|
+
POLICY_PRIVATE
|
|
220
|
+
};
|
|
@@ -10,7 +10,8 @@ const { templates } = require('../templates');
|
|
|
10
10
|
const { Gateway } = require('../gateway');
|
|
11
11
|
const os = require('os');
|
|
12
12
|
const punycode = require('punycode.js');
|
|
13
|
-
const { inlineHtml, inlineText, htmlToText, textToHtml
|
|
13
|
+
const { inlineHtml, inlineText, htmlToText, textToHtml } = require('@postalsys/email-text-tools');
|
|
14
|
+
const { messageWebSafeHtml } = require('../web-safe-html');
|
|
14
15
|
const { randomUUID: uuid } = require('crypto');
|
|
15
16
|
const { addTrackers } = require('../add-trackers');
|
|
16
17
|
const { getRawEmail } = require('../get-raw-email');
|
|
@@ -67,6 +68,7 @@ const {
|
|
|
67
68
|
EMAIL_DELIVERY_ERROR_NOTIFY,
|
|
68
69
|
EMAIL_SENT_NOTIFY
|
|
69
70
|
} = require('../consts');
|
|
71
|
+
const { buildRetentionPolicy } = require('../queue-retention');
|
|
70
72
|
|
|
71
73
|
// Configure download chunk size from environment or use default
|
|
72
74
|
const DOWNLOAD_CHUNK_SIZE = getByteSize(readEnvValue('EENGINE_CHUNK_SIZE')) || DEFAULT_DOWNLOAD_CHUNK_SIZE;
|
|
@@ -880,6 +882,13 @@ class BaseClient {
|
|
|
880
882
|
async queueMessageHandler(data, meta, connectionOptions) {
|
|
881
883
|
let accountData = await this.accountObject.loadAccountData();
|
|
882
884
|
|
|
885
|
+
// Submitting a stored draft skips content processing - the message body already exists.
|
|
886
|
+
// The draft path owns its own gateway load and SMTP-capability check (the effective
|
|
887
|
+
// gateway is only known after the draft's X-EE-* headers have been parsed)
|
|
888
|
+
if (meta && meta.draft) {
|
|
889
|
+
return this.queueDraftEntry(data, meta, accountData, connectionOptions);
|
|
890
|
+
}
|
|
891
|
+
|
|
883
892
|
// Load gateway configuration if specified
|
|
884
893
|
let gatewayData;
|
|
885
894
|
let gatewayObject;
|
|
@@ -2002,6 +2011,44 @@ class BaseClient {
|
|
|
2002
2011
|
});
|
|
2003
2012
|
}
|
|
2004
2013
|
|
|
2014
|
+
// Store the message in the queue and schedule the submit job
|
|
2015
|
+
let response = await this.pushMessageToQueue({ data, meta, raw, hasBcc, envelope, messageId, subject, sendAt, deliveryAttempts, gatewayData });
|
|
2016
|
+
|
|
2017
|
+
if (data.reference && (data.reference.message || data.reference.threadId)) {
|
|
2018
|
+
response.reference = {};
|
|
2019
|
+
if (data.reference.message) {
|
|
2020
|
+
response.reference.message = data.reference.message;
|
|
2021
|
+
response.reference.documentStore = documentStoreUsed;
|
|
2022
|
+
response.reference.success = referencedMessage ? true : false;
|
|
2023
|
+
if (!referencedMessage) {
|
|
2024
|
+
response.reference.error = 'Referenced message was not found';
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
if (data.reference.threadId) {
|
|
2028
|
+
response.reference.threadId = data.reference.threadId;
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
return response;
|
|
2033
|
+
}
|
|
2034
|
+
|
|
2035
|
+
/**
|
|
2036
|
+
* Stores an outbound message in the delivery queue and schedules the submit job
|
|
2037
|
+
* @param {Object} params
|
|
2038
|
+
* @param {Object} params.data - Message data (copy, sentMailPath, feedbackKey, dsn, proxy, localAddress, reference)
|
|
2039
|
+
* @param {Object} params.meta - Metadata for the queue job
|
|
2040
|
+
* @param {Buffer} params.raw - Raw RFC822 message
|
|
2041
|
+
* @param {boolean} params.hasBcc - Whether the raw message carries a Bcc header
|
|
2042
|
+
* @param {Object} params.envelope - SMTP envelope
|
|
2043
|
+
* @param {string} params.messageId - Message-ID header value
|
|
2044
|
+
* @param {string} params.subject - Message subject for queue listings
|
|
2045
|
+
* @param {Date} [params.sendAt] - Scheduled send time
|
|
2046
|
+
* @param {number} [params.deliveryAttempts] - Delivery attempt count override
|
|
2047
|
+
* @param {Object} [params.gatewayData] - Loaded gateway data
|
|
2048
|
+
* @param {Object} [params.draft] - Draft reference if the queued message is a stored draft
|
|
2049
|
+
* @returns {Object} Base queue response
|
|
2050
|
+
*/
|
|
2051
|
+
async pushMessageToQueue({ data, meta, raw, hasBcc, envelope, messageId, subject, sendAt, deliveryAttempts, gatewayData, draft }) {
|
|
2005
2052
|
let now = new Date();
|
|
2006
2053
|
|
|
2007
2054
|
//queue for later
|
|
@@ -2023,6 +2070,7 @@ class BaseClient {
|
|
|
2023
2070
|
envelope,
|
|
2024
2071
|
messageId,
|
|
2025
2072
|
reference: data.reference || {},
|
|
2073
|
+
draft: draft || null,
|
|
2026
2074
|
sendAt: (sendAt && sendAt.getTime()) || false,
|
|
2027
2075
|
created: now.getTime(),
|
|
2028
2076
|
copy: data.copy,
|
|
@@ -2060,11 +2108,9 @@ class BaseClient {
|
|
|
2060
2108
|
|
|
2061
2109
|
// Configure queue job options
|
|
2062
2110
|
let queueName = 'queued';
|
|
2063
|
-
let retention = typeof queueKeep === 'number' ? { age: 24 * 3600, count: queueKeep } : queueKeep;
|
|
2064
2111
|
let jobOpts = {
|
|
2065
2112
|
jobId: queueId,
|
|
2066
|
-
|
|
2067
|
-
removeOnFail: retention,
|
|
2113
|
+
...buildRetentionPolicy(queueKeep),
|
|
2068
2114
|
attempts: typeof deliveryAttempts === 'number' ? deliveryAttempts : defaultDeliveryAttempts,
|
|
2069
2115
|
backoff: {
|
|
2070
2116
|
type: 'exponential',
|
|
@@ -2092,30 +2138,93 @@ class BaseClient {
|
|
|
2092
2138
|
|
|
2093
2139
|
this.logger.info({ msg: 'Message queued for delivery', envelope, messageId, sendAt: (sendAt || now).toISOString(), queueId, job: job.id });
|
|
2094
2140
|
|
|
2095
|
-
|
|
2096
|
-
let response = {
|
|
2141
|
+
return {
|
|
2097
2142
|
response: 'Queued for delivery',
|
|
2098
2143
|
messageId,
|
|
2099
2144
|
sendAt: (sendAt || now).toISOString(),
|
|
2100
2145
|
queueId
|
|
2101
2146
|
};
|
|
2147
|
+
}
|
|
2102
2148
|
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2149
|
+
/**
|
|
2150
|
+
* Queues an existing draft message for delivery. The draft is resolved through the
|
|
2151
|
+
* backend-specific resolveDraftForSubmit(), its raw content is stored in the queue entry
|
|
2152
|
+
* (used by the SMTP and gateway delivery paths), and a draft reference travels along so
|
|
2153
|
+
* the delivery step can use the provider's native draft-send call and clean up the draft.
|
|
2154
|
+
* @param {Object} data - Submit options ({ envelope, sendAt, ... })
|
|
2155
|
+
* @param {Object} meta - Metadata carrying the draft marker ({ draft: { message } })
|
|
2156
|
+
* @param {Object} accountData - Already loaded account data
|
|
2157
|
+
* @param {Object} connectionOptions - Connection options
|
|
2158
|
+
* @returns {Object} Queue response
|
|
2159
|
+
*/
|
|
2160
|
+
async queueDraftEntry(data, meta, accountData, connectionOptions) {
|
|
2161
|
+
let licenseInfo = await this.call({ cmd: 'license' });
|
|
2162
|
+
|
|
2163
|
+
let { raw: draftRaw, draft, threadId } = await this.resolveDraftForSubmit(meta.draft.message, connectionOptions);
|
|
2164
|
+
|
|
2165
|
+
if (threadId) {
|
|
2166
|
+
// Keep the sent copy in the draft's thread (Gmail API accounts)
|
|
2167
|
+
data.reference = { threadId };
|
|
2168
|
+
}
|
|
2169
|
+
|
|
2170
|
+
// Run the draft through the same raw-message normalization as raw API submissions:
|
|
2171
|
+
// consumes X-EE control headers, applies the envelope override, backfills Message-ID
|
|
2172
|
+
// and Date, detects Bcc and derives the SMTP envelope from the headers
|
|
2173
|
+
let { raw, hasBcc, envelope, subject, messageId, sendAt, deliveryAttempts, gateway } = await getRawEmail(
|
|
2174
|
+
{
|
|
2175
|
+
raw: draftRaw,
|
|
2176
|
+
envelope: data.envelope,
|
|
2177
|
+
sendAt: data.sendAt,
|
|
2178
|
+
deliveryAttempts: data.deliveryAttempts,
|
|
2179
|
+
gateway: data.gateway
|
|
2180
|
+
},
|
|
2181
|
+
licenseInfo
|
|
2182
|
+
);
|
|
2183
|
+
|
|
2184
|
+
if (!envelope.to || !envelope.to.length) {
|
|
2185
|
+
let err = new Error('Draft message has no recipients');
|
|
2186
|
+
err.code = 'DraftHasNoRecipients';
|
|
2187
|
+
err.statusCode = 400;
|
|
2188
|
+
throw err;
|
|
2189
|
+
}
|
|
2190
|
+
|
|
2191
|
+
// Load gateway configuration if specified
|
|
2192
|
+
let gatewayData;
|
|
2193
|
+
if (gateway) {
|
|
2194
|
+
let gatewayObject = new Gateway({ gateway, redis: this.redis, secret: this.secret });
|
|
2195
|
+
try {
|
|
2196
|
+
gatewayData = await gatewayObject.loadGatewayData();
|
|
2197
|
+
} catch (err) {
|
|
2198
|
+
this.logger.info({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
|
|
2115
2199
|
}
|
|
2116
2200
|
}
|
|
2117
2201
|
|
|
2118
|
-
|
|
2202
|
+
// Verify SMTP capability
|
|
2203
|
+
if (!accountData.smtp && !accountData.oauth2 && !gatewayData) {
|
|
2204
|
+
// can not make connection
|
|
2205
|
+
let err = new Error('SMTP configuration not found');
|
|
2206
|
+
err.code = 'SMTPUnavailable';
|
|
2207
|
+
err.statusCode = 404;
|
|
2208
|
+
throw err;
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
return await this.pushMessageToQueue({ data, meta, raw, hasBcc, envelope, messageId, subject, sendAt, deliveryAttempts, gatewayData, draft });
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
/**
|
|
2215
|
+
* Resolves a stored draft message for sending. Implemented by subclasses.
|
|
2216
|
+
* Must verify that the message exists and is a draft, and return its raw content
|
|
2217
|
+
* together with the draft reference that is stored in the queue entry. May also
|
|
2218
|
+
* report the thread the draft belongs to (Gmail).
|
|
2219
|
+
* @param {string} id - API message id of the draft
|
|
2220
|
+
* @param {Object} connectionOptions - Connection options
|
|
2221
|
+
* @returns {Object} { raw: Buffer, draft: { message [, draftId] }, threadId? }
|
|
2222
|
+
*/
|
|
2223
|
+
async resolveDraftForSubmit() {
|
|
2224
|
+
let err = new Error('Draft submission not supported for this account type');
|
|
2225
|
+
err.code = 'UnsupportedOperation';
|
|
2226
|
+
err.statusCode = 400;
|
|
2227
|
+
throw err;
|
|
2119
2228
|
}
|
|
2120
2229
|
|
|
2121
2230
|
/**
|
|
@@ -2736,10 +2845,7 @@ class BaseClient {
|
|
|
2736
2845
|
let notifyWebSafeHtml = await settings.get('notifyWebSafeHtml');
|
|
2737
2846
|
if (notifyWebSafeHtml && messageData.text && (messageData.text.html || messageData.text.plain)) {
|
|
2738
2847
|
// convert to web safe
|
|
2739
|
-
messageData.text._generatedHtml =
|
|
2740
|
-
html: messageData.text.html,
|
|
2741
|
-
text: messageData.text.plain
|
|
2742
|
-
});
|
|
2848
|
+
messageData.text._generatedHtml = await messageWebSafeHtml(messageData);
|
|
2743
2849
|
|
|
2744
2850
|
// embed inline images as data URIs
|
|
2745
2851
|
if (messageData.text.html && messageData.attachments) {
|
|
@@ -3069,18 +3175,31 @@ class BaseClient {
|
|
|
3069
3175
|
}
|
|
3070
3176
|
|
|
3071
3177
|
// Handle sent mail copy to folder
|
|
3072
|
-
const
|
|
3178
|
+
const copyDeciderInputs = {
|
|
3073
3179
|
accountData,
|
|
3074
3180
|
data,
|
|
3075
3181
|
isGmail: this.isGmail,
|
|
3076
3182
|
isOutlook: this.isOutlook,
|
|
3077
3183
|
gatewayData
|
|
3078
|
-
}
|
|
3184
|
+
};
|
|
3185
|
+
const shouldCopy = SentMailCopyDecider.shouldCopy(copyDeciderInputs);
|
|
3079
3186
|
|
|
3080
3187
|
const connectionOptions = { allowSecondary: true };
|
|
3081
3188
|
|
|
3082
|
-
|
|
3083
|
-
|
|
3189
|
+
const sentCopySucceeded = shouldCopy ? await this.uploadToSentFolder(raw, data, queueId, messageId, connectionOptions) : false;
|
|
3190
|
+
|
|
3191
|
+
// Remove the submitted draft. Delete it permanently when a copy of the message
|
|
3192
|
+
// exists in the Sent Mail folder - either uploaded above, or filed by the provider
|
|
3193
|
+
// itself (Gmail and Outlook store SMTP-sent messages on their own, which is also
|
|
3194
|
+
// why the upload is suppressed for them). Otherwise move the draft to Trash so the
|
|
3195
|
+
// content is not lost
|
|
3196
|
+
if (data.draft) {
|
|
3197
|
+
await this.cleanupSubmittedDraft(data.draft, {
|
|
3198
|
+
permanent: sentCopySucceeded || SentMailCopyDecider.providerSavesSentCopy(copyDeciderInputs),
|
|
3199
|
+
queueId,
|
|
3200
|
+
messageId,
|
|
3201
|
+
connectionOptions
|
|
3202
|
+
});
|
|
3084
3203
|
}
|
|
3085
3204
|
|
|
3086
3205
|
// Update reference flags if needed
|
|
@@ -3121,6 +3240,7 @@ class BaseClient {
|
|
|
3121
3240
|
* @param {string} queueId - Queue ID for logging
|
|
3122
3241
|
* @param {string} messageId - Message ID for logging
|
|
3123
3242
|
* @param {Object} connectionOptions - IMAP connection options
|
|
3243
|
+
* @returns {boolean} Whether the message was stored in the Sent folder
|
|
3124
3244
|
*/
|
|
3125
3245
|
async uploadToSentFolder(raw, data, queueId, messageId, connectionOptions) {
|
|
3126
3246
|
try {
|
|
@@ -3142,10 +3262,32 @@ class BaseClient {
|
|
|
3142
3262
|
this.logger.error({ msg: 'IDLE error', err });
|
|
3143
3263
|
});
|
|
3144
3264
|
}
|
|
3265
|
+
|
|
3266
|
+
return true;
|
|
3145
3267
|
}
|
|
3146
3268
|
} catch (err) {
|
|
3147
3269
|
this.logger.error({ msg: 'Failed to upload Sent mail', queueId, messageId, err });
|
|
3148
3270
|
}
|
|
3271
|
+
|
|
3272
|
+
return false;
|
|
3273
|
+
}
|
|
3274
|
+
|
|
3275
|
+
/**
|
|
3276
|
+
* Removes a draft message after it was successfully submitted. Failures are logged
|
|
3277
|
+
* only - the message has already been sent, so the job must not fail or retry.
|
|
3278
|
+
* @param {Object} draft - Draft reference from the queue entry ({ message })
|
|
3279
|
+
* @param {Object} options
|
|
3280
|
+
* @param {boolean} options.permanent - Delete permanently instead of moving to Trash
|
|
3281
|
+
* @param {string} options.queueId - Queue ID for logging
|
|
3282
|
+
* @param {string} options.messageId - Message ID for logging
|
|
3283
|
+
* @param {Object} options.connectionOptions - IMAP connection options
|
|
3284
|
+
*/
|
|
3285
|
+
async cleanupSubmittedDraft(draft, { permanent, queueId, messageId, connectionOptions }) {
|
|
3286
|
+
try {
|
|
3287
|
+
await this.deleteMessage(draft.message, permanent, connectionOptions);
|
|
3288
|
+
} catch (err) {
|
|
3289
|
+
this.logger.error({ msg: 'Failed to remove submitted draft', queueId, messageId, draft: draft.message, err });
|
|
3290
|
+
}
|
|
3149
3291
|
}
|
|
3150
3292
|
|
|
3151
3293
|
/**
|
|
@@ -66,4 +66,19 @@ function buildSendRequest(raw, threadId) {
|
|
|
66
66
|
};
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
-
|
|
69
|
+
/**
|
|
70
|
+
* Builds the Gmail request that sends an existing draft resource. Gmail moves the message
|
|
71
|
+
* from Drafts to Sent itself, so no cleanup call is needed afterwards.
|
|
72
|
+
*
|
|
73
|
+
* @param {String} draftId - Gmail draft resource id (NOT the message id)
|
|
74
|
+
* @returns {Object} { targetEndpoint, contentType, payload } - endpoint is relative to GMAIL_API_BASE
|
|
75
|
+
*/
|
|
76
|
+
function buildDraftSendRequest(draftId) {
|
|
77
|
+
return {
|
|
78
|
+
targetEndpoint: `/gmail/v1/users/me/drafts/send`,
|
|
79
|
+
contentType: 'application/json',
|
|
80
|
+
payload: { id: draftId }
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
module.exports = { buildSendRequest, buildDraftSendRequest, JSON_SEND_LIMIT };
|
|
@@ -9,7 +9,7 @@ const addressparser = require('nodemailer/lib/addressparser');
|
|
|
9
9
|
const libmime = require('libmime');
|
|
10
10
|
const he = require('he');
|
|
11
11
|
const { BaseClient, metricsMeta } = require('./base-client');
|
|
12
|
-
const {
|
|
12
|
+
const { messageWebSafeHtml } = require('../web-safe-html');
|
|
13
13
|
const { emitChangeEvent } = require('../tools');
|
|
14
14
|
const { Gateway } = require('../gateway');
|
|
15
15
|
|
|
@@ -27,7 +27,7 @@ const {
|
|
|
27
27
|
const settings = require('../settings');
|
|
28
28
|
|
|
29
29
|
const { GMAIL_API_BASE, LIST_BATCH_SIZE, request: gmailApiRequest, executeBatchRequests } = require('./gmail/gmail-api');
|
|
30
|
-
const { buildSendRequest } = require('./gmail/send-request');
|
|
30
|
+
const { buildSendRequest, buildDraftSendRequest } = require('./gmail/send-request');
|
|
31
31
|
|
|
32
32
|
const MAX_GMAIL_BATCH_SIZE = 50;
|
|
33
33
|
|
|
@@ -69,6 +69,22 @@ function toGmailLabelId(label) {
|
|
|
69
69
|
return SYSTEM_LABELS_REV.hasOwnProperty(label) ? SYSTEM_LABELS_REV[label] : label;
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
+
// Extract the Message-ID header value (including angle brackets) from a raw RFC822 message,
|
|
73
|
+
// tolerating folded headers. Returns null if the message has no Message-ID header.
|
|
74
|
+
function extractMessageIdHeader(raw) {
|
|
75
|
+
let headerEnd = raw.indexOf('\r\n\r\n');
|
|
76
|
+
if (headerEnd < 0) {
|
|
77
|
+
headerEnd = raw.indexOf('\n\n');
|
|
78
|
+
}
|
|
79
|
+
let headerBlock = raw
|
|
80
|
+
.subarray(0, headerEnd >= 0 ? headerEnd : raw.length)
|
|
81
|
+
.toString()
|
|
82
|
+
// unfold wrapped header lines
|
|
83
|
+
.replace(/\r?\n[ \t]+/g, ' ');
|
|
84
|
+
let match = headerBlock.match(/^Message-ID:\s*(<[^>]+>)/im);
|
|
85
|
+
return match ? match[1] : null;
|
|
86
|
+
}
|
|
87
|
+
|
|
72
88
|
// Timing constants for Gmail Pub/Sub watch
|
|
73
89
|
const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h - how often to check if watch needs renewal
|
|
74
90
|
const MIN_WATCH_TTL = 24 * 3600 * 1000; // 1day - minimum time before renewing watch
|
|
@@ -1300,10 +1316,7 @@ class GmailClient extends BaseClient {
|
|
|
1300
1316
|
|
|
1301
1317
|
// Generate web-safe HTML if requested
|
|
1302
1318
|
if (options.preProcessHtml && formattedMessage.text && (formattedMessage.text.html || formattedMessage.text.plain)) {
|
|
1303
|
-
formattedMessage.text.html =
|
|
1304
|
-
html: formattedMessage.text.html,
|
|
1305
|
-
text: formattedMessage.text.plain
|
|
1306
|
-
});
|
|
1319
|
+
formattedMessage.text.html = await messageWebSafeHtml(formattedMessage);
|
|
1307
1320
|
formattedMessage.text.webSafe = true;
|
|
1308
1321
|
}
|
|
1309
1322
|
|
|
@@ -1539,6 +1552,64 @@ class GmailClient extends BaseClient {
|
|
|
1539
1552
|
return response;
|
|
1540
1553
|
}
|
|
1541
1554
|
|
|
1555
|
+
/**
|
|
1556
|
+
* Resolves a stored draft message for sending
|
|
1557
|
+
* Verifies that the message carries the DRAFT label, downloads its raw content and
|
|
1558
|
+
* looks up the Gmail draft resource id so the delivery step can use drafts.send
|
|
1559
|
+
* @param {string} emailId - Gmail message id of the draft
|
|
1560
|
+
* @returns {Object} { raw: Buffer, draft: { message, draftId }, threadId }
|
|
1561
|
+
*/
|
|
1562
|
+
async resolveDraftForSubmit(emailId) {
|
|
1563
|
+
await this.prepare();
|
|
1564
|
+
|
|
1565
|
+
// A single format=raw fetch provides the label check, the thread id and the raw content
|
|
1566
|
+
let messageData;
|
|
1567
|
+
try {
|
|
1568
|
+
messageData = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${emailId}`, 'get', { format: 'raw' });
|
|
1569
|
+
} catch (err) {
|
|
1570
|
+
if (err?.oauthRequest?.status === 404 || err?.oauthRequest?.response?.error?.code === 404) {
|
|
1571
|
+
let error = new Error('Requested message was not found');
|
|
1572
|
+
error.code = 'MessageNotFound';
|
|
1573
|
+
error.statusCode = 404;
|
|
1574
|
+
throw error;
|
|
1575
|
+
}
|
|
1576
|
+
throw err;
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
if (!messageData?.labelIds?.includes('DRAFT')) {
|
|
1580
|
+
let err = new Error('Requested message is not a draft');
|
|
1581
|
+
err.code = 'MessageNotDraft';
|
|
1582
|
+
err.statusCode = 400;
|
|
1583
|
+
throw err;
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
let raw = messageData?.raw ? Buffer.from(messageData.raw, 'base64url') : null;
|
|
1587
|
+
if (!raw) {
|
|
1588
|
+
let err = new Error('Requested message was not found');
|
|
1589
|
+
err.code = 'MessageNotFound';
|
|
1590
|
+
err.statusCode = 404;
|
|
1591
|
+
throw err;
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
// Find the draft resource that wraps this message (Gmail wraps every DRAFT-labeled
|
|
1595
|
+
// message in one, even messages.insert uploads). The lookup can still come up empty -
|
|
1596
|
+
// no Message-ID header, or the rfc822msgid search index lagging behind a fresh upload -
|
|
1597
|
+
// and such a message is sent as a raw copy instead of drafts.send at delivery time
|
|
1598
|
+
let draftId = null;
|
|
1599
|
+
let messageIdHeader = extractMessageIdHeader(raw);
|
|
1600
|
+
if (messageIdHeader) {
|
|
1601
|
+
try {
|
|
1602
|
+
let listing = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/drafts`, 'get', { q: `rfc822msgid:${messageIdHeader}` });
|
|
1603
|
+
draftId = listing?.drafts?.find(draftEntry => draftEntry?.message?.id === emailId)?.id || null;
|
|
1604
|
+
} catch (err) {
|
|
1605
|
+
// draft id resolution is best effort - fall back to sending the raw copy
|
|
1606
|
+
this.logger.info({ msg: 'Failed to resolve Gmail draft id', emailId, err });
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
return { raw, draft: { message: emailId, draftId }, threadId: messageData?.threadId };
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1542
1613
|
/**
|
|
1543
1614
|
* Sends a message via Gmail API or SMTP gateway
|
|
1544
1615
|
* @param {Object} data - Message data
|
|
@@ -1591,12 +1662,22 @@ class GmailClient extends BaseClient {
|
|
|
1591
1662
|
return false;
|
|
1592
1663
|
}
|
|
1593
1664
|
|
|
1594
|
-
//
|
|
1595
|
-
//
|
|
1596
|
-
|
|
1665
|
+
// A resolved draft is sent through drafts.send (Gmail moves the message from Drafts to
|
|
1666
|
+
// Sent itself); everything else goes out as a raw message - endpoint, content type and
|
|
1667
|
+
// payload encoding then depend on message size and threading, see
|
|
1668
|
+
// lib/email-client/gmail/send-request.js
|
|
1669
|
+
const { targetEndpoint, contentType, payload } = data.draft?.draftId
|
|
1670
|
+
? buildDraftSendRequest(data.draft.draftId)
|
|
1671
|
+
: buildSendRequest(raw, data?.reference?.threadId);
|
|
1597
1672
|
|
|
1598
|
-
// Send via Gmail API
|
|
1599
1673
|
const submitInfo = await this.request(`${GMAIL_API_BASE}${targetEndpoint}`, 'post', payload, { contentType });
|
|
1674
|
+
|
|
1675
|
+
if (data.draft && !data.draft.draftId) {
|
|
1676
|
+
// The draft resource could not be resolved at queue time, so the draft was sent as
|
|
1677
|
+
// a raw copy - remove the original draft message (the Gmail API can only move it
|
|
1678
|
+
// to Trash)
|
|
1679
|
+
await this.cleanupSubmittedDraft(data.draft, { permanent: false, queueId, messageId });
|
|
1680
|
+
}
|
|
1600
1681
|
/*
|
|
1601
1682
|
SEND RESPONSE {
|
|
1602
1683
|
id: '18f85d2eb6adb232',
|