emailengine-app 2.77.0 → 2.79.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/test.yml +80 -0
- package/.ncurc.js +23 -13
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +60 -0
- package/bin/emailengine.js +1 -1
- package/config/e2e.toml +2 -1
- package/config/test.toml +2 -1
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +1 -1
- package/lib/account/expected-identity.js +88 -0
- package/lib/account.js +145 -61
- package/lib/api-reference/format.js +105 -4
- package/lib/api-reference/index.js +24 -7
- package/lib/api-reference/model.js +148 -21
- package/lib/api-reference/schema-tree.js +282 -28
- package/lib/api-routes/account-routes.js +99 -36
- package/lib/api-routes/behavior-notes.js +3 -0
- 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 +397 -0
- package/lib/api-routes/route-helpers.js +223 -9
- package/lib/api-routes/route-metadata.js +28 -0
- package/lib/api-routes/settings-routes.js +30 -25
- 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 +319 -33
- package/lib/api-routes/webhook-route-routes.js +14 -4
- package/lib/append-list.js +3 -14
- package/lib/arf-detect.js +23 -1
- package/lib/auth-token.js +80 -8
- package/lib/autodetect-imap-settings.js +40 -16
- package/lib/base32.js +30 -0
- package/lib/bounce-detect.js +182 -62
- package/lib/consts.js +10 -0
- package/lib/db.js +20 -2
- package/lib/delivery-error.js +30 -1
- package/lib/egress-filter.js +89 -8
- package/lib/email-client/base-client.js +35 -113
- package/lib/email-client/gmail-client.js +22 -13
- package/lib/email-client/imap/listing-diff.js +3 -3
- package/lib/email-client/imap/mailbox.js +28 -93
- 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 +39 -28
- package/lib/email-client/message-builder.js +15 -15
- 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 +54 -55
- package/lib/email-client/smtp-pool-manager.js +1 -1
- package/lib/enum-descriptions.js +92 -2
- package/lib/export.js +2 -2
- package/lib/field-usage.js +133 -0
- package/lib/gateway.js +2 -2
- package/lib/get-raw-email.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 +17 -7
- package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
- package/lib/imapproxy/imap-server.js +40 -10
- package/lib/license-beacon.js +5 -10
- package/lib/lists.js +49 -1
- package/lib/llm-pre-process.js +6 -6
- package/lib/logger.js +5 -1
- package/lib/metrics-collector.js +2 -2
- package/lib/msgpack.js +62 -0
- package/lib/oauth/decode-jwt-payload.js +39 -0
- package/lib/oauth/gmail.js +9 -12
- package/lib/oauth/mail-ru.js +5 -7
- package/lib/oauth/outlook-identity.js +61 -0
- package/lib/oauth/outlook.js +9 -9
- package/lib/oauth/pubsub/google.js +25 -10
- package/lib/oauth/retry-setup.js +38 -0
- package/lib/oauth/scope-checker.js +1 -1
- package/lib/oauth2-apps.js +224 -295
- package/lib/openapi/build-document.js +15 -7
- package/lib/openapi/joi-schema.js +20 -0
- package/lib/outbox.js +145 -14
- package/lib/pre-process.js +9 -9
- package/lib/queue-stats.js +49 -0
- package/lib/read-env-value.js +37 -0
- 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 +223 -155
- package/lib/settings.js +84 -5
- package/lib/sub-script.js +2 -1
- package/lib/swagger-options.js +2 -1
- package/lib/templates.js +5 -5
- package/lib/threads.js +2 -2
- package/lib/token-audit-log.js +208 -0
- package/lib/token-permission-view.js +219 -0
- package/lib/token-permissions.js +172 -0
- package/lib/tokens.js +100 -16
- package/lib/tools.js +259 -85
- package/lib/totp.js +67 -0
- package/lib/ui-routes/account-routes.js +122 -26
- package/lib/ui-routes/admin-config-routes.js +20 -17
- package/lib/ui-routes/admin-entities-routes.js +66 -22
- package/lib/ui-routes/auth-routes.js +36 -48
- package/lib/ui-routes/export-routes.js +10 -4
- package/lib/ui-routes/oauth-config-routes.js +5 -5
- package/lib/ui-routes/reference-routes.js +11 -8
- package/lib/ui-routes/route-helpers.js +79 -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 +294 -0
- package/lib/ui-routes/unsubscribe-routes.js +19 -29
- package/lib/utils/is-email.js +34 -0
- package/lib/utils/network.js +2 -2
- package/lib/utils/to-camel-case.js +17 -0
- package/lib/web-safe-html.js +1 -1
- package/lib/webhook-egress.js +37 -0
- package/lib/webhook-routing.js +80 -0
- package/lib/webhooks.js +21 -15
- package/package.json +26 -27
- package/sbom.json +1 -0
- package/server.js +81 -42
- package/static/css/flyonui.css +1 -1
- package/static/css/public.css +3 -0
- package/static/css/src/app.tailwind.css +159 -9
- package/static/js/app.js +69 -0
- package/static/js/reference.js +741 -10
- package/static/js/ui.js +43 -0
- package/static/licenses.html +698 -1590
- package/translations/README.md +64 -0
- package/translations/de.mo +0 -0
- package/translations/de.po +164 -120
- package/translations/en.po +200 -161
- package/translations/et.mo +0 -0
- package/translations/et.po +163 -120
- package/translations/fr.mo +0 -0
- package/translations/fr.po +163 -120
- package/translations/ja.mo +0 -0
- package/translations/ja.po +163 -120
- package/translations/messages.pot +94 -64
- package/translations/nl.mo +0 -0
- package/translations/nl.po +164 -120
- package/translations/pl.mo +0 -0
- package/translations/pl.po +163 -120
- package/views/account-identity-error.hbs +34 -0
- package/views/accounts/account.hbs +69 -7
- package/views/accounts/browse.hbs +18 -35
- package/views/accounts/edit.hbs +1 -0
- package/views/accounts/register/imap.hbs +12 -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/layout/app.hbs +29 -5
- package/views/oauth-scope-error.hbs +1 -1
- package/views/partials/oauth_form.hbs +0 -15
- package/views/partials/reference/disclosure.hbs +8 -2
- package/views/partials/reference/nav.hbs +36 -9
- package/views/partials/reference/operation.hbs +48 -14
- package/views/partials/reference/params.hbs +17 -1
- package/views/partials/reference/schema-node.hbs +112 -54
- package/views/partials/reference/schema-tools.hbs +25 -0
- package/views/partials/reference/token-alert.hbs +35 -10
- 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/index.hbs +1 -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 +8 -2
- package/views/tokens/index.hbs +31 -4
- package/views/tokens/new.hbs +324 -2
- package/workers/api.js +299 -140
- package/workers/documents.js +46 -26
- package/workers/export.js +20 -8
- package/workers/imap-proxy.js +2 -2
- package/workers/imap.js +13 -7
- package/workers/smtp.js +13 -7
- package/workers/submit.js +41 -31
- package/workers/webhooks.js +60 -37
- package/lib/feature-flags.js +0 -48
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
|
|
|
@@ -2,23 +2,42 @@
|
|
|
2
2
|
|
|
3
3
|
const punycode = require('punycode.js');
|
|
4
4
|
const dns = require('dns').promises;
|
|
5
|
-
const {
|
|
6
|
-
const util = require('util');
|
|
5
|
+
const { XMLParser, XMLValidator } = require('fast-xml-parser');
|
|
7
6
|
const packageData = require('../package.json');
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
)
|
|
7
|
+
|
|
8
|
+
// Configured to produce the same tree shape as the xml2js options this module was written
|
|
9
|
+
// against: lowercased tag names, child elements always as arrays (but not the root), attributes
|
|
10
|
+
// grouped under `$`, text of an attributed element under `_`, and entity references decoded.
|
|
11
|
+
// The `isArray` jpath check is what keeps the root an object: only the root's jpath has no dot.
|
|
12
|
+
const xmlParser = new XMLParser({
|
|
13
|
+
ignoreDeclaration: true,
|
|
14
|
+
ignoreAttributes: false,
|
|
15
|
+
attributesGroupName: '$',
|
|
16
|
+
attributeNamePrefix: '',
|
|
17
|
+
textNodeName: '_',
|
|
18
|
+
isArray: (name, jpath, isLeafNode, isAttribute) => !isAttribute && jpath.includes('.'),
|
|
19
|
+
transformTagName: tag => tag.toLowerCase(),
|
|
20
|
+
parseTagValue: false,
|
|
21
|
+
trimValues: true,
|
|
22
|
+
htmlEntities: true
|
|
20
23
|
});
|
|
21
24
|
|
|
25
|
+
function parseXml(text) {
|
|
26
|
+
if (!text || !text.trim()) {
|
|
27
|
+
// xml2js resolved an empty document to null instead of erroring, callers check for it
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const validation = XMLValidator.validate(text);
|
|
32
|
+
if (validation !== true) {
|
|
33
|
+
let err = new Error(`Failed to parse XML: ${validation.err.msg}`);
|
|
34
|
+
err.code = 'EXmlParseError';
|
|
35
|
+
throw err;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return xmlParser.parse(text);
|
|
39
|
+
}
|
|
40
|
+
|
|
22
41
|
const { fetch: fetchCmd } = require('undici');
|
|
23
42
|
const { httpAgent } = require('./tools');
|
|
24
43
|
|
|
@@ -178,7 +197,7 @@ async function processAutoconfigFile(email, domain, text, source) {
|
|
|
178
197
|
} catch (err) {
|
|
179
198
|
//ignore
|
|
180
199
|
}
|
|
181
|
-
let json =
|
|
200
|
+
let json = parseXml(text);
|
|
182
201
|
|
|
183
202
|
let emailProviders = json && json.clientconfig && Array.isArray(json.clientconfig.emailprovider) ? json.clientconfig.emailprovider : [];
|
|
184
203
|
let incomingServer = emailProviders
|
|
@@ -697,7 +716,11 @@ async function resolveUsingAutodiscovery(email, domain, source) {
|
|
|
697
716
|
|
|
698
717
|
let text = await res.text();
|
|
699
718
|
|
|
700
|
-
|
|
719
|
+
return await processAutodiscoverResponse(text, source);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
async function processAutodiscoverResponse(text, source) {
|
|
723
|
+
let json = parseXml(text);
|
|
701
724
|
|
|
702
725
|
let imap = false;
|
|
703
726
|
let smtp = false;
|
|
@@ -829,6 +852,7 @@ module.exports.autodetectImapSettings = autodetectImapSettings;
|
|
|
829
852
|
// Exposed for unit testing of the pure parsing/matching helpers. These have no
|
|
830
853
|
// network side effects, so they can be exercised directly without mocking DNS or HTTP.
|
|
831
854
|
module.exports.processAutoconfigFile = processAutoconfigFile;
|
|
855
|
+
module.exports.processAutodiscoverResponse = processAutodiscoverResponse;
|
|
832
856
|
module.exports.getAppPassword = getAppPassword;
|
|
833
857
|
module.exports.resolveAppPassword = resolveAppPassword;
|
|
834
858
|
module.exports.escapeXml = escapeXml;
|
package/lib/base32.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// RFC 4648 base32 without padding. Replaces the unmaintained base32.js package; output is
|
|
4
|
+
// byte-identical to its encoder for the two uses in this codebase (otpauth: URL secrets and
|
|
5
|
+
// IMAP proxy connection ids), which never need padding or decoding.
|
|
6
|
+
|
|
7
|
+
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
|
8
|
+
|
|
9
|
+
function base32Encode(buf) {
|
|
10
|
+
let bits = 0;
|
|
11
|
+
let value = 0;
|
|
12
|
+
let output = '';
|
|
13
|
+
|
|
14
|
+
for (let octet of buf) {
|
|
15
|
+
value = (value << 8) | octet;
|
|
16
|
+
bits += 8;
|
|
17
|
+
while (bits >= 5) {
|
|
18
|
+
output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
|
|
19
|
+
bits -= 5;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (bits > 0) {
|
|
24
|
+
output += BASE32_ALPHABET[(value << (5 - bits)) & 31];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return output;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
module.exports = { base32Encode };
|
package/lib/bounce-detect.js
CHANGED
|
@@ -24,6 +24,136 @@
|
|
|
24
24
|
|
|
25
25
|
const libmime = require('libmime');
|
|
26
26
|
const simpleParser = require('mailparser').simpleParser;
|
|
27
|
+
const { toCamelCase } = require('./utils/to-camel-case');
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Splits the address type off a DSN value, eg. "rfc822; user@example.com"
|
|
31
|
+
*
|
|
32
|
+
* @param {string} value - Raw field value
|
|
33
|
+
* @returns {Object} { label, value }, with label absent when the value carries no type
|
|
34
|
+
*/
|
|
35
|
+
function splitAddressType(value) {
|
|
36
|
+
let splitPos = value.indexOf(';');
|
|
37
|
+
if (splitPos < 0) {
|
|
38
|
+
return { value: value.trim() };
|
|
39
|
+
}
|
|
40
|
+
return { label: value.substring(0, splitPos).trim(), value: value.substring(splitPos + 1).trim() };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Splits the body of a message/delivery-status part into its header blocks
|
|
45
|
+
*
|
|
46
|
+
* A DSN body is not a single header block. RFC 3464 splits it into a per-message block and a
|
|
47
|
+
* separate per-recipient block for every reported address, with an empty line between them.
|
|
48
|
+
* libmime.decodeHeaders() stops at the first empty line, as that is where a header block ends,
|
|
49
|
+
* so each block is decoded on its own.
|
|
50
|
+
*
|
|
51
|
+
* @param {string|Buffer} content - Raw message/delivery-status body
|
|
52
|
+
* @returns {Object[]} One header entries object per non-empty block, in source order
|
|
53
|
+
*/
|
|
54
|
+
function decodeDeliveryStatusBlocks(content) {
|
|
55
|
+
return (
|
|
56
|
+
(content || '')
|
|
57
|
+
.toString()
|
|
58
|
+
.replace(/\r\n|\r/g, '\n')
|
|
59
|
+
.split(/\n{2,}/)
|
|
60
|
+
.map(block => libmime.decodeHeaders(block))
|
|
61
|
+
// A block of nothing but a continuation line decodes to a single empty key, which is
|
|
62
|
+
// not a header and would otherwise be merged into the result
|
|
63
|
+
.filter(entries => Object.keys(entries).some(key => key))
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Tells whether a decoded DSN block describes a recipient rather than the message
|
|
69
|
+
*
|
|
70
|
+
* @param {Object} entries - Header entries of one block
|
|
71
|
+
* @returns {Boolean} True for a per-recipient block
|
|
72
|
+
*/
|
|
73
|
+
function isRecipientBlock(entries) {
|
|
74
|
+
return !!(entries['final-recipient'] || entries['original-recipient']);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Decodes a message/delivery-status body into the header entries of a single reported recipient
|
|
79
|
+
*
|
|
80
|
+
* A DSN may report on several recipients, but everything downstream of this describes one
|
|
81
|
+
* delivery. Merging every block together would mix them: a recipient that failed without a
|
|
82
|
+
* Diagnostic-Code would be paired with the diagnostic code of the next recipient. So the
|
|
83
|
+
* per-message fields are merged with exactly one per-recipient block, and a body that reports
|
|
84
|
+
* no recipient at all is merged whole.
|
|
85
|
+
*
|
|
86
|
+
* @param {string|Buffer} content - Raw message/delivery-status body
|
|
87
|
+
* @returns {Object} Header keys mapped to arrays of values, in source order
|
|
88
|
+
*/
|
|
89
|
+
function decodeDeliveryStatus(content) {
|
|
90
|
+
let blocks = decodeDeliveryStatusBlocks(content);
|
|
91
|
+
|
|
92
|
+
// The first reported recipient is the one described, the same one the bounce path has
|
|
93
|
+
// always read off the merged bag
|
|
94
|
+
let reported = blocks.find(isRecipientBlock);
|
|
95
|
+
|
|
96
|
+
// Prototype-less, the keys come straight from the message: with a plain object a
|
|
97
|
+
// "__proto__:" header would make entries[key] the inherited prototype rather than an array
|
|
98
|
+
let entries = Object.create(null);
|
|
99
|
+
for (let block of blocks) {
|
|
100
|
+
if (block !== reported && isRecipientBlock(block)) {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
for (let key of Object.keys(block)) {
|
|
105
|
+
entries[key] = (entries[key] || []).concat(block[key]);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return entries;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Builds the camelCased delivery report exposed for a message/delivery-status part
|
|
114
|
+
*
|
|
115
|
+
* Where decodeDeliveryStatus() returns the raw header entries, this turns them into the shape
|
|
116
|
+
* published on messageData.deliveryReport: keys camelCased, Arrival-Date normalized to an ISO
|
|
117
|
+
* timestamp, and a field that carries an address type reported as { label, value } - so
|
|
118
|
+
* "Final-Recipient: rfc822; user@example.com" becomes
|
|
119
|
+
* finalRecipient: { label: 'rfc822', value: 'user@example.com' }.
|
|
120
|
+
*
|
|
121
|
+
* @param {string|Buffer} content - Raw message/delivery-status body
|
|
122
|
+
* @returns {Object} Delivery report keyed by camelCased field name
|
|
123
|
+
*/
|
|
124
|
+
function parseDeliveryReport(content) {
|
|
125
|
+
let entries = decodeDeliveryStatus(content);
|
|
126
|
+
let structured = {};
|
|
127
|
+
|
|
128
|
+
for (let key of Object.keys(entries)) {
|
|
129
|
+
// The field names come from the message. "__proto__" names no DSN field, while assigning
|
|
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__') {
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
let displayKey = toCamelCase(key);
|
|
137
|
+
let value = entries[key].at(-1);
|
|
138
|
+
|
|
139
|
+
if (typeof value !== 'string') {
|
|
140
|
+
structured[displayKey] = value;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Only a leading token counts as an address type, a semicolon inside prose does not
|
|
145
|
+
if (/^[^\s;]+;/.test(value)) {
|
|
146
|
+
structured[displayKey] = splitAddressType(value);
|
|
147
|
+
} else if (key === 'arrival-date') {
|
|
148
|
+
let date = new Date(value.trim());
|
|
149
|
+
structured[displayKey] = date.toString() !== 'Invalid Date' ? date.toISOString() : value;
|
|
150
|
+
} else {
|
|
151
|
+
structured[displayKey] = value.trim();
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return structured;
|
|
156
|
+
}
|
|
27
157
|
|
|
28
158
|
/**
|
|
29
159
|
* Parses a message/delivery-status attachment to extract bounce information
|
|
@@ -41,38 +171,21 @@ const simpleParser = require('mailparser').simpleParser;
|
|
|
41
171
|
* @returns {string} [returns.messageId] - The original message ID
|
|
42
172
|
*/
|
|
43
173
|
function parseDeliveryStatus(content) {
|
|
44
|
-
// Ensure content is a trimmed string
|
|
45
|
-
content = (content || '').toString().trim();
|
|
46
|
-
|
|
47
174
|
// Parse RFC 3464 formatted headers
|
|
48
|
-
let entries =
|
|
175
|
+
let entries = decodeDeliveryStatus(content);
|
|
49
176
|
|
|
50
177
|
let result = {};
|
|
51
178
|
|
|
52
179
|
// Extract recipient address from Final-Recipient header (preferred)
|
|
53
180
|
// Format: "Final-Recipient: rfc822; user@example.com"
|
|
54
181
|
if (entries['final-recipient'] && entries['final-recipient'].length) {
|
|
55
|
-
|
|
56
|
-
let splitPos = rcpt.indexOf(';');
|
|
57
|
-
if (splitPos >= 0) {
|
|
58
|
-
// Extract address after the address-type (usually 'rfc822;')
|
|
59
|
-
result.recipient = rcpt.substr(splitPos + 1).trim();
|
|
60
|
-
} else {
|
|
61
|
-
// No address-type specified, use the whole value
|
|
62
|
-
result.recipient = rcpt.trim();
|
|
63
|
-
}
|
|
182
|
+
result.recipient = splitAddressType(entries['final-recipient'][0]).value;
|
|
64
183
|
}
|
|
65
184
|
|
|
66
185
|
// Fallback to Original-Recipient if Final-Recipient not found
|
|
67
186
|
// This might contain the intended recipient before aliasing/forwarding
|
|
68
187
|
if (!result.recipient && entries['original-recipient'] && entries['original-recipient'].length) {
|
|
69
|
-
|
|
70
|
-
let splitPos = rcpt.indexOf(';');
|
|
71
|
-
if (splitPos >= 0) {
|
|
72
|
-
result.recipient = rcpt.substr(splitPos + 1).trim();
|
|
73
|
-
} else {
|
|
74
|
-
result.recipient = rcpt.trim();
|
|
75
|
-
}
|
|
188
|
+
result.recipient = splitAddressType(entries['original-recipient'][0]).value;
|
|
76
189
|
}
|
|
77
190
|
|
|
78
191
|
// Extract delivery action (e.g., 'failed', 'delayed', 'delivered', 'relayed', 'expanded')
|
|
@@ -83,18 +196,8 @@ function parseDeliveryStatus(content) {
|
|
|
83
196
|
// Parse Diagnostic-Code header for detailed error information
|
|
84
197
|
// Format: "Diagnostic-Code: smtp; 550 5.1.1 User unknown"
|
|
85
198
|
if (entries['diagnostic-code'] && entries['diagnostic-code'].length) {
|
|
86
|
-
|
|
87
|
-
let
|
|
88
|
-
let respSource, respMessage;
|
|
89
|
-
|
|
90
|
-
if (splitPos >= 0) {
|
|
91
|
-
// Extract diagnostic-type (e.g., 'smtp')
|
|
92
|
-
respSource = code.substr(0, splitPos).trim();
|
|
93
|
-
respMessage = code.substr(splitPos + 1).trim();
|
|
94
|
-
} else {
|
|
95
|
-
// No diagnostic-type specified
|
|
96
|
-
respMessage = code.trim();
|
|
97
|
-
}
|
|
199
|
+
// label is the diagnostic type, eg. 'smtp'
|
|
200
|
+
let { label: respSource, value: respMessage } = splitAddressType(entries['diagnostic-code'][0]);
|
|
98
201
|
|
|
99
202
|
result.response = {};
|
|
100
203
|
if (respSource) {
|
|
@@ -116,31 +219,13 @@ function parseDeliveryStatus(content) {
|
|
|
116
219
|
// Extract Remote-MTA (the MTA that reported the failure)
|
|
117
220
|
// Format: "Remote-MTA: dns; mx.example.com"
|
|
118
221
|
if (entries['remote-mta'] && entries['remote-mta'].length) {
|
|
119
|
-
|
|
120
|
-
let splitPos = mta.indexOf(';');
|
|
121
|
-
if (splitPos >= 0) {
|
|
122
|
-
result.mta = mta
|
|
123
|
-
.substr(splitPos + 1)
|
|
124
|
-
.trim()
|
|
125
|
-
.toLowerCase();
|
|
126
|
-
} else {
|
|
127
|
-
result.mta = mta.trim().toLowerCase();
|
|
128
|
-
}
|
|
222
|
+
result.mta = splitAddressType(entries['remote-mta'][0]).value.toLowerCase();
|
|
129
223
|
}
|
|
130
224
|
|
|
131
225
|
// Fallback to Reporting-MTA if Remote-MTA not found
|
|
132
226
|
// This is the MTA generating the bounce report
|
|
133
227
|
if (!result.mta && entries['reporting-mta'] && entries['reporting-mta'].length) {
|
|
134
|
-
|
|
135
|
-
let splitPos = mta.indexOf(';');
|
|
136
|
-
if (splitPos >= 0) {
|
|
137
|
-
result.mta = mta
|
|
138
|
-
.substr(splitPos + 1)
|
|
139
|
-
.trim()
|
|
140
|
-
.toLowerCase();
|
|
141
|
-
} else {
|
|
142
|
-
result.mta = mta.trim().toLowerCase();
|
|
143
|
-
}
|
|
228
|
+
result.mta = splitAddressType(entries['reporting-mta'][0]).value.toLowerCase();
|
|
144
229
|
}
|
|
145
230
|
|
|
146
231
|
// Postfix-specific headers
|
|
@@ -157,16 +242,16 @@ function parseDeliveryStatus(content) {
|
|
|
157
242
|
}
|
|
158
243
|
|
|
159
244
|
/**
|
|
160
|
-
*
|
|
245
|
+
* Extracts the bounced message's identity from its already decoded headers
|
|
246
|
+
*
|
|
247
|
+
* Takes decoded entries rather than the raw attachment, as every caller has just decoded the
|
|
248
|
+
* same content, most of them to keep as the reported message headers.
|
|
161
249
|
*
|
|
162
|
-
* @param {
|
|
250
|
+
* @param {Object} entries - Header entries from libmime.decodeHeaders()
|
|
163
251
|
* @returns {Object} Parsed header information
|
|
164
252
|
* @returns {string} [returns.messageId] - The Message-ID header value
|
|
165
253
|
*/
|
|
166
|
-
function parseDeliveryHeaders(
|
|
167
|
-
content = (content || '').toString().trim();
|
|
168
|
-
let entries = libmime.decodeHeaders(content);
|
|
169
|
-
|
|
254
|
+
function parseDeliveryHeaders(entries) {
|
|
170
255
|
let result = {};
|
|
171
256
|
|
|
172
257
|
// Extract Message-ID from the original message headers
|
|
@@ -275,7 +360,7 @@ async function bounceDetect(sourceStream) {
|
|
|
275
360
|
// Process RFC822 headers attachment (contains headers of the original message)
|
|
276
361
|
if (messageHeaders) {
|
|
277
362
|
parsedMessageHeaders = libmime.decodeHeaders((messageHeaders.content || '').toString().trim());
|
|
278
|
-
result = Object.assign(result, parseDeliveryHeaders(
|
|
363
|
+
result = Object.assign(result, parseDeliveryHeaders(parsedMessageHeaders));
|
|
279
364
|
}
|
|
280
365
|
|
|
281
366
|
// Process complete original message attachment
|
|
@@ -317,7 +402,8 @@ async function bounceDetect(sourceStream) {
|
|
|
317
402
|
if (!messageHeaders) {
|
|
318
403
|
messageHeaders = originalAttachments.find(attachment => attachment.contentType?.toLowerCase() === 'text/rfc822-headers');
|
|
319
404
|
if (messageHeaders) {
|
|
320
|
-
|
|
405
|
+
let headerEntries = libmime.decodeHeaders((messageHeaders.content || '').toString().trim());
|
|
406
|
+
result = Object.assign(result, parseDeliveryHeaders(headerEntries));
|
|
321
407
|
}
|
|
322
408
|
}
|
|
323
409
|
}
|
|
@@ -376,7 +462,7 @@ async function bounceDetect(sourceStream) {
|
|
|
376
462
|
let headers = libmime.decodeHeaders(headerContent);
|
|
377
463
|
if (headers && headers['message-id']) {
|
|
378
464
|
parsedMessageHeaders = headers;
|
|
379
|
-
result = Object.assign(result, parseDeliveryHeaders(
|
|
465
|
+
result = Object.assign(result, parseDeliveryHeaders(headers));
|
|
380
466
|
}
|
|
381
467
|
}
|
|
382
468
|
}
|
|
@@ -838,4 +924,38 @@ async function bounceDetect(sourceStream) {
|
|
|
838
924
|
}
|
|
839
925
|
|
|
840
926
|
// Export the main function
|
|
841
|
-
|
|
927
|
+
/**
|
|
928
|
+
* Sets messageInfo.deliveryReport when a parsed DSN reports a delivery or a delay
|
|
929
|
+
*
|
|
930
|
+
* A bounce is handled by bounceDetect() instead, so only these two actions are reported here.
|
|
931
|
+
* Both the IMAP and the API paths call this with their own already parsed message.
|
|
932
|
+
*
|
|
933
|
+
* @param {Object} parsed - Message parsed with { keepDeliveryStatus: true }
|
|
934
|
+
* @param {Object} messageInfo - Message object to annotate
|
|
935
|
+
* @param {Object} logger - Logger to report a detected report on
|
|
936
|
+
* @returns {Boolean} True if a delivery report was set
|
|
937
|
+
*/
|
|
938
|
+
function applyDeliveryReport(parsed, messageInfo, logger) {
|
|
939
|
+
let deliveryStatus = parsed.attachments.find(attachment => attachment.contentType === 'message/delivery-status');
|
|
940
|
+
if (!deliveryStatus) {
|
|
941
|
+
return false;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
let structured = parseDeliveryReport(deliveryStatus.content);
|
|
945
|
+
if (!/^delivered|^delayed/i.test(structured.action)) {
|
|
946
|
+
return false;
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
logger.debug({
|
|
950
|
+
msg: 'Detected delivery report',
|
|
951
|
+
id: messageInfo.id,
|
|
952
|
+
uid: messageInfo.uid,
|
|
953
|
+
messageId: messageInfo.messageId,
|
|
954
|
+
report: structured
|
|
955
|
+
});
|
|
956
|
+
|
|
957
|
+
messageInfo.deliveryReport = structured;
|
|
958
|
+
return true;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
module.exports = { bounceDetect, decodeDeliveryStatus, parseDeliveryReport, applyDeliveryReport };
|
package/lib/consts.js
CHANGED
|
@@ -273,6 +273,16 @@ module.exports = {
|
|
|
273
273
|
'UND_ERR_HEADERS_TIMEOUT'
|
|
274
274
|
]),
|
|
275
275
|
|
|
276
|
+
// Error codes meaning "the IMAP connection is gone", as opposed to the command itself failing
|
|
277
|
+
CONNECTION_CLOSING_CODES: new Set(['IMAPConnectionClosing', 'EConnectionClosed', 'NoConnection']),
|
|
278
|
+
|
|
279
|
+
// Applied by lib/logger.js to the root logger, so every worker inherits it. A logged joi
|
|
280
|
+
// ValidationError carries the full submitted payload in `_original` and the offending value in
|
|
281
|
+
// each detail context, and `rawPacket` is a TLS-error field that can carry an unparsed
|
|
282
|
+
// credential frame - without these a failed validation writes plaintext passwords, OAuth2
|
|
283
|
+
// client secrets and access tokens into the log, the per-account log store and Sentry.
|
|
284
|
+
REDACTED_LOG_KEYS: ['req.headers.authorization', 'req.headers.cookie', 'err.rawPacket', 'err._original', 'err.details[*].context.value'],
|
|
285
|
+
|
|
276
286
|
generateWebhookTable() {
|
|
277
287
|
let entries = [];
|
|
278
288
|
|
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
|
|
|
@@ -222,6 +224,15 @@ module.exports.submitQueue = submitQueue;
|
|
|
222
224
|
module.exports.documentsQueue = documentsQueue;
|
|
223
225
|
module.exports.exportQueue = exportQueue;
|
|
224
226
|
|
|
227
|
+
// Queues addressable by the name the API and the stats payload use for them. `export` is
|
|
228
|
+
// deliberately absent: neither surface exposes it, and the {queue} route parameter is validated
|
|
229
|
+
// against this same set of names.
|
|
230
|
+
module.exports.QUEUES_BY_NAME = {
|
|
231
|
+
notify: notifyQueue,
|
|
232
|
+
submit: submitQueue,
|
|
233
|
+
documents: documentsQueue
|
|
234
|
+
};
|
|
235
|
+
|
|
225
236
|
// do not set up the flow producer by default
|
|
226
237
|
module.exports.getFlowProducer = () => new FlowProducer(module.exports.queueConf /*, Redis*/);
|
|
227
238
|
|
|
@@ -248,7 +259,14 @@ To run EmailEngine provide valid Redis configuration
|
|
|
248
259
|
process.exit(1);
|
|
249
260
|
}
|
|
250
261
|
|
|
251
|
-
|
|
262
|
+
// Only reached when the process stays up (the exit path above never returns), so this must
|
|
263
|
+
// not log at fatal. A post-connection error is retried by ioredis on its own, so it is a
|
|
264
|
+
// warning; config-class errors (forceClose) that did not trigger an exit are logged at error.
|
|
265
|
+
if (forceClose) {
|
|
266
|
+
logger.error({ msg: msg || 'Redis connection error', err });
|
|
267
|
+
} else {
|
|
268
|
+
logger.warn({ msg: msg || 'Redis connection error', err });
|
|
269
|
+
}
|
|
252
270
|
};
|
|
253
271
|
|
|
254
272
|
redis.on('connect', () => {
|