emailengine-app 2.78.0 → 2.79.1
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 +23 -13
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +68 -0
- package/config/e2e.toml +2 -1
- package/config/test.toml +2 -1
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +112 -36
- package/lib/api-reference/format.js +91 -4
- package/lib/api-reference/model.js +144 -19
- package/lib/api-reference/schema-tree.js +282 -28
- package/lib/api-routes/account-routes.js +80 -34
- package/lib/api-routes/blocklist-routes.js +21 -47
- package/lib/api-routes/chat-routes.js +10 -12
- package/lib/api-routes/delivery-test-routes.js +6 -26
- package/lib/api-routes/export-routes.js +2 -0
- package/lib/api-routes/gateway-routes.js +52 -11
- package/lib/api-routes/license-routes.js +2 -0
- package/lib/api-routes/mailbox-routes.js +29 -26
- package/lib/api-routes/message-routes.js +27 -21
- package/lib/api-routes/oauth2-app-routes.js +11 -29
- package/lib/api-routes/operation-impact.js +80 -0
- package/lib/api-routes/outbox-routes.js +15 -5
- package/lib/api-routes/permission-map.js +401 -0
- package/lib/api-routes/route-helpers.js +294 -9
- package/lib/api-routes/route-metadata.js +28 -0
- package/lib/api-routes/settings-routes.js +66 -38
- package/lib/api-routes/stats-routes.js +2 -2
- package/lib/api-routes/submit-routes.js +53 -31
- package/lib/api-routes/template-routes.js +3 -0
- package/lib/api-routes/token-routes.js +526 -72
- package/lib/api-routes/webhook-route-routes.js +14 -4
- package/lib/arf-detect.js +17 -4
- package/lib/auth-token.js +80 -8
- package/lib/bounce-detect.js +28 -17
- package/lib/consts.js +16 -0
- package/lib/db.js +26 -2
- package/lib/delivery-error.js +30 -1
- package/lib/email-client/base-client.js +27 -41
- package/lib/email-client/gmail-client.js +23 -17
- package/lib/email-client/imap/mailbox.js +58 -59
- package/lib/email-client/imap/subconnection.js +10 -7
- package/lib/email-client/imap/sync-operations.js +46 -46
- package/lib/email-client/imap-client.js +85 -28
- package/lib/email-client/message-builder.js +3 -3
- package/lib/email-client/notification-handler.js +1 -1
- package/lib/email-client/outlook/graph-api.js +10 -4
- package/lib/email-client/outlook-client.js +56 -64
- package/lib/email-client/smtp-pool-manager.js +1 -1
- package/lib/enum-descriptions.js +92 -2
- package/lib/export.js +1 -1
- package/lib/field-usage.js +133 -0
- package/lib/gateway.js +1 -1
- package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
- package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
- package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
- package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
- package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
- package/lib/imapproxy/imap-server.js +27 -7
- package/lib/license-beacon.js +4 -9
- package/lib/lists.js +49 -1
- package/lib/llm-pre-process.js +5 -5
- package/lib/logger.js +5 -1
- package/lib/lua/h-set-new-mark.lua +36 -0
- package/lib/message-port-stream.js +84 -1
- package/lib/metrics-collector.js +2 -2
- package/lib/oauth/gmail.js +9 -12
- package/lib/oauth/mail-ru.js +5 -7
- package/lib/oauth/outlook.js +9 -9
- package/lib/oauth/pubsub/google.js +25 -10
- package/lib/oauth/scope-checker.js +1 -1
- package/lib/oauth2-apps.js +290 -292
- package/lib/openapi/build-document.js +20 -8
- package/lib/openapi/joi-schema.js +20 -0
- package/lib/outbox.js +85 -17
- package/lib/pre-process.js +8 -8
- package/lib/queue-stats.js +49 -0
- package/lib/read-env-value.js +1 -1
- package/lib/reconnection-manager.js +2 -2
- package/lib/rewrite-text-nodes.js +4 -3
- package/lib/routes-ui.js +4 -0
- package/lib/schemas.js +218 -162
- package/lib/settings.js +98 -5
- package/lib/sub-script.js +2 -1
- package/lib/swagger-options.js +2 -1
- package/lib/templates.js +4 -4
- package/lib/threads.js +2 -2
- package/lib/token-audit-log.js +231 -0
- package/lib/token-permission-view.js +219 -0
- package/lib/token-permissions.js +172 -0
- package/lib/tokens.js +247 -66
- package/lib/tools.js +142 -37
- package/lib/ui-routes/account-routes.js +42 -15
- package/lib/ui-routes/admin-config-routes.js +18 -10
- package/lib/ui-routes/admin-entities-routes.js +117 -38
- package/lib/ui-routes/auth-routes.js +30 -24
- package/lib/ui-routes/export-routes.js +10 -4
- package/lib/ui-routes/oauth-config-routes.js +12 -12
- package/lib/ui-routes/reference-routes.js +3 -3
- package/lib/ui-routes/route-helpers.js +78 -2
- package/lib/ui-routes/settings-page.js +1 -1
- package/lib/ui-routes/smtp-test-routes.js +1 -1
- package/lib/ui-routes/suppression-list-routes.js +299 -0
- package/lib/ui-routes/unsubscribe-routes.js +19 -29
- package/lib/utils/decode-headers.js +42 -0
- package/lib/utils/header-map.js +48 -0
- package/lib/utils/network.js +2 -2
- package/lib/utils/unsafe-key.js +59 -0
- package/lib/web-safe-html.js +1 -1
- package/lib/webhook-routing.js +84 -0
- package/lib/webhooks.js +48 -14
- package/package.json +11 -10
- package/sbom.json +1 -1
- package/server.js +116 -55
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +136 -9
- package/static/js/reference.js +456 -10
- package/static/js/ui.js +43 -0
- package/static/licenses.html +51 -41
- package/translations/messages.pot +59 -59
- package/views/accounts/account.hbs +75 -13
- package/views/accounts/browse.hbs +19 -36
- package/views/accounts/edit.hbs +2 -2
- package/views/config/logging.hbs +6 -0
- package/views/config/oauth/app.hbs +0 -2
- package/views/config/security.hbs +13 -0
- package/views/gateways/edit.hbs +1 -1
- package/views/gateways/gateway.hbs +2 -2
- package/views/gateways/index.hbs +7 -7
- package/views/partials/accounts_table.hbs +7 -7
- package/views/partials/oauth_form.hbs +0 -15
- package/views/partials/reference/disclosure.hbs +8 -2
- package/views/partials/reference/operation.hbs +47 -13
- package/views/partials/reference/params.hbs +17 -1
- package/views/partials/reference/schema-node.hbs +110 -52
- package/views/partials/reference/schema-tools.hbs +25 -0
- package/views/partials/reference/try-it.hbs +84 -11
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/ui/checkbox.hbs +2 -2
- package/views/partials/ui/tabs.hbs +7 -1
- package/views/reference/token.hbs +4 -0
- package/views/suppression-lists/index.hbs +85 -0
- package/views/suppression-lists/list.hbs +87 -0
- package/views/templates/index.hbs +10 -4
- package/views/templates/template.hbs +1 -1
- package/views/tokens/index.hbs +53 -6
- package/views/tokens/new.hbs +334 -5
- package/workers/api.js +185 -102
- package/workers/documents.js +46 -26
- package/workers/export.js +20 -8
- package/workers/imap-proxy.js +2 -2
- package/workers/imap.js +77 -78
- package/workers/smtp.js +13 -7
- package/workers/submit.js +40 -30
- package/workers/webhooks.js +80 -26
- package/lib/feature-flags.js +0 -48
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
const Joi = require('joi');
|
|
4
4
|
const { webhooks: Webhooks } = require('../webhooks');
|
|
5
5
|
const { failAction } = require('../tools');
|
|
6
|
-
const { handleError, throwNotFound } = require('./route-helpers');
|
|
6
|
+
const { handleError, throwNotFound, maskSecrets, MASK_NOTE } = require('./route-helpers');
|
|
7
7
|
const { settingsSchema, apiResponses } = require('../schemas');
|
|
8
8
|
|
|
9
9
|
const webhookErrorFlagSchema = Joi.object({
|
|
@@ -27,7 +27,16 @@ async function init(args) {
|
|
|
27
27
|
|
|
28
28
|
async handler(request) {
|
|
29
29
|
try {
|
|
30
|
-
|
|
30
|
+
const listing = await Webhooks.list(request.query.page, request.query.pageSize);
|
|
31
|
+
|
|
32
|
+
// customHeaders and the target URL both carry credentials for the customer's own
|
|
33
|
+
// receiver, so a reader of this listing could otherwise post forged, correctly
|
|
34
|
+
// authenticated webhooks into it
|
|
35
|
+
for (const entry of listing.webhooks || []) {
|
|
36
|
+
maskSecrets(entry);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return listing;
|
|
31
40
|
} catch (err) {
|
|
32
41
|
handleError(request, err);
|
|
33
42
|
}
|
|
@@ -35,7 +44,7 @@ async function init(args) {
|
|
|
35
44
|
|
|
36
45
|
options: {
|
|
37
46
|
description: 'List webhook routes',
|
|
38
|
-
notes:
|
|
47
|
+
notes: `List custom webhook routes. ${MASK_NOTE}`,
|
|
39
48
|
tags: ['api', 'Webhooks'],
|
|
40
49
|
|
|
41
50
|
plugins: {
|
|
@@ -114,6 +123,7 @@ async function init(args) {
|
|
|
114
123
|
if (!webhookRouteData) {
|
|
115
124
|
throwNotFound();
|
|
116
125
|
}
|
|
126
|
+
maskSecrets(webhookRouteData);
|
|
117
127
|
return webhookRouteData;
|
|
118
128
|
} catch (err) {
|
|
119
129
|
handleError(request, err);
|
|
@@ -122,7 +132,7 @@ async function init(args) {
|
|
|
122
132
|
|
|
123
133
|
options: {
|
|
124
134
|
description: 'Get webhook route information',
|
|
125
|
-
notes:
|
|
135
|
+
notes: `Retrieve webhook route content and information. ${MASK_NOTE}`,
|
|
126
136
|
tags: ['api', 'Webhooks'],
|
|
127
137
|
|
|
128
138
|
plugins: {
|
package/lib/arf-detect.js
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
const libmime = require('libmime');
|
|
4
4
|
const addressparser = require('nodemailer/lib/addressparser');
|
|
5
5
|
const { toCamelCase } = require('./utils/to-camel-case');
|
|
6
|
+
const { decodeHeaders } = require('./utils/decode-headers');
|
|
7
|
+
const { isUnsafeTransformedKey } = require('./utils/unsafe-key');
|
|
6
8
|
|
|
7
9
|
const ARF_SINGLE = [
|
|
8
10
|
'feedback-type',
|
|
@@ -33,7 +35,7 @@ const arfDetect = async messageInfo => {
|
|
|
33
35
|
case 'message/feedback-report': {
|
|
34
36
|
// found a feedback report
|
|
35
37
|
|
|
36
|
-
const contents =
|
|
38
|
+
const contents = decodeHeaders((attachment.content || '').toString());
|
|
37
39
|
|
|
38
40
|
Object.keys(contents).forEach(key => {
|
|
39
41
|
let value = contents[key];
|
|
@@ -88,7 +90,7 @@ const arfDetect = async messageInfo => {
|
|
|
88
90
|
contents = contents.substr(0, headerPos.index);
|
|
89
91
|
}
|
|
90
92
|
|
|
91
|
-
const headers =
|
|
93
|
+
const headers = decodeHeaders(contents);
|
|
92
94
|
|
|
93
95
|
// Hotmail original recipient X-HmXmrOriginalRecipient
|
|
94
96
|
const addresses = addressparser([].concat(headers['x-hmxmroriginalrecipient'] || []).join(', '))
|
|
@@ -110,7 +112,7 @@ const arfDetect = async messageInfo => {
|
|
|
110
112
|
}
|
|
111
113
|
|
|
112
114
|
let sourceIp = [].concat(headers['x-sender-ip'] || []).pop();
|
|
113
|
-
if (sourceIp && !report['source-ip']) {
|
|
115
|
+
if (sourceIp && !report.arf['source-ip']) {
|
|
114
116
|
report.arf['source-ip'] = sourceIp;
|
|
115
117
|
}
|
|
116
118
|
|
|
@@ -211,10 +213,21 @@ function camelCaseComplaint(report) {
|
|
|
211
213
|
|
|
212
214
|
for (let subKey of ['arf', 'headers']) {
|
|
213
215
|
for (let key of Object.keys(report[subKey])) {
|
|
216
|
+
// decodeHeaders() dropped the prototype-shaped names at the parse boundary, but
|
|
217
|
+
// toCamelCase() re-creates one out of a name that boundary had no reason to refuse:
|
|
218
|
+
// "_-_proto__" camelCases into "__proto__" (a prototype swap) and "to-string" into
|
|
219
|
+
// "toString" (an own property shadowing the method), hence the transformed-key test
|
|
220
|
+
// covering every Object.prototype member. A feedback report is an attacker-supplied
|
|
221
|
+
// attachment, so the name is theirs to choose.
|
|
222
|
+
let displayKey = toCamelCase(key);
|
|
223
|
+
if (isUnsafeTransformedKey(displayKey)) {
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
|
|
214
227
|
if (!complaint[subKey]) {
|
|
215
228
|
complaint[subKey] = {};
|
|
216
229
|
}
|
|
217
|
-
complaint[subKey][
|
|
230
|
+
complaint[subKey][displayKey] = report[subKey][key];
|
|
218
231
|
}
|
|
219
232
|
}
|
|
220
233
|
|
package/lib/auth-token.js
CHANGED
|
@@ -2,12 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
// Shared token validation for the SMTP and IMAP-proxy submission servers. Both
|
|
4
4
|
// servers accept a 64-char hex API token as the password and apply the same
|
|
5
|
-
// checks (account binding, scope, IP allowlist). The logic lives here so the two
|
|
5
|
+
// checks (account binding, scope, permissions, IP allowlist). The logic lives here so the two
|
|
6
6
|
// auth handlers (lib/smtp-auth.js, lib/imap-proxy-auth.js) cannot drift apart -
|
|
7
7
|
// a token security-policy change is made once and applies to both surfaces.
|
|
8
8
|
|
|
9
9
|
const logger = require('./logger');
|
|
10
10
|
const tokens = require('./tokens');
|
|
11
|
+
const tokenPermissions = require('./token-permissions');
|
|
12
|
+
const tokenAuditLog = require('./token-audit-log');
|
|
13
|
+
const { SURFACE_GRANTS } = require('./api-routes/permission-map');
|
|
11
14
|
const { matchIp } = require('./utils/network');
|
|
12
15
|
|
|
13
16
|
// Reason-specific denial messages, shared verbatim by both auth handlers. The
|
|
@@ -16,22 +19,23 @@ const { matchIp } = require('./utils/network');
|
|
|
16
19
|
const REASON_MESSAGES = {
|
|
17
20
|
username: 'Access denied, invalid username',
|
|
18
21
|
scope: 'Access denied, invalid scope',
|
|
19
|
-
ip: 'Access denied, traffic not accepted from this IP'
|
|
22
|
+
ip: 'Access denied, traffic not accepted from this IP',
|
|
23
|
+
permissions: 'Access denied, token permissions do not allow this'
|
|
20
24
|
};
|
|
21
25
|
|
|
22
26
|
/**
|
|
23
27
|
* Validates a 64-char hex API token supplied as a server password.
|
|
24
28
|
*
|
|
25
|
-
* Performs the token lookup plus the account-binding, scope and
|
|
26
|
-
* checks. Does NOT throw - the caller maps the returned reason to
|
|
27
|
-
* protocol-specific error (SMTP and IMAP use different response shapes).
|
|
29
|
+
* Performs the token lookup plus the account-binding, scope, permission and
|
|
30
|
+
* IP-allowlist checks. Does NOT throw - the caller maps the returned reason to
|
|
31
|
+
* its own protocol-specific error (SMTP and IMAP use different response shapes).
|
|
28
32
|
*
|
|
29
33
|
* @param {Object} opts
|
|
30
34
|
* @param {String} opts.password - supplied password (candidate token)
|
|
31
35
|
* @param {String} opts.account - username the client authenticated as
|
|
32
36
|
* @param {String} opts.requiredScope - scope the token must hold ('smtp' | 'imap-proxy')
|
|
33
37
|
* @param {String} opts.remoteAddress - client IP, checked against token restrictions
|
|
34
|
-
* @returns {Promise<{authenticated: Boolean, reason: (null|'username'|'scope'|'ip')}>}
|
|
38
|
+
* @returns {Promise<{authenticated: Boolean, reason: (null|'username'|'scope'|'permissions'|'ip')}>}
|
|
35
39
|
*/
|
|
36
40
|
async function validateAuthToken({ password, account, requiredScope, remoteAddress }) {
|
|
37
41
|
if (!/^[0-9a-f]{64}$/i.test(password)) {
|
|
@@ -49,12 +53,33 @@ async function validateAuthToken({ password, account, requiredScope, remoteAddre
|
|
|
49
53
|
return { authenticated: false, reason: null };
|
|
50
54
|
}
|
|
51
55
|
|
|
56
|
+
// Built before the first check that can refuse, for the same reason as the HTTP surface: a
|
|
57
|
+
// trail that only held accepted logins would be silent about exactly the ones worth looking at.
|
|
58
|
+
const auditEntry = {
|
|
59
|
+
tokenId: tokenData.id,
|
|
60
|
+
ip: remoteAddress || null,
|
|
61
|
+
method: requiredScope,
|
|
62
|
+
path: requiredScope,
|
|
63
|
+
account
|
|
64
|
+
};
|
|
65
|
+
|
|
52
66
|
if (tokenData.account && tokenData.account !== account) {
|
|
67
|
+
// Logged like the refusals below it, rather than only into the per-token trail: a credential
|
|
68
|
+
// presented for someone else's account is the same class of event as a bad scope, and the
|
|
69
|
+
// application log is the record that leaves the instance.
|
|
70
|
+
logger.warn({
|
|
71
|
+
msg: 'Trying to use a token bound to another account',
|
|
72
|
+
tokenAccount: tokenData.account,
|
|
73
|
+
tokenId: tokenData.id,
|
|
74
|
+
account,
|
|
75
|
+
requestedScope: requiredScope
|
|
76
|
+
});
|
|
77
|
+
tokenAuditLog.denied(auditEntry, 'username');
|
|
53
78
|
return { authenticated: false, reason: 'username' };
|
|
54
79
|
}
|
|
55
80
|
|
|
56
81
|
if (tokenData.scopes && !tokenData.scopes.includes(requiredScope) && !tokenData.scopes.includes('*')) {
|
|
57
|
-
logger.
|
|
82
|
+
logger.warn({
|
|
58
83
|
msg: 'Trying to use invalid scope for a token',
|
|
59
84
|
tokenAccount: tokenData.account,
|
|
60
85
|
tokenId: tokenData.id,
|
|
@@ -62,11 +87,55 @@ async function validateAuthToken({ password, account, requiredScope, remoteAddre
|
|
|
62
87
|
requestedScope: requiredScope,
|
|
63
88
|
scopes: tokenData.scopes
|
|
64
89
|
});
|
|
90
|
+
tokenAuditLog.denied(auditEntry, 'scope');
|
|
65
91
|
return { authenticated: false, reason: 'scope' };
|
|
66
92
|
}
|
|
67
93
|
|
|
94
|
+
// Narrowing below the scope. Checked here rather than in each handler so a policy change cannot
|
|
95
|
+
// land on one submission surface and miss the other, which is why this module exists.
|
|
96
|
+
//
|
|
97
|
+
// An unknown scope resolves to no operation, which denies: a surface this function does not know
|
|
98
|
+
// how to describe must not be reachable by a narrowed token just because nobody mapped it.
|
|
99
|
+
// Object.hasOwn rather than a bare lookup: SCOPE_OPERATIONS['__proto__'] would otherwise return
|
|
100
|
+
// Object.prototype, and Object.values of that is an empty list - which would pass a
|
|
101
|
+
// "does it hold every grant" loop vacuously. A surface nobody mapped must be refused, not waved
|
|
102
|
+
// through, so an unknown scope resolves to no grants at all and denies below.
|
|
103
|
+
const requiredGrants = Object.hasOwn(SURFACE_GRANTS, requiredScope) ? SURFACE_GRANTS[requiredScope] : null;
|
|
104
|
+
|
|
105
|
+
// First refusal wins, so the reported reason names a grant the token actually lacks. An unmapped
|
|
106
|
+
// surface has no grants to check, and check() with no operation denies a narrowed token on
|
|
107
|
+
// UNCLASSIFIED - which is why this passes `null` through rather than skipping the loop.
|
|
108
|
+
//
|
|
109
|
+
// `action`/`group` land on the audit entry only in the refusal branch, and the accept path
|
|
110
|
+
// leaves them null on purpose. These surfaces do not perform an operation: they admit a session
|
|
111
|
+
// that may then exercise every grant the surface carries - five of them for the IMAP proxy - so
|
|
112
|
+
// naming one of the five on an accepted login would report a request that was never made. A
|
|
113
|
+
// refusal is the opposite case: exactly one grant decided it, and that one is worth recording.
|
|
114
|
+
let permissionCheck = { allowed: true, reason: null, required: null };
|
|
115
|
+
for (const operation of requiredGrants || [null]) {
|
|
116
|
+
permissionCheck = tokenPermissions.check({ tokenData, operation });
|
|
117
|
+
if (!permissionCheck.allowed) {
|
|
118
|
+
Object.assign(auditEntry, { action: operation && operation.action, group: operation && operation.group });
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (!permissionCheck.allowed) {
|
|
124
|
+
logger.warn({
|
|
125
|
+
msg: 'Token permissions do not allow this operation',
|
|
126
|
+
tokenAccount: tokenData.account,
|
|
127
|
+
tokenId: tokenData.id,
|
|
128
|
+
account,
|
|
129
|
+
requestedScope: requiredScope,
|
|
130
|
+
reason: permissionCheck.reason,
|
|
131
|
+
required: permissionCheck.required
|
|
132
|
+
});
|
|
133
|
+
tokenAuditLog.denied(auditEntry, permissionCheck.reason);
|
|
134
|
+
return { authenticated: false, reason: 'permissions' };
|
|
135
|
+
}
|
|
136
|
+
|
|
68
137
|
if (tokenData.restrictions && tokenData.restrictions.addresses && !matchIp(remoteAddress, tokenData.restrictions.addresses)) {
|
|
69
|
-
logger.
|
|
138
|
+
logger.warn({
|
|
70
139
|
msg: 'Trying to use invalid IP for a token',
|
|
71
140
|
tokenAccount: tokenData.account,
|
|
72
141
|
tokenId: tokenData.id,
|
|
@@ -74,9 +143,12 @@ async function validateAuthToken({ password, account, requiredScope, remoteAddre
|
|
|
74
143
|
remoteAddress,
|
|
75
144
|
addressAllowlist: tokenData.restrictions.addresses
|
|
76
145
|
});
|
|
146
|
+
tokenAuditLog.denied(auditEntry, 'ip');
|
|
77
147
|
return { authenticated: false, reason: 'ip' };
|
|
78
148
|
}
|
|
79
149
|
|
|
150
|
+
tokenAuditLog.allowed(auditEntry);
|
|
151
|
+
|
|
80
152
|
return { authenticated: true, reason: null };
|
|
81
153
|
}
|
|
82
154
|
|
package/lib/bounce-detect.js
CHANGED
|
@@ -22,7 +22,9 @@
|
|
|
22
22
|
* @requires mailparser - For parsing email messages
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
|
-
const
|
|
25
|
+
const { decodeHeaders } = require('./utils/decode-headers');
|
|
26
|
+
const { isUnsafeTransformedKey } = require('./utils/unsafe-key');
|
|
27
|
+
const { pushHeaderValue } = require('./utils/header-map');
|
|
26
28
|
const simpleParser = require('mailparser').simpleParser;
|
|
27
29
|
const { toCamelCase } = require('./utils/to-camel-case');
|
|
28
30
|
|
|
@@ -45,7 +47,7 @@ function splitAddressType(value) {
|
|
|
45
47
|
*
|
|
46
48
|
* A DSN body is not a single header block. RFC 3464 splits it into a per-message block and a
|
|
47
49
|
* separate per-recipient block for every reported address, with an empty line between them.
|
|
48
|
-
*
|
|
50
|
+
* decodeHeaders() stops at the first empty line, as that is where a header block ends,
|
|
49
51
|
* so each block is decoded on its own.
|
|
50
52
|
*
|
|
51
53
|
* @param {string|Buffer} content - Raw message/delivery-status body
|
|
@@ -57,7 +59,7 @@ function decodeDeliveryStatusBlocks(content) {
|
|
|
57
59
|
.toString()
|
|
58
60
|
.replace(/\r\n|\r/g, '\n')
|
|
59
61
|
.split(/\n{2,}/)
|
|
60
|
-
.map(block =>
|
|
62
|
+
.map(block => decodeHeaders(block))
|
|
61
63
|
// A block of nothing but a continuation line decodes to a single empty key, which is
|
|
62
64
|
// not a header and would otherwise be merged into the result
|
|
63
65
|
.filter(entries => Object.keys(entries).some(key => key))
|
|
@@ -126,14 +128,23 @@ function parseDeliveryReport(content) {
|
|
|
126
128
|
let structured = {};
|
|
127
129
|
|
|
128
130
|
for (let key of Object.keys(entries)) {
|
|
129
|
-
|
|
130
|
-
// it would hand the value to the Object.prototype setter and swap the report's prototype,
|
|
131
|
-
// and defining it as an own property instead leaves a key msgpack refuses to decode
|
|
132
|
-
if (!key || key === '__proto__') {
|
|
131
|
+
if (!key) {
|
|
133
132
|
continue;
|
|
134
133
|
}
|
|
135
134
|
|
|
135
|
+
// The field names come from the message. "__proto__" names no DSN field, while assigning
|
|
136
|
+
// it would hand the value to the Object.prototype setter and swap the report's prototype,
|
|
137
|
+
// and defining it as an own property instead leaves a key msgpack refuses to decode.
|
|
138
|
+
//
|
|
139
|
+
// Checked on the camelCased key rather than the raw name: decodeHeaders() already dropped
|
|
140
|
+
// the raw name at the parse boundary, but toCamelCase() re-creates it out of a name that
|
|
141
|
+
// boundary had no reason to refuse - "_-_proto__" camelCases straight into "__proto__",
|
|
142
|
+
// and "to-string" into "toString", which as an own property shadows the method on the
|
|
143
|
+
// published report - hence the transformed-key test covering every Object.prototype member.
|
|
136
144
|
let displayKey = toCamelCase(key);
|
|
145
|
+
if (isUnsafeTransformedKey(displayKey)) {
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
137
148
|
let value = entries[key].at(-1);
|
|
138
149
|
|
|
139
150
|
if (typeof value !== 'string') {
|
|
@@ -247,7 +258,7 @@ function parseDeliveryStatus(content) {
|
|
|
247
258
|
* Takes decoded entries rather than the raw attachment, as every caller has just decoded the
|
|
248
259
|
* same content, most of them to keep as the reported message headers.
|
|
249
260
|
*
|
|
250
|
-
* @param {Object} entries - Header entries from
|
|
261
|
+
* @param {Object} entries - Header entries from decodeHeaders()
|
|
251
262
|
* @returns {Object} Parsed header information
|
|
252
263
|
* @returns {string} [returns.messageId] - The Message-ID header value
|
|
253
264
|
*/
|
|
@@ -359,7 +370,7 @@ async function bounceDetect(sourceStream) {
|
|
|
359
370
|
|
|
360
371
|
// Process RFC822 headers attachment (contains headers of the original message)
|
|
361
372
|
if (messageHeaders) {
|
|
362
|
-
parsedMessageHeaders =
|
|
373
|
+
parsedMessageHeaders = decodeHeaders((messageHeaders.content || '').toString().trim());
|
|
363
374
|
result = Object.assign(result, parseDeliveryHeaders(parsedMessageHeaders));
|
|
364
375
|
}
|
|
365
376
|
|
|
@@ -374,11 +385,11 @@ async function bounceDetect(sourceStream) {
|
|
|
374
385
|
|
|
375
386
|
if (parsedOriginal.headerLines && Array.isArray(parsedOriginal.headerLines)) {
|
|
376
387
|
parsedOriginal.headerLines.forEach(entry => {
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
//
|
|
381
|
-
headers
|
|
388
|
+
// Preserve the original header value (after the key and colon).
|
|
389
|
+
// pushHeaderValue() skips names that resolve to an Object.prototype member,
|
|
390
|
+
// which a bare `!headers[key]` probe would have pushed onto, throwing out of
|
|
391
|
+
// the whole block and losing every header of the bounced message
|
|
392
|
+
pushHeaderValue(headers, entry.key, entry.line.substring(entry.key.length + 1).trim());
|
|
382
393
|
});
|
|
383
394
|
}
|
|
384
395
|
|
|
@@ -402,7 +413,7 @@ async function bounceDetect(sourceStream) {
|
|
|
402
413
|
if (!messageHeaders) {
|
|
403
414
|
messageHeaders = originalAttachments.find(attachment => attachment.contentType?.toLowerCase() === 'text/rfc822-headers');
|
|
404
415
|
if (messageHeaders) {
|
|
405
|
-
let headerEntries =
|
|
416
|
+
let headerEntries = decodeHeaders((messageHeaders.content || '').toString().trim());
|
|
406
417
|
result = Object.assign(result, parseDeliveryHeaders(headerEntries));
|
|
407
418
|
}
|
|
408
419
|
}
|
|
@@ -459,7 +470,7 @@ async function bounceDetect(sourceStream) {
|
|
|
459
470
|
// Additional validation: content should look like email headers
|
|
460
471
|
// Check for common header patterns (Received:, Message-ID:, Date:, From:)
|
|
461
472
|
if (/^\s*(Received|Message-ID|Date|From):/im.test(headerContent)) {
|
|
462
|
-
let headers =
|
|
473
|
+
let headers = decodeHeaders(headerContent);
|
|
463
474
|
if (headers && headers['message-id']) {
|
|
464
475
|
parsedMessageHeaders = headers;
|
|
465
476
|
result = Object.assign(result, parseDeliveryHeaders(headers));
|
|
@@ -905,7 +916,7 @@ async function bounceDetect(sourceStream) {
|
|
|
905
916
|
let end = text.substr(m.index + m[0].length).match(/\r?\n\r?\n|$/);
|
|
906
917
|
if (end) {
|
|
907
918
|
let headers = text.substr(m.index, m[0].length + end.index).trim();
|
|
908
|
-
let entries =
|
|
919
|
+
let entries = decodeHeaders(headers);
|
|
909
920
|
if (entries['message-id'] && entries['message-id'].length) {
|
|
910
921
|
result.messageId = entries['message-id'][0].trim();
|
|
911
922
|
// Only use these headers if we haven't found headers elsewhere
|
package/lib/consts.js
CHANGED
|
@@ -207,6 +207,12 @@ module.exports = {
|
|
|
207
207
|
|
|
208
208
|
NONCE_BYTES: 16,
|
|
209
209
|
|
|
210
|
+
// Longest account id EmailEngine accepts. Defined here rather than only on `accountIdSchema`
|
|
211
|
+
// because the token audit log truncates to it while writing, before route validation has had a
|
|
212
|
+
// chance to reject a longer one, and the two have to agree: a log that trimmed at a different
|
|
213
|
+
// length would store a string that names no account while claiming to name one.
|
|
214
|
+
MAX_ACCOUNT_ID_LENGTH: 256,
|
|
215
|
+
|
|
210
216
|
// Class names on the collapse marker web-safe HTML wraps quoted thread history in. Part of the
|
|
211
217
|
// output contract - consumers select on them to style or hide the block - so they are defined
|
|
212
218
|
// once here and referenced by both the generator (lib/web-safe-html.js) and the API docs.
|
|
@@ -273,6 +279,16 @@ module.exports = {
|
|
|
273
279
|
'UND_ERR_HEADERS_TIMEOUT'
|
|
274
280
|
]),
|
|
275
281
|
|
|
282
|
+
// Error codes meaning "the IMAP connection is gone", as opposed to the command itself failing
|
|
283
|
+
CONNECTION_CLOSING_CODES: new Set(['IMAPConnectionClosing', 'EConnectionClosed', 'NoConnection']),
|
|
284
|
+
|
|
285
|
+
// Applied by lib/logger.js to the root logger, so every worker inherits it. A logged joi
|
|
286
|
+
// ValidationError carries the full submitted payload in `_original` and the offending value in
|
|
287
|
+
// each detail context, and `rawPacket` is a TLS-error field that can carry an unparsed
|
|
288
|
+
// credential frame - without these a failed validation writes plaintext passwords, OAuth2
|
|
289
|
+
// client secrets and access tokens into the log, the per-account log store and Sentry.
|
|
290
|
+
REDACTED_LOG_KEYS: ['req.headers.authorization', 'req.headers.cookie', 'err.rawPacket', 'err._original', 'err.details[*].context.value'],
|
|
291
|
+
|
|
276
292
|
generateWebhookTable() {
|
|
277
293
|
let entries = [];
|
|
278
294
|
|
package/lib/db.js
CHANGED
|
@@ -108,9 +108,11 @@ const redis = new Redis(REDIS_CONF);
|
|
|
108
108
|
|
|
109
109
|
const reqisQueue = new Redis(REDIS_CONF);
|
|
110
110
|
|
|
111
|
+
// Passing an ioredis instance as `connection` (rather than connection options) is what keeps BullMQ
|
|
112
|
+
// from closing the client on its own: it marks the connection shared via isRedisInstance() and only
|
|
113
|
+
// disconnects the ones it created itself.
|
|
111
114
|
module.exports.queueConf = {
|
|
112
115
|
connection: reqisQueue,
|
|
113
|
-
sharedConnection: true, // Prevent BullMQ from closing shared connection
|
|
114
116
|
prefix: `${REDIS_PREFIX}bull`
|
|
115
117
|
};
|
|
116
118
|
|
|
@@ -131,6 +133,7 @@ const hSetBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-bigg
|
|
|
131
133
|
const hUpdateBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-update-bigger.lua'), 'utf-8');
|
|
132
134
|
const hSetExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-exists.lua'), 'utf-8');
|
|
133
135
|
const hSetNewScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-new.lua'), 'utf-8');
|
|
136
|
+
const hSetNewMarkScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-new-mark.lua'), 'utf-8');
|
|
134
137
|
const hIncrbyExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-incrby-exists.lua'), 'utf-8');
|
|
135
138
|
const eeListAddScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-add.lua'), 'utf-8');
|
|
136
139
|
const eeListRemoveScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-remove.lua'), 'utf-8');
|
|
@@ -196,6 +199,11 @@ redis.defineCommand('hSetNew', {
|
|
|
196
199
|
lua: hSetNewScript
|
|
197
200
|
});
|
|
198
201
|
|
|
202
|
+
redis.defineCommand('hSetNewMark', {
|
|
203
|
+
numberOfKeys: 1,
|
|
204
|
+
lua: hSetNewMarkScript
|
|
205
|
+
});
|
|
206
|
+
|
|
199
207
|
redis.defineCommand('hIncrbyExists', {
|
|
200
208
|
numberOfKeys: 1,
|
|
201
209
|
lua: hIncrbyExistsScript
|
|
@@ -222,6 +230,15 @@ module.exports.submitQueue = submitQueue;
|
|
|
222
230
|
module.exports.documentsQueue = documentsQueue;
|
|
223
231
|
module.exports.exportQueue = exportQueue;
|
|
224
232
|
|
|
233
|
+
// Queues addressable by the name the API and the stats payload use for them. `export` is
|
|
234
|
+
// deliberately absent: neither surface exposes it, and the {queue} route parameter is validated
|
|
235
|
+
// against this same set of names.
|
|
236
|
+
module.exports.QUEUES_BY_NAME = {
|
|
237
|
+
notify: notifyQueue,
|
|
238
|
+
submit: submitQueue,
|
|
239
|
+
documents: documentsQueue
|
|
240
|
+
};
|
|
241
|
+
|
|
225
242
|
// do not set up the flow producer by default
|
|
226
243
|
module.exports.getFlowProducer = () => new FlowProducer(module.exports.queueConf /*, Redis*/);
|
|
227
244
|
|
|
@@ -248,7 +265,14 @@ To run EmailEngine provide valid Redis configuration
|
|
|
248
265
|
process.exit(1);
|
|
249
266
|
}
|
|
250
267
|
|
|
251
|
-
|
|
268
|
+
// Only reached when the process stays up (the exit path above never returns), so this must
|
|
269
|
+
// not log at fatal. A post-connection error is retried by ioredis on its own, so it is a
|
|
270
|
+
// warning; config-class errors (forceClose) that did not trigger an exit are logged at error.
|
|
271
|
+
if (forceClose) {
|
|
272
|
+
logger.error({ msg: msg || 'Redis connection error', err });
|
|
273
|
+
} else {
|
|
274
|
+
logger.warn({ msg: msg || 'Redis connection error', err });
|
|
275
|
+
}
|
|
252
276
|
};
|
|
253
277
|
|
|
254
278
|
redis.on('connect', () => {
|
package/lib/delivery-error.js
CHANGED
|
@@ -82,4 +82,33 @@ function shouldDiscardJob(err, job) {
|
|
|
82
82
|
return isPermanentDeliveryError(err) && job.attemptsMade < job.opts.attempts;
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
|
|
85
|
+
// BullMQ increments job.attemptsMade when an attempt FAILS, not when it starts. The two helpers
|
|
86
|
+
// below encode that phase difference once, because getting it wrong by one is a recurring trap:
|
|
87
|
+
// inside a processor the ongoing attempt is attemptsMade + 1, while inside a worker 'failed' event
|
|
88
|
+
// handler the failed attempt is already counted. Used by the queue workers to decide whether a
|
|
89
|
+
// failure log is the final, operator-actionable record or a routine retryable attempt.
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Inside a job processor: is the CURRENTLY RUNNING attempt the job's last one?
|
|
93
|
+
*
|
|
94
|
+
* @param {Object} job - BullMQ job (mid-processing, attemptsMade not yet incremented)
|
|
95
|
+
* @returns {Boolean} True when a failure of this attempt will not be retried
|
|
96
|
+
*/
|
|
97
|
+
function willBeFinalAttempt(job) {
|
|
98
|
+
return job.attemptsMade + 1 >= (job.opts.attempts || 1);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Inside a worker 'failed' event handler: was the failure that just happened the job's last
|
|
103
|
+
* attempt? finishedOn covers a job ended by UnrecoverableError regardless of remaining attempts.
|
|
104
|
+
* (It used to also check `discarded`, for jobs ended by Job#discard(); BullMQ 6 removed both the
|
|
105
|
+
* method and the property, and UnrecoverableError is the replacement.)
|
|
106
|
+
*
|
|
107
|
+
* @param {Object} job - BullMQ job (attemptsMade already incremented for the failed attempt)
|
|
108
|
+
* @returns {Boolean} True when nothing will be retried and the job is finished for good
|
|
109
|
+
*/
|
|
110
|
+
function isFinalFailedAttempt(job) {
|
|
111
|
+
return !!job.finishedOn || job.attemptsMade >= (job.opts.attempts || 1);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
module.exports = { NON_RETRYABLE_CODES, isPermanentDeliveryError, shouldDiscardJob, willBeFinalAttempt, isFinalFailedAttempt };
|