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
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { Certs } = require('@postalsys/certs');
|
|
4
|
+
|
|
5
|
+
const { redis } = require('./db');
|
|
6
|
+
const getSecret = require('./get-secret');
|
|
7
|
+
const { encrypt, decrypt } = require('./encrypt');
|
|
8
|
+
const { httpAgent } = require('./tools');
|
|
9
|
+
const { REDIS_PREFIX, ACME_ENVIRONMENT, ACME_DIRECTORY_URL, ACME_OVERRIDE_PARTIAL } = require('./consts');
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Builds the Let's Encrypt certificate handler.
|
|
13
|
+
*
|
|
14
|
+
* Three workers need one: the API worker, which is the only one that provisions, and the SMTP
|
|
15
|
+
* server and the IMAP proxy, which read what it stored. Every argument is the same in all three, so
|
|
16
|
+
* this exists rather than the same twenty lines written out three times. That is not only about
|
|
17
|
+
* repetition: `environment` and `directoryUrl` belong inside the `acme` block, and two of the three
|
|
18
|
+
* copies used to pass `environment` at the top level, where the constructor never reads it. Nothing
|
|
19
|
+
* failed, because those two never provision, and nothing would have until one of them did.
|
|
20
|
+
*
|
|
21
|
+
* @param {Object} logger worker logger; the handler logs under `sub: 'acme'`
|
|
22
|
+
* @returns {Object} a `Certs` instance
|
|
23
|
+
*/
|
|
24
|
+
function createCertHandler(logger) {
|
|
25
|
+
if (ACME_OVERRIDE_PARTIAL) {
|
|
26
|
+
// Nothing here can tell which of the two was meant - an operator rehearsing against staging
|
|
27
|
+
// and one running a private CA under the default account name are the same instruction from
|
|
28
|
+
// here - so it is reported rather than repaired
|
|
29
|
+
logger.warn({
|
|
30
|
+
msg: 'Only one half of the ACME override is set, certificate orders will most likely be rejected',
|
|
31
|
+
environment: ACME_ENVIRONMENT,
|
|
32
|
+
directoryUrl: ACME_DIRECTORY_URL
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return new Certs({
|
|
37
|
+
redis,
|
|
38
|
+
namespace: `${REDIS_PREFIX}`,
|
|
39
|
+
|
|
40
|
+
acme: {
|
|
41
|
+
environment: ACME_ENVIRONMENT,
|
|
42
|
+
directoryUrl: ACME_DIRECTORY_URL
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
// long-lived client, see LiveDispatcher in lib/tools.js
|
|
46
|
+
dispatcher: httpAgent.live,
|
|
47
|
+
|
|
48
|
+
logger: logger.child({ sub: 'acme' }),
|
|
49
|
+
|
|
50
|
+
encryptFn: async value => {
|
|
51
|
+
const encryptSecret = await getSecret();
|
|
52
|
+
return encrypt(value, encryptSecret);
|
|
53
|
+
},
|
|
54
|
+
|
|
55
|
+
decryptFn: async value => {
|
|
56
|
+
const encryptSecret = await getSecret();
|
|
57
|
+
return decrypt(value, encryptSecret);
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
module.exports = { createCertHandler };
|
package/lib/consts.js
CHANGED
|
@@ -145,6 +145,13 @@ module.exports = {
|
|
|
145
145
|
// carry is the separate, read-only `_authFailureDisabledAt`.
|
|
146
146
|
AUTH_FAILURE_DISABLED_FIELD: '_authFailureDisabled',
|
|
147
147
|
|
|
148
|
+
// Account hash field recording which event wrote the current `lastErrorState`. Both
|
|
149
|
+
// `authenticationError` and `connectError` store their payload there, so without this the
|
|
150
|
+
// recovery path cannot tell them apart. Written next to `lastErrorState` and cleared with it;
|
|
151
|
+
// same leading-underscore convention as AUTH_FAILURE_DISABLED_FIELD, so unserializeAccountData()
|
|
152
|
+
// does not surface it.
|
|
153
|
+
LAST_ERROR_EVENT_FIELD: '_lastErrorEvent',
|
|
154
|
+
|
|
148
155
|
// The `lastErrorState.description` the safety net stores when it parks an account, and the log
|
|
149
156
|
// line it writes at the same moment. User-visible copy: reword it freely, nothing matches on it.
|
|
150
157
|
AUTH_FAILURE_DISABLED_DESCRIPTION: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
|
|
@@ -160,16 +167,53 @@ module.exports = {
|
|
|
160
167
|
|
|
161
168
|
REDIS_BATCH_DELETE_SIZE: 1000,
|
|
162
169
|
|
|
163
|
-
// When renewal becomes due is
|
|
164
|
-
//
|
|
165
|
-
//
|
|
166
|
-
// for exactly one lifetime
|
|
170
|
+
// When renewal becomes due is decided by @postalsys/certs, so there is no constant for it here.
|
|
171
|
+
// It asks Let's Encrypt through ACME Renewal Information where it can, and otherwise renews two
|
|
172
|
+
// thirds of the way through whatever lifetime the certificate was issued with. A fixed "renew
|
|
173
|
+
// when N days remain" threshold is correct for exactly one lifetime, and Let's Encrypt is
|
|
174
|
+
// shortening them from 90 days to 64 and then 45. https://letsencrypt.org/2025/12/02/from-90-to-45
|
|
175
|
+
|
|
176
|
+
// The ACME account and directory that lib/cert-handler.js hands to every worker.
|
|
177
|
+
//
|
|
178
|
+
// These two only make sense as a pair. The environment names the stored ACME account record and
|
|
179
|
+
// the directory names the CA that issued it, so pointing one at Let's Encrypt staging without
|
|
180
|
+
// moving the other presents an account key the staging CA has never seen, and every request is
|
|
181
|
+
// rejected. Override both or neither. Staging is https://acme-staging-v02.api.letsencrypt.org/directory,
|
|
182
|
+
// which is what to test issuance against: same asynchronous finalization as production, no rate
|
|
183
|
+
// limits worth worrying about, and certificates signed by an untrusted root - which is also why
|
|
184
|
+
// the default here has to stay production. A build that shipped staging by default would hand
|
|
185
|
+
// every IMAP, SMTP and HTTPS client a certificate it refuses.
|
|
186
|
+
ACME_ENVIRONMENT: (process.env.EENGINE_ACME_ENVIRONMENT || '').toString().trim() || 'emailengine',
|
|
187
|
+
ACME_DIRECTORY_URL: (process.env.EENGINE_ACME_DIRECTORY_URL || '').toString().trim() || 'https://acme-v02.api.letsencrypt.org/directory',
|
|
188
|
+
|
|
189
|
+
// Exactly one of the two was overridden, which is the combination the paragraph above says
|
|
190
|
+
// cannot work. Derived here, from the same reads the values themselves come from, so it can
|
|
191
|
+
// never disagree with them; lib/cert-handler.js is what reports it, since nothing in the CA's
|
|
192
|
+
// rejection says why every order failed.
|
|
193
|
+
ACME_OVERRIDE_PARTIAL:
|
|
194
|
+
!!(process.env.EENGINE_ACME_ENVIRONMENT || '').toString().trim() !== !!(process.env.EENGINE_ACME_DIRECTORY_URL || '').toString().trim(),
|
|
167
195
|
|
|
168
196
|
// do not attempt certificate renewal more often than once in 8 hours
|
|
169
197
|
BLOCK_TLS_RENEW: 8 * 3600 * 1000,
|
|
170
198
|
|
|
171
|
-
//
|
|
172
|
-
|
|
199
|
+
// How often the reconciler looks at the configured hostnames. Most passes do nothing: a valid
|
|
200
|
+
// certificate that was checked within BLOCK_TLS_RENEW is skipped without a call to anyone. The
|
|
201
|
+
// interval is what bounds how long a first certificate, or one whose record was lost, waits for
|
|
202
|
+
// its automatic attempt, which is why it is minutes rather than the hour renewal alone needs.
|
|
203
|
+
TLS_RENEW_CHECK_INTERVAL: 10 * 60 * 1000,
|
|
204
|
+
|
|
205
|
+
// How long a hostname whose last order failed is left alone by the reconciler. The certificate
|
|
206
|
+
// library arms its own failsafe lock on top of this (an hour after the CA answered, a minute
|
|
207
|
+
// after a transport error); this is the outer bound that also covers a name with no record at
|
|
208
|
+
// all, where the library has nothing to lock on.
|
|
209
|
+
TLS_RETRY_AFTER_FAILURE: 15 * 60 * 1000,
|
|
210
|
+
|
|
211
|
+
// Lifetime of a preflight probe token, in seconds. Long enough for a redirect chain and a slow
|
|
212
|
+
// reverse proxy, short enough that a token is not left answering for the rest of the day.
|
|
213
|
+
TLS_PREFLIGHT_TTL: 120,
|
|
214
|
+
|
|
215
|
+
// How long the preflight waits for the challenge path to answer
|
|
216
|
+
TLS_PREFLIGHT_TIMEOUT: 20 * 1000,
|
|
173
217
|
|
|
174
218
|
// default download chunk size 1MB
|
|
175
219
|
DEFAULT_DOWNLOAD_CHUNK_SIZE: 1000000,
|
|
@@ -244,6 +288,10 @@ module.exports = {
|
|
|
244
288
|
|
|
245
289
|
NONCE_BYTES: 16,
|
|
246
290
|
|
|
291
|
+
// Where the bull-board queue browser is mounted (lib/api-routes/bull-board-routes.js); the
|
|
292
|
+
// security headers key their bull-board profile on it
|
|
293
|
+
BULL_BOARD_BASE_PATH: '/admin/bull-board',
|
|
294
|
+
|
|
247
295
|
// Longest account id EmailEngine accepts. Defined here rather than only on `accountIdSchema`
|
|
248
296
|
// because the token audit log truncates to it while writing, before route validation has had a
|
|
249
297
|
// chance to reject a longer one, and the two have to agree: a log that trimmed at a different
|
|
@@ -344,7 +392,10 @@ module.exports = {
|
|
|
344
392
|
'req.query.access_token',
|
|
345
393
|
'err.rawPacket',
|
|
346
394
|
'err._original',
|
|
347
|
-
'err.details[*].context.value'
|
|
395
|
+
'err.details[*].context.value',
|
|
396
|
+
// the WHATWG URL parser attaches the string it rejected, and a stored proxy or webhook URL
|
|
397
|
+
// carries its credentials inline
|
|
398
|
+
'err.input'
|
|
348
399
|
],
|
|
349
400
|
|
|
350
401
|
generateWebhookTable() {
|
package/lib/db.js
CHANGED
|
@@ -133,6 +133,8 @@ const hSetBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-bigg
|
|
|
133
133
|
const hUpdateBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-update-bigger.lua'), 'utf-8');
|
|
134
134
|
const hSetExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-exists.lua'), 'utf-8');
|
|
135
135
|
const hSetNewScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-new.lua'), 'utf-8');
|
|
136
|
+
const hSetIfEqualsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-if-equals.lua'), 'utf-8');
|
|
137
|
+
const hDelIfEqualsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-del-if-equals.lua'), 'utf-8');
|
|
136
138
|
const hSetNewMarkScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-new-mark.lua'), 'utf-8');
|
|
137
139
|
const hIncrbyExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-incrby-exists.lua'), 'utf-8');
|
|
138
140
|
const eeListAddScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-add.lua'), 'utf-8');
|
|
@@ -199,6 +201,16 @@ redis.defineCommand('hSetNew', {
|
|
|
199
201
|
lua: hSetNewScript
|
|
200
202
|
});
|
|
201
203
|
|
|
204
|
+
redis.defineCommand('hSetIfEquals', {
|
|
205
|
+
numberOfKeys: 1,
|
|
206
|
+
lua: hSetIfEqualsScript
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
redis.defineCommand('hDelIfEquals', {
|
|
210
|
+
numberOfKeys: 1,
|
|
211
|
+
lua: hDelIfEqualsScript
|
|
212
|
+
});
|
|
213
|
+
|
|
202
214
|
redis.defineCommand('hSetNewMark', {
|
|
203
215
|
numberOfKeys: 1,
|
|
204
216
|
lua: hSetNewMarkScript
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// fetch() with every redirect hop vetted by an egress policy.
|
|
4
|
+
//
|
|
5
|
+
// undici follows redirects on its own and offers no hook to look at the intermediate hops, so a
|
|
6
|
+
// permitted destination can hand a request on to one the policy refuses: a domain whose
|
|
7
|
+
// autoconfig answers 302 to http://169.254.169.254/ gets the metadata service fetched on its
|
|
8
|
+
// behalf. Webhook deliveries solve this by not following at all (lib/webhook-request.js), because
|
|
9
|
+
// there is an operator to publish the final URL. Autodiscovery has neither: the destination is
|
|
10
|
+
// derived from whatever email address a caller typed, and a domain's autoconfig commonly lives
|
|
11
|
+
// behind a redirect or two. So here redirects are followed by hand, and each hop goes through the
|
|
12
|
+
// same check the first request did.
|
|
13
|
+
//
|
|
14
|
+
// No dependency on lib/tools.js on purpose: that module opens Redis on require, and this one has
|
|
15
|
+
// to stay testable as a pure helper.
|
|
16
|
+
|
|
17
|
+
// A domain's autoconfig commonly sits behind one or two hops (http to https, apex to www); five
|
|
18
|
+
// is generous for that and small enough that a redirect loop costs nothing worth mentioning
|
|
19
|
+
const MAX_REDIRECTS = 5;
|
|
20
|
+
|
|
21
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
22
|
+
|
|
23
|
+
// The only schemes a redirect may lead to. A Location of `file:` or `ftp:` is not a web hop, and
|
|
24
|
+
// undici would refuse it anyway - refusing it here names the reason
|
|
25
|
+
const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);
|
|
26
|
+
|
|
27
|
+
// Headers that describe a request body. Dropped when a redirect turns the request into a GET,
|
|
28
|
+
// which is what fetch() does too (a Content-Length for a body that is no longer sent breaks the
|
|
29
|
+
// request outright)
|
|
30
|
+
const BODY_HEADERS = new Set(['content-type', 'content-length', 'content-encoding', 'content-language', 'content-location']);
|
|
31
|
+
|
|
32
|
+
// Headers that authenticate a request to one specific origin, and so cannot travel to another one.
|
|
33
|
+
// A credential is issued against the host that asked for it; a redirect naming a different host is
|
|
34
|
+
// not a reason to hand it over. fetch() drops these on a cross-origin hop and so does this.
|
|
35
|
+
const CREDENTIAL_HEADERS = new Set(['authorization', 'cookie', 'proxy-authorization']);
|
|
36
|
+
|
|
37
|
+
function redirectError(message, code) {
|
|
38
|
+
let err = new Error(message);
|
|
39
|
+
err.code = code;
|
|
40
|
+
return err;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Resolves the Location header of a redirect against the URL that answered it.
|
|
45
|
+
*
|
|
46
|
+
* @param {string} location - Raw Location header
|
|
47
|
+
* @param {string} base - URL of the response carrying it
|
|
48
|
+
* @returns {URL} Absolute URL of the next hop. Returned parsed, so the caller can compare origins
|
|
49
|
+
* without building it a second time
|
|
50
|
+
* @throws {Error} EREDIRECTINVALID for an unparseable target, EREDIRECTSCHEME for a non-web one
|
|
51
|
+
*/
|
|
52
|
+
function resolveRedirect(location, base) {
|
|
53
|
+
let next;
|
|
54
|
+
try {
|
|
55
|
+
next = new URL(location, base);
|
|
56
|
+
} catch (err) {
|
|
57
|
+
throw redirectError(`Redirect from ${base} points at an invalid URL`, 'EREDIRECTINVALID');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (!ALLOWED_PROTOCOLS.has(next.protocol)) {
|
|
61
|
+
throw redirectError(`Redirect from ${base} points at an unsupported scheme (${next.protocol})`, 'EREDIRECTSCHEME');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return next;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Drops a set of headers from a plain header object (the only shape the callers pass).
|
|
69
|
+
*
|
|
70
|
+
* @param {Object} [headers] - Header name to value
|
|
71
|
+
* @param {Set} names - Lowercased header names to remove
|
|
72
|
+
* @returns {Object|undefined} Filtered copy
|
|
73
|
+
*/
|
|
74
|
+
function withoutHeaders(headers, names) {
|
|
75
|
+
return headers && Object.fromEntries(Object.entries(headers).filter(([name]) => !names.has(name.toLowerCase())));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Performs a fetch, following redirects one vetted hop at a time.
|
|
80
|
+
*
|
|
81
|
+
* `validateTarget(url)` runs before the first request and before every hop; whatever it throws
|
|
82
|
+
* ends the fetch. Redirect semantics match fetch(): 303 always becomes a bodyless GET, 301 and 302
|
|
83
|
+
* do so for anything but GET and HEAD, 307 and 308 replay the request unchanged, and a hop to
|
|
84
|
+
* another origin drops the credential headers. A 3xx without a Location is returned as it is,
|
|
85
|
+
* since it is not a redirect anyone can follow.
|
|
86
|
+
*
|
|
87
|
+
* @param {Function} fetchImpl - fetch implementation (undici fetch)
|
|
88
|
+
* @param {string} url - Destination URL
|
|
89
|
+
* @param {Object} [options] - fetch options (method, body, headers, dispatcher, signal) plus
|
|
90
|
+
* `validateTarget` (async url => void)
|
|
91
|
+
* @returns {Promise<Response>} The final response, with its body unread
|
|
92
|
+
* @throws {Error} EMAXREDIRECTS when the hop budget is spent, EREDIRECTINVALID / EREDIRECTSCHEME
|
|
93
|
+
* for a redirect that cannot be taken, or whatever validateTarget throws for a refused hop
|
|
94
|
+
*/
|
|
95
|
+
async function fetchWithVettedRedirects(fetchImpl, url, options) {
|
|
96
|
+
let { validateTarget, ...fetchOptions } = options || {};
|
|
97
|
+
|
|
98
|
+
let method = (fetchOptions.method || 'GET').toUpperCase();
|
|
99
|
+
let body = fetchOptions.body;
|
|
100
|
+
let headers = fetchOptions.headers;
|
|
101
|
+
let current = url;
|
|
102
|
+
|
|
103
|
+
for (let hop = 0; ; hop++) {
|
|
104
|
+
if (validateTarget) {
|
|
105
|
+
await validateTarget(current);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// redirect:'manual' makes undici return the 3xx itself, headers included, rather than
|
|
109
|
+
// the opaque response the browser spec prescribes
|
|
110
|
+
const res = await fetchImpl(current, Object.assign({}, fetchOptions, { method, body, headers, redirect: 'manual' }));
|
|
111
|
+
|
|
112
|
+
if (!REDIRECT_STATUSES.has(res.status)) {
|
|
113
|
+
return res;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const location = res.headers.get('location');
|
|
117
|
+
if (!location) {
|
|
118
|
+
return res;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// The hop is not taken, so its body is never read by the caller. Drain it here so the
|
|
122
|
+
// keep-alive socket goes back to the pool instead of staying pinned
|
|
123
|
+
await res.text().catch(() => false);
|
|
124
|
+
|
|
125
|
+
if (hop >= MAX_REDIRECTS) {
|
|
126
|
+
throw redirectError(`Too many redirects, gave up at ${current}`, 'EMAXREDIRECTS');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const next = resolveRedirect(location, current);
|
|
130
|
+
|
|
131
|
+
if (res.status === 303 || ((res.status === 301 || res.status === 302) && method !== 'GET' && method !== 'HEAD')) {
|
|
132
|
+
method = 'GET';
|
|
133
|
+
body = undefined;
|
|
134
|
+
headers = withoutHeaders(headers, BODY_HEADERS);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (next.origin !== new URL(current).origin) {
|
|
138
|
+
headers = withoutHeaders(headers, CREDENTIAL_HEADERS);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
current = next.toString();
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
module.exports = { fetchWithVettedRedirects, MAX_REDIRECTS };
|