emailengine-app 2.85.0 → 2.86.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/.ncurc.js +24 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +74 -0
- package/Dockerfile +14 -1
- package/ENVIRONMENT.md +139 -0
- package/README.md +1 -1
- package/config/default.toml +2 -0
- package/copy-static-files.sh +4 -2
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +4 -3
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +194 -165
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +78 -26
- package/lib/api-routes/blocklist-routes.js +68 -2
- package/lib/api-routes/delivery-test-routes.js +1 -1
- package/lib/api-routes/gateway-routes.js +82 -10
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +3 -3
- package/lib/api-routes/message-routes.js +15 -7
- package/lib/api-routes/oauth2-app-routes.js +15 -8
- package/lib/api-routes/outbox-routes.js +77 -66
- package/lib/api-routes/permission-map.js +55 -6
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +11 -4
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +4 -3
- package/lib/api-routes/template-routes.js +7 -6
- package/lib/api-routes/token-routes.js +11 -5
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +119 -4
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -46
- package/lib/db.js +14 -6
- package/lib/delivery-error.js +6 -0
- package/lib/deprecations.js +270 -0
- package/lib/email-client/base-client.js +130 -156
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +51 -11
- package/lib/email-client/imap/adaptive-idle-store.js +73 -0
- package/lib/email-client/imap/adaptive-idle.js +278 -0
- package/lib/email-client/imap/connection-errors.js +14 -1
- package/lib/email-client/imap/idle-settings.js +31 -5
- package/lib/email-client/imap/listing-diff.js +37 -0
- package/lib/email-client/imap/mailbox.js +372 -226
- package/lib/email-client/imap/subconnection.js +7 -29
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +227 -163
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/outlook-client.js +372 -338
- package/lib/email-client/smtp-pool-manager.js +16 -13
- package/lib/email-client/sync-state-fields.js +19 -0
- package/lib/encrypt.js +157 -41
- package/lib/enum-descriptions.js +3 -1
- package/lib/env-setting-overrides.js +288 -0
- package/lib/export-worker.js +751 -0
- package/lib/export.js +64 -15
- package/lib/gateway.js +17 -1
- package/lib/get-raw-email.js +25 -107
- package/lib/health.js +75 -0
- package/lib/lock-run.js +119 -0
- package/lib/logger-consts.js +48 -0
- package/lib/logger.js +1 -1
- package/lib/lua/z-head-scores.lua +28 -0
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +20 -1
- package/lib/oauth2-apps.js +630 -655
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/privileged-settings.js +2 -2
- package/lib/queue-browser/definitions.js +11 -0
- package/lib/queue-browser/index.js +68 -19
- package/lib/queue-job-actions.js +18 -1
- package/lib/queue-retention.js +48 -12
- package/lib/queue-stats.js +11 -2
- package/lib/read-env-value.js +3 -0
- package/lib/redis-memory-warnings.js +99 -0
- package/lib/redis-reconnect.js +29 -0
- package/lib/request-timing.js +23 -0
- package/lib/respawn-backoff.js +35 -0
- package/lib/rewrite-text-nodes.js +19 -59
- package/lib/schemas.js +163 -39
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/thread-diagnostics.js +18 -1
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +4 -3
- package/lib/tools.js +8 -41
- package/lib/ui-routes/admin-config-routes.js +64 -90
- package/lib/ui-routes/admin-entities-routes.js +2 -14
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/outlook-subscription-view.js +1 -1
- package/lib/ui-routes/overridable-fields.js +84 -0
- package/lib/ui-routes/queue-routes.js +8 -5
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/utils/decode-headers.js +3 -12
- package/lib/utils/filter-empty.js +20 -0
- package/lib/utils/int-setting.js +48 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/web-safe-html.js +18 -105
- package/lib/webhook-delivery.js +461 -0
- package/lib/webhook-failures.js +132 -0
- package/lib/webhook-request.js +29 -1
- package/lib/webhook-routing.js +30 -1
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +54 -41
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +21 -20
- package/sbom.json +304 -382
- package/server.js +149 -76
- package/static/js/ace/ace.js +1 -1
- package/static/licenses.html +21 -31
- package/translations/messages.pot +26 -26
- package/views/config/security.hbs +22 -0
- package/views/config/service.hbs +44 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/workers/api.js +102 -28
- package/workers/export.js +16 -631
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/webhooks.js +18 -432
- package/lib/email-client/outlook-fallback-poll.js +0 -30
|
@@ -23,7 +23,7 @@ const { credentialErrorStatus, isTransientCredentialError, resolveAuthServerCred
|
|
|
23
23
|
const { parseMessage } = require('../parse-message');
|
|
24
24
|
const libmime = require('libmime');
|
|
25
25
|
const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = require('../bounce-detect');
|
|
26
|
-
const {
|
|
26
|
+
const { collectCalendarEvents } = require('../calendar-event');
|
|
27
27
|
const { llmPreProcess, summaryFetchHeaders, summaryProvider } = require('../llm-pre-process');
|
|
28
28
|
const { notificationHeaderFields, narrowHeaders } = require('../utils/header-map');
|
|
29
29
|
const { mapConcurrent } = require('../utils/map-concurrent');
|
|
@@ -52,13 +52,13 @@ const {
|
|
|
52
52
|
getByteSize,
|
|
53
53
|
readEnvValue,
|
|
54
54
|
emitChangeEvent,
|
|
55
|
-
filterEmptyObjectValues,
|
|
56
55
|
getDateBuckets,
|
|
57
56
|
useAuthServerForOAuth2,
|
|
58
57
|
collectCidReferences,
|
|
59
58
|
embedCidImages
|
|
60
59
|
} = require('../tools');
|
|
61
|
-
const {
|
|
60
|
+
const { loadNotifyAttachments, API_ATTACHMENT_CONCURRENCY } = require('../notify-attachments');
|
|
61
|
+
const { TRACKING_SETTINGS, needsTrackingSettings, resolveTracking } = require('../utils/tracking-settings');
|
|
62
62
|
|
|
63
63
|
// Import application constants
|
|
64
64
|
const {
|
|
@@ -80,9 +80,12 @@ const {
|
|
|
80
80
|
AUTH_FAILURE_DISABLED_DESCRIPTION,
|
|
81
81
|
EMAIL_DELIVERY_ERROR_NOTIFY,
|
|
82
82
|
EMAIL_SENT_NOTIFY,
|
|
83
|
-
CHANGE_EVENT_RETRY_DELAYS
|
|
83
|
+
CHANGE_EVENT_RETRY_DELAYS,
|
|
84
|
+
NEW_MESSAGE_SETTINGS
|
|
84
85
|
} = require('../consts');
|
|
85
86
|
const { buildRetentionPolicy } = require('../queue-retention');
|
|
87
|
+
const { getFailedJobRetention } = require('../env-setting-overrides');
|
|
88
|
+
const outbox = require('../outbox');
|
|
86
89
|
const { readImapData } = require('../account/imap-data');
|
|
87
90
|
const { ReconnectBackoff } = require('./reconnect-backoff');
|
|
88
91
|
|
|
@@ -469,14 +472,56 @@ class BaseClient {
|
|
|
469
472
|
return null;
|
|
470
473
|
}
|
|
471
474
|
|
|
475
|
+
/**
|
|
476
|
+
* Stops syncing for an account flush. The Gmail API and Graph clients hold no connection, so
|
|
477
|
+
* pausing is closing them: timers stop and nothing more is processed until resume()
|
|
478
|
+
*/
|
|
479
|
+
async pause() {
|
|
480
|
+
await this.close();
|
|
481
|
+
return true;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Starts syncing again after a flush. Not awaited, the way IMAPClient.resume() is not: the
|
|
486
|
+
* caller is an RPC with a timeout, and init() can take a token refresh and a subscription
|
|
487
|
+
*/
|
|
472
488
|
async resume() {
|
|
473
|
-
|
|
489
|
+
this.resumeAfterFlush().catch(err => this.logger.error({ msg: 'Resuming failed', action: 'resume', account: this.account, err }));
|
|
490
|
+
return true;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* What resume() starts. A client that has more to do after a flush than reconnect overrides it
|
|
495
|
+
*/
|
|
496
|
+
async resumeAfterFlush() {
|
|
497
|
+
return await this.reconnect();
|
|
474
498
|
}
|
|
475
499
|
|
|
476
500
|
async reconnect() {
|
|
477
501
|
return null;
|
|
478
502
|
}
|
|
479
503
|
|
|
504
|
+
/**
|
|
505
|
+
* The account's connection state, for the connection counts behind /metrics and the
|
|
506
|
+
* dashboard. Answered from memory: the client is the only writer of the stored state after the
|
|
507
|
+
* account is created, so the stored value is this one. The Gmail API and Graph clients used to
|
|
508
|
+
* read it back from Redis instead, one HGET per account every second, one account at a time
|
|
509
|
+
* @returns {Promise<string>}
|
|
510
|
+
*/
|
|
511
|
+
async currentState() {
|
|
512
|
+
return this.state || 'disconnected';
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Removes what the provider keeps on the account's behalf (a Graph subscription, a Gmail Pub/Sub
|
|
517
|
+
* watch). Called while the account record still exists, because the request needs the
|
|
518
|
+
* account's token: once the record is unlinked there is no token left to make it with
|
|
519
|
+
* @returns {Promise<boolean>} True when something was removed
|
|
520
|
+
*/
|
|
521
|
+
async releaseRemoteResources() {
|
|
522
|
+
return false;
|
|
523
|
+
}
|
|
524
|
+
|
|
480
525
|
async getQuota() {
|
|
481
526
|
return false;
|
|
482
527
|
}
|
|
@@ -828,14 +873,6 @@ class BaseClient {
|
|
|
828
873
|
return `${REDIS_PREFIX}iam:${this.account}:g`;
|
|
829
874
|
}
|
|
830
875
|
|
|
831
|
-
getLoggedAccountsKey() {
|
|
832
|
-
return `${REDIS_PREFIX}iaz:logged`;
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
async currentState() {
|
|
836
|
-
return 'connected';
|
|
837
|
-
}
|
|
838
|
-
|
|
839
876
|
/**
|
|
840
877
|
* Creates a logger instance that logs to both main logger and account logger
|
|
841
878
|
* @returns {Object} Synthetic logger that duplicates logs to account storage
|
|
@@ -2609,24 +2646,13 @@ class BaseClient {
|
|
|
2609
2646
|
throw err;
|
|
2610
2647
|
}
|
|
2611
2648
|
|
|
2612
|
-
// Configure tracking settings
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
}
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
if (typeof trackClicks !== 'boolean') {
|
|
2620
|
-
trackClicks = trackingEnabled;
|
|
2621
|
-
}
|
|
2622
|
-
}
|
|
2623
|
-
|
|
2624
|
-
if (typeof trackOpens !== 'boolean') {
|
|
2625
|
-
trackOpens = await settings.get('trackOpens');
|
|
2626
|
-
if (typeof trackOpens !== 'boolean') {
|
|
2627
|
-
trackOpens = trackingEnabled;
|
|
2628
|
-
}
|
|
2629
|
-
}
|
|
2649
|
+
// Configure tracking settings: what the message itself does not decide comes from one read
|
|
2650
|
+
// of the instance settings
|
|
2651
|
+
const messageTracking = { trackingEnabled, trackClicks, trackOpens };
|
|
2652
|
+
({ trackClicks, trackOpens } = resolveTracking(
|
|
2653
|
+
messageTracking,
|
|
2654
|
+
needsTrackingSettings(messageTracking) ? await settings.getMulti(...TRACKING_SETTINGS) : undefined
|
|
2655
|
+
));
|
|
2630
2656
|
|
|
2631
2657
|
// Add tracking pixels and link tracking
|
|
2632
2658
|
if (raw && (trackClicks || trackOpens) && baseUrl) {
|
|
@@ -2707,13 +2733,10 @@ class BaseClient {
|
|
|
2707
2733
|
raw
|
|
2708
2734
|
});
|
|
2709
2735
|
|
|
2710
|
-
//
|
|
2711
|
-
await
|
|
2712
|
-
|
|
2713
|
-
let
|
|
2714
|
-
|
|
2715
|
-
// Configure delivery retry settings
|
|
2716
|
-
let defaultDeliveryAttempts = await settings.get('deliveryAttempts');
|
|
2736
|
+
// Retention and retry settings, read together
|
|
2737
|
+
const [queueSettings, failedRetention] = await Promise.all([settings.getMulti('queueKeep', 'deliveryAttempts'), getFailedJobRetention()]);
|
|
2738
|
+
let queueKeep = queueSettings.queueKeep ?? true;
|
|
2739
|
+
let defaultDeliveryAttempts = queueSettings.deliveryAttempts;
|
|
2717
2740
|
if (typeof defaultDeliveryAttempts !== 'number') {
|
|
2718
2741
|
defaultDeliveryAttempts = DEFAULT_DELIVERY_ATTEMPTS;
|
|
2719
2742
|
}
|
|
@@ -2735,7 +2758,7 @@ class BaseClient {
|
|
|
2735
2758
|
let queueName = 'queued';
|
|
2736
2759
|
let jobOpts = {
|
|
2737
2760
|
jobId: queueId,
|
|
2738
|
-
...buildRetentionPolicy(queueKeep),
|
|
2761
|
+
...buildRetentionPolicy(queueKeep, failedRetention),
|
|
2739
2762
|
attempts: typeof deliveryAttempts === 'number' ? deliveryAttempts : defaultDeliveryAttempts,
|
|
2740
2763
|
backoff: {
|
|
2741
2764
|
type: 'exponential',
|
|
@@ -2750,8 +2773,18 @@ class BaseClient {
|
|
|
2750
2773
|
jobOpts.delay = sendAt.getTime() - now.getTime();
|
|
2751
2774
|
}
|
|
2752
2775
|
|
|
2753
|
-
//
|
|
2754
|
-
|
|
2776
|
+
// The content and the job that points to it, written together, see outbox.enqueue()
|
|
2777
|
+
const job = await outbox.enqueue({
|
|
2778
|
+
redis: this.redis,
|
|
2779
|
+
queue: this.submitQueue,
|
|
2780
|
+
account: this.account,
|
|
2781
|
+
queueId,
|
|
2782
|
+
content: msgEntry,
|
|
2783
|
+
name: queueName,
|
|
2784
|
+
data: jobData,
|
|
2785
|
+
opts: jobOpts,
|
|
2786
|
+
logger: this.logger
|
|
2787
|
+
});
|
|
2755
2788
|
|
|
2756
2789
|
try {
|
|
2757
2790
|
await job.updateProgress({
|
|
@@ -2958,19 +2991,19 @@ class BaseClient {
|
|
|
2958
2991
|
async getMessageFetchOptions() {
|
|
2959
2992
|
let messageFetchOptions = {};
|
|
2960
2993
|
|
|
2994
|
+
const fetchSettings = await settings.getMulti('notifyText', 'notifyTextSize', 'notifyHeaders');
|
|
2995
|
+
|
|
2961
2996
|
// Configure text content fetching
|
|
2962
|
-
|
|
2963
|
-
if (notifyText) {
|
|
2997
|
+
if (fetchSettings.notifyText) {
|
|
2964
2998
|
messageFetchOptions.textType = '*';
|
|
2965
|
-
let notifyTextSize = await settings.get('notifyTextSize');
|
|
2966
2999
|
|
|
2967
|
-
if (notifyTextSize) {
|
|
2968
|
-
messageFetchOptions.maxBytes = notifyTextSize;
|
|
3000
|
+
if (fetchSettings.notifyTextSize) {
|
|
3001
|
+
messageFetchOptions.maxBytes = fetchSettings.notifyTextSize;
|
|
2969
3002
|
}
|
|
2970
3003
|
}
|
|
2971
3004
|
|
|
2972
3005
|
// Configure header fetching
|
|
2973
|
-
let notifyHeaders =
|
|
3006
|
+
let notifyHeaders = fetchSettings.notifyHeaders || [];
|
|
2974
3007
|
if (notifyHeaders.length) {
|
|
2975
3008
|
messageFetchOptions.headers = notifyHeaders.includes('*') ? true : notifyHeaders.length ? notifyHeaders : false;
|
|
2976
3009
|
}
|
|
@@ -3130,109 +3163,27 @@ class BaseClient {
|
|
|
3130
3163
|
}
|
|
3131
3164
|
}
|
|
3132
3165
|
|
|
3133
|
-
//
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
}
|
|
3142
|
-
if (!attachment.content) {
|
|
3143
|
-
try {
|
|
3144
|
-
attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
|
|
3145
|
-
} catch (err) {
|
|
3146
|
-
this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
|
|
3147
|
-
}
|
|
3148
|
-
}
|
|
3166
|
+
// The settings the rest of this pass reads, in one round trip instead of one each
|
|
3167
|
+
const { notifyAttachments, notifyAttachmentSize, notifyCalendarEvents, notifyWebSafeHtml } = await settings.getMulti(...NEW_MESSAGE_SETTINGS);
|
|
3168
|
+
|
|
3169
|
+
const loadAttachment = async attachment => {
|
|
3170
|
+
try {
|
|
3171
|
+
attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
|
|
3172
|
+
} catch (err) {
|
|
3173
|
+
this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
|
|
3149
3174
|
}
|
|
3175
|
+
};
|
|
3176
|
+
|
|
3177
|
+
// Download attachment content if configured
|
|
3178
|
+
if (notifyAttachments) {
|
|
3179
|
+
await loadNotifyAttachments(messageData.attachments, notifyAttachmentSize, loadAttachment, API_ATTACHMENT_CONCURRENCY);
|
|
3150
3180
|
}
|
|
3151
3181
|
|
|
3152
3182
|
// Fetch and process calendar events if needed
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
// Process calendar attachments, text/calendar before application/ics
|
|
3158
|
-
for (let attachment of [...messageData.attachments].sort(sortCalendarAttachments)) {
|
|
3159
|
-
if (CALENDAR_CONTENT_TYPES.includes(attachment.contentType)) {
|
|
3160
|
-
if (!attachment.content) {
|
|
3161
|
-
try {
|
|
3162
|
-
let calendarBuf = (await this.getAttachment(attachment.id))?.data;
|
|
3163
|
-
attachment.content = calendarBuf.toString('base64');
|
|
3164
|
-
} catch (err) {
|
|
3165
|
-
this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
|
|
3166
|
-
}
|
|
3167
|
-
}
|
|
3168
|
-
if (attachment.content) {
|
|
3169
|
-
let contentBuf = Buffer.from(attachment.content, 'base64');
|
|
3170
|
-
try {
|
|
3171
|
-
const event = parseCalendarEvent(contentBuf);
|
|
3172
|
-
if (!event) {
|
|
3173
|
-
continue;
|
|
3174
|
-
}
|
|
3175
|
-
|
|
3176
|
-
// Skip if we already processed this event
|
|
3177
|
-
if (calendarEventMap.has(event.eventId)) {
|
|
3178
|
-
if (attachment.filename) {
|
|
3179
|
-
let existingEntry = calendarEventMap.get(event.eventId);
|
|
3180
|
-
if (!existingEntry.filename) {
|
|
3181
|
-
// inject filename
|
|
3182
|
-
existingEntry.filename = attachment.filename;
|
|
3183
|
-
}
|
|
3184
|
-
}
|
|
3185
|
-
continue;
|
|
3186
|
-
}
|
|
3187
|
-
|
|
3188
|
-
// Store calendar event data
|
|
3189
|
-
calendarEventMap.set(
|
|
3190
|
-
event.eventId,
|
|
3191
|
-
filterEmptyObjectValues({
|
|
3192
|
-
eventId: event.eventId,
|
|
3193
|
-
attachment: attachment.id,
|
|
3194
|
-
method: attachment.method || event.method || null,
|
|
3195
|
-
|
|
3196
|
-
summary: event.summary,
|
|
3197
|
-
description: event.description,
|
|
3198
|
-
timezone: event.timezone,
|
|
3199
|
-
startDate: event.startDate,
|
|
3200
|
-
endDate: event.endDate,
|
|
3201
|
-
organizer: event.organizer,
|
|
3202
|
-
|
|
3203
|
-
filename: attachment.filename,
|
|
3204
|
-
contentType: attachment.contentType,
|
|
3205
|
-
encoding: 'base64',
|
|
3206
|
-
content: attachment.content
|
|
3207
|
-
})
|
|
3208
|
-
);
|
|
3209
|
-
} catch (err) {
|
|
3210
|
-
this.logger.error({
|
|
3211
|
-
msg: 'Failed to parse calendar event',
|
|
3212
|
-
attachment: Object.assign({}, attachment, { content: `${contentBuf.length} bytes` }),
|
|
3213
|
-
err
|
|
3214
|
-
});
|
|
3215
|
-
}
|
|
3216
|
-
}
|
|
3217
|
-
}
|
|
3218
|
-
}
|
|
3219
|
-
|
|
3220
|
-
if (calendarEventMap && calendarEventMap.size) {
|
|
3221
|
-
// Convert map to array and set default filenames
|
|
3222
|
-
messageData.calendarEvents = Array.from(calendarEventMap.values()).map(calendarEvent => {
|
|
3223
|
-
if (!calendarEvent.filename) {
|
|
3224
|
-
switch (calendarEvent.method && calendarEvent.method.toUpperCase()) {
|
|
3225
|
-
case 'CANCEL':
|
|
3226
|
-
case 'REQUEST':
|
|
3227
|
-
calendarEvent.filename = 'invite.ics';
|
|
3228
|
-
break;
|
|
3229
|
-
default:
|
|
3230
|
-
calendarEvent.filename = 'event.ics';
|
|
3231
|
-
break;
|
|
3232
|
-
}
|
|
3233
|
-
}
|
|
3234
|
-
return calendarEvent;
|
|
3235
|
-
});
|
|
3183
|
+
if (notifyCalendarEvents) {
|
|
3184
|
+
const calendarEvents = await collectCalendarEvents(messageData.attachments, loadAttachment, this.logger);
|
|
3185
|
+
if (calendarEvents) {
|
|
3186
|
+
messageData.calendarEvents = calendarEvents;
|
|
3236
3187
|
}
|
|
3237
3188
|
}
|
|
3238
3189
|
|
|
@@ -3253,7 +3204,6 @@ class BaseClient {
|
|
|
3253
3204
|
}
|
|
3254
3205
|
|
|
3255
3206
|
// Convert message HTML to web safe HTML
|
|
3256
|
-
let notifyWebSafeHtml = await settings.get('notifyWebSafeHtml');
|
|
3257
3207
|
if (notifyWebSafeHtml && messageData.text && (messageData.text.html || messageData.text.plain)) {
|
|
3258
3208
|
// convert to web safe
|
|
3259
3209
|
messageData.text._generatedHtml = await messageWebSafeHtml(messageData);
|
|
@@ -3628,7 +3578,7 @@ class BaseClient {
|
|
|
3628
3578
|
}
|
|
3629
3579
|
|
|
3630
3580
|
// Handle provider-specific message ID extraction
|
|
3631
|
-
const originalMessageId = ProviderMessageIdHandler.processResponse(info
|
|
3581
|
+
const originalMessageId = ProviderMessageIdHandler.processResponse(info);
|
|
3632
3582
|
|
|
3633
3583
|
// Update job progress
|
|
3634
3584
|
try {
|
|
@@ -3655,7 +3605,7 @@ class BaseClient {
|
|
|
3655
3605
|
|
|
3656
3606
|
// Clear cached SMTP error
|
|
3657
3607
|
try {
|
|
3658
|
-
await this.redis.
|
|
3608
|
+
await this.redis.hSetExists(this.getAccountKey(), 'smtpStatus', JSON.stringify({ created: Date.now(), status: 'ok', response: info.response }));
|
|
3659
3609
|
} catch (err) {
|
|
3660
3610
|
// ignore
|
|
3661
3611
|
}
|
|
@@ -3710,6 +3660,35 @@ class BaseClient {
|
|
|
3710
3660
|
return { response: info.response, messageId: info.messageId };
|
|
3711
3661
|
}
|
|
3712
3662
|
|
|
3663
|
+
/**
|
|
3664
|
+
* Puts the primary IMAP connection back into IDLE after a command that took it out, such as
|
|
3665
|
+
* an APPEND. Only the primary connection idles, and only while a mailbox is selected. IDLE
|
|
3666
|
+
* waits for the connection to be free (whenFree), so it never lands between the commands of
|
|
3667
|
+
* a sync or another API call holding the mailbox lock
|
|
3668
|
+
* @param {Object} connectionClient - The IMAP client the command ran on
|
|
3669
|
+
*/
|
|
3670
|
+
resumeIdle(connectionClient) {
|
|
3671
|
+
if (!this.imapClient || connectionClient !== this.imapClient || !this.imapClient.mailbox || this.imapClient.idling) {
|
|
3672
|
+
return;
|
|
3673
|
+
}
|
|
3674
|
+
// one wait per connection: another upload while it is pending would only add a second
|
|
3675
|
+
if (this.idleResumeFor === connectionClient) {
|
|
3676
|
+
return;
|
|
3677
|
+
}
|
|
3678
|
+
this.idleResumeFor = connectionClient;
|
|
3679
|
+
connectionClient
|
|
3680
|
+
.idle({ whenFree: true })
|
|
3681
|
+
.catch(err => {
|
|
3682
|
+
// a connection that closed while IDLE waited for it is reconnected by its close handler
|
|
3683
|
+
this.logger[err.code === 'NoConnection' ? 'debug' : 'warn']({ msg: 'IDLE error', err });
|
|
3684
|
+
})
|
|
3685
|
+
.finally(() => {
|
|
3686
|
+
if (this.idleResumeFor === connectionClient) {
|
|
3687
|
+
this.idleResumeFor = null;
|
|
3688
|
+
}
|
|
3689
|
+
});
|
|
3690
|
+
}
|
|
3691
|
+
|
|
3713
3692
|
/**
|
|
3714
3693
|
* Uploads sent message to the Sent folder via IMAP
|
|
3715
3694
|
* @param {Buffer} raw - Raw message content
|
|
@@ -3733,12 +3712,7 @@ class BaseClient {
|
|
|
3733
3712
|
|
|
3734
3713
|
const connectionClient = await this.getImapConnection(connectionOptions, 'submitMessage');
|
|
3735
3714
|
await connectionClient.append(sentMailbox.path, raw, ['\\Seen']);
|
|
3736
|
-
|
|
3737
|
-
if (connectionClient === this.imapClient && this.imapClient.mailbox && !this.imapClient.idling) {
|
|
3738
|
-
this.imapClient.idle().catch(err => {
|
|
3739
|
-
this.logger.error({ msg: 'IDLE error', err });
|
|
3740
|
-
});
|
|
3741
|
-
}
|
|
3715
|
+
this.resumeIdle(connectionClient);
|
|
3742
3716
|
|
|
3743
3717
|
return true;
|
|
3744
3718
|
}
|
|
@@ -3875,7 +3849,7 @@ class BaseClient {
|
|
|
3875
3849
|
if (smtpStatus) {
|
|
3876
3850
|
// Store SMTP error for the account
|
|
3877
3851
|
try {
|
|
3878
|
-
await this.redis.
|
|
3852
|
+
await this.redis.hSetExists(this.getAccountKey(), 'smtpStatus', JSON.stringify(smtpStatus));
|
|
3879
3853
|
} catch (storeErr) {
|
|
3880
3854
|
// ignore
|
|
3881
3855
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { readEnvValue, getDuration } = require('../tools');
|
|
4
|
+
|
|
5
|
+
const DEFAULT_FALLBACK_POLL_INTERVAL = 10 * 60 * 1000;
|
|
6
|
+
const MIN_FALLBACK_POLL_INTERVAL = 10 * 1000;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Reads a fallback poll interval: a duration ("10m", "30s") or a bare number of milliseconds.
|
|
10
|
+
* Blank and anything unreadable get the default
|
|
11
|
+
* @param {*} value - The raw environment value
|
|
12
|
+
* @param {Object} opts
|
|
13
|
+
* @param {boolean} opts.allowOff - Whether 0 switches the poller off; otherwise 0 gets the default
|
|
14
|
+
* @param {number} [opts.min] - Shortest interval a positive value is raised to
|
|
15
|
+
* @returns {number} Milliseconds, 0 when the poller is off
|
|
16
|
+
*/
|
|
17
|
+
function parsePollInterval(value, { allowOff, min = 0 }) {
|
|
18
|
+
// blank is "unset", which getDuration() would read as 0
|
|
19
|
+
const raw = String(value ?? '').trim();
|
|
20
|
+
const duration = raw ? getDuration(raw) : DEFAULT_FALLBACK_POLL_INTERVAL;
|
|
21
|
+
if (typeof duration !== 'number' || !Number.isFinite(duration) || duration < 0 || (duration === 0 && !allowOff)) {
|
|
22
|
+
return DEFAULT_FALLBACK_POLL_INTERVAL;
|
|
23
|
+
}
|
|
24
|
+
return duration && Math.max(duration, min);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* EENGINE_GMAIL_FALLBACK_POLL_INTERVAL: how often a Gmail API account polls for changes when no
|
|
29
|
+
* Pub/Sub notification arrives. A bare number of milliseconds was the only form it used to accept,
|
|
30
|
+
* and the integration tier still sets one; a "10m" fell through to the default without a word. This
|
|
31
|
+
* poller can not be switched off, so 0 gets the default
|
|
32
|
+
* @param {*} value - The raw environment value
|
|
33
|
+
* @returns {number} Milliseconds
|
|
34
|
+
*/
|
|
35
|
+
function parseGmailFallbackPollInterval(value) {
|
|
36
|
+
return parsePollInterval(value, { allowOff: false });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL: 0 switches the periodic pass off, and a positive value is
|
|
41
|
+
* never shorter than ten seconds, so a typo can not point every account at Graph in a loop
|
|
42
|
+
* @param {*} value - The raw environment value
|
|
43
|
+
* @returns {number} Milliseconds, 0 when the pass is off
|
|
44
|
+
*/
|
|
45
|
+
function parseFallbackPollInterval(value) {
|
|
46
|
+
return parsePollInterval(value, { allowOff: true, min: MIN_FALLBACK_POLL_INTERVAL });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const GMAIL_FALLBACK_POLL_INTERVAL = parseGmailFallbackPollInterval(readEnvValue('EENGINE_GMAIL_FALLBACK_POLL_INTERVAL'));
|
|
50
|
+
|
|
51
|
+
// The interval of the periodic missed-notification recovery pass (OutlookClient.setupFallbackPollTimer()).
|
|
52
|
+
// Its own module so the admin UI, which runs in the API worker, reads the same value the account
|
|
53
|
+
// workers run with
|
|
54
|
+
const OUTLOOK_FALLBACK_POLL_INTERVAL = parseFallbackPollInterval(readEnvValue('EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL'));
|
|
55
|
+
|
|
56
|
+
module.exports = {
|
|
57
|
+
parseGmailFallbackPollInterval,
|
|
58
|
+
parseFallbackPollInterval,
|
|
59
|
+
GMAIL_FALLBACK_POLL_INTERVAL,
|
|
60
|
+
OUTLOOK_FALLBACK_POLL_INTERVAL,
|
|
61
|
+
DEFAULT_FALLBACK_POLL_INTERVAL
|
|
62
|
+
};
|
|
@@ -12,7 +12,7 @@ const { BaseClient, metricsMeta } = require('./base-client');
|
|
|
12
12
|
const { isSafePathSegment } = require('../utils/provider-id');
|
|
13
13
|
const { isTransientCredentialError } = require('./credential-errors');
|
|
14
14
|
const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
|
|
15
|
-
const { emitChangeEvent, toCamelCase, collectCidReferences, embedCidImages, truncateTextContents
|
|
15
|
+
const { emitChangeEvent, toCamelCase, collectCidReferences, embedCidImages, truncateTextContents } = require('../tools');
|
|
16
16
|
const { Gateway } = require('../gateway');
|
|
17
17
|
|
|
18
18
|
const {
|
|
@@ -29,6 +29,15 @@ const {
|
|
|
29
29
|
const settings = require('../settings');
|
|
30
30
|
|
|
31
31
|
const { GMAIL_API_BASE, LIST_BATCH_SIZE, request: gmailApiRequest, executeBatchRequests } = require('./gmail/gmail-api');
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Whether a Gmail API request failed because the resource does not exist
|
|
35
|
+
* @param {Error} err - Error thrown by request()
|
|
36
|
+
* @returns {boolean}
|
|
37
|
+
*/
|
|
38
|
+
function isGmailNotFound(err) {
|
|
39
|
+
return err?.oauthRequest?.status === 404 || err?.oauthRequest?.response?.error?.code === 404;
|
|
40
|
+
}
|
|
32
41
|
const { buildSendRequest, buildDraftSendRequest } = require('./gmail/send-request');
|
|
33
42
|
const { pushHeaderValue } = require('../utils/header-map');
|
|
34
43
|
|
|
@@ -99,9 +108,9 @@ function extractMessageIdHeader(raw) {
|
|
|
99
108
|
const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h - how often to check if watch needs renewal
|
|
100
109
|
const MIN_WATCH_TTL = 24 * 3600 * 1000; // 1day - minimum time before renewing watch
|
|
101
110
|
// 10min default - fallback polling if no Pub/Sub notifications. Overridable via
|
|
102
|
-
// EENGINE_GMAIL_FALLBACK_POLL_INTERVAL (
|
|
103
|
-
// without waiting the full interval.
|
|
104
|
-
const FALLBACK_POLLING_INTERVAL =
|
|
111
|
+
// EENGINE_GMAIL_FALLBACK_POLL_INTERVAL (a duration, or milliseconds) so integration tests can
|
|
112
|
+
// exercise the poller without waiting the full interval.
|
|
113
|
+
const { GMAIL_FALLBACK_POLL_INTERVAL: FALLBACK_POLLING_INTERVAL } = require('./fallback-poll');
|
|
105
114
|
|
|
106
115
|
/*
|
|
107
116
|
Gmail API implementation status:
|
|
@@ -476,7 +485,7 @@ class GmailClient extends BaseClient {
|
|
|
476
485
|
let historyId = Number(profileRes?.historyId) || null;
|
|
477
486
|
if (!accountData.googleHistoryId) {
|
|
478
487
|
// set as initial
|
|
479
|
-
await this.redis.
|
|
488
|
+
await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', historyId.toString());
|
|
480
489
|
accountData.googleHistoryId = historyId;
|
|
481
490
|
this.logger.info({ msg: 'Re-set missing Google History ID', account: this.account, historyId });
|
|
482
491
|
}
|
|
@@ -582,8 +591,30 @@ class GmailClient extends BaseClient {
|
|
|
582
591
|
return true;
|
|
583
592
|
}
|
|
584
593
|
|
|
585
|
-
|
|
586
|
-
|
|
594
|
+
/**
|
|
595
|
+
* Stops the account's Gmail Pub/Sub watch. Without this a deleted account's watch went on
|
|
596
|
+
* publishing every mailbox change to the topic until it lapsed, up to seven days later
|
|
597
|
+
* @returns {Promise<boolean>} True when a watch was stopped
|
|
598
|
+
*/
|
|
599
|
+
async releaseRemoteResources() {
|
|
600
|
+
try {
|
|
601
|
+
// Most accounts have no watch to stop, which the one stored field tells without loading
|
|
602
|
+
// and decrypting the whole account
|
|
603
|
+
if (!(await this.accountObject.getStoredField('watchResponse'))) {
|
|
604
|
+
return false;
|
|
605
|
+
}
|
|
606
|
+
const accountData = await this.accountObject.loadAccountData(this.account, false);
|
|
607
|
+
if (!accountData._app?.pubSubApp || !accountData.watchResponse) {
|
|
608
|
+
return false;
|
|
609
|
+
}
|
|
610
|
+
await this.prepare();
|
|
611
|
+
await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/stop`, 'post', Buffer.alloc(0));
|
|
612
|
+
this.logger.info({ msg: 'Stopped Gmail pubsub watch', account: this.account });
|
|
613
|
+
return true;
|
|
614
|
+
} catch (err) {
|
|
615
|
+
this.logger.warn({ msg: 'Failed to stop Gmail pubsub watch', account: this.account, err });
|
|
616
|
+
return false;
|
|
617
|
+
}
|
|
587
618
|
}
|
|
588
619
|
|
|
589
620
|
async delete() {
|
|
@@ -891,6 +922,12 @@ class GmailClient extends BaseClient {
|
|
|
891
922
|
let resultList = await Promise.allSettled(promises);
|
|
892
923
|
for (let entry of resultList) {
|
|
893
924
|
if (entry.status === 'rejected') {
|
|
925
|
+
if (isGmailNotFound(entry.reason)) {
|
|
926
|
+
// Deleted between the listing and this fetch. Skipped like a message that
|
|
927
|
+
// moved out of the page, instead of failing every other message on it
|
|
928
|
+
this.logger.debug({ msg: 'Listed message no longer exists', account: this.account, err: entry.reason });
|
|
929
|
+
continue;
|
|
930
|
+
}
|
|
894
931
|
throw entry.reason;
|
|
895
932
|
}
|
|
896
933
|
if (entry.value) {
|
|
@@ -951,6 +988,8 @@ class GmailClient extends BaseClient {
|
|
|
951
988
|
return {
|
|
952
989
|
deleted: result && result.labelIds?.includes('TRASH'),
|
|
953
990
|
moved: {
|
|
991
|
+
// the same shape IMAP and Graph answer with, deleteMessages() already named it
|
|
992
|
+
destination: SYSTEM_NAMES.TRASH,
|
|
954
993
|
message: result.id
|
|
955
994
|
}
|
|
956
995
|
};
|
|
@@ -1594,7 +1633,7 @@ class GmailClient extends BaseClient {
|
|
|
1594
1633
|
try {
|
|
1595
1634
|
messageData = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${emailId}`, 'get', { format: 'raw' });
|
|
1596
1635
|
} catch (err) {
|
|
1597
|
-
if (err
|
|
1636
|
+
if (isGmailNotFound(err)) {
|
|
1598
1637
|
let error = new Error('Requested message was not found');
|
|
1599
1638
|
error.code = 'MessageNotFound';
|
|
1600
1639
|
error.statusCode = 404;
|
|
@@ -3212,7 +3251,7 @@ class GmailClient extends BaseClient {
|
|
|
3212
3251
|
// advance the durable cursor once an entry is handled (processed or skipped)
|
|
3213
3252
|
let advanceHistoryCursor = async historyEntryId => {
|
|
3214
3253
|
if (historyEntryId && historyEntryId > lastHistoryId) {
|
|
3215
|
-
await this.redis.
|
|
3254
|
+
await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
|
|
3216
3255
|
lastHistoryId = historyEntryId;
|
|
3217
3256
|
}
|
|
3218
3257
|
};
|
|
@@ -3303,7 +3342,7 @@ class GmailClient extends BaseClient {
|
|
|
3303
3342
|
if (entry?.id) {
|
|
3304
3343
|
// mark the entry as in flight before touching it, so a
|
|
3305
3344
|
// worker death mid-entry is attributable on restart
|
|
3306
|
-
await this.redis.
|
|
3345
|
+
await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryProcessing', JSON.stringify({ id: entry.id, count: attempts + 1 }));
|
|
3307
3346
|
}
|
|
3308
3347
|
|
|
3309
3348
|
try {
|
|
@@ -3343,7 +3382,7 @@ class GmailClient extends BaseClient {
|
|
|
3343
3382
|
|
|
3344
3383
|
// Update to newest history ID
|
|
3345
3384
|
if (newestHistoryId && newestHistoryId > currentHistoryId) {
|
|
3346
|
-
await this.redis.
|
|
3385
|
+
await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', newestHistoryId.toString());
|
|
3347
3386
|
}
|
|
3348
3387
|
|
|
3349
3388
|
// the run finished without dying, drop the in-flight marker
|
|
@@ -3447,6 +3486,7 @@ class GmailClient extends BaseClient {
|
|
|
3447
3486
|
module.exports = {
|
|
3448
3487
|
GmailClient,
|
|
3449
3488
|
PageCursor,
|
|
3489
|
+
isGmailNotFound,
|
|
3450
3490
|
SKIP_LABELS: Object.freeze([...SKIP_LABELS]),
|
|
3451
3491
|
SYSTEM_LABELS: Object.freeze({ ...SYSTEM_LABELS }),
|
|
3452
3492
|
SYSTEM_NAMES: Object.freeze({ ...SYSTEM_NAMES })
|