@fedify/relay 2.1.30 → 2.1.32

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.
@@ -1,34 +1,822 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { createRequire } from "node:module";
4
+ import { n as __require, r as __toESM, t as __commonJSMin } from "./chunk-D_gRT_KG.js";
5
5
  import { getLogger } from "@logtape/logtape";
6
- import process$1 from "node:process";
7
6
  import dns from "node:dns/promises";
8
7
  import { isIP } from "node:net";
9
- //#region \0rolldown/runtime.js
10
- var __create = Object.create;
11
- var __defProp = Object.defineProperty;
12
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
- var __getOwnPropNames = Object.getOwnPropertyNames;
14
- var __getProtoOf = Object.getPrototypeOf;
15
- var __hasOwnProp = Object.prototype.hasOwnProperty;
16
- var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
17
- var __copyProps = (to, from, except, desc) => {
18
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
19
- key = keys[i];
20
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
21
- get: ((k) => from[k]).bind(null, key),
22
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
8
+ import process$1 from "node:process";
9
+ //#region ../vocab-runtime/dist/crypto-key-BR2FO0pB.js
10
+ const grants = /* @__PURE__ */ new WeakMap();
11
+ /**
12
+ * Issues a grant for the given URL's origin and addresses. This does not
13
+ * validate the addresses; callers validate them before issuing, and pinners
14
+ * validate them again right before connecting.
15
+ * @param url The URL whose origin the grant is bound to.
16
+ * @param addresses The addresses to connect to.
17
+ * @returns A new grant.
18
+ */
19
+ function issuePinGrant(url, addresses) {
20
+ const grant = Object.freeze(Object.create(null));
21
+ let hostname = url.hostname;
22
+ if (hostname.startsWith("[") && hostname.endsWith("]")) hostname = hostname.slice(1, -1);
23
+ const record = Object.freeze({
24
+ origin: url.origin,
25
+ hostname,
26
+ addresses: Object.freeze(addresses.map(({ address, family }) => Object.freeze({
27
+ address,
28
+ family
29
+ })))
30
+ });
31
+ grants.set(grant, {
32
+ record,
33
+ revoked: false
34
+ });
35
+ return grant;
36
+ }
37
+ /**
38
+ * Checks that the given grant was issued by {@link issuePinGrant}, has not
39
+ * been revoked, and was issued for the origin of the given URL.
40
+ * @param grant The grant to redeem.
41
+ * @param url The URL to connect to.
42
+ * @returns What the grant stands for.
43
+ * @throws {TypeError} If the grant cannot be used for the URL.
44
+ */
45
+ function redeemPinGrant(grant, url) {
46
+ const state = typeof grant === "object" && grant !== null ? grants.get(grant) : void 0;
47
+ if (state == null) throw new TypeError("Invalid pin grant.");
48
+ if (state.revoked) throw new TypeError("The pin grant has been revoked.");
49
+ if (url.origin !== state.record.origin) throw new TypeError(`The pin grant for ${state.record.origin} cannot be used for ${url.origin}.`);
50
+ return state.record;
51
+ }
52
+ /**
53
+ * Revokes the given grant so that it can no longer be redeemed.
54
+ * @param grant The grant to revoke.
55
+ */
56
+ function revokePinGrant(grant) {
57
+ const state = grants.get(grant);
58
+ if (state != null) state.revoked = true;
59
+ }
60
+ var UrlError = class extends Error {
61
+ /**
62
+ * The failure category. Defaults to `"disallowed"`.
63
+ * `"dns"` includes lookup errors and results with no usable IP addresses.
64
+ * @since 2.0.29
65
+ */
66
+ reason;
67
+ constructor(message, options) {
68
+ super(message, options);
69
+ this.name = "UrlError";
70
+ this.reason = options?.reason ?? "disallowed";
71
+ }
72
+ };
73
+ /**
74
+ * Resolves all addresses of the given hostname through `node:dns/promises`.
75
+ * The default `dns` object is looked up on every call so that tests can still
76
+ * stub `dns.lookup()`.
77
+ * @internal
78
+ */
79
+ function lookupAllAddresses(hostname) {
80
+ return dns.lookup(hostname, { all: true });
81
+ }
82
+ /**
83
+ * Limits concurrent lookups started by the returned function. A pending
84
+ * caller can abort before its lookup starts. Once `dns.lookup()` has started,
85
+ * it cannot be cancelled, so its slot remains occupied until the underlying
86
+ * lookup settles, even if its caller aborts. This bounds the number of
87
+ * outstanding getaddrinfo calls made by users of this function.
88
+ * @internal
89
+ */
90
+ function createBoundedLookup(lookup, maxConcurrent = 1) {
91
+ if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1) throw new RangeError("maxConcurrent must be a positive integer");
92
+ let active = 0;
93
+ const waiting = /* @__PURE__ */ new Set();
94
+ function release() {
95
+ active--;
96
+ while (waiting.size > 0) {
97
+ const next = waiting.values().next().value;
98
+ waiting.delete(next);
99
+ next.signal?.removeEventListener("abort", next.onAbort);
100
+ if (next.signal?.aborted) {
101
+ next.reject(next.signal.reason);
102
+ continue;
103
+ }
104
+ active++;
105
+ next.resolve();
106
+ break;
107
+ }
108
+ }
109
+ function acquire(signal) {
110
+ signal?.throwIfAborted();
111
+ if (active < maxConcurrent) {
112
+ active++;
113
+ return Promise.resolve();
114
+ }
115
+ return new Promise((resolve, reject) => {
116
+ const entry = {
117
+ signal,
118
+ resolve,
119
+ reject,
120
+ onAbort() {
121
+ if (!waiting.delete(entry)) return;
122
+ signal?.removeEventListener("abort", entry.onAbort);
123
+ reject(signal?.reason);
124
+ }
125
+ };
126
+ waiting.add(entry);
127
+ signal?.addEventListener("abort", entry.onAbort, { once: true });
128
+ if (signal?.aborted) entry.onAbort();
129
+ });
130
+ }
131
+ return async (hostname, signal) => {
132
+ await acquire(signal);
133
+ let started = false;
134
+ try {
135
+ signal?.throwIfAborted();
136
+ const pending = lookup(hostname);
137
+ started = true;
138
+ pending.then(release, release);
139
+ if (signal == null) return await pending;
140
+ let onAbort;
141
+ const aborted = new Promise((_, reject) => {
142
+ onAbort = () => reject(signal.reason);
143
+ signal.addEventListener("abort", onAbort, { once: true });
144
+ if (signal.aborted) onAbort();
145
+ });
146
+ try {
147
+ return await Promise.race([pending, aborted]);
148
+ } finally {
149
+ if (onAbort != null) signal.removeEventListener("abort", onAbort);
150
+ }
151
+ } finally {
152
+ if (!started) release();
153
+ }
154
+ };
155
+ }
156
+ createBoundedLookup(lookupAllAddresses, 2);
157
+ /**
158
+ * Checks the parts of a URL that can be validated without resolving it:
159
+ * the protocol, the `localhost` hostname, and IP literal hostnames.
160
+ * @throws {UrlError} If the URL is not allowed.
161
+ * @internal
162
+ */
163
+ function parsePublicUrl(url) {
164
+ const parsed = new URL(url);
165
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new UrlError(`Unsupported protocol: ${parsed.protocol}`);
166
+ let hostname = parsed.hostname;
167
+ if (hostname.startsWith("[") && hostname.endsWith("]")) hostname = hostname.slice(1, -1);
168
+ if (hostname === "localhost") throw new UrlError("Localhost is not allowed");
169
+ const family = isIP(hostname);
170
+ if (family !== 0) validatePublicIpAddress(hostname, family);
171
+ return {
172
+ url: parsed,
173
+ hostname,
174
+ family
175
+ };
176
+ }
177
+ /**
178
+ * Resolves the given hostname and checks that every returned IP address is
179
+ * public.
180
+ * @returns The IP addresses of the hostname, without non-IP entries.
181
+ * @throws {UrlError} If the lookup fails, returns no IP address, or returns
182
+ * any non-public address.
183
+ * @internal
184
+ */
185
+ async function lookupPublicAddresses(hostname, lookup) {
186
+ let addresses;
187
+ try {
188
+ addresses = await lookup(hostname);
189
+ } catch (error) {
190
+ throw new UrlError("DNS lookup failed", {
191
+ cause: error,
192
+ reason: "dns"
193
+ });
194
+ }
195
+ validateLookupAddresses(addresses);
196
+ return addresses.filter(({ address }) => isIP(address) !== 0).map(({ address }) => ({
197
+ address,
198
+ family: isIP(address)
199
+ }));
200
+ }
201
+ /**
202
+ * Checks that the given IP address is public. This is used right before
203
+ * connecting to an address that passed {@link lookupPublicAddresses}.
204
+ * @throws {UrlError} If the address is not a public IP address.
205
+ * @internal
206
+ */
207
+ function assertPublicAddress(address) {
208
+ const family = isIP(address.address);
209
+ if (family === 0 || family !== address.family) throw new UrlError(`Invalid or private address: ${address.address}`);
210
+ validatePublicIpAddress(address.address, family);
211
+ }
212
+ /**
213
+ * Validates the IP addresses returned by `node:dns.lookup()`.
214
+ *
215
+ * Cloudflare Workers' `node:dns` implementation currently maps every record
216
+ * in a DNS-over-HTTPS `Answer` array—including CNAME records—to a
217
+ * `LookupAddress`, even though Node.js specifies that the `address` field must
218
+ * contain an IPv4 or IPv6 literal. See:
219
+ * https://github.com/cloudflare/workerd/issues/6886
220
+ *
221
+ * Work around that bug by ignoring non-IP entries only when the lookup also
222
+ * returns at least one actual IP address. This remains fail-closed: a result
223
+ * containing no IP addresses is rejected, and every returned IP address is
224
+ * still validated and must be public. This workaround can be revisited once
225
+ * the Workerd issue is fixed in supported Cloudflare Workers runtimes.
226
+ *
227
+ * @internal
228
+ */
229
+ function validateLookupAddresses(addresses) {
230
+ let ipAddressCount = 0;
231
+ for (const { address } of addresses) {
232
+ const family = isIP(address);
233
+ if (family === 0) continue;
234
+ ipAddressCount++;
235
+ validatePublicIpAddress(address, family);
236
+ }
237
+ if (ipAddressCount === 0) throw new UrlError("DNS lookup did not return any IP address", { reason: "dns" });
238
+ }
239
+ function validatePublicIpAddress(address, family) {
240
+ if (family === 4 && isValidPublicIPv4Address(address) || family === 6 && isValidPublicIPv6Address(address)) return;
241
+ throw new UrlError(`Invalid or private address: ${address}`);
242
+ }
243
+ function isValidPublicIPv4Address(address) {
244
+ const parts = parseIPv4Address(address);
245
+ if (parts == null) return false;
246
+ const value = ipv4PartsToNumber(parts);
247
+ return !nonPublicIPv4Prefixes.some(({ base, prefix }) => matchesIPv4Prefix(value, base, prefix));
248
+ }
249
+ function isValidPublicIPv6Address(address) {
250
+ const words = parseIPv6Address(address);
251
+ if (words == null) return false;
252
+ if (nonPublicIPv6Prefixes.some(({ words: prefixWords, prefix }) => matchesIPv6Prefix(words, prefixWords, prefix))) return false;
253
+ for (const { extractIPv4, prefix, words: prefixWords } of ipv6WithIPv4Prefixes) {
254
+ if (!matchesIPv6Prefix(words, prefixWords, prefix)) continue;
255
+ const ipv4Address = extractIPv4(words);
256
+ if (ipv4Address != null && !isValidPublicIPv4Address(ipv4Address)) return false;
257
+ }
258
+ return true;
259
+ }
260
+ function expandIPv6Address(address) {
261
+ address = address.toLowerCase();
262
+ const ipv4Delimiter = address.lastIndexOf(":");
263
+ if (address.includes(".") && ipv4Delimiter >= 0) {
264
+ const ipv4Parts = parseIPv4Address(address.substring(ipv4Delimiter + 1));
265
+ if (ipv4Parts == null) return address;
266
+ const high = (ipv4Parts[0] << 8) + ipv4Parts[1];
267
+ const low = (ipv4Parts[2] << 8) + ipv4Parts[3];
268
+ address = address.substring(0, ipv4Delimiter + 1) + high.toString(16) + ":" + low.toString(16);
269
+ }
270
+ if (address === "::") return "0000:0000:0000:0000:0000:0000:0000:0000";
271
+ if (address.startsWith("::")) address = "0000" + address;
272
+ if (address.endsWith("::")) address = address + "0000";
273
+ address = address.replace("::", ":0000".repeat(8 - (address.match(/:/g) || []).length) + ":");
274
+ return address.split(":").map((part) => part.padStart(4, "0")).join(":");
275
+ }
276
+ const nonPublicIPv4Prefixes = [
277
+ ipv4Prefix("0.0.0.0/8", "RFC 6890"),
278
+ ipv4Prefix("10.0.0.0/8", "RFC 1918"),
279
+ ipv4Prefix("100.64.0.0/10", "RFC 6598"),
280
+ ipv4Prefix("127.0.0.0/8", "RFC 1122"),
281
+ ipv4Prefix("169.254.0.0/16", "RFC 3927"),
282
+ ipv4Prefix("172.16.0.0/12", "RFC 1918"),
283
+ ipv4Prefix("192.0.0.0/24", "RFC 6890"),
284
+ ipv4Prefix("192.0.2.0/24", "RFC 5737"),
285
+ ipv4Prefix("192.88.99.0/24", "RFC 7526"),
286
+ ipv4Prefix("192.168.0.0/16", "RFC 1918"),
287
+ ipv4Prefix("198.18.0.0/15", "RFC 2544"),
288
+ ipv4Prefix("198.51.100.0/24", "RFC 5737"),
289
+ ipv4Prefix("203.0.113.0/24", "RFC 5737"),
290
+ ipv4Prefix("224.0.0.0/4", "RFC 5771"),
291
+ ipv4Prefix("240.0.0.0/4", "RFC 1112")
292
+ ];
293
+ const nonPublicIPv6Prefixes = [
294
+ ipv6Prefix("::/16", "RFC 4291"),
295
+ ipv6Prefix("2001::/32", "RFC 4380"),
296
+ ipv6Prefix("2002::/16", "RFC 3056"),
297
+ ipv6Prefix("64:ff9b:1::/48", "RFC 8215"),
298
+ ipv6Prefix("fc00::/7", "RFC 4193"),
299
+ ipv6Prefix("fe80::/10", "RFC 4291"),
300
+ ipv6Prefix("ff00::/8", "RFC 4291")
301
+ ];
302
+ const ipv6WithIPv4Prefixes = [{
303
+ ...ipv6Prefix("64:ff9b::/96", "RFC 6052"),
304
+ extractIPv4: (words) => ipv4FromWords(words[6], words[7])
305
+ }];
306
+ function ipv4Prefix(cidr, rfc) {
307
+ const [address, prefixText] = cidr.split("/");
308
+ const prefix = parseInt(prefixText, 10);
309
+ const parts = parseIPv4Address(address);
310
+ if (parts == null || !Number.isInteger(prefix) || prefix < 0 || prefix > 32) throw new Error(`Invalid IPv4 prefix: ${cidr}`);
311
+ return {
312
+ cidr,
313
+ base: ipv4PartsToNumber(parts),
314
+ prefix,
315
+ rfc
316
+ };
317
+ }
318
+ function ipv6Prefix(cidr, rfc) {
319
+ const [address, prefixText] = cidr.split("/");
320
+ const prefix = parseInt(prefixText, 10);
321
+ const words = parseIPv6Address(address);
322
+ if (words == null || !Number.isInteger(prefix) || prefix < 0 || prefix > 128) throw new Error(`Invalid IPv6 prefix: ${cidr}`);
323
+ return {
324
+ cidr,
325
+ words,
326
+ prefix,
327
+ rfc
328
+ };
329
+ }
330
+ function parseIPv4Address(address) {
331
+ const parts = address.split(".").map((part) => {
332
+ if (!/^\d+$/.test(part)) return NaN;
333
+ return parseInt(part, 10);
334
+ });
335
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return null;
336
+ return parts;
337
+ }
338
+ function parseIPv6Address(address) {
339
+ const parts = expandIPv6Address(address).split(":");
340
+ if (parts.length !== 8) return null;
341
+ const words = parts.map((part) => {
342
+ if (!/^[0-9a-f]{1,4}$/i.test(part)) return NaN;
343
+ return parseInt(part, 16);
344
+ });
345
+ if (words.some((word) => !Number.isInteger(word) || word < 0 || word > 65535)) return null;
346
+ return words;
347
+ }
348
+ function ipv4PartsToNumber(parts) {
349
+ return parts[0] * 2 ** 24 + parts[1] * 2 ** 16 + parts[2] * 2 ** 8 + parts[3];
350
+ }
351
+ function ipv4FromWords(highWord, lowWord) {
352
+ return [
353
+ highWord >> 8,
354
+ highWord & 255,
355
+ lowWord >> 8,
356
+ lowWord & 255
357
+ ].join(".");
358
+ }
359
+ function matchesIPv4Prefix(address, prefixBase, prefixLength) {
360
+ const blockSize = 2 ** (32 - prefixLength);
361
+ return Math.floor(address / blockSize) === Math.floor(prefixBase / blockSize);
362
+ }
363
+ function matchesIPv6Prefix(address, prefixWords, prefixLength) {
364
+ let remaining = prefixLength;
365
+ for (let i = 0; i < 8 && remaining > 0; i++) if (remaining >= 16) {
366
+ if (address[i] !== prefixWords[i]) return false;
367
+ remaining -= 16;
368
+ } else {
369
+ const mask = 65535 << 16 - remaining & 65535;
370
+ if ((address[i] & mask) !== (prefixWords[i] & mask)) return false;
371
+ remaining = 0;
372
+ }
373
+ return true;
374
+ }
375
+ const logger$1 = getLogger([
376
+ "fedify",
377
+ "runtime",
378
+ "fetch"
379
+ ]);
380
+ /**
381
+ * The first Bun version that honors `proxy: false` when proxy environment
382
+ * variables are set at startup. Earlier versions send pinned requests
383
+ * through the proxy, with the validated IP address as the target.
384
+ */
385
+ const PROXY_FALSE_MIN_VERSION = "1.4.3";
386
+ const PROXY_VARIABLES = [
387
+ "HTTP_PROXY",
388
+ "http_proxy",
389
+ "HTTPS_PROXY",
390
+ "https_proxy",
391
+ "ALL_PROXY",
392
+ "all_proxy"
393
+ ];
394
+ const FALLBACK_ERROR_CODES = new Set([
395
+ "ConnectionRefused",
396
+ "ECONNREFUSED",
397
+ "EHOSTUNREACH",
398
+ "ENETUNREACH",
399
+ "ETIMEDOUT"
400
+ ]);
401
+ /**
402
+ * Bun versions before 1.3.11 verify the server certificate against the `Host`
403
+ * header, including a non-default port, instead of `tls.serverName`, so
404
+ * pinned requests to HTTPS servers on non-default ports always fail the check
405
+ * there. A custom `checkServerIdentity` cannot stand in for it: these
406
+ * versions send the whole request before a failing custom check aborts it
407
+ * (and 1.3.10 even reuses the connection for the next request), so such
408
+ * requests are refused instead.
409
+ */
410
+ const HOST_HEADER_IDENTITY_RANGE = "<1.3.11";
411
+ /**
412
+ * Creates a pinner for Bun. Every request is sent to an IP literal URL with
413
+ * the original `Host` header, `tls.serverName` set to the original hostname
414
+ * (so that the certificate is still verified against it), and `proxy: false`.
415
+ *
416
+ * GET and HEAD requests fall back to the next address on transport errors
417
+ * raised before a response arrives. Other methods use only the first
418
+ * address, since a transport error does not guarantee that the request did
419
+ * not reach the server, and retrying it could deliver an activity twice.
420
+ * Together with the transport retries of `doubleKnock()`, a GET request is
421
+ * attempted at most twice per address. Note that Bun 1.4 also reports
422
+ * a connection reset after the request was sent as a `TypeError`, so GET and
423
+ * HEAD requests may be repeated against the next address in that case, which
424
+ * is acceptable for these idempotent methods.
425
+ *
426
+ * Bun versions before 1.3.11 verify certificates against the `Host` header,
427
+ * which includes a non-default port, and cannot safely check them against
428
+ * the original hostname in any other way, so requests to HTTPS servers on
429
+ * non-default ports fail there with a `TypeError` before connecting.
430
+ *
431
+ * Bun versions before 1.4.3 ignore `proxy: false` when proxy environment
432
+ * variables are set, so requests go through the proxy with the validated IP
433
+ * address as the target. In that case a warning is logged once.
434
+ * @param options The pinner options.
435
+ * @returns The pinner.
436
+ */
437
+ function createBunPinner({ verifyAddress }) {
438
+ let proxyWarningPending = ignoresProxyFalse() && hasProxyVariables();
439
+ return {
440
+ supports(url) {
441
+ return url.protocol === "http:" || url.protocol === "https:";
442
+ },
443
+ async fetch(grant, request, signal) {
444
+ const url = new URL(request.url);
445
+ const { hostname, addresses } = redeemPinGrant(grant, url);
446
+ if (proxyWarningPending) {
447
+ proxyWarningPending = false;
448
+ logger$1.warn("Bun {version} ignores proxy: false while proxy environment variables are set, so outbound requests go through the proxy instead of connecting directly to the validated addresses. Upgrade to Bun {minVersion} or later, or unset the proxy environment variables; see {url}.", {
449
+ version: getBun()?.version,
450
+ minVersion: PROXY_FALSE_MIN_VERSION,
451
+ url: "https://fedify.dev/manual/deploy#bun-behind-an-http-proxy"
452
+ });
453
+ }
454
+ const fallback = request.method === "GET" || request.method === "HEAD";
455
+ const candidates = fallback ? addresses : addresses.slice(0, 1);
456
+ const body = request.body == null ? null : await request.arrayBuffer();
457
+ let lastError = /* @__PURE__ */ new TypeError(`No address to connect to for ${url.host}.`);
458
+ for (const address of candidates) {
459
+ throwIfAborted(signal, request.signal);
460
+ verifyAddress(address);
461
+ const headers = new Headers(request.headers);
462
+ headers.set("Host", url.host);
463
+ const init = {
464
+ method: request.method,
465
+ headers,
466
+ body,
467
+ redirect: "manual",
468
+ signal: signal == null || signal === request.signal ? request.signal : anySignal(signal, request.signal),
469
+ proxy: false
470
+ };
471
+ if (url.protocol === "https:") init.tls = getTlsOptions(url, hostname);
472
+ try {
473
+ return await fetch(toAddressUrl(url, address), init);
474
+ } catch (error) {
475
+ throwIfAborted(signal, request.signal);
476
+ if (!fallback || !isFallbackError(error)) throw error;
477
+ lastError = error;
478
+ }
479
+ }
480
+ throw lastError;
481
+ },
482
+ release() {}
483
+ };
484
+ }
485
+ function getTlsOptions(url, hostname) {
486
+ const bun = getBun();
487
+ if (url.port !== "" && bun != null && bun.semver.satisfies(bun.version, HOST_HEADER_IDENTITY_RANGE)) throw new TypeError(`Bun ${bun.version} cannot verify the certificate of ${url.host} when connecting to a validated address; upgrade to Bun 1.3.11 or later to fetch from HTTPS servers on non-default ports.`);
488
+ return isIP(hostname) === 0 ? { serverName: hostname } : {};
489
+ }
490
+ /**
491
+ * Combines two signals without `AbortSignal.any()`, which Bun 1.1.0 lacks.
492
+ */
493
+ function anySignal(a, b) {
494
+ if (a.aborted) return a;
495
+ if (b.aborted) return b;
496
+ const controller = new AbortController();
497
+ const abort = (event) => {
498
+ controller.abort(event.target.reason);
499
+ a.removeEventListener("abort", abort);
500
+ b.removeEventListener("abort", abort);
501
+ };
502
+ a.addEventListener("abort", abort);
503
+ b.addEventListener("abort", abort);
504
+ return controller.signal;
505
+ }
506
+ function toAddressUrl(url, address) {
507
+ const result = new URL(url);
508
+ result.hostname = address.family === 6 ? `[${address.address}]` : address.address;
509
+ return result;
510
+ }
511
+ function isFallbackError(error) {
512
+ if (error instanceof Error && error.name === "AbortError") return false;
513
+ if (error instanceof TypeError) return true;
514
+ const code = error?.code;
515
+ return typeof code === "string" && FALLBACK_ERROR_CODES.has(code);
516
+ }
517
+ function throwIfAborted(...signals) {
518
+ for (const signal of signals) signal?.throwIfAborted();
519
+ }
520
+ function getBun() {
521
+ return globalThis.Bun;
522
+ }
523
+ function ignoresProxyFalse() {
524
+ const bun = getBun();
525
+ if (bun == null) return false;
526
+ return !bun.semver.satisfies(bun.version, `>=${PROXY_FALSE_MIN_VERSION}`);
527
+ }
528
+ function hasProxyVariables() {
529
+ const env = globalThis.process?.env;
530
+ if (env == null) return false;
531
+ return PROXY_VARIABLES.some((name) => (env[name] ?? "") !== "");
532
+ }
533
+ /**
534
+ * Creates a pinner for Node.js. Every request is sent through the global
535
+ * `fetch()` with an undici `Agent` as the `dispatcher`. The agent's
536
+ * `connect.lookup` answers only with the addresses of live grants for
537
+ * the hostname, checking each of them again right before connecting, and
538
+ * fails when there are none, so a connection can never be made to an address
539
+ * that was not validated.
540
+ *
541
+ * The agent is shared by the requests of all grants, so keep-alive
542
+ * connections are reused. A pooled connection was made to an address of
543
+ * a grant that was valid when it was connected, so reusing it from another
544
+ * session of the same origin still reaches a validated address. Response
545
+ * bodies have to be consumed or cancelled for their connections to return to
546
+ * the pool, which sessions do when they are closed.
547
+ *
548
+ * Since the dispatcher is passed explicitly, neither proxy environment
549
+ * variables nor the global dispatcher (e.g., `NODE_USE_ENV_PROXY=1`) apply.
550
+ * @param options The pinner options.
551
+ * @returns The pinner.
552
+ */
553
+ function createNodePinner({ verifyAddress, undici }) {
554
+ const grants = /* @__PURE__ */ new Map();
555
+ function lookup(hostname, options, callback) {
556
+ let addresses;
557
+ try {
558
+ addresses = getGrantedAddresses(hostname, options.family);
559
+ } catch (error) {
560
+ callback(error, []);
561
+ return;
562
+ }
563
+ if (options.all) callback(null, addresses);
564
+ else callback(null, addresses[0].address, addresses[0].family);
565
+ }
566
+ function getGrantedAddresses(hostname, family) {
567
+ const addresses = /* @__PURE__ */ new Map();
568
+ for (const [grant, record] of grants.get(hostname) ?? []) {
569
+ try {
570
+ redeemPinGrant(grant, new URL(record.origin));
571
+ } catch {
572
+ continue;
573
+ }
574
+ for (const address of record.addresses) addresses.set(address.address, address);
575
+ }
576
+ const familyNumber = family === "IPv4" ? 4 : family === "IPv6" ? 6 : typeof family === "number" ? family : 0;
577
+ const result = [...addresses.values()].filter((address) => familyNumber === 0 || address.family === familyNumber);
578
+ if (result.length < 1) throw new UrlError(`No validated address to connect to: ${hostname}`);
579
+ for (const address of result) verifyAddress(address);
580
+ return result;
581
+ }
582
+ const agent = new undici.Agent({ connect: { lookup } });
583
+ return {
584
+ supports(url) {
585
+ return url.protocol === "http:" || url.protocol === "https:";
586
+ },
587
+ async fetch(grant, request, signal) {
588
+ const record = redeemPinGrant(grant, new URL(request.url));
589
+ if (isIP(record.hostname) !== 0) for (const address of record.addresses) verifyAddress(address);
590
+ let registered = grants.get(record.hostname);
591
+ if (registered == null) {
592
+ registered = /* @__PURE__ */ new Map();
593
+ grants.set(record.hostname, registered);
594
+ }
595
+ registered.set(grant, record);
596
+ return await fetch(request, {
597
+ redirect: "manual",
598
+ signal: signal == null || signal === request.signal ? request.signal : AbortSignal.any([signal, request.signal]),
599
+ dispatcher: agent
600
+ });
601
+ },
602
+ release(grant) {
603
+ for (const [hostname, registered] of grants) {
604
+ if (!registered.delete(grant)) continue;
605
+ if (registered.size < 1) grants.delete(hostname);
606
+ break;
607
+ }
608
+ }
609
+ };
610
+ }
611
+ /**
612
+ * Detects the current runtime. Cloudflare Workers is checked first, since
613
+ * `process` can exist there with `nodejs_compat`, and Deno and Bun before
614
+ * Node.js, since both provide `process.versions.node`.
615
+ * @returns The current runtime.
616
+ */
617
+ function detectRuntime() {
618
+ const g = globalThis;
619
+ if (g.navigator?.userAgent === "Cloudflare-Workers") return "cfworkers";
620
+ if ("Deno" in globalThis) return "deno";
621
+ if ("Bun" in globalThis) return "bun";
622
+ if (g.process?.versions?.node != null) return "node";
623
+ return "other";
624
+ }
625
+ let runtimePinner;
626
+ /**
627
+ * Gets the production pinner of the current runtime, which rejects
628
+ * non-public addresses right before connecting. Deno and Cloudflare Workers
629
+ * have no pinner.
630
+ * @returns The pinner, or `null` if the runtime has none.
631
+ */
632
+ function getRuntimePinner() {
633
+ runtimePinner ??= createRuntimePinner(detectRuntime());
634
+ return runtimePinner;
635
+ }
636
+ async function createRuntimePinner(runtime) {
637
+ switch (runtime) {
638
+ case "bun": return createBunPinner({ verifyAddress: assertPublicAddress });
639
+ case "node": return createNodePinner({
640
+ verifyAddress: assertPublicAddress,
641
+ undici: await import("./undici-CjF8_EAQ.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1))
642
+ });
643
+ default: return null;
644
+ }
645
+ }
646
+ const logger$2 = getLogger([
647
+ "fedify",
648
+ "runtime",
649
+ "fetch"
650
+ ]);
651
+ /**
652
+ * Creates {@link PublicFetch.openPublicFetch} and
653
+ * {@link PublicFetch.withPublicFetch} bound to the given pinner and lookup.
654
+ * This is exported only for tests; it is not exported from any entry point.
655
+ * @param dependencies The pinner and the default lookup function.
656
+ * @returns The functions.
657
+ */
658
+ function createPublicFetch(dependencies) {
659
+ async function openPublicFetch(url, options = {}) {
660
+ const { url: parsed, hostname, family } = parsePublicUrl(url);
661
+ if (parsed.username !== "" || parsed.password !== "") throw new UrlError("URLs with credentials are not allowed");
662
+ const lookup = options.lookup ?? dependencies.lookup;
663
+ let addresses;
664
+ if (family !== 0) addresses = [{
665
+ address: hostname,
666
+ family
667
+ }];
668
+ else if (lookup === lookupAllAddresses && !await canResolve()) return createSession(parsed, globalFetch);
669
+ else {
670
+ options.signal?.throwIfAborted();
671
+ addresses = await lookupPublicAddresses(hostname, lookup);
672
+ options.signal?.throwIfAborted();
673
+ }
674
+ const pinner = await dependencies.pinner();
675
+ if (pinner == null || !pinner.supports(parsed)) {
676
+ logUnpinned(parsed);
677
+ return createSession(parsed, globalFetch);
678
+ }
679
+ const grant = issuePinGrant(parsed, addresses);
680
+ return createSession(parsed, (input, init) => pinner.fetch(grant, new Request(input, init), init.signal ?? void 0), {
681
+ grant,
682
+ pinner
683
+ });
684
+ }
685
+ async function withPublicFetch(url, fn, options) {
686
+ const session = await openPublicFetch(url, options);
687
+ try {
688
+ const result = await fn(session.fetch);
689
+ if (result instanceof Response) throw new TypeError("withPublicFetch() callbacks must not return a Response, since its body is cancelled when the session is closed.");
690
+ return result;
691
+ } catch (error) {
692
+ logger$2.debug("Failed while fetching {url}; closing the session: {error}", {
693
+ url: session.url.href,
694
+ error
695
+ });
696
+ throw error;
697
+ } finally {
698
+ await session.close();
699
+ }
700
+ }
701
+ return {
702
+ openPublicFetch,
703
+ withPublicFetch
704
+ };
705
+ }
706
+ const runtimePublicFetch = createPublicFetch({
707
+ pinner: getRuntimePinner,
708
+ lookup: lookupAllAddresses
709
+ });
710
+ /**
711
+ * Validates the URL, resolves its hostname, checks that every resolved
712
+ * address is public, and opens a session that connects only to those
713
+ * addresses. Connections are pinned on Node.js and Bun. On other runtimes,
714
+ * the session uses the global `fetch()` after the check.
715
+ * @param url The URL to open a session for.
716
+ * @param options The options.
717
+ * @returns The session. It must be closed.
718
+ * @throws {UrlError} If the URL is not allowed, or its hostname cannot be
719
+ * resolved (with `reason: "dns"`).
720
+ */
721
+ const openPublicFetch = runtimePublicFetch.openPublicFetch;
722
+ runtimePublicFetch.withPublicFetch;
723
+ /**
724
+ * Opens a session that neither validates nor pins addresses, for callers that
725
+ * allow private addresses. It has the same rules as {@link openPublicFetch}
726
+ * sessions otherwise: requests are limited to the URL's origin, redirects are
727
+ * never followed, and unconsumed response bodies are cancelled on close.
728
+ * It grants nothing beyond calling the global `fetch()` directly.
729
+ * @param url The URL to open a session for.
730
+ * @returns The session. It must be closed.
731
+ */
732
+ function openDirectFetch(url) {
733
+ return Promise.resolve(createSession(new URL(url), globalFetch));
734
+ }
735
+ /**
736
+ * Starts cancelling the body of a response without waiting for it to settle.
737
+ * The cancellation of a branch of a tee (e.g., a body cloned by a fetch mock)
738
+ * settles only after the other branch is cancelled too, per the Streams
739
+ * standard, so awaiting it could block forever. Failures are only logged.
740
+ */
741
+ function cancelResponseBody$1(response, url) {
742
+ response.body?.cancel().catch((error) => {
743
+ logger$2.debug("Failed to cancel a response body from {url}: {error}", {
744
+ url: url.href,
745
+ error
746
+ });
747
+ });
748
+ }
749
+ function globalFetch(input, init) {
750
+ return fetch(input, init);
751
+ }
752
+ function createSession(url, send, pin) {
753
+ const origin = url.origin;
754
+ const tracked = [];
755
+ let closed = false;
756
+ async function sessionFetch(input, init) {
757
+ if (closed) throw new TypeError("The fetch session is closed.");
758
+ const target = new URL(input instanceof Request ? input.url : input);
759
+ if (target.origin !== origin) throw new TypeError(`A fetch session for ${origin} cannot fetch ${target.origin}.`);
760
+ const response = await send(input, {
761
+ ...init,
762
+ redirect: "manual"
23
763
  });
764
+ if (closed) {
765
+ cancelResponseBody$1(response, url);
766
+ throw new TypeError("The fetch session is closed.");
767
+ }
768
+ tracked.push(response);
769
+ return response;
24
770
  }
25
- return to;
26
- };
27
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
28
- value: mod,
29
- enumerable: true
30
- }) : target, mod));
31
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
771
+ async function close() {
772
+ if (closed) return;
773
+ closed = true;
774
+ for (const response of tracked) {
775
+ if (response.body == null || response.bodyUsed) continue;
776
+ if (response.body.locked) {
777
+ logger$2.debug("Cannot cancel a locked response body from {url}.", { url: url.href });
778
+ continue;
779
+ }
780
+ cancelResponseBody$1(response, url);
781
+ }
782
+ if (pin == null) return;
783
+ revokePinGrant(pin.grant);
784
+ await pin.pinner.release(pin.grant);
785
+ }
786
+ return {
787
+ get url() {
788
+ return new URL(url);
789
+ },
790
+ fetch: sessionFetch,
791
+ close
792
+ };
793
+ }
794
+ async function canResolve() {
795
+ if (!("Deno" in globalThis)) return true;
796
+ return (await Deno.permissions.query({ name: "net" })).state === "granted";
797
+ }
798
+ const loggedUnpinned = /* @__PURE__ */ new Set();
799
+ function logUnpinned(url) {
800
+ const runtime = detectRuntime();
801
+ const key = `${runtime} ${url.protocol}`;
802
+ if (loggedUnpinned.has(key)) return;
803
+ loggedUnpinned.add(key);
804
+ logger$2.debug("Outbound {protocol} connections are not pinned to validated addresses on {runtime}; the hostname is resolved again when connecting.", {
805
+ runtime,
806
+ protocol: url.protocol
807
+ });
808
+ }
809
+ /**
810
+ * Narrows a {@link CryptoKeyLike} to the ambient `CryptoKey` type, for passing
811
+ * it to `crypto.subtle` or to APIs that still declare the ambient type.
812
+ *
813
+ * This is internal to Fedify and is not exported from the package entry point.
814
+ * @param key The key to narrow.
815
+ * @returns The same key, typed as the ambient `CryptoKey`.
816
+ */
817
+ function asCryptoKey(key) {
818
+ return key;
819
+ }
32
820
  //#endregion
