emailengine-app 2.79.8 → 2.80.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/dependabot.yml +22 -0
- package/.github/workflows/test.yml +39 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +69 -0
- package/DOCKER_DEPLOYMENT.md +6 -7
- package/Dockerfile +35 -11
- package/config/default.toml +7 -2
- package/copy-static-files.sh +23 -5
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +43 -0
- package/lib/account/account-state.js +62 -0
- package/lib/account.js +60 -3
- package/lib/api-routes/account-routes.js +20 -0
- package/lib/api-routes/bull-board-routes.js +3 -2
- package/lib/api-routes/index.js +1 -1
- package/lib/api-routes/route-helpers.js +8 -0
- package/lib/api-routes/settings-routes.js +17 -2
- package/lib/auth-token.js +73 -2
- package/lib/autodetect-imap-settings.js +379 -69
- package/lib/cert-handler.js +62 -0
- package/lib/consts.js +58 -7
- package/lib/db.js +12 -0
- package/lib/egress-fetch.js +145 -0
- package/lib/email-client/base-client.js +234 -66
- package/lib/email-client/credential-errors.js +118 -0
- package/lib/email-client/gmail/gmail-api.js +2 -1
- package/lib/email-client/gmail-client.js +70 -64
- package/lib/email-client/imap/connection-errors.js +52 -0
- package/lib/email-client/imap/listing-diff.js +47 -6
- package/lib/email-client/imap/mailbox.js +457 -379
- package/lib/email-client/imap/subconnection.js +15 -11
- package/lib/email-client/imap/sync-operations.js +46 -59
- package/lib/email-client/imap-client.js +136 -95
- package/lib/email-client/message-builder.js +11 -11
- package/lib/email-client/outlook/graph-api.js +2 -1
- package/lib/email-client/outlook-client.js +219 -106
- package/lib/export.js +35 -2
- package/lib/handlebars-helpers.js +129 -0
- package/lib/imap-proxy-auth.js +96 -21
- package/lib/imapproxy/imap-core/README.md +1 -0
- package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
- package/lib/imapproxy/imap-server.js +56 -66
- package/lib/lua/h-del-if-equals.lua +39 -0
- package/lib/lua/h-set-if-equals.lua +39 -0
- package/lib/openapi/index.js +3 -0
- package/lib/outbox.js +28 -3
- package/lib/rate-limit.js +23 -4
- package/lib/routes-ui.js +4 -34
- package/lib/schemas.js +42 -3
- package/lib/security-headers.js +411 -0
- package/lib/sentry.js +36 -4
- package/lib/smtp-auth.js +86 -7
- package/lib/tls/context.js +376 -0
- package/lib/tls/der.js +223 -0
- package/lib/tls/provision.js +555 -0
- package/lib/tls/self-signed.js +282 -0
- package/lib/tls/status.js +431 -0
- package/lib/tls/store.js +666 -0
- package/lib/tools.js +337 -147
- package/lib/ui-routes/account-routes.js +47 -33
- package/lib/ui-routes/admin-config-routes.js +22 -1
- package/lib/ui-routes/auth-routes.js +16 -1
- package/lib/ui-routes/export-routes.js +4 -0
- package/lib/ui-routes/internals-routes.js +3 -5
- package/lib/ui-routes/mcp-consent-routes.js +7 -0
- package/lib/ui-routes/network-config-routes.js +58 -48
- package/lib/ui-routes/route-helpers.js +24 -8
- package/lib/ui-routes/smtp-test-routes.js +7 -0
- package/lib/ui-routes/tls-config-routes.js +581 -0
- package/lib/utils/mailbox-path.js +51 -0
- package/lib/utils/severity.js +31 -0
- package/lib/webhook-egress.js +5 -0
- package/package.json +21 -24
- package/sbom.json +1 -1
- package/server.js +53 -36
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +11 -0
- package/static/js/ace/css/ace.css +1462 -0
- package/static/js/ace/css/kuroir-1.png +0 -0
- package/static/js/ace/css/kuroir-2.png +0 -0
- package/static/js/ace/css/main-1.png +0 -0
- package/static/js/ace/css/main-10.svg +4 -0
- package/static/js/ace/css/main-11.svg +5 -0
- package/static/js/ace/css/main-12.svg +4 -0
- package/static/js/ace/css/main-13.png +0 -0
- package/static/js/ace/css/main-14.png +0 -0
- package/static/js/ace/css/main-15.png +0 -0
- package/static/js/ace/css/main-16.png +0 -0
- package/static/js/ace/css/main-17.png +0 -0
- package/static/js/ace/css/main-18.png +0 -0
- package/static/js/ace/css/main-19.png +0 -0
- package/static/js/ace/css/main-2.png +0 -0
- package/static/js/ace/css/main-20.png +0 -0
- package/static/js/ace/css/main-21.png +0 -0
- package/static/js/ace/css/main-22.png +0 -0
- package/static/js/ace/css/main-23.png +0 -0
- package/static/js/ace/css/main-24.png +0 -0
- package/static/js/ace/css/main-25.svg +1 -0
- package/static/js/ace/css/main-26.png +0 -0
- package/static/js/ace/css/main-3.png +0 -0
- package/static/js/ace/css/main-4.png +0 -0
- package/static/js/ace/css/main-5.svg +7 -0
- package/static/js/ace/css/main-6.svg +9 -0
- package/static/js/ace/css/main-7.svg +7 -0
- package/static/js/ace/css/main-8.svg +9 -0
- package/static/js/ace/css/main-9.svg +6 -0
- package/static/js/ace/css/theme/kuroir.css +78 -0
- package/static/js/ace/css/theme/tomorrow_night.css +128 -0
- package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
- package/static/js/ace/css/theme/xcode.css +106 -0
- package/static/js/ace/css/tomorrow_night-1.png +0 -0
- package/static/js/ace/css/tomorrow_night-2.png +0 -0
- package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
- package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
- package/static/js/ace/css/xcode-1.png +0 -0
- package/static/js/ace/css/xcode-2.png +0 -0
- package/static/js/app.js +34 -0
- package/static/js/ee-client.js +256 -102
- package/static/js/public.js +13 -2
- package/static/js/ui.js +40 -25
- package/static/licenses.html +393 -1282
- package/static/vendor/simplewebauthn/browser.min.js +2 -2
- package/translations/messages.pot +203 -157
- package/views/account/login-redirect.hbs +22 -0
- package/views/accounts/account.hbs +15 -37
- package/views/accounts/browse.hbs +3 -1
- package/views/accounts/edit.hbs +1 -1
- package/views/accounts/register/imap-server.hbs +1 -1
- package/views/config/ai.hbs +1 -1
- package/views/config/branding.hbs +2 -2
- package/views/config/document-store/chat.hbs +1 -1
- package/views/config/document-store/index.hbs +1 -1
- package/views/config/imap-proxy.hbs +1 -4
- package/views/config/license.hbs +1 -1
- package/views/config/mcp.hbs +1 -1
- package/views/config/network.hbs +14 -16
- package/views/config/oauth/app.hbs +2 -2
- package/views/config/service.hbs +1 -1
- package/views/config/smtp.hbs +1 -4
- package/views/config/tls-upload.hbs +81 -0
- package/views/config/tls.hbs +492 -0
- package/views/config/webhooks.hbs +2 -2
- package/views/error.hbs +4 -2
- package/views/internals/index.hbs +1 -1
- package/views/layout/app.hbs +3 -11
- package/views/mcp/authorize.hbs +1 -1
- package/views/partials/ace_assets.hbs +13 -0
- package/views/partials/add_account_modal.hbs +1 -1
- package/views/partials/address_list.hbs +4 -4
- package/views/partials/filter_editor_js.hbs +2 -2
- package/views/partials/gateway_js.hbs +1 -1
- package/views/partials/oauth_form.hbs +1 -1
- package/views/partials/public_theme_init.hbs +1 -1
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/template_form.hbs +2 -2
- package/views/partials/test_send.hbs +7 -4
- package/views/partials/theme_init.hbs +1 -1
- package/views/partials/tls_security_card.hbs +25 -53
- package/views/partials/ui/alert-banner.hbs +3 -2
- package/views/partials/ui/badge.hbs +6 -2
- package/views/partials/ui/btn.hbs +5 -2
- package/views/partials/ui/details.hbs +2 -2
- package/views/partials/webhooks_editor_functions.hbs +1 -1
- package/views/reference/redirect.hbs +1 -1
- package/views/templates/template.hbs +2 -2
- package/views/tokens/new.hbs +1 -1
- package/views/unsubscribe.hbs +1 -1
- package/views/webhooks/webhook.hbs +2 -2
- package/workers/api.js +131 -242
- package/workers/export.js +1 -5
- package/workers/imap-proxy.js +4 -1
- package/workers/imap.js +1 -3
- package/workers/smtp.js +59 -83
- package/workers/submit.js +6 -12
- package/workers/webhooks.js +6 -17
- package/static/front/EmailEngine_logo_horiz.png +0 -0
- package/static/front/EmailEngine_logo_vert.png +0 -0
- package/static/front/index.html +0 -57
- package/static/front/logo.png +0 -0
- package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
- package/views/partials/tls_security_js.hbs +0 -64
- package/views/partials/tls_security_modal.hbs +0 -22
package/lib/imap-proxy-auth.js
CHANGED
|
@@ -11,8 +11,77 @@ const { redis } = require('./db');
|
|
|
11
11
|
const { Account } = require('./account');
|
|
12
12
|
const getSecret = require('./get-secret');
|
|
13
13
|
const { isApiBasedApp } = require('./oauth2-apps');
|
|
14
|
-
const { validateAuthToken, REASON_MESSAGES } = require('./auth-token');
|
|
14
|
+
const { validateAuthToken, withAuthFailureBudget, REASON_MESSAGES } = require('./auth-token');
|
|
15
15
|
const { constantTimeEqual } = require('./tools');
|
|
16
|
+
const { isTransientCredentialError } = require('./email-client/credential-errors');
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Tags an error as an IMAP authentication rejection for the proxy client.
|
|
20
|
+
*
|
|
21
|
+
* @param {Error} err - Error to tag
|
|
22
|
+
* @returns {Error} the same error
|
|
23
|
+
*/
|
|
24
|
+
function failImapAuth(err) {
|
|
25
|
+
err.authenticationFailed = true;
|
|
26
|
+
err.serverResponseCode = 'AUTHENTICATIONFAILED';
|
|
27
|
+
err.responseStatus = 'NO';
|
|
28
|
+
return err;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const authenticationFailedError = message => failImapAuth(new Error(message));
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Tags an error as a temporary failure the client should retry rather than a rejected password.
|
|
35
|
+
* Deliberately without the authenticationFailed flag: nothing refused the credential, the service
|
|
36
|
+
* that holds it was unreachable. RFC 5530 [UNAVAILABLE] is the code for exactly that, and the
|
|
37
|
+
* response status has to be set explicitly - an error reaching the IMAP server with no `response`
|
|
38
|
+
* is rendered as BAD and counts against the connection's bad-command budget.
|
|
39
|
+
*
|
|
40
|
+
* @param {Error} err - Error to tag
|
|
41
|
+
* @returns {Error} the same error
|
|
42
|
+
*/
|
|
43
|
+
function failImapUnavailable(err) {
|
|
44
|
+
err.serverResponseCode = 'UNAVAILABLE';
|
|
45
|
+
err.responseStatus = 'NO';
|
|
46
|
+
return err;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Decides how a failed attempt to obtain the account's upstream credentials is answered. One
|
|
51
|
+
* authentication server serves every account on the instance, so its bad minute must not reach a
|
|
52
|
+
* desktop client as a wrong password - which is what makes the user retype a working one.
|
|
53
|
+
*
|
|
54
|
+
* @param {Error} err - The credential failure
|
|
55
|
+
* @returns {Error} the same error, tagged with the response to send
|
|
56
|
+
*/
|
|
57
|
+
function classifyCredentialFailure(err) {
|
|
58
|
+
return isTransientCredentialError(err) ? failImapUnavailable(err) : failImapAuth(err);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Whether an error already names the IMAP response to answer the client with, as opposed to being
|
|
63
|
+
* an internal proxy fault. Both a refusal and a temporary failure carry one.
|
|
64
|
+
*
|
|
65
|
+
* @param {Error} err - The error to check
|
|
66
|
+
* @returns {boolean} True when the error carries an IMAP response
|
|
67
|
+
*/
|
|
68
|
+
function isImapResponseError(err) {
|
|
69
|
+
return !!err && (!!err.authenticationFailed || err.serverResponseCode === 'AUTHENTICATIONFAILED' || err.serverResponseCode === 'UNAVAILABLE');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Renders a tagged failure as the error the IMAP server answers the client with. imap-core reads
|
|
74
|
+
* the status off `response`, and an error that carries none is answered BAD, which counts against
|
|
75
|
+
* the connection's bad-command budget instead of telling the client what happened.
|
|
76
|
+
*
|
|
77
|
+
* @param {Error} err - The tagged failure
|
|
78
|
+
* @returns {Error} A new error carrying the response line to send
|
|
79
|
+
*/
|
|
80
|
+
function toImapResponseError(err) {
|
|
81
|
+
let error = new Error(`${err.serverResponseCode ? `[${err.serverResponseCode}] ` : ''}${err.responseText || err.message || 'Authentication failed'}`);
|
|
82
|
+
error.response = err.responseStatus || 'NO';
|
|
83
|
+
return error;
|
|
84
|
+
}
|
|
16
85
|
|
|
17
86
|
/**
|
|
18
87
|
* Builds the IMAP proxy authentication handler.
|
|
@@ -22,7 +91,9 @@ const { constantTimeEqual } = require('./tools');
|
|
|
22
91
|
* @returns {Function} async authenticate(auth, session) -> { accountObject, accountData }
|
|
23
92
|
*/
|
|
24
93
|
function createImapProxyAuthHandler({ call }) {
|
|
25
|
-
|
|
94
|
+
// The credential check proper. Everything it throws is a refusal the client caused, which
|
|
95
|
+
// is what the failure budget in authenticate() counts.
|
|
96
|
+
async function verifyCredentials(auth, session) {
|
|
26
97
|
let account = auth.username;
|
|
27
98
|
|
|
28
99
|
let imapPassword = await settings.get('imapProxyServerPassword');
|
|
@@ -36,10 +107,7 @@ function createImapProxyAuthHandler({ call }) {
|
|
|
36
107
|
});
|
|
37
108
|
|
|
38
109
|
if (!result.authenticated) {
|
|
39
|
-
|
|
40
|
-
err.serverResponseCode = 'AUTHENTICATIONFAILED';
|
|
41
|
-
err.responseStatus = 'NO';
|
|
42
|
-
throw err;
|
|
110
|
+
throw authenticationFailedError(REASON_MESSAGES[result.reason] || 'Access denied, failed to authenticate user');
|
|
43
111
|
}
|
|
44
112
|
}
|
|
45
113
|
|
|
@@ -48,19 +116,31 @@ function createImapProxyAuthHandler({ call }) {
|
|
|
48
116
|
try {
|
|
49
117
|
accountData = await accountObject.loadAccountData();
|
|
50
118
|
} catch (err) {
|
|
51
|
-
let respErr = new Error('Failed to authenticate user');
|
|
52
|
-
respErr.serverResponseCode = 'AUTHENTICATIONFAILED';
|
|
53
|
-
respErr.responseStatus = 'NO';
|
|
54
|
-
|
|
55
119
|
if (!err.output || err.output.statusCode !== 404) {
|
|
56
120
|
// only log non-obvious errors
|
|
57
121
|
logger.error({ msg: 'Failed to load account data', account: auth.username, err });
|
|
58
122
|
}
|
|
59
123
|
|
|
60
|
-
throw
|
|
124
|
+
throw authenticationFailedError('Failed to authenticate user');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (!accountData) {
|
|
128
|
+
throw authenticationFailedError('Access denied, failed to authenticate user');
|
|
61
129
|
}
|
|
62
130
|
|
|
63
|
-
|
|
131
|
+
return { accountObject, accountData };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return async function authenticate(auth, session) {
|
|
135
|
+
let verified = await withAuthFailureBudget(
|
|
136
|
+
{ remoteAddress: session.remoteAddress, account: auth.username },
|
|
137
|
+
() => verifyCredentials(auth, session),
|
|
138
|
+
() => authenticationFailedError(REASON_MESSAGES.limited)
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
// Past the credential check: a refusal from here on is about the account, not about
|
|
142
|
+
// what the client presented, so it does not count against the client's budget
|
|
143
|
+
if (isApiBasedApp(verified.accountData?._app)) {
|
|
64
144
|
let respErr = new Error('IMAP is not supported for API-based accounts');
|
|
65
145
|
respErr.authenticationFailed = true;
|
|
66
146
|
respErr.serverResponseCode = 'ACCOUNTDISABLED';
|
|
@@ -68,15 +148,10 @@ function createImapProxyAuthHandler({ call }) {
|
|
|
68
148
|
throw respErr;
|
|
69
149
|
}
|
|
70
150
|
|
|
71
|
-
|
|
72
|
-
let err = new Error('Access denied, failed to authenticate user');
|
|
73
|
-
err.serverResponseCode = 'AUTHENTICATIONFAILED';
|
|
74
|
-
err.responseStatus = 'NO';
|
|
75
|
-
throw err;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
return { accountObject, accountData };
|
|
151
|
+
return verified;
|
|
79
152
|
};
|
|
80
153
|
}
|
|
81
154
|
|
|
82
|
-
|
|
155
|
+
// Only what the proxy server and its tests reach for: the two taggers are reached through
|
|
156
|
+
// classifyCredentialFailure(), which is the decision that has to be made in one place
|
|
157
|
+
module.exports = { createImapProxyAuthHandler, classifyCredentialFailure, isImapResponseError, toImapResponseError };
|
|
@@ -30,6 +30,7 @@ means re-applying these.
|
|
|
30
30
|
| `e97950e7` | 2026-06-05 | Close leaks and a worker crash found in the connection hardening review |
|
|
31
31
|
| `d51e92d2` | 2026-06-06 | Prevent post-BYE command dispatch during teardown |
|
|
32
32
|
| `31f6a590` | 2026-07-26 | Fix the dead teardown guard in the notification listener |
|
|
33
|
+
| `74856cf6` | 2026-09-02 | Drop the built-in self-signed key/certificate pair from `tls-options.js`; a listener with TLS and no certificate is refused at startup instead of served with a key that ships in every copy |
|
|
33
34
|
|
|
34
35
|
Earlier local changes (`09085d12`, `0a389560`, `7e2e94f3`, `04c2aa90`, `1d6df05e`, `612d9f96`,
|
|
35
36
|
`13edec58`, `2e0bf1ce`, `b9a3e06c`, `b58a827e`, `1813f089`) are maintenance: dependency swaps
|
|
@@ -5,53 +5,12 @@ const crypto = require('crypto');
|
|
|
5
5
|
// Expose to the world
|
|
6
6
|
module.exports = getTLSOptions;
|
|
7
7
|
|
|
8
|
+
// No built-in key or certificate. Upstream ships a self-signed localhost pair here as the
|
|
9
|
+
// fallback for a server configured with TLS but no certificate, and that private key is the
|
|
10
|
+
// same in every copy of the library, so a listener secured by it is readable by anyone with the
|
|
11
|
+
// source. EmailEngine's IMAP proxy refuses to start with TLS and no certificate instead
|
|
12
|
+
// (assertTlsCredentials in lib/tools.js), and the STARTTLS upgrade is disabled in proxy mode.
|
|
8
13
|
const tlsDefaults = {
|
|
9
|
-
key:
|
|
10
|
-
'-----BEGIN RSA PRIVATE KEY-----\n' +
|
|
11
|
-
'MIIEpAIBAAKCAQEA6Z5Qqhw+oWfhtEiMHE32Ht94mwTBpAfjt3vPpX8M7DMCTwHs\n' +
|
|
12
|
-
'1xcXvQ4lQ3rwreDTOWdoJeEEy7gMxXqH0jw0WfBx+8IIJU69xstOyT7FRFDvA1yT\n' +
|
|
13
|
-
'RXY2yt9K5s6SKken/ebMfmZR+03ND4UFsDzkz0FfgcjrkXmrMF5Eh5UXX/+9YHeU\n' +
|
|
14
|
-
'xlp0gMAt+/SumSmgCaysxZLjLpd4uXz+X+JVxsk1ACg1NoEO7lWJC/3WBP7MIcu2\n' +
|
|
15
|
-
'wVsMd2XegLT0gWYfT1/jsIH64U/mS/SVXC9QhxMl9Yfko2kx1OiYhDxhHs75RJZh\n' +
|
|
16
|
-
'rNRxgfiwgSb50Gw4NAQaDIxr/DJPdLhgnpY6UQIDAQABAoIBAE+tfzWFjJbgJ0ql\n' +
|
|
17
|
-
's6Ozs020Sh4U8TZQuonJ4HhBbNbiTtdDgNObPK1uNadeNtgW5fOeIRdKN6iDjVeN\n' +
|
|
18
|
-
'AuXhQrmqGDYVZ1HSGUfD74sTrZQvRlWPLWtzdhybK6Css41YAyPFo9k4bJ2ZW2b/\n' +
|
|
19
|
-
'p4EEQ8WsNja9oBpttMU6YYUchGxo1gujN8hmfDdXUQx3k5Xwx4KA68dveJ8GasIt\n' +
|
|
20
|
-
'd+0Jd/FVwCyyx8HTiF1FF8QZYQeAXxbXJgLBuCsMQJghlcpBEzWkscBR3Ap1U0Zi\n' +
|
|
21
|
-
'4oat8wrPZGCblaA6rNkRUVbc/+Vw0stnuJ/BLHbPxyBs6w495yBSjBqUWZMvljNz\n' +
|
|
22
|
-
'm9/aK0ECgYEA9oVIVAd0enjSVIyAZNbw11ElidzdtBkeIJdsxqhmXzeIFZbB39Gd\n' +
|
|
23
|
-
'bjtAVclVbq5mLsI1j22ER2rHA4Ygkn6vlLghK3ZMPxZa57oJtmL3oP0RvOjE4zRV\n' +
|
|
24
|
-
'dzKexNGo9gU/x9SQbuyOmuauvAYhXZxeLpv+lEfsZTqqrvPUGeBiEQcCgYEA8poG\n' +
|
|
25
|
-
'WVnykWuTmCe0bMmvYDsWpAEiZnFLDaKcSbz3O7RMGbPy1cypmqSinIYUpURBT/WY\n' +
|
|
26
|
-
'wVPAGtjkuTXtd1Cy58m7PqziB7NNWMcsMGj+lWrTPZ6hCHIBcAImKEPpd+Y9vGJX\n' +
|
|
27
|
-
'oatFJguqAGOz7rigBq6iPfeQOCWpmprNAuah++cCgYB1gcybOT59TnA7mwlsh8Qf\n' +
|
|
28
|
-
'bm+tSllnin2A3Y0dGJJLmsXEPKtHS7x2Gcot2h1d98V/TlWHe5WNEUmx1VJbYgXB\n' +
|
|
29
|
-
'pw8wj2ACxl4ojNYqWPxegaLd4DpRbtW6Tqe9e47FTnU7hIggR6QmFAWAXI+09l8y\n' +
|
|
30
|
-
'amssNShqjE9lu5YDi6BTKwKBgQCuIlKGViLfsKjrYSyHnajNWPxiUhIgGBf4PI0T\n' +
|
|
31
|
-
'/Jg1ea/aDykxv0rKHnw9/5vYGIsM2st/kR7l5mMecg/2Qa145HsLfMptHo1ZOPWF\n' +
|
|
32
|
-
'9gcuttPTegY6aqKPhGthIYX2MwSDMM+X0ri6m0q2JtqjclAjG7yG4CjbtGTt/UlE\n' +
|
|
33
|
-
'WMlSZwKBgQDslGeLUnkW0bsV5EG3AKRUyPKz/6DVNuxaIRRhOeWVKV101claqXAT\n' +
|
|
34
|
-
'wXOpdKrvkjZbT4AzcNrlGtRl3l7dEVXTu+dN7/ZieJRu7zaStlAQZkIyP9O3DdQ3\n' +
|
|
35
|
-
'rIcetQpfrJ1cAqz6Ng0pD0mh77vQ13WG1BBmDFa2A9BuzLoBituf4g==\n' +
|
|
36
|
-
'-----END RSA PRIVATE KEY-----',
|
|
37
|
-
cert:
|
|
38
|
-
'-----BEGIN CERTIFICATE-----\n' +
|
|
39
|
-
'MIICpDCCAYwCCQCuVLVKVTXnAjANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDEwls\n' +
|
|
40
|
-
'b2NhbGhvc3QwHhcNMTUwMjEyMTEzMjU4WhcNMjUwMjA5MTEzMjU4WjAUMRIwEAYD\n' +
|
|
41
|
-
'VQQDEwlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDp\n' +
|
|
42
|
-
'nlCqHD6hZ+G0SIwcTfYe33ibBMGkB+O3e8+lfwzsMwJPAezXFxe9DiVDevCt4NM5\n' +
|
|
43
|
-
'Z2gl4QTLuAzFeofSPDRZ8HH7wgglTr3Gy07JPsVEUO8DXJNFdjbK30rmzpIqR6f9\n' +
|
|
44
|
-
'5sx+ZlH7Tc0PhQWwPOTPQV+ByOuReaswXkSHlRdf/71gd5TGWnSAwC379K6ZKaAJ\n' +
|
|
45
|
-
'rKzFkuMul3i5fP5f4lXGyTUAKDU2gQ7uVYkL/dYE/swhy7bBWwx3Zd6AtPSBZh9P\n' +
|
|
46
|
-
'X+OwgfrhT+ZL9JVcL1CHEyX1h+SjaTHU6JiEPGEezvlElmGs1HGB+LCBJvnQbDg0\n' +
|
|
47
|
-
'BBoMjGv8Mk90uGCeljpRAgMBAAEwDQYJKoZIhvcNAQELBQADggEBABXm8GPdY0sc\n' +
|
|
48
|
-
'mMUFlgDqFzcevjdGDce0QfboR+M7WDdm512Jz2SbRTgZD/4na42ThODOZz9z1AcM\n' +
|
|
49
|
-
'zLgx2ZNZzVhBz0odCU4JVhOCEks/OzSyKeGwjIb4JAY7dh+Kju1+6MNfQJ4r1Hza\n' +
|
|
50
|
-
'SVXH0+JlpJDaJ73NQ2JyfqELmJ1mTcptkA/N6rQWhlzycTBSlfogwf9xawgVPATP\n' +
|
|
51
|
-
'4AuwgjHl12JI2HVVs1gu65Y3slvaHRCr0B4+Kg1GYNLLcbFcK+NEHrHmPxy9TnTh\n' +
|
|
52
|
-
'Zwp1dsNQU+Xkylz8IUANWSLHYZOMtN2e5SKIdwTtl5C8YxveuY8YKb1gDExnMraT\n' +
|
|
53
|
-
'VGXQDqPleug=\n' +
|
|
54
|
-
'-----END CERTIFICATE-----',
|
|
55
14
|
honorCipherOrder: true,
|
|
56
15
|
requestOCSP: false,
|
|
57
16
|
sessionIdContext: crypto.createHash('sha256').update(process.argv.join(' ')).digest('hex').slice(0, 32),
|
|
@@ -15,17 +15,17 @@ const {
|
|
|
15
15
|
hasEnvValue,
|
|
16
16
|
readEnvValue,
|
|
17
17
|
emitChangeEvent,
|
|
18
|
-
loadTlsConfig
|
|
18
|
+
loadTlsConfig,
|
|
19
|
+
assertTlsCredentials
|
|
19
20
|
} = require('../tools');
|
|
20
21
|
const { getLocalAddress } = require('../utils/network');
|
|
21
22
|
|
|
22
23
|
const { redis } = require('../db');
|
|
23
|
-
const { createImapProxyAuthHandler } = require('../imap-proxy-auth');
|
|
24
|
-
const getSecret = require('../get-secret');
|
|
24
|
+
const { createImapProxyAuthHandler, classifyCredentialFailure, isImapResponseError, toImapResponseError } = require('../imap-proxy-auth');
|
|
25
25
|
const settings = require('../settings');
|
|
26
26
|
|
|
27
|
-
const {
|
|
28
|
-
const {
|
|
27
|
+
const { createCertHandler } = require('../cert-handler');
|
|
28
|
+
const { createTlsContext, applyTlsContext } = require('../tls/context');
|
|
29
29
|
|
|
30
30
|
config.imap = config.imap || {
|
|
31
31
|
enabled: false,
|
|
@@ -42,7 +42,7 @@ const EENGINE_TIMEOUT = getDuration(readEnvValue('EENGINE_TIMEOUT') || config.se
|
|
|
42
42
|
const EENGINE_LOG_RAW = hasEnvValue('EENGINE_LOG_RAW') ? getBoolean(readEnvValue('EENGINE_LOG_RAW')) : getBoolean(config.log.raw);
|
|
43
43
|
const DISABLE_IMAP_COMPRESSION = getBoolean(readEnvValue('EENGINE_DISABLE_COMPRESSION'));
|
|
44
44
|
|
|
45
|
-
const {
|
|
45
|
+
const { TLS_DEFAULTS } = require('../consts');
|
|
46
46
|
|
|
47
47
|
let callQueue = new Map();
|
|
48
48
|
let mids = 0;
|
|
@@ -163,14 +163,6 @@ class PassThroughLogger extends PassThrough {
|
|
|
163
163
|
// without booting this worker. call() is injected for the Account instance.
|
|
164
164
|
const authenticateImapProxy = createImapProxyAuthHandler({ call });
|
|
165
165
|
|
|
166
|
-
// Tag a credential-loading failure as an IMAP authentication rejection for the proxy client.
|
|
167
|
-
function failImapAuth(err) {
|
|
168
|
-
err.authenticationFailed = true;
|
|
169
|
-
err.serverResponseCode = 'AUTHENTICATIONFAILED';
|
|
170
|
-
err.responseStatus = 'NO';
|
|
171
|
-
return err;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
166
|
async function onAuth(auth, session) {
|
|
175
167
|
let account = auth.username;
|
|
176
168
|
|
|
@@ -193,7 +185,7 @@ async function onAuth(auth, session) {
|
|
|
193
185
|
try {
|
|
194
186
|
imapAuth = await resolveCredentials(account, 'imap');
|
|
195
187
|
} catch (err) {
|
|
196
|
-
throw
|
|
188
|
+
throw classifyCredentialFailure(err);
|
|
197
189
|
}
|
|
198
190
|
} else {
|
|
199
191
|
if (!accountData.oauth2.accessToken || !accountData.oauth2.expires || accountData.oauth2.expires < new Date(Date.now() + 30 * 1000)) {
|
|
@@ -201,7 +193,7 @@ async function onAuth(auth, session) {
|
|
|
201
193
|
try {
|
|
202
194
|
accountData = await accountObject.renewAccessToken();
|
|
203
195
|
} catch (err) {
|
|
204
|
-
throw
|
|
196
|
+
throw classifyCredentialFailure(err);
|
|
205
197
|
}
|
|
206
198
|
}
|
|
207
199
|
imapAuth = { user: accountData.oauth2.auth.user, accessToken: accountData.oauth2.accessToken };
|
|
@@ -224,7 +216,7 @@ async function onAuth(auth, session) {
|
|
|
224
216
|
try {
|
|
225
217
|
imapConnectionConfig.auth = await resolveCredentials(account, 'imap');
|
|
226
218
|
} catch (err) {
|
|
227
|
-
throw
|
|
219
|
+
throw classifyCredentialFailure(err);
|
|
228
220
|
}
|
|
229
221
|
}
|
|
230
222
|
|
|
@@ -461,13 +453,9 @@ const createServer = function (options = {}) {
|
|
|
461
453
|
});
|
|
462
454
|
})
|
|
463
455
|
.catch(err => {
|
|
464
|
-
if (err
|
|
456
|
+
if (isImapResponseError(err)) {
|
|
465
457
|
serverLogger.warn({ msg: 'Upstream authentication failed', account, cid: session.id, err });
|
|
466
|
-
|
|
467
|
-
`${err.serverResponseCode ? `[${err.serverResponseCode}] ` : ''}${err.responseText || err.message || 'Authentication failed'}`
|
|
468
|
-
);
|
|
469
|
-
error.response = err.responseStatus || 'NO';
|
|
470
|
-
return callback(error);
|
|
458
|
+
return callback(toImapResponseError(err));
|
|
471
459
|
} else {
|
|
472
460
|
serverLogger.error({ msg: 'Failed to create proxy', account, cid: session.id, err });
|
|
473
461
|
return callback(err);
|
|
@@ -476,14 +464,10 @@ const createServer = function (options = {}) {
|
|
|
476
464
|
})
|
|
477
465
|
.catch(err => {
|
|
478
466
|
let entry = { msg: 'Authentication check failed', username: login.username, cid: session.id, remoteAddress: session.remoteAddress, err };
|
|
479
|
-
if (err
|
|
480
|
-
//
|
|
467
|
+
if (isImapResponseError(err)) {
|
|
468
|
+
// a refused login or a temporary failure the client is told to retry, not a proxy fault
|
|
481
469
|
serverLogger.warn(entry);
|
|
482
|
-
|
|
483
|
-
`${err.serverResponseCode ? `[${err.serverResponseCode}] ` : ''}${err.responseText || err.message || 'Authentication failed'}`
|
|
484
|
-
);
|
|
485
|
-
error.response = err.responseStatus || 'NO';
|
|
486
|
-
return callback(error);
|
|
470
|
+
return callback(toImapResponseError(err));
|
|
487
471
|
}
|
|
488
472
|
serverLogger.error(entry);
|
|
489
473
|
return callback(err);
|
|
@@ -493,6 +477,11 @@ const createServer = function (options = {}) {
|
|
|
493
477
|
return server;
|
|
494
478
|
};
|
|
495
479
|
|
|
480
|
+
// The running listener and the TLS material it serves, kept at module level so the certificate
|
|
481
|
+
// reload command can reach both without restarting the worker.
|
|
482
|
+
let proxyServer = null;
|
|
483
|
+
let tlsContext = null;
|
|
484
|
+
|
|
496
485
|
module.exports.run = async () => {
|
|
497
486
|
const serverOptions = {
|
|
498
487
|
useProxy: await settings.get('imapProxyServerProxy'),
|
|
@@ -507,59 +496,37 @@ module.exports.run = async () => {
|
|
|
507
496
|
const port = await settings.get('imapProxyServerPort');
|
|
508
497
|
const host = await settings.get('imapProxyServerHost');
|
|
509
498
|
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
namespace: `${REDIS_PREFIX}`,
|
|
513
|
-
|
|
514
|
-
environment: 'ee',
|
|
515
|
-
|
|
516
|
-
logger: logger.child({ sub: 'acme' }),
|
|
517
|
-
|
|
518
|
-
encryptFn: async value => {
|
|
519
|
-
const encryptSecret = await getSecret();
|
|
520
|
-
return encrypt(value, encryptSecret);
|
|
521
|
-
},
|
|
522
|
-
|
|
523
|
-
decryptFn: async value => {
|
|
524
|
-
const encryptSecret = await getSecret();
|
|
525
|
-
return decrypt(value, encryptSecret);
|
|
526
|
-
}
|
|
527
|
-
});
|
|
499
|
+
// Reads what the API worker provisioned; this one never orders a certificate itself.
|
|
500
|
+
let certs = createCertHandler(logger);
|
|
528
501
|
|
|
529
502
|
let tls = await settings.get('imapProxyServerTLSEnabled');
|
|
530
503
|
|
|
531
504
|
if (tls) {
|
|
532
505
|
serverOptions.secure = true;
|
|
533
506
|
|
|
534
|
-
//
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
507
|
+
// Environment and config-file material first, then whatever EmailEngine manages itself.
|
|
508
|
+
// The order used to be the other way round here, so an operator-supplied certificate was
|
|
509
|
+
// overwritten by an automatic one; lib/tls/context.js owns the precedence now.
|
|
538
510
|
loadTlsConfig(serverOptions, 'EENGINE_IMAPPROXY_TLS_');
|
|
539
511
|
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
.concat(certificateData.ca || [])
|
|
548
|
-
.flatMap(entry => entry)
|
|
549
|
-
.join('\n');
|
|
550
|
-
serverOptions.key = certificateData.privateKey;
|
|
551
|
-
}
|
|
552
|
-
}
|
|
512
|
+
// The material loaded above is snapshotted inside, at entry, so a later refresh does not
|
|
513
|
+
// read what this resolution wrote back into serverOptions as if the operator had supplied
|
|
514
|
+
// it.
|
|
515
|
+
tlsContext = await createTlsContext({ certs, logger, listenerOptions: serverOptions });
|
|
516
|
+
Object.assign(serverOptions, tlsContext.options);
|
|
517
|
+
|
|
518
|
+
assertTlsCredentials(serverOptions, 'The IMAP proxy');
|
|
553
519
|
}
|
|
554
520
|
|
|
555
521
|
const server = createServer(serverOptions);
|
|
522
|
+
proxyServer = server;
|
|
556
523
|
|
|
557
524
|
try {
|
|
558
525
|
await new Promise((resolve, reject) => {
|
|
559
526
|
server.once('error', err => reject(err));
|
|
560
527
|
server.listen(port || config.imap.port, host || config.imap.host, () => resolve(server));
|
|
561
528
|
});
|
|
562
|
-
await emitChangeEvent(logger, null, 'imapProxyServerState', 'listening');
|
|
529
|
+
await emitChangeEvent(logger, null, 'imapProxyServerState', 'listening', { tls: tlsContext ? tlsContext.active : null });
|
|
563
530
|
} catch (err) {
|
|
564
531
|
await emitChangeEvent(logger, null, 'imapProxyServerState', 'failed', {
|
|
565
532
|
error: { message: err.message, code: err.code || null }
|
|
@@ -569,3 +536,26 @@ module.exports.run = async () => {
|
|
|
569
536
|
|
|
570
537
|
return server;
|
|
571
538
|
};
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Re-resolves the TLS material and hands it to the running proxy.
|
|
542
|
+
*
|
|
543
|
+
* Sessions already established keep the context they negotiated with. An IMAP client can hold a
|
|
544
|
+
* connection open for days, so restarting the worker to install a renewed certificate is the
|
|
545
|
+
* expensive way to do this.
|
|
546
|
+
*
|
|
547
|
+
* @returns {Promise<Object>} What the listener is serving after the reload
|
|
548
|
+
*/
|
|
549
|
+
module.exports.reloadCertificates = async () => {
|
|
550
|
+
const result = await applyTlsContext({
|
|
551
|
+
context: proxyServer ? tlsContext : null,
|
|
552
|
+
apply: options => proxyServer.updateSecureContext(options),
|
|
553
|
+
logger
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
if (result.updated) {
|
|
557
|
+
await emitChangeEvent(logger, null, 'imapProxyServerState', 'listening', { tls: result.tls });
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
return result;
|
|
561
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
--[[
|
|
2
|
+
Script: h-del-if-equals.lua
|
|
3
|
+
Purpose: Drops a set of hash fields only when a guard field still holds the value the caller read,
|
|
4
|
+
so a record that was replaced between the read and the delete is left for whoever wrote it.
|
|
5
|
+
|
|
6
|
+
The error state of an account is read, judged and then dropped. Everything in between is
|
|
7
|
+
an await, and another failure written in that window would be deleted by a decision taken
|
|
8
|
+
before it existed - leaving the account reporting a healthy state it is not in.
|
|
9
|
+
|
|
10
|
+
KEYS:
|
|
11
|
+
[1] hashKey - The hash key to operate on
|
|
12
|
+
|
|
13
|
+
ARGV:
|
|
14
|
+
[1] guardKey - The hash field whose value the decision was taken on
|
|
15
|
+
[2] expected - The value the caller read; an empty string means "expect the field to be absent"
|
|
16
|
+
[3..] fields - The fields to delete
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
1 if the guard matched and the fields were dropped
|
|
20
|
+
0 if the guard holds something else, meaning the record is no longer the one that was judged
|
|
21
|
+
--]]
|
|
22
|
+
|
|
23
|
+
local hashKey = KEYS[1];
|
|
24
|
+
local guardKey = ARGV[1];
|
|
25
|
+
local expected = ARGV[2];
|
|
26
|
+
|
|
27
|
+
-- HGET answers a missing field with false, which is the same test as any other mismatch once it
|
|
28
|
+
-- is read as the empty string
|
|
29
|
+
local current = redis.call("HGET", hashKey, guardKey) or "";
|
|
30
|
+
|
|
31
|
+
if current ~= expected then
|
|
32
|
+
return 0;
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
if #ARGV > 2 then
|
|
36
|
+
redis.call("HDEL", hashKey, unpack(ARGV, 3));
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
return 1;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
--[[
|
|
2
|
+
Script: h-set-if-equals.lua
|
|
3
|
+
Purpose: Replaces a hash field only when it still holds the value the caller last read, so two
|
|
4
|
+
processes that both decided to replace the same record converge on one winner instead of
|
|
5
|
+
overwriting each other.
|
|
6
|
+
|
|
7
|
+
HSETNX converges only when the field is absent. Deleting first and then HSETNX looks
|
|
8
|
+
equivalent but is not: between the delete and the set, a second process sees an empty field
|
|
9
|
+
and wins the HSETNX too, and both walk away believing they own the record.
|
|
10
|
+
|
|
11
|
+
KEYS:
|
|
12
|
+
[1] hashKey - The hash key to operate on
|
|
13
|
+
|
|
14
|
+
ARGV:
|
|
15
|
+
[1] entryKey - The hash field name
|
|
16
|
+
[2] value - The value to set
|
|
17
|
+
[3] expected - The value the caller read; an empty string means "expect the field to be absent"
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
1 if the field matched and was replaced (or was absent as expected and created)
|
|
21
|
+
0 if the field holds something else, meaning another process got there first
|
|
22
|
+
--]]
|
|
23
|
+
|
|
24
|
+
local hashKey = KEYS[1];
|
|
25
|
+
local entryKey = ARGV[1];
|
|
26
|
+
|
|
27
|
+
local value = ARGV[2];
|
|
28
|
+
local expected = ARGV[3];
|
|
29
|
+
|
|
30
|
+
-- HGET answers a missing field with false, which is the same test as any other mismatch once it
|
|
31
|
+
-- is read as the empty string
|
|
32
|
+
local current = redis.call("HGET", hashKey, entryKey) or "";
|
|
33
|
+
|
|
34
|
+
if current ~= expected then
|
|
35
|
+
return 0;
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
redis.call("HSET", hashKey, entryKey, value);
|
|
39
|
+
return 1;
|
package/lib/openapi/index.js
CHANGED
|
@@ -80,6 +80,9 @@ function registerOpenApiRoute(server, options) {
|
|
|
80
80
|
options: {
|
|
81
81
|
auth: false,
|
|
82
82
|
cors: options.cors,
|
|
83
|
+
// A machine-facing document: JSON errors, no CSRF check, the API response headers.
|
|
84
|
+
// Not `api`, which would list this route in the document it serves
|
|
85
|
+
tags: ['external'],
|
|
83
86
|
|
|
84
87
|
handler(request, h) {
|
|
85
88
|
// Shallow copy: `servers` already exists in the built document, so replacing it here
|
package/lib/outbox.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
const { submitQueue, redis } = require('./db');
|
|
4
4
|
const { REDIS_PREFIX } = require('../lib/consts');
|
|
5
|
+
const msgpack = require('./msgpack');
|
|
5
6
|
|
|
6
7
|
// Job reads and removals are issued in bounded batches. ioredis writes each command as it is
|
|
7
8
|
// issued, so a batch costs one round trip rather than one per job, while the bound keeps an account
|
|
@@ -18,6 +19,32 @@ function outboxKey(account) {
|
|
|
18
19
|
return `${REDIS_PREFIX}iaq:${account}`;
|
|
19
20
|
}
|
|
20
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Decodes a message stored in an account's outbox hash.
|
|
24
|
+
*
|
|
25
|
+
* The stored value is always a msgpack map. lib/msgpack decodes the first value of a buffer and
|
|
26
|
+
* ignores whatever follows, so a foreign or truncated value does not necessarily throw: a buffer
|
|
27
|
+
* that happens to start with a byte that is a valid scalar comes back as that scalar. Anything
|
|
28
|
+
* other than a map is unusable as a queued message and must be treated like an undecodable one -
|
|
29
|
+
* the submit worker stamps its job metadata onto the entry, and doing that to a scalar throws a
|
|
30
|
+
* TypeError that would otherwise be reported and retried as a delivery failure.
|
|
31
|
+
*
|
|
32
|
+
* @param {Buffer} entryBuf - Raw hash field value
|
|
33
|
+
* @returns {Object} Decoded queue entry
|
|
34
|
+
* @throws {Error} If the value is not a msgpack map
|
|
35
|
+
*/
|
|
36
|
+
function decodeQueueEntry(entryBuf) {
|
|
37
|
+
let queueEntry = msgpack.decode(entryBuf);
|
|
38
|
+
|
|
39
|
+
// Every other msgpack type decodes to something a queued message can never be: nil, a scalar,
|
|
40
|
+
// a Buffer (bin), an array, or a Date (timestamp extension)
|
|
41
|
+
if (!queueEntry || typeof queueEntry !== 'object' || Array.isArray(queueEntry) || Buffer.isBuffer(queueEntry) || queueEntry instanceof Date) {
|
|
42
|
+
throw new Error('Unexpected outbox entry format');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return queueEntry;
|
|
46
|
+
}
|
|
47
|
+
|
|
21
48
|
function formatQueueEntry(job) {
|
|
22
49
|
let scheduled = job.timestamp + (Number(job.opts.delay) || 0);
|
|
23
50
|
|
|
@@ -265,8 +292,6 @@ async function removeJobs(queueIds, options) {
|
|
|
265
292
|
return removed;
|
|
266
293
|
}
|
|
267
294
|
|
|
268
|
-
// selectPageRanges is exported for its own tests: it is the pagination arithmetic, and exercising it
|
|
269
|
-
// through list() alone would need a queue populated across all four states to cover the cases.
|
|
270
295
|
// selectPageRanges and JOB_STATES are exported for the pagination tests: exercising the arithmetic
|
|
271
296
|
// through list() alone would need a queue populated across all four states to cover the cases.
|
|
272
|
-
module.exports = { list, del, get, removeJobs, selectPageRanges, JOB_STATES };
|
|
297
|
+
module.exports = { list, del, get, removeJobs, decodeQueueEntry, selectPageRanges, JOB_STATES };
|
package/lib/rate-limit.js
CHANGED
|
@@ -41,14 +41,33 @@ const checkRateLimit = async (key, count, allowed, windowSize) => {
|
|
|
41
41
|
throw resErr || expireErr;
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
// Inclusive: the request that was just counted is admitted up to and including the limit
|
|
45
|
+
return windowResult({ key, count: resVal, success: resVal <= allowed, allowed, now, windowEnds });
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// Reads a window's counter without adding to it. For guards that count failures only: the check
|
|
49
|
+
// ahead of an authentication attempt must not spend the budget of the client making it, so it
|
|
50
|
+
// only looks, and only a refusal is recorded (through checkRateLimit) afterwards.
|
|
51
|
+
const peekRateLimit = async (key, allowed, windowSize) => {
|
|
52
|
+
let now = Date.now();
|
|
53
|
+
let { windowKey, windowEnds } = rateLimitWindowKey(key, windowSize, now);
|
|
54
|
+
|
|
55
|
+
let count = Number(await redis.get(windowKey)) || 0;
|
|
56
|
+
|
|
57
|
+
// Exclusive: nothing was counted, so the question is whether one more attempt still fits
|
|
58
|
+
return windowResult({ key, count, success: count < allowed, allowed, now, windowEnds });
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// One result shape for both reads, so a field added to one cannot silently miss the other
|
|
62
|
+
function windowResult({ key, count, success, allowed, now, windowEnds }) {
|
|
44
63
|
return {
|
|
45
64
|
key,
|
|
46
|
-
success
|
|
47
|
-
count
|
|
65
|
+
success,
|
|
66
|
+
count,
|
|
48
67
|
allowed,
|
|
49
68
|
ttl: (windowEnds - now) / 1000,
|
|
50
69
|
ttlReset: new Date(windowEnds).toISOString()
|
|
51
70
|
};
|
|
52
|
-
}
|
|
71
|
+
}
|
|
53
72
|
|
|
54
|
-
module.exports = { checkRateLimit, rateLimitWindowKey };
|
|
73
|
+
module.exports = { checkRateLimit, peekRateLimit, rateLimitWindowKey };
|