emailengine-app 2.75.0 → 2.77.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/release.yaml +24 -19
- package/.github/workflows/test.yml +0 -10
- package/.ncurc.js +14 -2
- package/.release-please-manifest.json +3 -0
- package/CHANGELOG.md +38 -0
- package/README.md +1 -1
- package/config/e2e.toml +1 -1
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +71 -4
- package/lib/address-strategies.js +18 -0
- package/lib/api-reference/code-samples.js +194 -0
- package/lib/api-reference/format.js +179 -0
- package/lib/api-reference/index.js +205 -0
- package/lib/api-reference/model.js +336 -0
- package/lib/api-reference/schema-tree.js +366 -0
- package/lib/api-routes/account-routes.js +117 -37
- package/lib/api-routes/behavior-notes.js +54 -0
- package/lib/api-routes/blocklist-routes.js +9 -9
- package/lib/api-routes/changes-routes.js +6 -4
- package/lib/api-routes/chat-routes.js +3 -3
- package/lib/api-routes/delivery-test-routes.js +24 -6
- package/lib/api-routes/export-routes.js +14 -12
- package/lib/api-routes/gateway-routes.js +11 -11
- package/lib/api-routes/license-routes.js +7 -7
- package/lib/api-routes/mailbox-routes.js +18 -9
- package/lib/api-routes/message-routes.js +55 -35
- package/lib/api-routes/oauth2-app-routes.js +22 -16
- package/lib/api-routes/outbox-routes.js +7 -7
- package/lib/api-routes/pubsub-routes.js +3 -3
- package/lib/api-routes/route-helpers.js +3 -0
- package/lib/api-routes/settings-routes.js +10 -9
- package/lib/api-routes/stats-routes.js +3 -3
- package/lib/api-routes/submit-routes.js +213 -56
- package/lib/api-routes/template-routes.js +13 -13
- package/lib/api-routes/token-routes.js +15 -10
- package/lib/api-routes/webhook-route-routes.js +5 -5
- package/lib/consts.js +7 -0
- package/lib/email-client/base-client.js +230 -31
- package/lib/email-client/gmail/send-request.js +16 -1
- package/lib/email-client/gmail-client.js +89 -5
- package/lib/email-client/imap-client.js +103 -1
- package/lib/email-client/message-builder.js +24 -7
- package/lib/email-client/outlook/send-request.js +18 -1
- package/lib/email-client/outlook-client.js +79 -4
- package/lib/enum-descriptions.js +130 -0
- package/lib/imapproxy/imap-server.js +30 -26
- package/lib/imapproxy/upstream-client.js +38 -0
- package/lib/oauth2-apps.js +9 -3
- package/lib/openapi/build-document.js +318 -0
- package/lib/openapi/index.js +95 -0
- package/lib/openapi/joi-schema.js +523 -0
- package/lib/routes-ui.js +5 -1
- package/lib/schemas.js +76 -17
- package/lib/swagger-options.js +173 -0
- package/lib/tokens.js +69 -5
- package/lib/ui-routes/admin-entities-routes.js +3 -0
- package/lib/ui-routes/dashboard-routes.js +2 -26
- package/lib/ui-routes/reference-routes.js +195 -0
- package/lib/ui-routes/route-helpers.js +11 -0
- package/package.json +19 -26
- package/playwright.config.js +1 -1
- package/prepare-bundle-deps.sh +28 -0
- package/release-please-config.json +11 -0
- package/sbom.json +0 -1
- package/server.js +22 -2
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +90 -0
- package/static/js/ee-client.js +238 -8
- package/static/js/reference.js +736 -0
- package/static/js/ui.js +61 -33
- package/static/licenses.html +16 -16
- package/translations/messages.pot +13 -13
- package/views/config/ai.hbs +1 -1
- package/views/config/document-store/chat.hbs +5 -5
- package/views/config/document-store/index.hbs +2 -2
- package/views/config/document-store/pre-processing/index.hbs +1 -1
- package/views/config/email-processing.hbs +1 -1
- package/views/config/imap-proxy.hbs +1 -1
- package/views/config/license.hbs +1 -1
- package/views/config/oauth/index.hbs +3 -3
- package/views/config/security.hbs +1 -1
- package/views/config/smtp.hbs +2 -2
- package/views/dashboard.hbs +1 -1
- package/views/layout/app.hbs +18 -7
- package/views/partials/oauth_form.hbs +4 -4
- package/views/partials/reference/anchor-link.hbs +20 -0
- package/views/partials/reference/disclosure.hbs +37 -0
- package/views/partials/reference/nav.hbs +93 -0
- package/views/partials/reference/operation.hbs +127 -0
- package/views/partials/reference/params.hbs +20 -0
- package/views/partials/reference/schema-node.hbs +99 -0
- package/views/partials/reference/schema.hbs +19 -0
- package/views/partials/reference/section-heading.hbs +16 -0
- package/views/partials/reference/token-alert.hbs +24 -0
- package/views/partials/reference/try-field.hbs +31 -0
- package/views/partials/reference/try-it.hbs +78 -0
- package/views/partials/side_menu.hbs +1 -1
- package/views/partials/ui/badge.hbs +4 -2
- package/views/partials/ui/page-header.hbs +1 -1
- package/views/partials/ui/search-input.hbs +31 -0
- package/views/partials/ui/setting-ref.hbs +1 -1
- package/views/partials/ui/stat-card.hbs +4 -2
- package/views/partials/ui/tab.hbs +6 -1
- package/views/partials/ui/tabs.hbs +2 -2
- package/views/reference/index.hbs +76 -0
- package/views/reference/redirect.hbs +49 -0
- package/views/reference/tag.hbs +28 -0
- package/views/reference/token.hbs +49 -0
- package/views/tokens/index.hbs +9 -1
- package/views/webhooks/index.hbs +3 -3
- package/workers/api.js +37 -215
- package/Gruntfile.js +0 -58
- package/views/swagger/index.hbs +0 -82
|
@@ -49,7 +49,8 @@ const {
|
|
|
49
49
|
readEnvValue,
|
|
50
50
|
emitChangeEvent,
|
|
51
51
|
filterEmptyObjectValues,
|
|
52
|
-
getDateBuckets
|
|
52
|
+
getDateBuckets,
|
|
53
|
+
resolveCredentials
|
|
53
54
|
} = require('../tools');
|
|
54
55
|
|
|
55
56
|
// Import application constants
|
|
@@ -79,6 +80,25 @@ const MAX_IMAP_AUTH_FAILURE_TIME = getDuration(readEnvValue('EENGINE_MAX_IMAP_AU
|
|
|
79
80
|
// Map to track pending idempotency operations to prevent duplicate processing
|
|
80
81
|
const pendingIdempotencyOperations = new Map();
|
|
81
82
|
|
|
83
|
+
// Failing to reach a remote endpoint is a connection problem, not a rejected credential. Both
|
|
84
|
+
// OAuth2 credential sources (EmailEngine's own token refresh and an external authentication server)
|
|
85
|
+
// use this to avoid reporting an unreachable host as an authentication error, which would webhook
|
|
86
|
+
// and park every account on the instance over a brief outage.
|
|
87
|
+
const TRANSIENT_CONNECT_CODES = new Set([
|
|
88
|
+
'ENOTFOUND',
|
|
89
|
+
'ETIMEDOUT',
|
|
90
|
+
'ECONNREFUSED',
|
|
91
|
+
'ECONNRESET',
|
|
92
|
+
'EAI_AGAIN',
|
|
93
|
+
'UND_ERR_CONNECT_TIMEOUT',
|
|
94
|
+
'UND_ERR_SOCKET',
|
|
95
|
+
'UND_ERR_HEADERS_TIMEOUT'
|
|
96
|
+
]);
|
|
97
|
+
|
|
98
|
+
function isTransientNetworkError(err) {
|
|
99
|
+
return !!err && TRANSIENT_CONNECT_CODES.has(err.code);
|
|
100
|
+
}
|
|
101
|
+
|
|
82
102
|
/**
|
|
83
103
|
* Check if an error is a transient error that should be retried
|
|
84
104
|
* @param {Error} err - The error to check
|
|
@@ -558,6 +578,50 @@ class BaseClient {
|
|
|
558
578
|
throw error;
|
|
559
579
|
}
|
|
560
580
|
|
|
581
|
+
// An external authentication server owns this account's tokens, so EmailEngine must ask for
|
|
582
|
+
// one instead of renewing from a stored refresh token (it has none). The app is still
|
|
583
|
+
// resolved above, because the caller needs it for the provider's host and port.
|
|
584
|
+
if (accountData.oauth2.useAuthServer) {
|
|
585
|
+
try {
|
|
586
|
+
let authData = await resolveCredentials(accountObject.account, target);
|
|
587
|
+
// The auth server owns the credentials, but a shared mailbox is still addressed by
|
|
588
|
+
// the configured delegatedUser - same precedence as the stored-token path above.
|
|
589
|
+
return {
|
|
590
|
+
oauth2User: accountData.oauth2.auth.delegatedUser || authData.user,
|
|
591
|
+
accessToken: authData.accessToken,
|
|
592
|
+
oauth2App
|
|
593
|
+
};
|
|
594
|
+
} catch (err) {
|
|
595
|
+
// A transient failure to reach the auth server is a connection problem, not a
|
|
596
|
+
// rejected credential. Reporting it as an authentication error would webhook every
|
|
597
|
+
// account on the instance and park them in an error state over a brief blip.
|
|
598
|
+
if (isTransientNetworkError(err)) {
|
|
599
|
+
ctx.logger.error({
|
|
600
|
+
msg: 'Network error while resolving credentials from the authentication server',
|
|
601
|
+
account: accountObject.account,
|
|
602
|
+
target,
|
|
603
|
+
code: err.code,
|
|
604
|
+
err
|
|
605
|
+
});
|
|
606
|
+
throw err;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
err.authenticationFailed = true;
|
|
610
|
+
await ctx.notify(false, AUTH_ERROR_NOTIFY, {
|
|
611
|
+
response: err.message,
|
|
612
|
+
serverResponseCode: 'HTTPRequestError'
|
|
613
|
+
});
|
|
614
|
+
ctx.logger.error({
|
|
615
|
+
msg: 'Failed to resolve OAuth2 credentials from the authentication server',
|
|
616
|
+
account: accountObject.account,
|
|
617
|
+
target,
|
|
618
|
+
err
|
|
619
|
+
});
|
|
620
|
+
ctx.state = AUTH_ERROR_NOTIFY;
|
|
621
|
+
throw err;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
561
625
|
// Check if token needs refresh (with 30 second buffer)
|
|
562
626
|
if (!accountData.oauth2.accessToken || !accountData.oauth2.expires || accountData.oauth2.expires < new Date(now + 30 * 1000)) {
|
|
563
627
|
// renew access token
|
|
@@ -569,17 +633,7 @@ class BaseClient {
|
|
|
569
633
|
accessToken = accountData.oauth2.accessToken;
|
|
570
634
|
} catch (err) {
|
|
571
635
|
// Transient network errors are not authentication failures
|
|
572
|
-
|
|
573
|
-
err.code === 'ENOTFOUND' ||
|
|
574
|
-
err.code === 'ETIMEDOUT' ||
|
|
575
|
-
err.code === 'ECONNREFUSED' ||
|
|
576
|
-
err.code === 'ECONNRESET' ||
|
|
577
|
-
err.code === 'EAI_AGAIN' ||
|
|
578
|
-
err.code === 'UND_ERR_CONNECT_TIMEOUT' ||
|
|
579
|
-
err.code === 'UND_ERR_SOCKET' ||
|
|
580
|
-
err.code === 'UND_ERR_HEADERS_TIMEOUT';
|
|
581
|
-
|
|
582
|
-
if (isNetworkError) {
|
|
636
|
+
if (isTransientNetworkError(err)) {
|
|
583
637
|
ctx.logger.error({
|
|
584
638
|
msg: 'Network error during OAuth2 token refresh',
|
|
585
639
|
account: accountObject.account,
|
|
@@ -882,6 +936,13 @@ class BaseClient {
|
|
|
882
936
|
async queueMessageHandler(data, meta, connectionOptions) {
|
|
883
937
|
let accountData = await this.accountObject.loadAccountData();
|
|
884
938
|
|
|
939
|
+
// Submitting a stored draft skips content processing - the message body already exists.
|
|
940
|
+
// The draft path owns its own gateway load and SMTP-capability check (the effective
|
|
941
|
+
// gateway is only known after the draft's X-EE-* headers have been parsed)
|
|
942
|
+
if (meta && meta.draft) {
|
|
943
|
+
return this.queueDraftEntry(data, meta, accountData, connectionOptions);
|
|
944
|
+
}
|
|
945
|
+
|
|
885
946
|
// Load gateway configuration if specified
|
|
886
947
|
let gatewayData;
|
|
887
948
|
let gatewayObject;
|
|
@@ -2004,6 +2065,44 @@ class BaseClient {
|
|
|
2004
2065
|
});
|
|
2005
2066
|
}
|
|
2006
2067
|
|
|
2068
|
+
// Store the message in the queue and schedule the submit job
|
|
2069
|
+
let response = await this.pushMessageToQueue({ data, meta, raw, hasBcc, envelope, messageId, subject, sendAt, deliveryAttempts, gatewayData });
|
|
2070
|
+
|
|
2071
|
+
if (data.reference && (data.reference.message || data.reference.threadId)) {
|
|
2072
|
+
response.reference = {};
|
|
2073
|
+
if (data.reference.message) {
|
|
2074
|
+
response.reference.message = data.reference.message;
|
|
2075
|
+
response.reference.documentStore = documentStoreUsed;
|
|
2076
|
+
response.reference.success = referencedMessage ? true : false;
|
|
2077
|
+
if (!referencedMessage) {
|
|
2078
|
+
response.reference.error = 'Referenced message was not found';
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
if (data.reference.threadId) {
|
|
2082
|
+
response.reference.threadId = data.reference.threadId;
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
return response;
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
/**
|
|
2090
|
+
* Stores an outbound message in the delivery queue and schedules the submit job
|
|
2091
|
+
* @param {Object} params
|
|
2092
|
+
* @param {Object} params.data - Message data (copy, sentMailPath, feedbackKey, dsn, proxy, localAddress, reference)
|
|
2093
|
+
* @param {Object} params.meta - Metadata for the queue job
|
|
2094
|
+
* @param {Buffer} params.raw - Raw RFC822 message
|
|
2095
|
+
* @param {boolean} params.hasBcc - Whether the raw message carries a Bcc header
|
|
2096
|
+
* @param {Object} params.envelope - SMTP envelope
|
|
2097
|
+
* @param {string} params.messageId - Message-ID header value
|
|
2098
|
+
* @param {string} params.subject - Message subject for queue listings
|
|
2099
|
+
* @param {Date} [params.sendAt] - Scheduled send time
|
|
2100
|
+
* @param {number} [params.deliveryAttempts] - Delivery attempt count override
|
|
2101
|
+
* @param {Object} [params.gatewayData] - Loaded gateway data
|
|
2102
|
+
* @param {Object} [params.draft] - Draft reference if the queued message is a stored draft
|
|
2103
|
+
* @returns {Object} Base queue response
|
|
2104
|
+
*/
|
|
2105
|
+
async pushMessageToQueue({ data, meta, raw, hasBcc, envelope, messageId, subject, sendAt, deliveryAttempts, gatewayData, draft }) {
|
|
2007
2106
|
let now = new Date();
|
|
2008
2107
|
|
|
2009
2108
|
//queue for later
|
|
@@ -2025,6 +2124,7 @@ class BaseClient {
|
|
|
2025
2124
|
envelope,
|
|
2026
2125
|
messageId,
|
|
2027
2126
|
reference: data.reference || {},
|
|
2127
|
+
draft: draft || null,
|
|
2028
2128
|
sendAt: (sendAt && sendAt.getTime()) || false,
|
|
2029
2129
|
created: now.getTime(),
|
|
2030
2130
|
copy: data.copy,
|
|
@@ -2092,30 +2192,93 @@ class BaseClient {
|
|
|
2092
2192
|
|
|
2093
2193
|
this.logger.info({ msg: 'Message queued for delivery', envelope, messageId, sendAt: (sendAt || now).toISOString(), queueId, job: job.id });
|
|
2094
2194
|
|
|
2095
|
-
|
|
2096
|
-
let response = {
|
|
2195
|
+
return {
|
|
2097
2196
|
response: 'Queued for delivery',
|
|
2098
2197
|
messageId,
|
|
2099
2198
|
sendAt: (sendAt || now).toISOString(),
|
|
2100
2199
|
queueId
|
|
2101
2200
|
};
|
|
2201
|
+
}
|
|
2102
2202
|
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2203
|
+
/**
|
|
2204
|
+
* Queues an existing draft message for delivery. The draft is resolved through the
|
|
2205
|
+
* backend-specific resolveDraftForSubmit(), its raw content is stored in the queue entry
|
|
2206
|
+
* (used by the SMTP and gateway delivery paths), and a draft reference travels along so
|
|
2207
|
+
* the delivery step can use the provider's native draft-send call and clean up the draft.
|
|
2208
|
+
* @param {Object} data - Submit options ({ envelope, sendAt, ... })
|
|
2209
|
+
* @param {Object} meta - Metadata carrying the draft marker ({ draft: { message } })
|
|
2210
|
+
* @param {Object} accountData - Already loaded account data
|
|
2211
|
+
* @param {Object} connectionOptions - Connection options
|
|
2212
|
+
* @returns {Object} Queue response
|
|
2213
|
+
*/
|
|
2214
|
+
async queueDraftEntry(data, meta, accountData, connectionOptions) {
|
|
2215
|
+
let licenseInfo = await this.call({ cmd: 'license' });
|
|
2216
|
+
|
|
2217
|
+
let { raw: draftRaw, draft, threadId } = await this.resolveDraftForSubmit(meta.draft.message, connectionOptions);
|
|
2218
|
+
|
|
2219
|
+
if (threadId) {
|
|
2220
|
+
// Keep the sent copy in the draft's thread (Gmail API accounts)
|
|
2221
|
+
data.reference = { threadId };
|
|
2222
|
+
}
|
|
2223
|
+
|
|
2224
|
+
// Run the draft through the same raw-message normalization as raw API submissions:
|
|
2225
|
+
// consumes X-EE control headers, applies the envelope override, backfills Message-ID
|
|
2226
|
+
// and Date, detects Bcc and derives the SMTP envelope from the headers
|
|
2227
|
+
let { raw, hasBcc, envelope, subject, messageId, sendAt, deliveryAttempts, gateway } = await getRawEmail(
|
|
2228
|
+
{
|
|
2229
|
+
raw: draftRaw,
|
|
2230
|
+
envelope: data.envelope,
|
|
2231
|
+
sendAt: data.sendAt,
|
|
2232
|
+
deliveryAttempts: data.deliveryAttempts,
|
|
2233
|
+
gateway: data.gateway
|
|
2234
|
+
},
|
|
2235
|
+
licenseInfo
|
|
2236
|
+
);
|
|
2237
|
+
|
|
2238
|
+
if (!envelope.to || !envelope.to.length) {
|
|
2239
|
+
let err = new Error('Draft message has no recipients');
|
|
2240
|
+
err.code = 'DraftHasNoRecipients';
|
|
2241
|
+
err.statusCode = 400;
|
|
2242
|
+
throw err;
|
|
2243
|
+
}
|
|
2244
|
+
|
|
2245
|
+
// Load gateway configuration if specified
|
|
2246
|
+
let gatewayData;
|
|
2247
|
+
if (gateway) {
|
|
2248
|
+
let gatewayObject = new Gateway({ gateway, redis: this.redis, secret: this.secret });
|
|
2249
|
+
try {
|
|
2250
|
+
gatewayData = await gatewayObject.loadGatewayData();
|
|
2251
|
+
} catch (err) {
|
|
2252
|
+
this.logger.info({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
|
|
2115
2253
|
}
|
|
2116
2254
|
}
|
|
2117
2255
|
|
|
2118
|
-
|
|
2256
|
+
// Verify SMTP capability
|
|
2257
|
+
if (!accountData.smtp && !accountData.oauth2 && !gatewayData) {
|
|
2258
|
+
// can not make connection
|
|
2259
|
+
let err = new Error('SMTP configuration not found');
|
|
2260
|
+
err.code = 'SMTPUnavailable';
|
|
2261
|
+
err.statusCode = 404;
|
|
2262
|
+
throw err;
|
|
2263
|
+
}
|
|
2264
|
+
|
|
2265
|
+
return await this.pushMessageToQueue({ data, meta, raw, hasBcc, envelope, messageId, subject, sendAt, deliveryAttempts, gatewayData, draft });
|
|
2266
|
+
}
|
|
2267
|
+
|
|
2268
|
+
/**
|
|
2269
|
+
* Resolves a stored draft message for sending. Implemented by subclasses.
|
|
2270
|
+
* Must verify that the message exists and is a draft, and return its raw content
|
|
2271
|
+
* together with the draft reference that is stored in the queue entry. May also
|
|
2272
|
+
* report the thread the draft belongs to (Gmail).
|
|
2273
|
+
* @param {string} id - API message id of the draft
|
|
2274
|
+
* @param {Object} connectionOptions - Connection options
|
|
2275
|
+
* @returns {Object} { raw: Buffer, draft: { message [, draftId] }, threadId? }
|
|
2276
|
+
*/
|
|
2277
|
+
async resolveDraftForSubmit() {
|
|
2278
|
+
let err = new Error('Draft submission not supported for this account type');
|
|
2279
|
+
err.code = 'UnsupportedOperation';
|
|
2280
|
+
err.statusCode = 400;
|
|
2281
|
+
throw err;
|
|
2119
2282
|
}
|
|
2120
2283
|
|
|
2121
2284
|
/**
|
|
@@ -3066,18 +3229,31 @@ class BaseClient {
|
|
|
3066
3229
|
}
|
|
3067
3230
|
|
|
3068
3231
|
// Handle sent mail copy to folder
|
|
3069
|
-
const
|
|
3232
|
+
const copyDeciderInputs = {
|
|
3070
3233
|
accountData,
|
|
3071
3234
|
data,
|
|
3072
3235
|
isGmail: this.isGmail,
|
|
3073
3236
|
isOutlook: this.isOutlook,
|
|
3074
3237
|
gatewayData
|
|
3075
|
-
}
|
|
3238
|
+
};
|
|
3239
|
+
const shouldCopy = SentMailCopyDecider.shouldCopy(copyDeciderInputs);
|
|
3076
3240
|
|
|
3077
3241
|
const connectionOptions = { allowSecondary: true };
|
|
3078
3242
|
|
|
3079
|
-
|
|
3080
|
-
|
|
3243
|
+
const sentCopySucceeded = shouldCopy ? await this.uploadToSentFolder(raw, data, queueId, messageId, connectionOptions) : false;
|
|
3244
|
+
|
|
3245
|
+
// Remove the submitted draft. Delete it permanently when a copy of the message
|
|
3246
|
+
// exists in the Sent Mail folder - either uploaded above, or filed by the provider
|
|
3247
|
+
// itself (Gmail and Outlook store SMTP-sent messages on their own, which is also
|
|
3248
|
+
// why the upload is suppressed for them). Otherwise move the draft to Trash so the
|
|
3249
|
+
// content is not lost
|
|
3250
|
+
if (data.draft) {
|
|
3251
|
+
await this.cleanupSubmittedDraft(data.draft, {
|
|
3252
|
+
permanent: sentCopySucceeded || SentMailCopyDecider.providerSavesSentCopy(copyDeciderInputs),
|
|
3253
|
+
queueId,
|
|
3254
|
+
messageId,
|
|
3255
|
+
connectionOptions
|
|
3256
|
+
});
|
|
3081
3257
|
}
|
|
3082
3258
|
|
|
3083
3259
|
// Update reference flags if needed
|
|
@@ -3118,6 +3294,7 @@ class BaseClient {
|
|
|
3118
3294
|
* @param {string} queueId - Queue ID for logging
|
|
3119
3295
|
* @param {string} messageId - Message ID for logging
|
|
3120
3296
|
* @param {Object} connectionOptions - IMAP connection options
|
|
3297
|
+
* @returns {boolean} Whether the message was stored in the Sent folder
|
|
3121
3298
|
*/
|
|
3122
3299
|
async uploadToSentFolder(raw, data, queueId, messageId, connectionOptions) {
|
|
3123
3300
|
try {
|
|
@@ -3139,10 +3316,32 @@ class BaseClient {
|
|
|
3139
3316
|
this.logger.error({ msg: 'IDLE error', err });
|
|
3140
3317
|
});
|
|
3141
3318
|
}
|
|
3319
|
+
|
|
3320
|
+
return true;
|
|
3142
3321
|
}
|
|
3143
3322
|
} catch (err) {
|
|
3144
3323
|
this.logger.error({ msg: 'Failed to upload Sent mail', queueId, messageId, err });
|
|
3145
3324
|
}
|
|
3325
|
+
|
|
3326
|
+
return false;
|
|
3327
|
+
}
|
|
3328
|
+
|
|
3329
|
+
/**
|
|
3330
|
+
* Removes a draft message after it was successfully submitted. Failures are logged
|
|
3331
|
+
* only - the message has already been sent, so the job must not fail or retry.
|
|
3332
|
+
* @param {Object} draft - Draft reference from the queue entry ({ message })
|
|
3333
|
+
* @param {Object} options
|
|
3334
|
+
* @param {boolean} options.permanent - Delete permanently instead of moving to Trash
|
|
3335
|
+
* @param {string} options.queueId - Queue ID for logging
|
|
3336
|
+
* @param {string} options.messageId - Message ID for logging
|
|
3337
|
+
* @param {Object} options.connectionOptions - IMAP connection options
|
|
3338
|
+
*/
|
|
3339
|
+
async cleanupSubmittedDraft(draft, { permanent, queueId, messageId, connectionOptions }) {
|
|
3340
|
+
try {
|
|
3341
|
+
await this.deleteMessage(draft.message, permanent, connectionOptions);
|
|
3342
|
+
} catch (err) {
|
|
3343
|
+
this.logger.error({ msg: 'Failed to remove submitted draft', queueId, messageId, draft: draft.message, err });
|
|
3344
|
+
}
|
|
3146
3345
|
}
|
|
3147
3346
|
|
|
3148
3347
|
/**
|
|
@@ -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 };
|
|
@@ -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
|
|
@@ -1536,6 +1552,64 @@ class GmailClient extends BaseClient {
|
|
|
1536
1552
|
return response;
|
|
1537
1553
|
}
|
|
1538
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
|
+
|
|
1539
1613
|
/**
|
|
1540
1614
|
* Sends a message via Gmail API or SMTP gateway
|
|
1541
1615
|
* @param {Object} data - Message data
|
|
@@ -1588,12 +1662,22 @@ class GmailClient extends BaseClient {
|
|
|
1588
1662
|
return false;
|
|
1589
1663
|
}
|
|
1590
1664
|
|
|
1591
|
-
//
|
|
1592
|
-
//
|
|
1593
|
-
|
|
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);
|
|
1594
1672
|
|
|
1595
|
-
// Send via Gmail API
|
|
1596
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
|
+
}
|
|
1597
1681
|
/*
|
|
1598
1682
|
SEND RESPONSE {
|
|
1599
1683
|
id: '18f85d2eb6adb232',
|
|
@@ -26,6 +26,7 @@ const {
|
|
|
26
26
|
readEnvValue,
|
|
27
27
|
validUidValidity,
|
|
28
28
|
getDuration,
|
|
29
|
+
download,
|
|
29
30
|
LRUCache
|
|
30
31
|
} = require('../tools');
|
|
31
32
|
const { getLocalAddress } = require('../utils/network');
|
|
@@ -143,6 +144,14 @@ class IMAPClient extends BaseClient {
|
|
|
143
144
|
// Secondary connection for commands that shouldn't interrupt IDLE
|
|
144
145
|
this.commandClient = null;
|
|
145
146
|
|
|
147
|
+
// The client whose folder listing connect() already fetched and registered a
|
|
148
|
+
// Mailbox for. syncMailboxes() consumes it once to skip a listing refresh that
|
|
149
|
+
// would only re-issue the LIST connect() just ran. Keyed on the client rather
|
|
150
|
+
// than a plain flag so a marker that is never consumed - a setup that finished
|
|
151
|
+
// just as the account was paused - can not make an unrelated later sync, such
|
|
152
|
+
// as an operator-requested one, skip its refresh
|
|
153
|
+
this.listedClient = null;
|
|
154
|
+
|
|
146
155
|
// Flag indicating if mailbox synchronization is in progress
|
|
147
156
|
this.syncing = false;
|
|
148
157
|
|
|
@@ -908,6 +917,13 @@ class IMAPClient extends BaseClient {
|
|
|
908
917
|
// Handle flag changes
|
|
909
918
|
imapClient.on('flags', event => this.handleFlagsEvent(imapClient, event));
|
|
910
919
|
|
|
920
|
+
// The loop above registered a Mailbox for every listed folder, which is what
|
|
921
|
+
// processListing() would have done, so the sync that follows this call has
|
|
922
|
+
// nothing left to discover from a second listing. Keep the two registration
|
|
923
|
+
// paths in step - a filtering rule added to processListing() alone would never
|
|
924
|
+
// be applied during connection setup
|
|
925
|
+
this.listedClient = imapClient;
|
|
926
|
+
|
|
911
927
|
return response;
|
|
912
928
|
}
|
|
913
929
|
|
|
@@ -1179,13 +1195,37 @@ class IMAPClient extends BaseClient {
|
|
|
1179
1195
|
clearTimeout(this.resyncTimer);
|
|
1180
1196
|
clearTimeout(this.completedTimer);
|
|
1181
1197
|
|
|
1198
|
+
// Consumed unconditionally, so every later pass on this connection refreshes as
|
|
1199
|
+
// usual (see the field declaration for why this is keyed on the client)
|
|
1200
|
+
const listingIsFresh = this.listedClient === this.imapClient;
|
|
1201
|
+
this.listedClient = null;
|
|
1202
|
+
|
|
1182
1203
|
if (!this.imapClient || !this.imapClient.usable) {
|
|
1183
1204
|
this.logger.debug({ msg: 'Skipped syncing', reason: 'no imap client' });
|
|
1184
1205
|
return;
|
|
1185
1206
|
}
|
|
1186
1207
|
|
|
1187
1208
|
// Refresh folder list and sync new folders
|
|
1188
|
-
let synced
|
|
1209
|
+
let synced;
|
|
1210
|
+
if (!listingIsFresh) {
|
|
1211
|
+
try {
|
|
1212
|
+
synced = await this.refreshFolderList();
|
|
1213
|
+
} catch (err) {
|
|
1214
|
+
if (!err.responseStatus || !this.imapClient || !this.imapClient.usable || !this.mailboxes.size) {
|
|
1215
|
+
// Only a tagged command failure is tolerated. Network-level errors carry
|
|
1216
|
+
// no responseStatus and keep propagating (same rule as in mailbox.js), a
|
|
1217
|
+
// dead connection has to be re-established, and with no folder tracked
|
|
1218
|
+
// there would be nothing left to sync anyway
|
|
1219
|
+
throw err;
|
|
1220
|
+
}
|
|
1221
|
+
// The refresh only looks for folder changes - the folders already tracked
|
|
1222
|
+
// can be synced without it, and the next pass tries again. Some servers
|
|
1223
|
+
// refuse a repeated LIST on an otherwise healthy session (one Exchange-alike
|
|
1224
|
+
// answers "NO [SERVERBUG]"), and letting that throw used to tear down an
|
|
1225
|
+
// authenticated connection and reconnect on every attempt
|
|
1226
|
+
this.logger.warn({ msg: 'Failed to refresh folder list, syncing known folders', err });
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1189
1229
|
|
|
1190
1230
|
// Sync existing folders that weren't just synced
|
|
1191
1231
|
for (let mailbox of this.mailboxes.values()) {
|
|
@@ -1498,6 +1538,13 @@ class IMAPClient extends BaseClient {
|
|
|
1498
1538
|
this.imapClient = null;
|
|
1499
1539
|
}
|
|
1500
1540
|
|
|
1541
|
+
if (prevImapClient === this.listedClient) {
|
|
1542
|
+
// Only reachable when this start() returns before connect() reassigns
|
|
1543
|
+
// the marker (e.g. an account with no usable credentials). Without it
|
|
1544
|
+
// the closed client stays referenced until some later setup or sync
|
|
1545
|
+
this.listedClient = null;
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1501
1548
|
// The close handler that maintains the connection count was removed
|
|
1502
1549
|
// above, so update the tracking for the replaced client manually
|
|
1503
1550
|
await this.untrackConnection(prevImapClient);
|
|
@@ -2310,6 +2357,61 @@ class IMAPClient extends BaseClient {
|
|
|
2310
2357
|
return mailbox.getAttachment(message, false, options, connectionOptions);
|
|
2311
2358
|
}
|
|
2312
2359
|
|
|
2360
|
+
/**
|
|
2361
|
+
* Resolves a stored draft message for sending
|
|
2362
|
+
* Verifies that the message is a draft and downloads its raw content
|
|
2363
|
+
* @param {string} id - API message id of the draft
|
|
2364
|
+
* @param {Object} connectionOptions - Connection options
|
|
2365
|
+
* @returns {Object} { raw: Buffer, draft: { message } }
|
|
2366
|
+
*/
|
|
2367
|
+
async resolveDraftForSubmit(id, connectionOptions) {
|
|
2368
|
+
connectionOptions = connectionOptions || { allowSecondary: true };
|
|
2369
|
+
|
|
2370
|
+
this.checkIMAPConnection(connectionOptions);
|
|
2371
|
+
|
|
2372
|
+
let buf = Buffer.from(id, 'base64url');
|
|
2373
|
+
let message = await this.unpackUid(buf.subarray(0, 8));
|
|
2374
|
+
if (!message) {
|
|
2375
|
+
let err = new Error('Requested message was not found');
|
|
2376
|
+
err.code = 'MessageNotFound';
|
|
2377
|
+
err.statusCode = 404;
|
|
2378
|
+
throw err;
|
|
2379
|
+
}
|
|
2380
|
+
|
|
2381
|
+
// The message counts as a draft when it is stored in the Drafts folder or carries
|
|
2382
|
+
// the \Draft flag (covers accounts that keep drafts in a non-special-use folder)
|
|
2383
|
+
const inDraftsFolder = this.mailboxes.get(normalizePath(message.path))?.listingEntry?.specialUse === '\\Drafts';
|
|
2384
|
+
if (!inDraftsFolder) {
|
|
2385
|
+
// fetch flags only - nothing else from the message is needed for the check
|
|
2386
|
+
let messageData = await this.getMessage(id, { fields: { uid: true, flags: true } }, connectionOptions);
|
|
2387
|
+
if (!messageData) {
|
|
2388
|
+
let err = new Error('Requested message was not found');
|
|
2389
|
+
err.code = 'MessageNotFound';
|
|
2390
|
+
err.statusCode = 404;
|
|
2391
|
+
throw err;
|
|
2392
|
+
}
|
|
2393
|
+
|
|
2394
|
+
if (!(messageData.flags || []).includes('\\Draft')) {
|
|
2395
|
+
let err = new Error('Requested message is not a draft');
|
|
2396
|
+
err.code = 'MessageNotDraft';
|
|
2397
|
+
err.statusCode = 400;
|
|
2398
|
+
throw err;
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
let rawStream = await this.getRawMessage(id, {}, connectionOptions);
|
|
2403
|
+
if (!rawStream) {
|
|
2404
|
+
let err = new Error('Requested message was not found');
|
|
2405
|
+
err.code = 'MessageNotFound';
|
|
2406
|
+
err.statusCode = 404;
|
|
2407
|
+
throw err;
|
|
2408
|
+
}
|
|
2409
|
+
|
|
2410
|
+
let raw = await download(rawStream);
|
|
2411
|
+
|
|
2412
|
+
return { raw, draft: { message: id } };
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2313
2415
|
/**
|
|
2314
2416
|
* Lists messages in a mailbox with pagination and search
|
|
2315
2417
|
* @param {Object} options - Listing options including path, search criteria, pagination
|