33
821
  //#region ../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js
34
822
  /** only globals that common to node and browsers are allowed */
@@ -25775,7 +26563,7 @@ const preloadedContexts = {
25775
26563
  "https://purl.archive.org/miscellany": miscellany_default
25776
26564
  };
25777
26565
  var name = "@fedify/vocab-runtime";
25778
- var version = "2.1.30";
26566
+ var version = "2.1.32";
25779
26567
  /**
25780
26568
  * Error thrown when fetching a JSON-LD document failed.
25781
26569
  */
@@ -26095,214 +26883,6 @@ var HttpHeaderLink = class HttpHeaderLink {
26095
26883
  return new this(...inputs).toString();
26096
26884
  }
26097
26885
  };
26098
- var UrlError = class extends Error {
26099
- /**
26100
- * The failure category. Defaults to `"disallowed"`.
26101
- * `"dns"` includes lookup errors and results with no usable IP addresses.
26102
- * @since 2.0.29
26103
- */
26104
- reason;
26105
- constructor(message, options) {
26106
- super(message, options);
26107
- this.name = "UrlError";
26108
- this.reason = options?.reason ?? "disallowed";
26109
- }
26110
- };
26111
- /**
26112
- * Validates a URL to prevent SSRF attacks.
26113
- */
26114
- async function validatePublicUrl(url) {
26115
- const parsed = new URL(url);
26116
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new UrlError(`Unsupported protocol: ${parsed.protocol}`);
26117
- let hostname = parsed.hostname;
26118
- if (hostname.startsWith("[") && hostname.endsWith("]")) hostname = hostname.slice(1, -1);
26119
- if (hostname === "localhost") throw new UrlError("Localhost is not allowed");
26120
- const hostnameFamily = isIP(hostname);
26121
- if (hostnameFamily !== 0) {
26122
- validatePublicIpAddress(hostname, hostnameFamily);
26123
- return;
26124
- }
26125
- if ("Deno" in globalThis && !isIP(hostname)) {
26126
- if ((await Deno.permissions.query({ name: "net" })).state !== "granted") return;
26127
- }
26128
- if ("Bun" in globalThis) {
26129
- if (hostname === "example.com" || hostname.endsWith(".example.com")) return;
26130
- else if (hostname === "fedify-test.internal") throw new UrlError("Invalid or private address: fedify-test.internal");
26131
- }
26132
- let addresses;
26133
- try {
26134
- addresses = await dns.lookup(hostname, { all: true });
26135
- } catch (error) {
26136
- throw new UrlError("DNS lookup failed", {
26137
- cause: error,
26138
- reason: "dns"
26139
- });
26140
- }
26141
- validateLookupAddresses(addresses);
26142
- }
26143
- /**
26144
- * Validates the IP addresses returned by `node:dns.lookup()`.
26145
- *
26146
- * Cloudflare Workers' `node:dns` implementation currently maps every record
26147
- * in a DNS-over-HTTPS `Answer` array—including CNAME records—to a
26148
- * `LookupAddress`, even though Node.js specifies that the `address` field must
26149
- * contain an IPv4 or IPv6 literal. See:
26150
- * https://github.com/cloudflare/workerd/issues/6886
26151
- *
26152
- * Work around that bug by ignoring non-IP entries only when the lookup also
26153
- * returns at least one actual IP address. This remains fail-closed: a result
26154
- * containing no IP addresses is rejected, and every returned IP address is
26155
- * still validated and must be public. This workaround can be revisited once
26156
- * the Workerd issue is fixed in supported Cloudflare Workers runtimes.
26157
- *
26158
- * @internal
26159
- */
26160
- function validateLookupAddresses(addresses) {
26161
- let ipAddressCount = 0;
26162
- for (const { address } of addresses) {
26163
- const family = isIP(address);
26164
- if (family === 0) continue;
26165
- ipAddressCount++;
26166
- validatePublicIpAddress(address, family);
26167
- }
26168
- if (ipAddressCount === 0) throw new UrlError("DNS lookup did not return any IP address", { reason: "dns" });
26169
- }
26170
- function validatePublicIpAddress(address, family) {
26171
- if (family === 4 && isValidPublicIPv4Address(address) || family === 6 && isValidPublicIPv6Address(address)) return;
26172
- throw new UrlError(`Invalid or private address: ${address}`);
26173
- }
26174
- function isValidPublicIPv4Address(address) {
26175
- const parts = parseIPv4Address(address);
26176
- if (parts == null) return false;
26177
- const value = ipv4PartsToNumber(parts);
26178
- return !nonPublicIPv4Prefixes.some(({ base, prefix }) => matchesIPv4Prefix(value, base, prefix));
26179
- }
26180
- function isValidPublicIPv6Address(address) {
26181
- const words = parseIPv6Address(address);
26182
- if (words == null) return false;
26183
- if (nonPublicIPv6Prefixes.some(({ words: prefixWords, prefix }) => matchesIPv6Prefix(words, prefixWords, prefix))) return false;
26184
- for (const { extractIPv4, prefix, words: prefixWords } of ipv6WithIPv4Prefixes) {
26185
- if (!matchesIPv6Prefix(words, prefixWords, prefix)) continue;
26186
- const ipv4Address = extractIPv4(words);
26187
- if (ipv4Address != null && !isValidPublicIPv4Address(ipv4Address)) return false;
26188
- }
26189
- return true;
26190
- }
26191
- function expandIPv6Address(address) {
26192
- address = address.toLowerCase();
26193
- const ipv4Delimiter = address.lastIndexOf(":");
26194
- if (address.includes(".") && ipv4Delimiter >= 0) {
26195
- const ipv4Parts = parseIPv4Address(address.substring(ipv4Delimiter + 1));
26196
- if (ipv4Parts == null) return address;
26197
- const high = (ipv4Parts[0] << 8) + ipv4Parts[1];
26198
- const low = (ipv4Parts[2] << 8) + ipv4Parts[3];
26199
- address = address.substring(0, ipv4Delimiter + 1) + high.toString(16) + ":" + low.toString(16);
26200
- }
26201
- if (address === "::") return "0000:0000:0000:0000:0000:0000:0000:0000";
26202
- if (address.startsWith("::")) address = "0000" + address;
26203
- if (address.endsWith("::")) address = address + "0000";
26204
- address = address.replace("::", ":0000".repeat(8 - (address.match(/:/g) || []).length) + ":");
26205
- return address.split(":").map((part) => part.padStart(4, "0")).join(":");
26206
- }
26207
- const nonPublicIPv4Prefixes = [
26208
- ipv4Prefix("0.0.0.0/8", "RFC 6890"),
26209
- ipv4Prefix("10.0.0.0/8", "RFC 1918"),
26210
- ipv4Prefix("100.64.0.0/10", "RFC 6598"),
26211
- ipv4Prefix("127.0.0.0/8", "RFC 1122"),
26212
- ipv4Prefix("169.254.0.0/16", "RFC 3927"),
26213
- ipv4Prefix("172.16.0.0/12", "RFC 1918"),
26214
- ipv4Prefix("192.0.0.0/24", "RFC 6890"),
26215
- ipv4Prefix("192.0.2.0/24", "RFC 5737"),
26216
- ipv4Prefix("192.88.99.0/24", "RFC 7526"),
26217
- ipv4Prefix("192.168.0.0/16", "RFC 1918"),
26218
- ipv4Prefix("198.18.0.0/15", "RFC 2544"),
26219
- ipv4Prefix("198.51.100.0/24", "RFC 5737"),
26220
- ipv4Prefix("203.0.113.0/24", "RFC 5737"),
26221
- ipv4Prefix("224.0.0.0/4", "RFC 5771"),
26222
- ipv4Prefix("240.0.0.0/4", "RFC 1112")
26223
- ];
26224
- const nonPublicIPv6Prefixes = [
26225
- ipv6Prefix("::/16", "RFC 4291"),
26226
- ipv6Prefix("2001::/32", "RFC 4380"),
26227
- ipv6Prefix("2002::/16", "RFC 3056"),
26228
- ipv6Prefix("64:ff9b:1::/48", "RFC 8215"),
26229
- ipv6Prefix("fc00::/7", "RFC 4193"),
26230
- ipv6Prefix("fe80::/10", "RFC 4291"),
26231
- ipv6Prefix("ff00::/8", "RFC 4291")
26232
- ];
26233
- const ipv6WithIPv4Prefixes = [{
26234
- ...ipv6Prefix("64:ff9b::/96", "RFC 6052"),
26235
- extractIPv4: (words) => ipv4FromWords(words[6], words[7])
26236
- }];
26237
- function ipv4Prefix(cidr, rfc) {
26238
- const [address, prefixText] = cidr.split("/");
26239
- const prefix = parseInt(prefixText, 10);
26240
- const parts = parseIPv4Address(address);
26241
- if (parts == null || !Number.isInteger(prefix) || prefix < 0 || prefix > 32) throw new Error(`Invalid IPv4 prefix: ${cidr}`);
26242
- return {
26243
- cidr,
26244
- base: ipv4PartsToNumber(parts),
26245
- prefix,
26246
- rfc
26247
- };
26248
- }
26249
- function ipv6Prefix(cidr, rfc) {
26250
- const [address, prefixText] = cidr.split("/");
26251
- const prefix = parseInt(prefixText, 10);
26252
- const words = parseIPv6Address(address);
26253
- if (words == null || !Number.isInteger(prefix) || prefix < 0 || prefix > 128) throw new Error(`Invalid IPv6 prefix: ${cidr}`);
26254
- return {
26255
- cidr,
26256
- words,
26257
- prefix,
26258
- rfc
26259
- };
26260
- }
26261
- function parseIPv4Address(address) {
26262
- const parts = address.split(".").map((part) => {
26263
- if (!/^\d+$/.test(part)) return NaN;
26264
- return parseInt(part, 10);
26265
- });
26266
- if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return null;
26267
- return parts;
26268
- }
26269
- function parseIPv6Address(address) {
26270
- const parts = expandIPv6Address(address).split(":");
26271
- if (parts.length !== 8) return null;
26272
- const words = parts.map((part) => {
26273
- if (!/^[0-9a-f]{1,4}$/i.test(part)) return NaN;
26274
- return parseInt(part, 16);
26275
- });
26276
- if (words.some((word) => !Number.isInteger(word) || word < 0 || word > 65535)) return null;
26277
- return words;
26278
- }
26279
- function ipv4PartsToNumber(parts) {
26280
- return parts[0] * 2 ** 24 + parts[1] * 2 ** 16 + parts[2] * 2 ** 8 + parts[3];
26281
- }
26282
- function ipv4FromWords(highWord, lowWord) {
26283
- return [
26284
- highWord >> 8,
26285
- highWord & 255,
26286
- lowWord >> 8,
26287
- lowWord & 255
26288
- ].join(".");
26289
- }
26290
- function matchesIPv4Prefix(address, prefixBase, prefixLength) {
26291
- const blockSize = 2 ** (32 - prefixLength);
26292
- return Math.floor(address / blockSize) === Math.floor(prefixBase / blockSize);
26293
- }
26294
- function matchesIPv6Prefix(address, prefixWords, prefixLength) {
26295
- let remaining = prefixLength;
26296
- for (let i = 0; i < 8 && remaining > 0; i++) if (remaining >= 16) {
26297
- if (address[i] !== prefixWords[i]) return false;
26298
- remaining -= 16;
26299
- } else {
26300
- const mask = 65535 << 16 - remaining & 65535;
26301
- if ((address[i] & mask) !== (prefixWords[i] & mask)) return false;
26302
- remaining = 0;
26303
- }
26304
- return true;
26305
- }
26306
26886
  const logger = getLogger([
26307
26887
  "fedify",
26308
26888
  "runtime",
@@ -26310,16 +26890,34 @@ const logger = getLogger([
26310
26890
  ]);
26311
26891
  const DEFAULT_MAX_REDIRECTION = 20;
26312
26892
  /**
26313
- * Gets a {@link RemoteDocument} from the given response.
26893
+ * Starts cancelling the body of a response without waiting for it to settle.
26894
+ * The cancellation of a branch of a tee (e.g., a body cloned by a fetch mock)
26895
+ * settles only after the other branch is cancelled too, per the Streams
26896
+ * standard, so awaiting it could block forever. Failures are only logged.
26897
+ * @param response The response whose body is cancelled.
26898
+ * @param url The URL of the response, for logging.
26899
+ */
26900
+ function cancelResponseBody(response, url) {
26901
+ response.body?.cancel().catch((error) => {
26902
+ logger.debug("Failed to cancel the response body from {url}: {error}", {
26903
+ url,
26904
+ error
26905
+ });
26906
+ });
26907
+ }
26908
+ /**
26909
+ * Gets a {@link RemoteDocument} from the given response, or the URL of an
26910
+ * alternate document to load instead. When an alternate document is found,
26911
+ * the response body has been either read or its cancellation has been started
26912
+ * (without waiting for it), so that the alternate document can be loaded after
26913
+ * the response's session is closed.
26314
26914
  * @param url The URL of the document to load.
26315
26915
  * @param response The response to get the document from.
26316
- * @param fetch The function to fetch the document.
26317
- * @returns The loaded remote document.
26916
+ * @returns The loaded remote document, or the alternate document URL.
26318
26917
  * @throws {FetchError} If the response is not OK.
26319
- * @internal
26320
26918
  */
26321
- async function getRemoteDocument(url, response, fetch) {
26322
- const documentUrl = response.url === "" ? url : response.url;
26919
+ async function parseRemoteDocument(url, response) {
26920
+ const documentUrl = url;
26323
26921
  const docUrl = new URL(documentUrl);
26324
26922
  if (!response.ok) {
26325
26923
  logger.error("Failed to fetch document: {status} {url} {headers}", {
@@ -26356,7 +26954,8 @@ async function getRemoteDocument(url, response, fetch) {
26356
26954
  alternateUrl: altUri.href,
26357
26955
  url: documentUrl
26358
26956
  });
26359
- return await fetch(altUri.href);
26957
+ cancelResponseBody(response, documentUrl);
26958
+ return { alternate: altUri.href };
26360
26959
  }
26361
26960
  }
26362
26961
  }
@@ -26381,7 +26980,7 @@ async function getRemoteDocument(url, response, fetch) {
26381
26980
  alternateUrl: attribs.href,
26382
26981
  url: documentUrl
26383
26982
  });
26384
- return await fetch(new URL(attribs.href, docUrl).href);
26983
+ return { alternate: new URL(attribs.href, docUrl).href };
26385
26984
  }
26386
26985
  }
