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
package/lib/web-safe-html.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const { analyze } = require('@postalsys/email-content');
|
|
3
|
+
const { analyze, canonicalisePlainText } = require('@postalsys/email-content');
|
|
4
4
|
// Resolved at call time rather than destructured here: the package exposes mimeHtml through a
|
|
5
5
|
// lazy getter, and touching it loads jsdom (tens of MB of heap) into every process that merely
|
|
6
6
|
// requires this module, the main process included.
|
|
7
7
|
const textTools = require('@postalsys/email-text-tools');
|
|
8
|
-
const {
|
|
8
|
+
const { attributeValueRegex } = require('./tools');
|
|
9
|
+
const { getOverridableSettings } = require('./env-setting-overrides');
|
|
9
10
|
const { COLLAPSE_CLASS, COLLAPSE_TOGGLE_CLASS } = require('./consts');
|
|
10
11
|
const logger = require('./logger');
|
|
11
12
|
const he = require('he');
|
|
@@ -53,54 +54,16 @@ const MIN_COLLAPSE_CHARS = 120;
|
|
|
53
54
|
const MAX_ANALYZE_CHARS = 256 * 1024;
|
|
54
55
|
|
|
55
56
|
// Opt-out for operators who need the previous output shape, or who do not want to pay for
|
|
56
|
-
// extraction on every notified message
|
|
57
|
-
|
|
57
|
+
// extraction on every notified message: the disableThreadCollapse setting, or
|
|
58
|
+
// EENGINE_DISABLE_THREAD_COLLAPSE, which wins when set (lib/env-setting-overrides.js). Read per
|
|
59
|
+
// message through that module's short cache, so a change applies without a restart.
|
|
58
60
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
* collapsible. juice inlines the block and the sanitizer then drops the tag.
|
|
66
|
-
*
|
|
67
|
-
* Kept byte for byte identical to INLINE_STYLE_BLOCK in @postalsys/email-text-tools, so the two
|
|
68
|
-
* can be diffed when that package restyles quoted text.
|
|
69
|
-
*/
|
|
70
|
-
const PLAINTEXT_STYLE_BLOCK = `<style>
|
|
71
|
-
|
|
72
|
-
body, td, th, p {
|
|
73
|
-
font-family: sans-serif;
|
|
74
|
-
font-size: 12px;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
blockquote {
|
|
78
|
-
border-left-width: 2px;
|
|
79
|
-
border-left-style: solid;
|
|
80
|
-
|
|
81
|
-
border-left-color: darkblue;
|
|
82
|
-
color: darkblue;
|
|
83
|
-
|
|
84
|
-
margin: 1rem 0;
|
|
85
|
-
padding-left: 1rem;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
blockquote blockquote{
|
|
89
|
-
border-left-color: royalblue;
|
|
90
|
-
color: royalblue;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
blockquote blockquote blockquote{
|
|
94
|
-
border-left-color: dodgerblue;
|
|
95
|
-
color: dodgerblue;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
blockquote blockquote blockquote blockquote{
|
|
99
|
-
border-left-color: darkblue;
|
|
100
|
-
color: darkblue;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
</style>`;
|
|
61
|
+
// Base styles for messages that only have a plain text body. mimeHtml() applies the same block
|
|
62
|
+
// whenever it converts text to HTML itself; once a collapse marker is involved the conversion happens
|
|
63
|
+
// here instead, so the styling has to travel with it, or a plain text reply would lose its quote
|
|
64
|
+
// colouring the moment it became collapsible. juice inlines the block and the sanitizer drops the tag.
|
|
65
|
+
// Taken from the package rather than kept as a copy, which had already drifted from it.
|
|
66
|
+
const PLAINTEXT_STYLE_BLOCK = textTools.INLINE_STYLE_BLOCK;
|
|
104
67
|
|
|
105
68
|
// Table internals can not host a wrapper element. A <details> opened between table cells is
|
|
106
69
|
// foster-parented out of the table by the HTML parser, which would leave the content behind and
|
|
@@ -136,36 +99,6 @@ function formatSender(from) {
|
|
|
136
99
|
return address || name || null;
|
|
137
100
|
}
|
|
138
101
|
|
|
139
|
-
/**
|
|
140
|
-
* Normalizes text the same way the extractor does, so the offsets it reports index this string.
|
|
141
|
-
*
|
|
142
|
-
* Mirrors canonicaliseText() in @postalsys/email-content: BOM removal, LF line endings, NUL
|
|
143
|
-
* removal and NFC normalization. Anything else would shift the offsets.
|
|
144
|
-
*
|
|
145
|
-
* There is no HTML counterpart on purpose. HTML offsets come from source ranges over the string
|
|
146
|
-
* exactly as it was handed to the extractor, so HTML must not be normalized before slicing it.
|
|
147
|
-
*
|
|
148
|
-
* @param {string} text - Decoded plain text body
|
|
149
|
-
* @returns {string} Canonical text
|
|
150
|
-
*/
|
|
151
|
-
function canonicaliseText(text) {
|
|
152
|
-
let canonical = text;
|
|
153
|
-
|
|
154
|
-
if (canonical.charCodeAt(0) === 0xfeff) {
|
|
155
|
-
canonical = canonical.slice(1);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
canonical = canonical.replace(/\r\n?/g, '\n').replace(/\0/g, '');
|
|
159
|
-
|
|
160
|
-
try {
|
|
161
|
-
canonical = canonical.normalize('NFC');
|
|
162
|
-
} catch (_err) {
|
|
163
|
-
// Extremely long or malformed input can defeat NFC. Unnormalized text still slices.
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
return canonical;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
102
|
/**
|
|
170
103
|
* Finds the offset where the quoted tail of a message starts.
|
|
171
104
|
*
|
|
@@ -375,7 +308,7 @@ async function collapseThreadHistory(messageData) {
|
|
|
375
308
|
// Text offsets index the extractor's canonical form, so the same normalization has to be
|
|
376
309
|
// applied before slicing. It is done here rather than up front because the HTML path,
|
|
377
310
|
// which is the common one, has no use for it.
|
|
378
|
-
collapsed = collapseText(
|
|
311
|
+
collapsed = collapseText(canonicalisePlainText(text), cut.offset);
|
|
379
312
|
}
|
|
380
313
|
|
|
381
314
|
return collapsed ? { html: collapsed } : null;
|
|
@@ -415,24 +348,6 @@ function stripReservedClasses(html) {
|
|
|
415
348
|
});
|
|
416
349
|
}
|
|
417
350
|
|
|
418
|
-
/**
|
|
419
|
-
* Last-resort rendering when the sanitizer itself fails.
|
|
420
|
-
*
|
|
421
|
-
* mimeHtml() throws RangeError on hostile nesting (a few thousand nested elements or quote
|
|
422
|
-
* levels). The message is still delivered and still has to be readable, so it is shown as escaped
|
|
423
|
-
* text rather than dropped. Never the unconverted HTML: that has not been sanitized.
|
|
424
|
-
*
|
|
425
|
-
* @param {Object} source - `{ html, text }` as handed to mimeHtml()
|
|
426
|
-
* @returns {string} Escaped text in a wrapper
|
|
427
|
-
*/
|
|
428
|
-
function escapedTextFallback(source) {
|
|
429
|
-
let text = source.text || '';
|
|
430
|
-
if (!text && source.html) {
|
|
431
|
-
text = he.decode(source.html.toString().replace(/<[^>]*>/g, ' '));
|
|
432
|
-
}
|
|
433
|
-
return `<div style="overflow: auto; white-space: pre-wrap;">${he.escape(text.toString())}</div>`;
|
|
434
|
-
}
|
|
435
|
-
|
|
436
351
|
/**
|
|
437
352
|
* Converts the bodies of a message object into sanitized, web-safe HTML.
|
|
438
353
|
*
|
|
@@ -447,7 +362,8 @@ async function messageWebSafeHtml(messageData) {
|
|
|
447
362
|
|
|
448
363
|
let source = { html, text: messageData.text.plain };
|
|
449
364
|
|
|
450
|
-
|
|
365
|
+
const { disableThreadCollapse } = await getOverridableSettings('disableThreadCollapse');
|
|
366
|
+
if (!disableThreadCollapse) {
|
|
451
367
|
try {
|
|
452
368
|
let collapsed = await collapseThreadHistory(messageData);
|
|
453
369
|
if (collapsed) {
|
|
@@ -459,12 +375,9 @@ async function messageWebSafeHtml(messageData) {
|
|
|
459
375
|
}
|
|
460
376
|
}
|
|
461
377
|
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
logger.warn({ msg: 'Failed to convert message to web-safe HTML, rendering it as text', err });
|
|
466
|
-
return escapedTextFallback({ html: messageData.text.html, text: messageData.text.plain });
|
|
467
|
-
}
|
|
378
|
+
// mimeHtml() does not throw: on hostile input (thousands of nested elements or quote levels)
|
|
379
|
+
// it falls back to escaped text itself, which is what the catch that used to be here did
|
|
380
|
+
return textTools.mimeHtml(source);
|
|
468
381
|
}
|
|
469
382
|
|
|
470
383
|
/**
|
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The notify queue's job processor: decides whether and where a queued webhook event is delivered,
|
|
4
|
+
// sends it, and records the outcome. It used to be written inline in workers/webhooks.js, which a
|
|
5
|
+
// test cannot import (requiring it starts a BullMQ worker and talks to the parent thread), so its
|
|
6
|
+
// decisions were only tested through the helpers it calls. Everything with a side effect is passed
|
|
7
|
+
// in, see createWebhookProcessor().
|
|
8
|
+
|
|
9
|
+
const { UnrecoverableError, DelayedError } = require('bullmq');
|
|
10
|
+
|
|
11
|
+
const { redactUrlCredentials, splitUrlCredentials } = require('./tools');
|
|
12
|
+
const { sendWebhookRequest, isUnrecoverableWebhookError, baseDeliveryHeaders, signDelivery } = require('./webhook-request');
|
|
13
|
+
const { willBeFinalAttempt } = require('./delivery-error');
|
|
14
|
+
const { penaltyKey, penaltyFor } = require('./webhook-penalty');
|
|
15
|
+
const {
|
|
16
|
+
resolveTargetUrl,
|
|
17
|
+
isDeliverableRoute,
|
|
18
|
+
eventAllowed,
|
|
19
|
+
defaultRouteTakes,
|
|
20
|
+
headerLevels,
|
|
21
|
+
deliveryCustomHeaders,
|
|
22
|
+
isRouteMappingMissing
|
|
23
|
+
} = require('./webhook-routing');
|
|
24
|
+
const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('./consts');
|
|
25
|
+
|
|
26
|
+
// The payload fields of `data` that are logged as they are; anything else only marks it partial
|
|
27
|
+
const LOGGED_DATA_KEYS = new Set(['id', 'uid', 'path', 'messageId']);
|
|
28
|
+
|
|
29
|
+
const getAccountKey = account => `${REDIS_PREFIX}iad:${account}`;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Log context shared by every line about one job
|
|
33
|
+
* @param {Object} job - BullMQ job
|
|
34
|
+
* @returns {Object} Fields to spread into a log entry
|
|
35
|
+
*/
|
|
36
|
+
const jobLogFields = job => ({ action: 'webhook', queue: job.queue.name, job: job.id, event: job.name, account: job.data.account });
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The job payload reduced to what is safe and useful to log: everything except `data`, of which
|
|
40
|
+
* only the identifying fields are kept
|
|
41
|
+
* @param {Object} payload - Job data
|
|
42
|
+
* @returns {Object} Loggable copy
|
|
43
|
+
*/
|
|
44
|
+
function filterLogData(payload) {
|
|
45
|
+
let filteredData = {};
|
|
46
|
+
for (let key of Object.keys(payload)) {
|
|
47
|
+
if (key !== 'data') {
|
|
48
|
+
filteredData[key] = payload[key];
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let filteredSubData = {};
|
|
53
|
+
let isPartial = false;
|
|
54
|
+
for (let dataKey of Object.keys(payload.data || {})) {
|
|
55
|
+
if (LOGGED_DATA_KEYS.has(dataKey)) {
|
|
56
|
+
filteredSubData[dataKey] = payload.data[dataKey];
|
|
57
|
+
} else {
|
|
58
|
+
isPartial = true;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (isPartial) {
|
|
62
|
+
if (Object.keys(filteredSubData).length) {
|
|
63
|
+
filteredSubData.partial = true;
|
|
64
|
+
} else {
|
|
65
|
+
filteredSubData = true;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
filteredData[key] = filteredSubData;
|
|
69
|
+
}
|
|
70
|
+
return filteredData;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Loads the custom route a job was queued for. Removes `_route` from the payload, so it is never
|
|
75
|
+
* delivered
|
|
76
|
+
* @returns {Promise<Object>} `{ skip }` when nothing is to be sent, otherwise `{ customRoute, customMapping }`
|
|
77
|
+
*/
|
|
78
|
+
async function loadCustomRoute(job, deps) {
|
|
79
|
+
if (!job.data._route || !job.data._route.id) {
|
|
80
|
+
return {};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let customRoute = await deps.webhooks.getMeta(job.data._route.id);
|
|
84
|
+
let customMapping = job.data._route.mapping;
|
|
85
|
+
let mappingMissing = isRouteMappingMissing(job.data._route);
|
|
86
|
+
delete job.data._route;
|
|
87
|
+
|
|
88
|
+
if (!isDeliverableRoute(customRoute)) {
|
|
89
|
+
return { skip: true };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (mappingMissing) {
|
|
93
|
+
deps.logger.warn({
|
|
94
|
+
msg: 'Custom webhook route has no mapped payload, not sending',
|
|
95
|
+
...jobLogFields(job),
|
|
96
|
+
code: 'missing_mapping',
|
|
97
|
+
route: customRoute.id
|
|
98
|
+
});
|
|
99
|
+
return { skip: true };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return { customRoute, customMapping };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Parses the account's custom header list. A value that does not parse is ignored, as before
|
|
107
|
+
* @returns {Object[]|undefined} Header entries
|
|
108
|
+
*/
|
|
109
|
+
function parseAccountHeaders(json, job, logger) {
|
|
110
|
+
if (!json) {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
return JSON.parse(json);
|
|
115
|
+
} catch (err) {
|
|
116
|
+
// do not log the header values, they may carry authentication secrets
|
|
117
|
+
logger.debug({ msg: 'Failed to parse custom webhook headers', ...jobLogFields(job), jsonLength: json.length, err });
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Delays the job while its target is penalised; see lib/webhook-penalty.js. The attempt count is
|
|
124
|
+
* not spent by the wait
|
|
125
|
+
* @returns {Promise<string|null>} The target's penalty key, for recordFailure()
|
|
126
|
+
* @throws {DelayedError} When the job was moved to the delayed set
|
|
127
|
+
*/
|
|
128
|
+
async function waitOutPenalty(job, token, webhooks, deps) {
|
|
129
|
+
const targetPenaltyKey = penaltyKey(webhooks);
|
|
130
|
+
if (!targetPenaltyKey) {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
let remaining = await deps.redis.pttl(targetPenaltyKey);
|
|
134
|
+
if (remaining > 0) {
|
|
135
|
+
deps.logger.debug({
|
|
136
|
+
msg: 'Webhook target is penalised, delaying delivery',
|
|
137
|
+
...jobLogFields(job),
|
|
138
|
+
code: 'target_penalised',
|
|
139
|
+
webhooks: redactUrlCredentials(webhooks),
|
|
140
|
+
delay: remaining
|
|
141
|
+
});
|
|
142
|
+
await job.moveToDelayed(Date.now() + remaining, token);
|
|
143
|
+
throw new DelayedError();
|
|
144
|
+
}
|
|
145
|
+
return targetPenaltyKey;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Decides whether a job is delivered and, if it is, where and with which header lists. Every
|
|
150
|
+
* check that can skip a job runs here, in the order the inline processor ran them
|
|
151
|
+
* @returns {Promise<Object|null>} Delivery plan, or null when the job is completed without sending
|
|
152
|
+
*/
|
|
153
|
+
async function planDelivery(job, token, deps) {
|
|
154
|
+
const { redis, settings, logger, openAccountField } = deps;
|
|
155
|
+
let accountKey = getAccountKey(job.data.account);
|
|
156
|
+
|
|
157
|
+
// Keep the route id reachable for the completed/failed event handlers, which see this same
|
|
158
|
+
// job instance after _route has been deleted from the payload. Stashed before the early
|
|
159
|
+
// returns below so a job that never reaches delivery still reports which route queued it.
|
|
160
|
+
if (job.data._route && job.data._route.id) {
|
|
161
|
+
job.__routeId = job.data._route.id;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// One round trip for the existence check and the two account fields a delivery may need.
|
|
165
|
+
// The fields are opened where they are used, below.
|
|
166
|
+
let [accountExists, storedWebhooks, storedCustomHeaders] = await redis.hmget(accountKey, 'account', 'webhooks', 'webhooksCustomHeaders');
|
|
167
|
+
if (!accountExists && job.name !== ACCOUNT_DELETED_NOTIFY) {
|
|
168
|
+
logger.debug({ msg: 'Account not found', ...jobLogFields(job), code: 'account_not_found' });
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (!(await settings.get('webhooksEnabled'))) {
|
|
173
|
+
logger.debug({ msg: 'Webhooks are disabled', ...jobLogFields(job), code: 'webhooks_disabled' });
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
let { skip, customRoute, customMapping } = await loadCustomRoute(job, deps);
|
|
178
|
+
if (skip) {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
let accountWebhooks = await openAccountField('webhooks', storedWebhooks, job.data.account);
|
|
183
|
+
|
|
184
|
+
// the global setting is only fetched when neither a custom route nor the account override decides the target
|
|
185
|
+
let target = resolveTargetUrl(customRoute && customRoute.targetUrl, accountWebhooks, null);
|
|
186
|
+
if (!target.url) {
|
|
187
|
+
target = resolveTargetUrl(null, null, await settings.get('webhooks'));
|
|
188
|
+
}
|
|
189
|
+
let webhooks = target.url;
|
|
190
|
+
if (!webhooks) {
|
|
191
|
+
// A skipped delivery still reports the job as completed, so without this line a
|
|
192
|
+
// missing target is indistinguishable from a successful delivery - it reads as the
|
|
193
|
+
// receiver being slow rather than as nothing having been sent
|
|
194
|
+
logger.debug({ msg: 'Webhook URL is not set', ...jobLogFields(job), code: 'no_target_url' });
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const targetPenaltyKey = await waitOutPenalty(job, token, webhooks, deps);
|
|
199
|
+
|
|
200
|
+
// Only the header lists that travel to this target are loaded; lib/webhook-routing.js
|
|
201
|
+
// holds the rule and the reasons
|
|
202
|
+
let levels = headerLevels(target.source);
|
|
203
|
+
let accountHeadersJson = levels.includes('account') ? await openAccountField('webhooksCustomHeaders', storedCustomHeaders, job.data.account) : null;
|
|
204
|
+
let accountCustomHeaders = parseAccountHeaders(accountHeadersJson, job, logger);
|
|
205
|
+
|
|
206
|
+
if (!customRoute) {
|
|
207
|
+
// custom routes have their own mappings; the default route follows webhookEvents and
|
|
208
|
+
// inboxNewOnly, by the same rule pushToQueue() applied before queueing
|
|
209
|
+
let { webhookEvents, inboxNewOnly } = await settings.getMulti('webhookEvents', 'inboxNewOnly');
|
|
210
|
+
if (!defaultRouteTakes(job.name, job.data, { webhookEvents, inboxNewOnly })) {
|
|
211
|
+
logger.trace({
|
|
212
|
+
msg: 'Webhook event not taken by the default route',
|
|
213
|
+
...jobLogFields(job),
|
|
214
|
+
code: eventAllowed(webhookEvents, job.name) ? 'inbox_new_only' : 'event_not_whitelisted',
|
|
215
|
+
webhookEvents
|
|
216
|
+
});
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return {
|
|
222
|
+
accountKey,
|
|
223
|
+
customRoute,
|
|
224
|
+
customMapping,
|
|
225
|
+
accountWebhooks,
|
|
226
|
+
target,
|
|
227
|
+
// never log the raw target URL, it may embed basic auth credentials
|
|
228
|
+
redactedWebhooks: redactUrlCredentials(webhooks),
|
|
229
|
+
accountCustomHeaders,
|
|
230
|
+
targetPenaltyKey
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Builds the request: the body, and every header that goes with it, the signature last
|
|
236
|
+
* @returns {Promise<Object>} `{ url, headers, body }`
|
|
237
|
+
*/
|
|
238
|
+
async function buildRequest(job, plan, deps) {
|
|
239
|
+
let { url: parsed, authorization } = splitUrlCredentials(plan.target.url);
|
|
240
|
+
let headers = Object.assign(baseDeliveryHeaders(authorization), {
|
|
241
|
+
'X-EE-Wh-Id': (job.id || '').toString(),
|
|
242
|
+
'X-EE-Wh-Attempts-Made': (job.attemptsMade || 0).toString(),
|
|
243
|
+
'X-EE-Wh-Queued-Time': Math.round(Math.max(0, (Date.now() - job.timestamp) / 1000)) + 's'
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
if (plan.customRoute) {
|
|
247
|
+
headers['X-EE-Wh-Custom-Route'] = plan.customRoute.id;
|
|
248
|
+
}
|
|
249
|
+
Object.assign(
|
|
250
|
+
headers,
|
|
251
|
+
deliveryCustomHeaders(plan.target.source, {
|
|
252
|
+
route: plan.customRoute && plan.customRoute.customHeaders,
|
|
253
|
+
global: headerLevels(plan.target.source).includes('global') ? await deps.settings.get('webhooksCustomHeaders') : null,
|
|
254
|
+
account: plan.accountCustomHeaders
|
|
255
|
+
})
|
|
256
|
+
);
|
|
257
|
+
|
|
258
|
+
let webhookPayload = plan.customMapping || job.data;
|
|
259
|
+
if (webhookPayload.eventId) {
|
|
260
|
+
headers['X-EE-Wh-Event-Id'] = webhookPayload.eventId;
|
|
261
|
+
webhookPayload.eventId = undefined; // not included in JSON
|
|
262
|
+
}
|
|
263
|
+
let body = Buffer.from(JSON.stringify(webhookPayload));
|
|
264
|
+
|
|
265
|
+
// Explicitly set Content-Length to prevent undici mismatch errors
|
|
266
|
+
headers['Content-Length'] = body.length.toString();
|
|
267
|
+
|
|
268
|
+
signDelivery(headers, body, await deps.getServiceSecret());
|
|
269
|
+
|
|
270
|
+
return { url: parsed.toString(), headers, body };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Writes the error flag of whichever level decided the target: the custom route, the account
|
|
275
|
+
* override or the global setting. An empty flag clears it, by removing the field: every successful
|
|
276
|
+
* delivery clears, and a removal of a field that is not there changes nothing, so Redis neither
|
|
277
|
+
* writes nor replicates it. Never throws, a missed flag write must not change the outcome of the
|
|
278
|
+
* delivery
|
|
279
|
+
*/
|
|
280
|
+
async function writeErrorFlag(plan, flag, deps) {
|
|
281
|
+
try {
|
|
282
|
+
if (plan.customRoute || plan.accountWebhooks) {
|
|
283
|
+
const [key, field] = plan.customRoute
|
|
284
|
+
? [deps.webhooks.getWebhooksContentKey(), `${plan.customRoute.id}:webhookErrorFlag`]
|
|
285
|
+
: [plan.accountKey, 'webhookErrorFlag'];
|
|
286
|
+
await (flag ? deps.redis.hset(key, field, JSON.stringify(flag)) : deps.redis.hdel(key, field));
|
|
287
|
+
} else if (flag) {
|
|
288
|
+
await deps.settings.set('webhookErrorFlag', flag);
|
|
289
|
+
} else {
|
|
290
|
+
await deps.settings.clear('webhookErrorFlag');
|
|
291
|
+
}
|
|
292
|
+
} catch (err) {
|
|
293
|
+
// ignore
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Records a failed attempt everywhere it is read back: the target penalty, the job's progress
|
|
299
|
+
* field (for the queue browser), the log, the error flag and the metrics
|
|
300
|
+
*/
|
|
301
|
+
async function recordFailure(job, plan, request, err, duration, deps) {
|
|
302
|
+
const { redis, logger } = deps;
|
|
303
|
+
|
|
304
|
+
// egress and redirect failures are thrown as UnrecoverableError, so they are final as well
|
|
305
|
+
let isFinalAttempt = willBeFinalAttempt(job) || isUnrecoverableWebhookError(err);
|
|
306
|
+
|
|
307
|
+
// A target that held the attempt until it timed out is penalised so the next deliveries to
|
|
308
|
+
// it do not each cost the same wait
|
|
309
|
+
let penalty = penaltyFor(err, deps.timeout || DEFAULT_WEBHOOK_REQUEST_TIMEOUT);
|
|
310
|
+
if (penalty && plan.targetPenaltyKey) {
|
|
311
|
+
try {
|
|
312
|
+
await redis.set(plan.targetPenaltyKey, '1', 'PX', penalty);
|
|
313
|
+
} catch (penaltyErr) {
|
|
314
|
+
// a missed penalty costs the queue one more timeout, nothing else
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// BullMQ keeps only the message of a failure on the job. The code and the HTTP status
|
|
319
|
+
// are what explain it, so they are recorded the way the submit worker records its own
|
|
320
|
+
// delivery errors, for the queue browser to read back
|
|
321
|
+
try {
|
|
322
|
+
await job.updateProgress({ status: 'error', error: { message: err.message, code: err.code, statusCode: err.statusCode }, duration });
|
|
323
|
+
} catch (progressErr) {
|
|
324
|
+
// ignore
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
logger[isFinalAttempt ? 'error' : 'warn']({
|
|
328
|
+
msg: 'Failed posting webhook',
|
|
329
|
+
...jobLogFields(job),
|
|
330
|
+
code: 'result_fail',
|
|
331
|
+
webhooks: plan.redactedWebhooks,
|
|
332
|
+
requestBodySize: request.body.length,
|
|
333
|
+
accountWebhooks: !!plan.accountWebhooks,
|
|
334
|
+
route: plan.customRoute && plan.customRoute.id,
|
|
335
|
+
err
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
await writeErrorFlag(
|
|
339
|
+
plan,
|
|
340
|
+
{
|
|
341
|
+
event: job.name,
|
|
342
|
+
message: err.message,
|
|
343
|
+
time: Date.now(),
|
|
344
|
+
// stored without credentials: the flag is read back through the webhook route
|
|
345
|
+
// listing, the account page and the settings API. A route's own URL is the target
|
|
346
|
+
url: plan.redactedWebhooks,
|
|
347
|
+
code: err.code,
|
|
348
|
+
statusCode: err.statusCode
|
|
349
|
+
},
|
|
350
|
+
deps
|
|
351
|
+
);
|
|
352
|
+
|
|
353
|
+
deps.metrics('webhooks', 'inc', { event: job.name, status: 'fail' });
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Sends a planned delivery and records the outcome
|
|
358
|
+
* @returns {Promise<Object>} The job's return value, stored by BullMQ
|
|
359
|
+
*/
|
|
360
|
+
async function deliver(job, plan, deps) {
|
|
361
|
+
const { logger } = deps;
|
|
362
|
+
|
|
363
|
+
// the redacted target stays reachable for the failed event handler
|
|
364
|
+
job.__redactedTargetUrl = plan.redactedWebhooks;
|
|
365
|
+
|
|
366
|
+
logger.trace({
|
|
367
|
+
msg: 'Processing webhook',
|
|
368
|
+
...jobLogFields(job),
|
|
369
|
+
code: 'processing',
|
|
370
|
+
webhooks: plan.redactedWebhooks,
|
|
371
|
+
accountWebhooks: !!plan.accountWebhooks,
|
|
372
|
+
data: filterLogData(job.data),
|
|
373
|
+
route: plan.customRoute && plan.customRoute.id
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
let request = await buildRequest(job, plan, deps);
|
|
377
|
+
|
|
378
|
+
let start = Date.now();
|
|
379
|
+
let duration;
|
|
380
|
+
try {
|
|
381
|
+
let status;
|
|
382
|
+
try {
|
|
383
|
+
status = await sendWebhookRequest(deps.fetch, request.url, {
|
|
384
|
+
method: 'post',
|
|
385
|
+
body: request.body,
|
|
386
|
+
headers: request.headers,
|
|
387
|
+
dispatcher: deps.dispatcher,
|
|
388
|
+
timeout: deps.timeout,
|
|
389
|
+
validateTarget: deps.validateTarget
|
|
390
|
+
});
|
|
391
|
+
duration = Date.now() - start;
|
|
392
|
+
} catch (err) {
|
|
393
|
+
duration = Date.now() - start;
|
|
394
|
+
throw err.cause || err;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
logger.trace({
|
|
398
|
+
msg: 'Webhook posted',
|
|
399
|
+
...jobLogFields(job),
|
|
400
|
+
code: 'result_success',
|
|
401
|
+
webhooks: plan.redactedWebhooks,
|
|
402
|
+
requestBodySize: request.body.length,
|
|
403
|
+
accountWebhooks: !!plan.accountWebhooks,
|
|
404
|
+
status,
|
|
405
|
+
route: plan.customRoute && plan.customRoute.id
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
await writeErrorFlag(plan, null, deps);
|
|
409
|
+
deps.metrics('webhooks', 'inc', { event: job.name, status: 'success' });
|
|
410
|
+
|
|
411
|
+
// Stored by BullMQ as the job's return value in the same write that completes it, so
|
|
412
|
+
// a retained completed job shows what the endpoint answered and how long it took
|
|
413
|
+
return { status: 'delivered', statusCode: status, duration };
|
|
414
|
+
} catch (err) {
|
|
415
|
+
await recordFailure(job, plan, request, err, duration, deps);
|
|
416
|
+
|
|
417
|
+
// Spending the remaining attempts on an unrecoverable failure only delays the operator
|
|
418
|
+
// seeing the real reason in the error flag. Fail the job now and keep the message.
|
|
419
|
+
if (isUnrecoverableWebhookError(err)) {
|
|
420
|
+
// UnrecoverableError copies the message only, and the failed-event handler logs the
|
|
421
|
+
// error it is given, so carry the code over or that log loses the actual reason
|
|
422
|
+
let unrecoverableErr = new UnrecoverableError(err.message);
|
|
423
|
+
unrecoverableErr.code = err.code;
|
|
424
|
+
throw unrecoverableErr;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
throw err;
|
|
428
|
+
} finally {
|
|
429
|
+
if (duration) {
|
|
430
|
+
deps.metrics('webhookReq', 'observe', duration);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Creates the notify queue's job processor
|
|
437
|
+
* @param {Object} deps
|
|
438
|
+
* @param {Object} deps.redis - ioredis client (hmget, pttl, set, hset)
|
|
439
|
+
* @param {Object} deps.settings - lib/settings (get, getMulti, set, clear)
|
|
440
|
+
* @param {Object} deps.webhooks - lib/webhooks instance (getMeta, getWebhooksContentKey)
|
|
441
|
+
* @param {Object} deps.logger - pino logger
|
|
442
|
+
* @param {Function} deps.metrics - (key, method, ...args) metrics reporter
|
|
443
|
+
* @param {Function} deps.openAccountField - (field, value, account) decrypts an account field
|
|
444
|
+
* @param {Function} deps.getServiceSecret - Resolves the HMAC signing secret
|
|
445
|
+
* @param {Function} deps.fetch - fetch implementation
|
|
446
|
+
* @param {Object} [deps.dispatcher] - undici dispatcher
|
|
447
|
+
* @param {number|false} [deps.timeout] - Attempt timeout in ms, false for the default
|
|
448
|
+
* @param {Function} [deps.validateTarget] - Egress policy check
|
|
449
|
+
* @returns {Function} async (job, token) => result
|
|
450
|
+
*/
|
|
451
|
+
function createWebhookProcessor(deps) {
|
|
452
|
+
return async function processWebhookJob(job, token) {
|
|
453
|
+
let plan = await planDelivery(job, token, deps);
|
|
454
|
+
if (!plan) {
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
return await deliver(job, plan, deps);
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
module.exports = { createWebhookProcessor, filterLogData };
|