emailengine-app 2.84.0 → 2.84.2
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/.dockerignore +6 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +35 -0
- package/Dockerfile +2 -2
- package/bin/emailengine.js +15 -0
- package/data/google-crawlers.json +1 -1
- package/docker-compose.yml +1 -1
- package/lib/account/own-account-key.js +42 -0
- package/lib/account-assignment.js +1 -33
- package/lib/account.js +32 -19
- package/lib/add-trackers.js +11 -4
- package/lib/api-routes/account-routes.js +67 -14
- package/lib/api-routes/gateway-routes.js +9 -3
- package/lib/api-routes/message-routes.js +7 -1
- package/lib/api-routes/mint-bounds.js +11 -0
- package/lib/api-routes/route-helpers.js +125 -3
- package/lib/api-routes/submit-routes.js +4 -2
- package/lib/auth-token.js +23 -10
- package/lib/bounce-detect.js +17 -5
- package/lib/consts.js +34 -0
- package/lib/create-imap-client.js +41 -2
- package/lib/email-client/base-client.js +20 -10
- package/lib/email-client/gmail-client.js +21 -7
- package/lib/email-client/imap/mailbox.js +10 -4
- package/lib/email-client/imap/response-metrics.js +75 -0
- package/lib/email-client/imap-client.js +5 -2
- package/lib/email-client/message-builder.js +7 -2
- package/lib/email-client/outlook/graph-api.js +17 -2
- package/lib/email-client/outlook-client.js +6 -3
- package/lib/email-client/smtp-pool-manager.js +6 -0
- package/lib/encrypt.js +9 -0
- package/lib/export.js +3 -1
- package/lib/get-raw-email.js +4 -2
- package/lib/imap-proxy-auth.js +14 -1
- package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
- package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
- package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
- package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
- package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
- package/lib/mcp/listen.js +10 -1
- package/lib/oauth/external-account-config.js +3 -1
- package/lib/oauth/gmail.js +21 -48
- package/lib/oauth/mail-ru.js +5 -38
- package/lib/oauth/outlook.js +26 -44
- package/lib/pbkdf2-phc.js +18 -1
- package/lib/privileged-settings.js +6 -3
- package/lib/redis-scan-delete.js +15 -1
- package/lib/schemas.js +78 -32
- package/lib/settings.js +13 -1
- package/lib/smtp-auth.js +23 -0
- package/lib/tools.js +245 -56
- package/lib/ui-routes/account-routes.js +16 -37
- package/lib/ui-routes/admin-config-routes.js +10 -38
- package/lib/ui-routes/admin-entities-routes.js +22 -24
- package/lib/ui-routes/auth-routes.js +47 -24
- package/lib/ui-routes/connection-security-form.js +74 -0
- package/lib/ui-routes/form-lists.js +46 -0
- package/lib/ui-routes/mcp-consent-routes.js +5 -1
- package/lib/ui-routes/oauth-config-routes.js +9 -18
- package/lib/ui-routes/sign-in-helpers.js +59 -0
- package/lib/ui-routes/unsubscribe-routes.js +6 -3
- package/lib/utils/map-concurrent.js +36 -0
- package/lib/utils/network.js +28 -0
- package/lib/utils/provider-id.js +27 -0
- package/lib/utils/require-tls.js +33 -0
- package/lib/web-safe-html.js +5 -6
- package/lib/webhook-penalty.js +75 -0
- package/lib/webhook-routing.js +22 -2
- package/package.json +21 -21
- package/sbom.json +1 -1
- package/server.js +74 -38
- package/static/js/ace/ace.js +1 -1
- package/static/js/ace/mode-handlebars.js +1 -1
- package/static/js/ace/mode-html.js +1 -1
- package/static/js/ace/mode-javascript.js +1 -1
- package/static/js/ace/mode-markdown.js +1 -1
- package/static/js/ace/worker-html.js +1 -1
- package/static/js/ace/worker-javascript.js +1 -1
- package/static/js/ace/worker-json.js +1 -1
- package/static/js/ee-client.js +5 -0
- package/static/licenses.html +23 -23
- package/translations/messages.pot +66 -66
- package/views/account/security.hbs +10 -0
- package/views/accounts/account.hbs +11 -11
- package/views/accounts/edit.hbs +6 -2
- package/views/partials/gateway_form.hbs +3 -1
- package/workers/api.js +43 -3
- package/workers/webhooks.js +39 -3
- package/config/test.toml +0 -46
- package/install.sh +0 -428
- package/setup-production.sh +0 -215
- package/systemd/emailengine.service +0 -97
- package/systemd/nginx-proxy.conf +0 -77
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Label values for the `imap_responses` counter.
|
|
4
|
+
//
|
|
5
|
+
// ImapFlow reports every tagged response as `{ response, code }`: the status (OK, NO, BAD, ...)
|
|
6
|
+
// and the bracketed response code when there is one (`[ALERT]`, `[AUTHENTICATIONFAILED]`).
|
|
7
|
+
// Both are atoms the server chose, and every distinct label value is a new series held by the
|
|
8
|
+
// Prometheus registry on the main thread for the life of the process, so a server (or a proxy on
|
|
9
|
+
// the path) that varies them grows that memory without bound. Only the vocabulary below reaches
|
|
10
|
+
// the counter; anything else is counted under `other`, which keeps the count right while bounding
|
|
11
|
+
// the series.
|
|
12
|
+
|
|
13
|
+
// RFC 9051 status responses, plus the two a tagged response may carry on some servers
|
|
14
|
+
const KNOWN_RESPONSES = new Set(['OK', 'NO', 'BAD', 'BYE', 'PREAUTH']);
|
|
15
|
+
|
|
16
|
+
// RFC 9051 and RFC 5530 response codes, plus the extension codes EmailEngine reacts to
|
|
17
|
+
const KNOWN_CODES = new Set([
|
|
18
|
+
'ALERT',
|
|
19
|
+
'ALREADYEXISTS',
|
|
20
|
+
'APPENDUID',
|
|
21
|
+
'AUTHENTICATIONFAILED',
|
|
22
|
+
'AUTHORIZATIONFAILED',
|
|
23
|
+
'BADCHARSET',
|
|
24
|
+
'CANNOT',
|
|
25
|
+
'CAPABILITY',
|
|
26
|
+
'CLIENTBUG',
|
|
27
|
+
'CLOSED',
|
|
28
|
+
'COMPRESSIONACTIVE',
|
|
29
|
+
'CONTACTADMIN',
|
|
30
|
+
'COPYUID',
|
|
31
|
+
'CORRUPTION',
|
|
32
|
+
'EXPIRED',
|
|
33
|
+
'EXPUNGEISSUED',
|
|
34
|
+
'HASCHILDREN',
|
|
35
|
+
'HIGHESTMODSEQ',
|
|
36
|
+
'INUSE',
|
|
37
|
+
'LIMIT',
|
|
38
|
+
'NOMODSEQ',
|
|
39
|
+
'NONEXISTENT',
|
|
40
|
+
'NOPERM',
|
|
41
|
+
'OVERQUOTA',
|
|
42
|
+
'PARSE',
|
|
43
|
+
'PERMANENTFLAGS',
|
|
44
|
+
'PRIVACYREQUIRED',
|
|
45
|
+
'READ-ONLY',
|
|
46
|
+
'READ-WRITE',
|
|
47
|
+
'SERVERBUG',
|
|
48
|
+
'TRYCREATE',
|
|
49
|
+
'UIDNEXT',
|
|
50
|
+
'UIDNOTSTICKY',
|
|
51
|
+
'UIDVALIDITY',
|
|
52
|
+
'UNAVAILABLE',
|
|
53
|
+
'UNKNOWN-CTE',
|
|
54
|
+
'UNSEEN'
|
|
55
|
+
]);
|
|
56
|
+
|
|
57
|
+
const OTHER = 'other';
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {Object} data - the `response` event payload from ImapFlow
|
|
61
|
+
* @returns {{response: String, code?: String}} the label values to count
|
|
62
|
+
*/
|
|
63
|
+
function imapResponseLabels(data) {
|
|
64
|
+
let response = data && typeof data.response === 'string' ? data.response.toUpperCase() : '';
|
|
65
|
+
let labels = { response: KNOWN_RESPONSES.has(response) ? response : OTHER };
|
|
66
|
+
|
|
67
|
+
if (data && data.code !== undefined && data.code !== null) {
|
|
68
|
+
let code = typeof data.code === 'string' ? data.code.toUpperCase() : '';
|
|
69
|
+
labels.code = KNOWN_CODES.has(code) ? code : OTHER;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return labels;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
module.exports = { imapResponseLabels, KNOWN_RESPONSES, KNOWN_CODES };
|
|
@@ -13,6 +13,7 @@ const { BaseClient } = require('./base-client');
|
|
|
13
13
|
const { oauth2Apps } = require('../oauth2-apps');
|
|
14
14
|
|
|
15
15
|
const { Subconnection } = require('./imap/subconnection');
|
|
16
|
+
const { imapResponseLabels } = require('./imap/response-metrics');
|
|
16
17
|
const { decodeStoredListing, diffMailboxListing, buildStoredListingObject, matchesListingEntry, configuredPathIndex } = require('./imap/listing-diff');
|
|
17
18
|
const { samePath } = require('../utils/mailbox-path');
|
|
18
19
|
const { detachImapClient } = require('./imap/detach-client');
|
|
@@ -1834,9 +1835,11 @@ class IMAPClient extends BaseClient {
|
|
|
1834
1835
|
}
|
|
1835
1836
|
});
|
|
1836
1837
|
|
|
1837
|
-
// Track IMAP command/response metrics
|
|
1838
|
+
// Track IMAP command/response metrics. The response status and code are atoms the
|
|
1839
|
+
// server chose, and a Prometheus label value is a series on the main thread, so
|
|
1840
|
+
// only the known vocabulary becomes a label and anything else is counted as `other`
|
|
1838
1841
|
imapClient.on('response', data => {
|
|
1839
|
-
metricsMeta({}, this.logger, 'imapResponses', 'inc', data);
|
|
1842
|
+
metricsMeta({}, this.logger, 'imapResponses', 'inc', imapResponseLabels(data));
|
|
1840
1843
|
|
|
1841
1844
|
// update byte counters as well
|
|
1842
1845
|
let imapStats = imapClient.stats(true);
|
|
@@ -5,6 +5,7 @@ const { oauth2ProviderData } = require('../oauth2-apps');
|
|
|
5
5
|
const { useAuthServerForConnection, redactUrlCredentials } = require('../tools');
|
|
6
6
|
const { resolveAuthServerCredentials } = require('./credential-errors');
|
|
7
7
|
const { getLocalAddress } = require('../utils/network');
|
|
8
|
+
const { applyRequireTls } = require('../utils/require-tls');
|
|
8
9
|
const settings = require('../settings');
|
|
9
10
|
const { TLS_DEFAULTS } = require('../consts');
|
|
10
11
|
const util = require('util');
|
|
@@ -85,7 +86,8 @@ class SmtpConfigBuilder {
|
|
|
85
86
|
const config = {
|
|
86
87
|
host: gatewayData.host,
|
|
87
88
|
port: gatewayData.port,
|
|
88
|
-
secure: gatewayData.secure
|
|
89
|
+
secure: gatewayData.secure,
|
|
90
|
+
requireTLS: gatewayData.requireTLS
|
|
89
91
|
};
|
|
90
92
|
|
|
91
93
|
if (gatewayData.user || gatewayData.pass) {
|
|
@@ -170,12 +172,14 @@ class SmtpConfigBuilder {
|
|
|
170
172
|
// Build SMTP logger wrapper
|
|
171
173
|
const smtpLogger = this.buildSmtpLogger();
|
|
172
174
|
|
|
173
|
-
// Create settings object
|
|
175
|
+
// Create settings object. `account` names whose logger `transactionLog` writes to, so the
|
|
176
|
+
// pool manager does not share a logged pool between accounts (lib/email-client/smtp-pool-manager.js)
|
|
174
177
|
const smtpSettings = Object.assign(
|
|
175
178
|
{
|
|
176
179
|
name,
|
|
177
180
|
localAddress: address,
|
|
178
181
|
transactionLog: true,
|
|
182
|
+
account: this.account,
|
|
179
183
|
logger: smtpLogger
|
|
180
184
|
},
|
|
181
185
|
smtpConnectionConfig
|
|
@@ -194,6 +198,7 @@ class SmtpConfigBuilder {
|
|
|
194
198
|
|
|
195
199
|
// Apply TLS defaults
|
|
196
200
|
this.applyTlsDefaults(smtpSettings);
|
|
201
|
+
applyRequireTls(smtpSettings);
|
|
197
202
|
|
|
198
203
|
// Apply proxy configuration
|
|
199
204
|
await this.applyProxyConfig(smtpSettings, accountData, data);
|
|
@@ -87,8 +87,23 @@ async function request(context, url, method, payload, options = {}) {
|
|
|
87
87
|
|
|
88
88
|
options.headers.Prefer = preferValues.join(', ');
|
|
89
89
|
|
|
90
|
-
// Construct full API URL if not already absolute
|
|
91
|
-
|
|
90
|
+
// Construct full API URL if not already absolute. An absolute URL comes from a Graph
|
|
91
|
+
// response (@odata.nextLink, @odata.deltaLink) and is only followed on the Graph origin
|
|
92
|
+
// the app is configured for: the bearer token goes with the request, and a response is
|
|
93
|
+
// not a place to take a new host from
|
|
94
|
+
let apiUrl;
|
|
95
|
+
if (/^https:/.test(url)) {
|
|
96
|
+
let graphOrigin = new URL(context.oAuth2Client.apiBase).origin;
|
|
97
|
+
if (new URL(url).origin !== graphOrigin) {
|
|
98
|
+
let error = new Error('Refusing to follow a Graph link outside the configured API origin');
|
|
99
|
+
error.code = 'InvalidGraphUrl';
|
|
100
|
+
error.statusCode = 502;
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
apiUrl = url;
|
|
104
|
+
} else {
|
|
105
|
+
apiUrl = new URL(`/v1.0${url}`, context.oAuth2Client.apiBase).href;
|
|
106
|
+
}
|
|
92
107
|
|
|
93
108
|
let result = await context.oAuth2Client.request(tokenData.accessToken, apiUrl, method, payload, options);
|
|
94
109
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
const { BaseClient, metricsMeta } = require('./base-client');
|
|
4
|
+
const { isSafePathSegment } = require('../utils/provider-id');
|
|
4
5
|
const { isTransientCredentialError } = require('./credential-errors');
|
|
5
6
|
const { Account } = require('../account');
|
|
6
7
|
const { checkAccountScopes } = require('../oauth/scope-checker');
|
|
@@ -4123,8 +4124,10 @@ class OutlookClient extends BaseClient {
|
|
|
4123
4124
|
async getAttachmentContent(attachmentId, options) {
|
|
4124
4125
|
options = options || {};
|
|
4125
4126
|
|
|
4126
|
-
// Decode compound attachment ID
|
|
4127
|
-
|
|
4127
|
+
// Decode compound attachment ID. Both parts become path segments of the Graph URL, so a
|
|
4128
|
+
// part that would leave its segment (`..`, a slash) is an invalid id rather than a request
|
|
4129
|
+
// for a different resource
|
|
4130
|
+
const [emailId, id] = this.unpackApiId(attachmentId, parts => parts.length >= 2 && isSafePathSegment(parts[0]) && isSafePathSegment(parts[1]));
|
|
4128
4131
|
|
|
4129
4132
|
await this.prepare();
|
|
4130
4133
|
|
|
@@ -4163,7 +4166,7 @@ class OutlookClient extends BaseClient {
|
|
|
4163
4166
|
let attachmentResponse;
|
|
4164
4167
|
|
|
4165
4168
|
try {
|
|
4166
|
-
attachmentResponse = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/attachments/${id}`);
|
|
4169
|
+
attachmentResponse = await this.request(`/${this.oauth2UserPath}/messages/${encodeURIComponent(emailId)}/attachments/${encodeURIComponent(id)}`);
|
|
4167
4170
|
} catch (err) {
|
|
4168
4171
|
throw attachmentErrorHandler(err);
|
|
4169
4172
|
}
|
|
@@ -29,6 +29,12 @@ function generatePoolKey(smtpSettings) {
|
|
|
29
29
|
for (const key of CONNECTION_IDENTITY_KEYS) {
|
|
30
30
|
limitedSettings[key] = smtpSettings[key];
|
|
31
31
|
}
|
|
32
|
+
// A transaction log is written through the account's own logger, so two accounts on the same
|
|
33
|
+
// gateway must not share a logged pool: the first account's log used to receive the envelopes
|
|
34
|
+
// and server replies of every account sending through it
|
|
35
|
+
if (smtpSettings.transactionLog && smtpSettings.account) {
|
|
36
|
+
limitedSettings.account = smtpSettings.account;
|
|
37
|
+
}
|
|
32
38
|
const serializedSettings = JSON.stringify(limitedSettings);
|
|
33
39
|
return crypto.createHash('sha256').update(serializedSettings).digest('hex');
|
|
34
40
|
}
|
package/lib/encrypt.js
CHANGED
|
@@ -225,6 +225,15 @@ function encrypt(cleartext, secret) {
|
|
|
225
225
|
return cleartext;
|
|
226
226
|
}
|
|
227
227
|
|
|
228
|
+
// Never encrypted twice. A stored value that did not decrypt (the secret was rotated without
|
|
229
|
+
// `emailengine encrypt`) is read back as the ciphertext it is, and a partial update of the
|
|
230
|
+
// record used to write it back encrypted again, which put the only recoverable copy of the
|
|
231
|
+
// credential beyond the rotation CLI. Ciphertext is left as it is, so a later run with the
|
|
232
|
+
// right secret still opens it
|
|
233
|
+
if (typeof cleartext === 'string' && parseEncryptedData(cleartext).format !== 'cleartext') {
|
|
234
|
+
return cleartext;
|
|
235
|
+
}
|
|
236
|
+
|
|
228
237
|
// Random per value: GCM is only secure while no IV repeats under a key, and every value this
|
|
229
238
|
// process writes shares one key
|
|
230
239
|
const iv = crypto.randomBytes(IV_LENGTH);
|
package/lib/export.js
CHANGED
|
@@ -515,7 +515,9 @@ class Export {
|
|
|
515
515
|
const exports = [];
|
|
516
516
|
for (const key of keys) {
|
|
517
517
|
const data = await redis.hgetall(key);
|
|
518
|
-
|
|
518
|
+
// the glob also matches the exports of an account whose id begins with this one and
|
|
519
|
+
// a colon, so the record's own account field decides
|
|
520
|
+
if (data && data.exportId && data.account === account) {
|
|
519
521
|
exports.push({
|
|
520
522
|
exportId: data.exportId,
|
|
521
523
|
status: data.status,
|
package/lib/get-raw-email.js
CHANGED
|
@@ -16,7 +16,7 @@ const msgpack = require('./msgpack');
|
|
|
16
16
|
const crypto = require('crypto');
|
|
17
17
|
const { parseMessage } = require('./parse-message');
|
|
18
18
|
|
|
19
|
-
const { MIME_BOUNDARY_PREFIX } = require('./consts');
|
|
19
|
+
const { MIME_BOUNDARY_PREFIX, MAX_DELIVERY_ATTEMPTS } = require('./consts');
|
|
20
20
|
|
|
21
21
|
// Runs a message through the splitter and the headers rewriter and collects the result.
|
|
22
22
|
//
|
|
@@ -89,7 +89,9 @@ async function processMessage(data, licenseInfo) {
|
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
if (deliveryAttemptsVal && !isNaN(deliveryAttemptsVal)) {
|
|
92
|
-
|
|
92
|
+
// within the bounds the API schema gives the same option; the header is what a stored
|
|
93
|
+
// draft or an SMTP submission carries, and nothing else validates it
|
|
94
|
+
deliveryAttempts = Math.min(Math.max(Math.round(Number(deliveryAttemptsVal)), 1), MAX_DELIVERY_ATTEMPTS);
|
|
93
95
|
}
|
|
94
96
|
|
|
95
97
|
if (gatewayVal) {
|
package/lib/imap-proxy-auth.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
const logger = require('./logger');
|
|
9
9
|
const settings = require('./settings');
|
|
10
10
|
const { redis } = require('./db');
|
|
11
|
-
const { Account } = require('./account');
|
|
11
|
+
const { Account, isImapDisabled, authFailureDisabledAt } = require('./account');
|
|
12
12
|
const getSecret = require('./get-secret');
|
|
13
13
|
const { isApiBasedApp } = require('./oauth2-apps');
|
|
14
14
|
const { validateAuthToken, withAuthFailureBudget, REASON_MESSAGES } = require('./auth-token');
|
|
@@ -132,6 +132,19 @@ function createImapProxyAuthHandler({ call }) {
|
|
|
132
132
|
throw respErr;
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
+
// An account whose IMAP the operator switched off (send-only), or that the auth-failure
|
|
136
|
+
// safety net parked, is not reachable through the proxy either: a proxy session is an
|
|
137
|
+
// IMAP connection made with the account's credentials, the very thing both switches stop
|
|
138
|
+
if (isImapDisabled(verified.accountData)) {
|
|
139
|
+
let respErr = new Error(
|
|
140
|
+
authFailureDisabledAt(verified.accountData) ? 'Account is disabled after repeated authentication failures' : 'IMAP is disabled for this account'
|
|
141
|
+
);
|
|
142
|
+
respErr.authenticationFailed = true;
|
|
143
|
+
respErr.serverResponseCode = 'ACCOUNTDISABLED';
|
|
144
|
+
respErr.responseStatus = 'NO';
|
|
145
|
+
throw respErr;
|
|
146
|
+
}
|
|
147
|
+
|
|
135
148
|
return verified;
|
|
136
149
|
};
|
|
137
150
|
}
|
|
@@ -5,6 +5,13 @@ const imapHandler = require('./handler/imap-handler');
|
|
|
5
5
|
const MAX_MESSAGE_SIZE = 1 * 1024 * 1024;
|
|
6
6
|
const MAX_BAD_COMMANDS = 50;
|
|
7
7
|
|
|
8
|
+
// Longest command text one command may accumulate across its literal-terminated segments. The
|
|
9
|
+
// parser caps one line at 1 MB, but a command may announce up to 32 literals before login and
|
|
10
|
+
// every segment that ends in `{N}` is appended to the same payload, so one unauthenticated
|
|
11
|
+
// connection could hold about 33 MB while trickling its final line; a thousand of them is the
|
|
12
|
+
// worker's memory. The same bound as the line, for the whole command
|
|
13
|
+
const MAX_COMMAND_PAYLOAD = 1024 * 1024;
|
|
14
|
+
|
|
8
15
|
// Every literal is buffered in memory until the command line is complete, so a single command must
|
|
9
16
|
// not be able to announce literals without bound. Real commands carry a few at most (LOGIN has two).
|
|
10
17
|
const MAX_LITERALS_PER_COMMAND = 32;
|
|
@@ -113,6 +120,15 @@ class IMAPCommand {
|
|
|
113
120
|
|
|
114
121
|
this.payload += command.value;
|
|
115
122
|
|
|
123
|
+
if (this.payload.length > MAX_COMMAND_PAYLOAD) {
|
|
124
|
+
this.connection.send((this.tag || '*') + ' BAD Command too long');
|
|
125
|
+
this.abortCommand();
|
|
126
|
+
let err = new Error('Command too long');
|
|
127
|
+
err.responseCode = 400;
|
|
128
|
+
err.code = 'CommandTooLong';
|
|
129
|
+
return callback(err);
|
|
130
|
+
}
|
|
131
|
+
|
|
116
132
|
if (this.first) {
|
|
117
133
|
// fetch tag and command name
|
|
118
134
|
this.first = false;
|
|
@@ -311,54 +327,81 @@ class IMAPCommand {
|
|
|
311
327
|
}
|
|
312
328
|
|
|
313
329
|
if (typeof handler.handler === 'function') {
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
if (!this.countBadResponses()) {
|
|
322
|
-
// stop processing
|
|
323
|
-
return;
|
|
324
|
-
}
|
|
330
|
+
const complete = (err, response) => {
|
|
331
|
+
if (err) {
|
|
332
|
+
this.connection.send(this.tag + ' ' + (err.response || 'BAD') + ' ' + err.message);
|
|
333
|
+
if (!err.response || err.response === 'BAD') {
|
|
334
|
+
if (!this.countBadResponses()) {
|
|
335
|
+
// stop processing
|
|
336
|
+
return;
|
|
325
337
|
}
|
|
326
|
-
return next(err);
|
|
327
338
|
}
|
|
339
|
+
return next(err);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// send EXPUNGE, EXISTS etc queued notices
|
|
343
|
+
this.sendNotifications(handler, () => {
|
|
344
|
+
// send command ready response
|
|
345
|
+
this.connection.writeStream.write({
|
|
346
|
+
tag: this.tag,
|
|
347
|
+
command: response.response,
|
|
348
|
+
attributes: []
|
|
349
|
+
.concat(
|
|
350
|
+
response.code
|
|
351
|
+
? {
|
|
352
|
+
type: 'SECTION',
|
|
353
|
+
section: [
|
|
354
|
+
{
|
|
355
|
+
type: 'TEXT',
|
|
356
|
+
value: response.code
|
|
357
|
+
}
|
|
358
|
+
]
|
|
359
|
+
}
|
|
360
|
+
: []
|
|
361
|
+
)
|
|
362
|
+
.concat({
|
|
363
|
+
type: 'TEXT',
|
|
364
|
+
value: response.message || this.command + ' completed'
|
|
365
|
+
})
|
|
366
|
+
});
|
|
328
367
|
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
//
|
|
332
|
-
this
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
attributes: []
|
|
336
|
-
.concat(
|
|
337
|
-
response.code
|
|
338
|
-
? {
|
|
339
|
-
type: 'SECTION',
|
|
340
|
-
section: [
|
|
341
|
-
{
|
|
342
|
-
type: 'TEXT',
|
|
343
|
-
value: response.code
|
|
344
|
-
}
|
|
345
|
-
]
|
|
346
|
-
}
|
|
347
|
-
: []
|
|
348
|
-
)
|
|
349
|
-
.concat({
|
|
350
|
-
type: 'TEXT',
|
|
351
|
-
value: response.message || this.command + ' completed'
|
|
352
|
-
})
|
|
353
|
-
});
|
|
354
|
-
|
|
355
|
-
if (this.connection.state === 'Proxy') {
|
|
356
|
-
// switch to proxy mode
|
|
357
|
-
return this.connection.session.onProxy(this.connection.unbind());
|
|
368
|
+
if (this.connection.state === 'Proxy') {
|
|
369
|
+
// switch to proxy mode, once: the client socket is handed to
|
|
370
|
+
// exactly one upstream session, the one of the login that
|
|
371
|
+
// moved the connection into this state
|
|
372
|
+
if (this.connection._proxyHandedOff) {
|
|
373
|
+
return;
|
|
358
374
|
}
|
|
375
|
+
this.connection._proxyHandedOff = true;
|
|
376
|
+
return this.connection.session.onProxy(this.connection.unbind());
|
|
377
|
+
}
|
|
359
378
|
|
|
360
|
-
|
|
361
|
-
|
|
379
|
+
next();
|
|
380
|
+
});
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
if (!handler.authenticates) {
|
|
384
|
+
return handler.handler.call(this.connection, this.parsed, complete, next);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// One credential check at a time per connection. A client that pipelines several
|
|
388
|
+
// LOGIN or AUTHENTICATE commands used to have them all run at once: each success
|
|
389
|
+
// opened its own upstream session and the socket ended up attached to several of
|
|
390
|
+
// them, with the rest leaked. Set before the handler runs (an AUTHENTICATE waiting
|
|
391
|
+
// for its SASL continuation holds it too); a success moves the connection out of
|
|
392
|
+
// the state these commands are allowed in, so only a refused attempt clears it
|
|
393
|
+
if (this.connection._authInFlight) {
|
|
394
|
+
return complete(null, { response: 'NO', message: 'Authentication already in progress' });
|
|
395
|
+
}
|
|
396
|
+
this.connection._authInFlight = true;
|
|
397
|
+
handler.handler.call(
|
|
398
|
+
this.connection,
|
|
399
|
+
this.parsed,
|
|
400
|
+
(err, response) => {
|
|
401
|
+
if (err || !response || response.response !== 'OK') {
|
|
402
|
+
this.connection._authInFlight = false;
|
|
403
|
+
}
|
|
404
|
+
return complete(err, response);
|
|
362
405
|
},
|
|
363
406
|
next
|
|
364
407
|
);
|
|
@@ -31,6 +31,11 @@ class IMAPStream extends Writable {
|
|
|
31
31
|
|
|
32
32
|
// unprocessed chars from the last parsing iteration
|
|
33
33
|
this._remainder = '';
|
|
34
|
+
// chunks of an unfinished line that arrived with no line break in them, kept apart until
|
|
35
|
+
// one arrives so that a line trickled in small segments is not re-joined and re-scanned
|
|
36
|
+
// from its start for every segment (that was quadratic in the line length)
|
|
37
|
+
this._remainderParts = [];
|
|
38
|
+
this._remainderLength = 0;
|
|
34
39
|
this._literal = false;
|
|
35
40
|
this._literalReady = false;
|
|
36
41
|
|
|
@@ -57,7 +62,7 @@ class IMAPStream extends Writable {
|
|
|
57
62
|
* encrypted session (STARTTLS command injection).
|
|
58
63
|
*/
|
|
59
64
|
reset() {
|
|
60
|
-
this.
|
|
65
|
+
this._clearRemainder();
|
|
61
66
|
this._literal = false;
|
|
62
67
|
this._literalReady = false;
|
|
63
68
|
this._expecting = 0;
|
|
@@ -73,12 +78,31 @@ class IMAPStream extends Writable {
|
|
|
73
78
|
return done();
|
|
74
79
|
}
|
|
75
80
|
|
|
76
|
-
let
|
|
77
|
-
|
|
81
|
+
let str = chunk.toString('binary');
|
|
82
|
+
|
|
83
|
+
if (!this._expecting && !this._literalReady && str.indexOf('\n') < 0) {
|
|
84
|
+
// No line ends in this chunk and no literal is being read, so nothing can be parsed
|
|
85
|
+
// yet: keep the chunk and scan it once the line break arrives. The cap applies to
|
|
86
|
+
// what is kept, so a line that never ends is refused the same as before
|
|
87
|
+
if (this._remainder.length + this._remainderLength + str.length > this._maxLineLength) {
|
|
88
|
+
this._clearRemainder();
|
|
89
|
+
return done(new Error('Command line too long'));
|
|
90
|
+
}
|
|
91
|
+
this._remainderParts.push(str);
|
|
92
|
+
this._remainderLength += str.length;
|
|
93
|
+
return done();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
let prefix = this._clearRemainder();
|
|
97
|
+
let data = prefix + str;
|
|
78
98
|
|
|
79
99
|
// start reading data
|
|
80
|
-
// regex is passed as an argument because we need to keep count of the lastIndex property
|
|
81
|
-
|
|
100
|
+
// regex is passed as an argument because we need to keep count of the lastIndex property.
|
|
101
|
+
// The prefix was already scanned for a line break and has none, so the search starts at
|
|
102
|
+
// its end (one character back, in case a CR LF straddles the two)
|
|
103
|
+
let regex = /\r?\n/g;
|
|
104
|
+
regex.lastIndex = Math.max(0, prefix.length - 1);
|
|
105
|
+
this._readValue(regex, data, 0, done);
|
|
82
106
|
}
|
|
83
107
|
|
|
84
108
|
/**
|
|
@@ -179,6 +203,7 @@ class IMAPStream extends Writable {
|
|
|
179
203
|
// connection to proxy mode never calls back, and whatever the client pipelined after it
|
|
180
204
|
// has to be handed to the upstream server instead of being dropped (see takeRemainder).
|
|
181
205
|
this._pending = { data, pos };
|
|
206
|
+
let sync = true;
|
|
182
207
|
this.oncommand(
|
|
183
208
|
{
|
|
184
209
|
value: line,
|
|
@@ -186,9 +211,31 @@ class IMAPStream extends Writable {
|
|
|
186
211
|
},
|
|
187
212
|
() => {
|
|
188
213
|
this._pending = null;
|
|
189
|
-
|
|
214
|
+
// A command that completes synchronously (NOOP, CAPABILITY, ID) used to call back
|
|
215
|
+
// into this method from inside it, so one chunk of a few thousand pipelined
|
|
216
|
+
// commands grew the stack until it overflowed and the RangeError, thrown inside
|
|
217
|
+
// the socket's data handler, took the whole worker down. Only that case is
|
|
218
|
+
// deferred; a command that went through I/O calls back on a fresh stack
|
|
219
|
+
if (sync) {
|
|
220
|
+
setImmediate(() => this._readValue(regex, data, pos, done));
|
|
221
|
+
} else {
|
|
222
|
+
this._readValue(regex, data, pos, done);
|
|
223
|
+
}
|
|
190
224
|
}
|
|
191
225
|
);
|
|
226
|
+
sync = false;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Takes the unfinished line out of the buffers
|
|
231
|
+
* @returns {String} what was kept
|
|
232
|
+
*/
|
|
233
|
+
_clearRemainder() {
|
|
234
|
+
let line = this._remainder + this._remainderParts.join('');
|
|
235
|
+
this._remainder = '';
|
|
236
|
+
this._remainderParts = [];
|
|
237
|
+
this._remainderLength = 0;
|
|
238
|
+
return line;
|
|
192
239
|
}
|
|
193
240
|
|
|
194
241
|
/**
|
|
@@ -206,9 +253,9 @@ class IMAPStream extends Writable {
|
|
|
206
253
|
}
|
|
207
254
|
this._pending = null;
|
|
208
255
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
256
|
+
let kept = this._clearRemainder();
|
|
257
|
+
if (kept) {
|
|
258
|
+
chunks.push(Buffer.from(kept, 'binary'));
|
|
212
259
|
}
|
|
213
260
|
|
|
214
261
|
let buffered = this.writableBuffer || (this._writableState && typeof this._writableState.getBuffer === 'function' && this._writableState.getBuffer()) || [];
|
|
@@ -225,10 +272,8 @@ class IMAPStream extends Writable {
|
|
|
225
272
|
* Flushes remaining bytes
|
|
226
273
|
*/
|
|
227
274
|
_flushData() {
|
|
228
|
-
let line;
|
|
229
|
-
if (
|
|
230
|
-
line = this._remainder;
|
|
231
|
-
this._remainder = '';
|
|
275
|
+
let line = this._clearRemainder();
|
|
276
|
+
if (line) {
|
|
232
277
|
this.oncommand(Buffer.from(line, 'binary'));
|
|
233
278
|
}
|
|
234
279
|
}
|
|
@@ -889,7 +889,9 @@ function textToHtml(str) {
|
|
|
889
889
|
encoded
|
|
890
890
|
.replace(/\r?\n/g, '\n')
|
|
891
891
|
.trim() // normalize line endings
|
|
892
|
-
.
|
|
892
|
+
// rtrim every line. The group keeps this linear: /[ \t]+$/gm retried a run of
|
|
893
|
+
// spaces inside a line from every position in it, quadratic in the run
|
|
894
|
+
.replace(/(^|[^ \t])[ \t]+$/gm, '$1')
|
|
893
895
|
.trim() // trim empty line endings
|
|
894
896
|
.replace(/\n\n+/g, '</p><p>')
|
|
895
897
|
.trim() // insert <p> to multiple linebreaks
|
package/lib/mcp/listen.js
CHANGED
|
@@ -182,7 +182,16 @@ async function runRecheckPass() {
|
|
|
182
182
|
const groups = new Map();
|
|
183
183
|
for (const stream of mcpListenStreams) {
|
|
184
184
|
const subscription = stream.mcpSubscription;
|
|
185
|
-
if (!subscription || !subscription.recheck
|
|
185
|
+
if (!subscription || !subscription.recheck) {
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (!subscription.resourceUris.size) {
|
|
189
|
+
// Nothing left to deliver, and nothing left to re-check the credential against: a
|
|
190
|
+
// stream in this state used to stay open past a token revocation for as long as the
|
|
191
|
+
// client kept it. The client resubscribes if it wants more
|
|
192
|
+
if (!stream._finalized && !stream.destroyed) {
|
|
193
|
+
stream.finalize();
|
|
194
|
+
}
|
|
186
195
|
continue;
|
|
187
196
|
}
|
|
188
197
|
let group = groups.get(subscription.credentialId);
|
|
@@ -153,7 +153,9 @@ function extractFromFormat(rawText, format) {
|
|
|
153
153
|
try {
|
|
154
154
|
parsed = JSON.parse(rawText);
|
|
155
155
|
} catch (err) {
|
|
156
|
-
|
|
156
|
+
// Without the parser's message: V8 quotes the offending text in it, and this string reaches
|
|
157
|
+
// the verify report, so it would hand back the first characters of whatever was read
|
|
158
|
+
throw makeError('Subject token source did not return valid JSON', 'ESubjectTokenRead', null, { cause: err });
|
|
157
159
|
}
|
|
158
160
|
let field = format.subject_token_field_name;
|
|
159
161
|
let value = parsed && typeof parsed === 'object' ? parsed[field] : undefined;
|