26387
26986
  document = JSON.parse(html);
@@ -26391,11 +26990,11 @@ async function getRemoteDocument(url, response, fetch) {
26391
26990
  url: documentUrl,
26392
26991
  headers: Object.fromEntries(response.headers.entries())
26393
26992
  });
26394
- return {
26993
+ return { document: {
26395
26994
  contextUrl,
26396
26995
  document,
26397
26996
  documentUrl
26398
- };
26997
+ } };
26399
26998
  }
26400
26999
  /**
26401
27000
  * Creates a JSON-LD document loader that utilizes the browser's `fetch` API.
@@ -26421,8 +27020,53 @@ async function getRemoteDocument(url, response, fetch) {
26421
27020
  * @returns The document loader.
26422
27021
  * @since 1.3.0
26423
27022
  */
26424
- function getDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAgent } = {}) {
27023
+ function getDocumentLoader(options = {}) {
27024
+ return createDocumentLoader(options);
27025
+ }
27026
+ /**
27027
+ * The implementation of {@link getDocumentLoader}, with injectable
27028
+ * dependencies. This is not exported from any entry point.
27029
+ * @param options Options for the document loader.
27030
+ * @param deps The dependencies.
27031
+ * @returns The document loader.
27032
+ */
27033
+ function createDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAgent } = {}, deps = {}) {
26425
27034
  const tracer = trace.getTracerProvider().getTracer(name, version);
27035
+ async function openHop(url, signal) {
27036
+ try {
27037
+ if (deps.openHop != null) return await deps.openHop(url);
27038
+ return allowPrivateAddress ? await openDirectFetch(url) : await openPublicFetch(url, { signal });
27039
+ } catch (error) {
27040
+ if (error instanceof UrlError) if (error.reason === "dns") logger.debug("DNS lookup failed for {url}", {
27041
+ url,
27042
+ error
27043
+ });
27044
+ else logger.error("Disallowed private URL: {url}", {
27045
+ url,
27046
+ error
27047
+ });
27048
+ throw error;
27049
+ }
27050
+ }
27051
+ async function fetchHop(session, url, span, options) {
27052
+ try {
27053
+ const request = createActivityPubRequest(url, { userAgent });
27054
+ logRequest(logger, request);
27055
+ const response = await session.fetch(request, {
27056
+ redirect: "manual",
27057
+ signal: options?.signal
27058
+ });
27059
+ span.setAttribute("http.response.status_code", response.status);
27060
+ if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
27061
+ const location = response.headers.get("Location");
27062
+ cancelResponseBody(response, url);
27063
+ return { location };
27064
+ }
27065
+ return await parseRemoteDocument(url, response);
27066
+ } finally {
27067
+ await session.close();
27068
+ }
27069
+ }
26426
27070
  async function load(url, options, redirected = 0, visited = /* @__PURE__ */ new Set()) {
26427
27071
  options?.signal?.throwIfAborted();
26428
27072
  const parsedUrl = new URL(url);
@@ -26437,33 +27081,15 @@ function getDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAge
26437
27081
  documentUrl: currentUrl
26438
27082
  };
26439
27083
  }
26440
- if (!allowPrivateAddress) try {
26441
- await validatePublicUrl(currentUrl);
26442
- } catch (error) {
26443
- if (error instanceof UrlError) if (error.reason === "dns") logger.debug("DNS lookup failed for {url}", {
26444
- url: currentUrl,
26445
- error
26446
- });
26447
- else logger.error("Disallowed private URL: {url}", {
26448
- url: currentUrl,
26449
- error
26450
- });
26451
- throw error;
26452
- }
27084
+ const session = await openHop(currentUrl, options?.signal);
26453
27085
  visited.add(currentUrl);
26454
27086
  return await tracer.startActiveSpan("activitypub.fetch_document", {
26455
27087
  kind: SpanKind.CLIENT,
26456
27088
  attributes: { "url.full": currentUrl }
26457
27089
  }, async (span) => {
26458
27090
  try {
26459
- const request = createActivityPubRequest(currentUrl, { userAgent });
26460
- logRequest(logger, request);
26461
- const response = await fetch(request, {
26462
- redirect: "manual",
26463
- signal: options?.signal
26464
- });
26465
- span.setAttribute("http.response.status_code", response.status);
26466
- if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
27091
+ const outcome = await fetchHop(session, currentUrl, span, options);
27092
+ if ("location" in outcome) {
26467
27093
  if (redirected >= DEFAULT_MAX_REDIRECTION) {
26468
27094
  logger.error("Too many redirections ({redirections}) while fetching document.", {
26469
27095
  redirections: redirected + 1,
@@ -26471,7 +27097,7 @@ function getDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAge
26471
27097
  });
26472
27098
  throw new FetchError(currentUrl, `Too many redirections (${redirected + 1})`);
26473
27099
  }
26474
- const redirectUrl = new URL(response.headers.get("Location"), response.url === "" ? currentUrl : response.url).href;
27100
+ const redirectUrl = new URL(outcome.location, currentUrl).href;
26475
27101
  span.setAttribute("http.redirect.url", redirectUrl);
26476
27102
  if (visited.has(redirectUrl)) {
26477
27103
  logger.error("Detected a redirect loop while fetching document: {url} -> {redirectUrl}", {
@@ -26482,12 +27108,14 @@ function getDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAge
26482
27108
  }
26483
27109
  return await load(redirectUrl, options, redirected + 1, visited);
26484
27110
  }
26485
- const result = await getRemoteDocument(currentUrl, response, async (alternateUrl) => {
27111
+ let result;
27112
+ if ("alternate" in outcome) {
27113
+ const alternateUrl = outcome.alternate;
26486
27114
  options?.signal?.throwIfAborted();
26487
27115
  if (redirected >= DEFAULT_MAX_REDIRECTION) throw new FetchError(currentUrl, `Too many redirections (${redirected + 1})`);
26488
27116
  if (visited.has(alternateUrl)) throw new FetchError(currentUrl, `Redirect loop detected: ${alternateUrl}`);
26489
- return await load(alternateUrl, options, redirected + 1, visited);
26490
- });
27117
+ result = await load(alternateUrl, options, redirected + 1, visited);
27118
+ } else result = outcome.document;
26491
27119
  span.setAttribute("docloader.document_url", result.documentUrl);
26492
27120
  if (result.contextUrl != null) span.setAttribute("docloader.context_url", result.contextUrl);
26493
27121
  return result;
@@ -26760,7 +27388,7 @@ constants.reduce((prev, tupple) => {
26760
27388
  */
26761
27389
  async function exportSpki(key) {
26762
27390
  validateCryptoKey(key);
26763
- let pem = a(await crypto.subtle.exportKey("spki", key));
27391
+ let pem = a(await crypto.subtle.exportKey("spki", asCryptoKey(key)));
26764
27392
  pem = (pem.match(/.{1,64}/g) || []).join("\n");
26765
27393
  return `-----BEGIN PUBLIC KEY-----\n${pem}\n-----END PUBLIC KEY-----\n`;
26766
27394
  }