@fedify/vocab-runtime 2.2.18 → 2.2.20

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.
Files changed (114) hide show
  1. package/deno.json +5 -2
  2. package/dist/internal.cjs +6 -0
  3. package/dist/internal.d.cts +3 -0
  4. package/dist/internal.d.ts +3 -0
  5. package/dist/internal.js +3 -0
  6. package/dist/mod.cjs +105 -252
  7. package/dist/mod.d.cts +5 -28
  8. package/dist/mod.d.ts +6 -28
  9. package/dist/mod.js +99 -245
  10. package/dist/public-fetch-BC-nWJNM.d.ts +143 -0
  11. package/dist/public-fetch-CFnW7XMn.cjs +821 -0
  12. package/dist/public-fetch-DBpt3xxf.d.cts +143 -0
  13. package/dist/public-fetch-Dfmc_Kfy.js +772 -0
  14. package/dist/tests/{body-CbvYxP3V.mjs → body-B9_hb-GO.mjs} +1 -1
  15. package/dist/tests/{body-CaJBg0tr.cjs → body-pOSG2RFb.cjs} +1 -1
  16. package/dist/tests/body.test.cjs +1 -1
  17. package/dist/tests/body.test.mjs +1 -1
  18. package/dist/tests/decimal.test.cjs +6 -6
  19. package/dist/tests/decimal.test.mjs +6 -6
  20. package/dist/tests/{docloader-jQMjHIRI.mjs → docloader-Bdlp7FkK.mjs} +103 -37
  21. package/dist/tests/{docloader-k2T5kUlV.cjs → docloader-Ck3VfY29.cjs} +107 -35
  22. package/dist/tests/docloader.test.cjs +569 -1273
  23. package/dist/tests/docloader.test.mjs +515 -1238
  24. package/dist/tests/esm-CnLt0wAF.mjs +1225 -0
  25. package/dist/tests/esm-CxbqfkLP.cjs +1208 -0
  26. package/dist/tests/internal/multicodec.test.cjs +1 -1
  27. package/dist/tests/internal/multicodec.test.mjs +1 -1
  28. package/dist/tests/{key-BDIsC6hV.mjs → key-GEdpxA4M.mjs} +2 -2
  29. package/dist/tests/{key-BarKGLQz.cjs → key-L6ReMuUb.cjs} +2 -2
  30. package/dist/tests/key.test.cjs +2 -2
  31. package/dist/tests/key.test.mjs +2 -2
  32. package/dist/tests/{langstr-BsqFJupv.cjs → langstr-CZpWmpo5.cjs} +1 -1
  33. package/dist/tests/{langstr-ABdAOKlF.mjs → langstr-DTB4sl0a.mjs} +1 -1
  34. package/dist/tests/langstr.test.cjs +1 -1
  35. package/dist/tests/langstr.test.mjs +1 -1
  36. package/dist/tests/langtag.test.cjs +1 -1
  37. package/dist/tests/langtag.test.mjs +1 -1
  38. package/dist/tests/link.test.mjs +1 -1
  39. package/dist/tests/multibase/multibase.test.cjs +1 -1
  40. package/dist/tests/multibase/multibase.test.mjs +1 -1
  41. package/dist/tests/node-C3bjFjL1.mjs +84 -0
  42. package/dist/tests/node-DWD76vPo.cjs +90 -0
  43. package/dist/tests/pin-grant-CU-o367k.cjs +70 -0
  44. package/dist/tests/pin-grant-HW3B6SKv.mjs +53 -0
  45. package/dist/tests/pin-grant.test.cjs +88 -0
  46. package/dist/tests/pin-grant.test.d.cts +1 -0
  47. package/dist/tests/pin-grant.test.d.mts +1 -0
  48. package/dist/tests/pin-grant.test.mjs +88 -0
  49. package/dist/tests/pinners/bun.test.cjs +167 -0
  50. package/dist/tests/pinners/bun.test.d.cts +1 -0
  51. package/dist/tests/pinners/bun.test.d.mts +1 -0
  52. package/dist/tests/pinners/bun.test.mjs +167 -0
  53. package/dist/tests/pinners/node.test.cjs +269 -0
  54. package/dist/tests/pinners/node.test.d.cts +1 -0
  55. package/dist/tests/pinners/node.test.d.mts +1 -0
  56. package/dist/tests/pinners/node.test.mjs +268 -0
  57. package/dist/tests/pinners/pinners.test.cjs +197 -0
  58. package/dist/tests/pinners/pinners.test.d.cts +1 -0
  59. package/dist/tests/pinners/pinners.test.d.mts +1 -0
  60. package/dist/tests/pinners/pinners.test.mjs +197 -0
  61. package/dist/tests/pinners/testdata/node-child.cjs +135 -0
  62. package/dist/tests/pinners/testdata/node-child.d.cts +1 -0
  63. package/dist/tests/pinners/testdata/node-child.d.mts +1 -0
  64. package/dist/tests/pinners/testdata/node-child.mjs +134 -0
  65. package/dist/tests/pinners-BjE-YJLL.cjs +221 -0
  66. package/dist/tests/pinners-ZgZDx9y6.mjs +203 -0
  67. package/dist/tests/public-fetch-Ddjfxbwc.cjs +187 -0
  68. package/dist/tests/public-fetch-Yi7Vks9s.mjs +170 -0
  69. package/dist/tests/public-fetch.test.cjs +1074 -0
  70. package/dist/tests/public-fetch.test.d.cts +1 -0
  71. package/dist/tests/public-fetch.test.d.mts +1 -0
  72. package/dist/tests/public-fetch.test.mjs +1074 -0
  73. package/dist/tests/{request-BngWcP0t.cjs → request-B3NUKbyk.cjs} +1 -1
  74. package/dist/tests/{request-BE7XIrGw.mjs → request-BSg3IQzf.mjs} +1 -1
  75. package/dist/tests/request.test.cjs +1 -1
  76. package/dist/tests/request.test.mjs +1 -1
  77. package/dist/tests/support-D5-KVjWZ.cjs +363 -0
  78. package/dist/tests/support-M5ClN-no.mjs +272 -0
  79. package/dist/tests/{url-vZTgkIZg.cjs → url-DLuSj57U.cjs} +88 -12
  80. package/dist/tests/{url-3fyJuqC0.mjs → url-DQWrMGhu.mjs} +65 -13
  81. package/dist/tests/url.test.cjs +4 -1
  82. package/dist/tests/url.test.mjs +4 -1
  83. package/package.json +14 -3
  84. package/src/docloader.test.ts +784 -32
  85. package/src/docloader.ts +179 -67
  86. package/src/internal.ts +13 -0
  87. package/src/pin-grant.test.ts +118 -0
  88. package/src/pin-grant.ts +99 -0
  89. package/src/pinners/bun.test.ts +278 -0
  90. package/src/pinners/bun.ts +223 -0
  91. package/src/pinners/mod.ts +59 -0
  92. package/src/pinners/node.test.ts +415 -0
  93. package/src/pinners/node.ts +144 -0
  94. package/src/pinners/pinners.test.ts +316 -0
  95. package/src/pinners/testdata/node-child.ts +147 -0
  96. package/src/pinners/testdata/proxy-child.ts +82 -0
  97. package/src/pinners/testdata/support.ts +343 -0
  98. package/src/pinners/testdata/tls-cert.pem +12 -0
  99. package/src/pinners/testdata/tls-child.ts +88 -0
  100. package/src/pinners/testdata/tls-key.pem +5 -0
  101. package/src/pinners/types.ts +48 -0
  102. package/src/public-fetch.test.ts +1286 -0
  103. package/src/public-fetch.ts +338 -0
  104. package/src/testdata/public-fetch-deno-worker.ts +74 -0
  105. package/src/url.test.ts +11 -0
  106. package/src/url.ts +113 -22
  107. package/tsdown.config.ts +12 -3
  108. /package/dist/tests/{langtag-LDBqlxHv.mjs → langtag-D8FWxjv8.mjs} +0 -0
  109. /package/dist/tests/{langtag-DgySESmk.cjs → langtag-a2-s9uyi.cjs} +0 -0
  110. /package/dist/tests/{link-CYszIegt.mjs → link-CHMtH2-k.mjs} +0 -0
  111. /package/dist/tests/{multibase-8zhYPa7o.cjs → multibase-BmWaK56H.cjs} +0 -0
  112. /package/dist/tests/{multibase-Ds75BvXs.mjs → multibase-D642Uv3S.mjs} +0 -0
  113. /package/dist/tests/{multicodec-ByS9XLsw.cjs → multicodec-B-_CSt1M.cjs} +0 -0
  114. /package/dist/tests/{multicodec-BBPZjRfg.mjs → multicodec-caWdG98t.mjs} +0 -0
@@ -0,0 +1,772 @@
1
+
2
+ import { getLogger } from "@logtape/logtape";
3
+ import dns from "node:dns/promises";
4
+ import { isIP } from "node:net";
5
+ //#region src/pin-grant.ts
6
+ const grants = /* @__PURE__ */ new WeakMap();
7
+ /**
8
+ * Issues a grant for the given URL's origin and addresses. This does not
9
+ * validate the addresses; callers validate them before issuing, and pinners
10
+ * validate them again right before connecting.
11
+ * @param url The URL whose origin the grant is bound to.
12
+ * @param addresses The addresses to connect to.
13
+ * @returns A new grant.
14
+ */
15
+ function issuePinGrant(url, addresses) {
16
+ const grant = Object.freeze(Object.create(null));
17
+ let hostname = url.hostname;
18
+ if (hostname.startsWith("[") && hostname.endsWith("]")) hostname = hostname.slice(1, -1);
19
+ const record = Object.freeze({
20
+ origin: url.origin,
21
+ hostname,
22
+ addresses: Object.freeze(addresses.map(({ address, family }) => Object.freeze({
23
+ address,
24
+ family
25
+ })))
26
+ });
27
+ grants.set(grant, {
28
+ record,
29
+ revoked: false
30
+ });
31
+ return grant;
32
+ }
33
+ /**
34
+ * Checks that the given grant was issued by {@link issuePinGrant}, has not
35
+ * been revoked, and was issued for the origin of the given URL.
36
+ * @param grant The grant to redeem.
37
+ * @param url The URL to connect to.
38
+ * @returns What the grant stands for.
39
+ * @throws {TypeError} If the grant cannot be used for the URL.
40
+ */
41
+ function redeemPinGrant(grant, url) {
42
+ const state = typeof grant === "object" && grant !== null ? grants.get(grant) : void 0;
43
+ if (state == null) throw new TypeError("Invalid pin grant.");
44
+ if (state.revoked) throw new TypeError("The pin grant has been revoked.");
45
+ if (url.origin !== state.record.origin) throw new TypeError(`The pin grant for ${state.record.origin} cannot be used for ${url.origin}.`);
46
+ return state.record;
47
+ }
48
+ /**
49
+ * Revokes the given grant so that it can no longer be redeemed.
50
+ * @param grant The grant to revoke.
51
+ */
52
+ function revokePinGrant(grant) {
53
+ const state = grants.get(grant);
54
+ if (state != null) state.revoked = true;
55
+ }
56
+ //#endregion
57
+ //#region src/url.ts
58
+ var UrlError = class extends Error {
59
+ /**
60
+ * The failure category. Defaults to `"disallowed"`.
61
+ * `"dns"` includes lookup errors and results with no usable IP addresses.
62
+ * @since 2.0.29
63
+ */
64
+ reason;
65
+ constructor(message, options) {
66
+ super(message, options);
67
+ this.name = "UrlError";
68
+ this.reason = options?.reason ?? "disallowed";
69
+ }
70
+ };
71
+ /**
72
+ * Validates a URL to prevent SSRF attacks.
73
+ *
74
+ * This function only checks the addresses that the hostname currently
75
+ * resolves to; it does not pin the connection to those addresses. A request
76
+ * made after this check resolves the hostname again, so this function alone
77
+ * does not prevent DNS rebinding.
78
+ */
79
+ async function validatePublicUrl(url) {
80
+ const { hostname, family } = parsePublicUrl(url);
81
+ if (family !== 0) return;
82
+ if ("Deno" in globalThis) {
83
+ if ((await Deno.permissions.query({ name: "net" })).state !== "granted") return;
84
+ }
85
+ if ("Bun" in globalThis) {
86
+ if (hostname === "example.com" || hostname.endsWith(".example.com")) return;
87
+ else if (hostname === "fedify-test.internal") throw new UrlError("Invalid or private address: fedify-test.internal");
88
+ }
89
+ await lookupPublicAddresses(hostname, lookupAllAddresses);
90
+ }
91
+ /**
92
+ * Resolves all addresses of the given hostname through `node:dns/promises`.
93
+ * The default `dns` object is looked up on every call so that tests can still
94
+ * stub `dns.lookup()`.
95
+ * @internal
96
+ */
97
+ function lookupAllAddresses(hostname) {
98
+ return dns.lookup(hostname, { all: true });
99
+ }
100
+ /**
101
+ * Checks the parts of a URL that can be validated without resolving it:
102
+ * the protocol, the `localhost` hostname, and IP literal hostnames.
103
+ * @throws {UrlError} If the URL is not allowed.
104
+ * @internal
105
+ */
106
+ function parsePublicUrl(url) {
107
+ const parsed = new URL(url);
108
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new UrlError(`Unsupported protocol: ${parsed.protocol}`);
109
+ let hostname = parsed.hostname;
110
+ if (hostname.startsWith("[") && hostname.endsWith("]")) hostname = hostname.slice(1, -1);
111
+ if (hostname === "localhost") throw new UrlError("Localhost is not allowed");
112
+ const family = isIP(hostname);
113
+ if (family !== 0) validatePublicIpAddress(hostname, family);
114
+ return {
115
+ url: parsed,
116
+ hostname,
117
+ family
118
+ };
119
+ }
120
+ /**
121
+ * Resolves the given hostname and checks that every returned IP address is
122
+ * public.
123
+ * @returns The IP addresses of the hostname, without non-IP entries.
124
+ * @throws {UrlError} If the lookup fails, returns no IP address, or returns
125
+ * any non-public address.
126
+ * @internal
127
+ */
128
+ async function lookupPublicAddresses(hostname, lookup) {
129
+ let addresses;
130
+ try {
131
+ addresses = await lookup(hostname);
132
+ } catch (error) {
133
+ throw new UrlError("DNS lookup failed", {
134
+ cause: error,
135
+ reason: "dns"
136
+ });
137
+ }
138
+ validateLookupAddresses(addresses);
139
+ return addresses.filter(({ address }) => isIP(address) !== 0).map(({ address }) => ({
140
+ address,
141
+ family: isIP(address)
142
+ }));
143
+ }
144
+ /**
145
+ * Checks that the given IP address is public. This is used right before
146
+ * connecting to an address that passed {@link lookupPublicAddresses}.
147
+ * @throws {UrlError} If the address is not a public IP address.
148
+ * @internal
149
+ */
150
+ function assertPublicAddress(address) {
151
+ const family = isIP(address.address);
152
+ if (family === 0 || family !== address.family) throw new UrlError(`Invalid or private address: ${address.address}`);
153
+ validatePublicIpAddress(address.address, family);
154
+ }
155
+ /**
156
+ * Validates the IP addresses returned by `node:dns.lookup()`.
157
+ *
158
+ * Cloudflare Workers' `node:dns` implementation currently maps every record
159
+ * in a DNS-over-HTTPS `Answer` array—including CNAME records—to a
160
+ * `LookupAddress`, even though Node.js specifies that the `address` field must
161
+ * contain an IPv4 or IPv6 literal. See:
162
+ * https://github.com/cloudflare/workerd/issues/6886
163
+ *
164
+ * Work around that bug by ignoring non-IP entries only when the lookup also
165
+ * returns at least one actual IP address. This remains fail-closed: a result
166
+ * containing no IP addresses is rejected, and every returned IP address is
167
+ * still validated and must be public. This workaround can be revisited once
168
+ * the Workerd issue is fixed in supported Cloudflare Workers runtimes.
169
+ *
170
+ * @internal
171
+ */
172
+ function validateLookupAddresses(addresses) {
173
+ let ipAddressCount = 0;
174
+ for (const { address } of addresses) {
175
+ const family = isIP(address);
176
+ if (family === 0) continue;
177
+ ipAddressCount++;
178
+ validatePublicIpAddress(address, family);
179
+ }
180
+ if (ipAddressCount === 0) throw new UrlError("DNS lookup did not return any IP address", { reason: "dns" });
181
+ }
182
+ function validatePublicIpAddress(address, family) {
183
+ if (family === 4 && isValidPublicIPv4Address(address) || family === 6 && isValidPublicIPv6Address(address)) return;
184
+ throw new UrlError(`Invalid or private address: ${address}`);
185
+ }
186
+ function isValidPublicIPv4Address(address) {
187
+ const parts = parseIPv4Address(address);
188
+ if (parts == null) return false;
189
+ const value = ipv4PartsToNumber(parts);
190
+ return !nonPublicIPv4Prefixes.some(({ base, prefix }) => matchesIPv4Prefix(value, base, prefix));
191
+ }
192
+ function isValidPublicIPv6Address(address) {
193
+ const words = parseIPv6Address(address);
194
+ if (words == null) return false;
195
+ if (nonPublicIPv6Prefixes.some(({ words: prefixWords, prefix }) => matchesIPv6Prefix(words, prefixWords, prefix))) return false;
196
+ for (const { extractIPv4, prefix, words: prefixWords } of ipv6WithIPv4Prefixes) {
197
+ if (!matchesIPv6Prefix(words, prefixWords, prefix)) continue;
198
+ const ipv4Address = extractIPv4(words);
199
+ if (ipv4Address != null && !isValidPublicIPv4Address(ipv4Address)) return false;
200
+ }
201
+ return true;
202
+ }
203
+ function expandIPv6Address(address) {
204
+ address = address.toLowerCase();
205
+ const ipv4Delimiter = address.lastIndexOf(":");
206
+ if (address.includes(".") && ipv4Delimiter >= 0) {
207
+ const ipv4Parts = parseIPv4Address(address.substring(ipv4Delimiter + 1));
208
+ if (ipv4Parts == null) return address;
209
+ const high = (ipv4Parts[0] << 8) + ipv4Parts[1];
210
+ const low = (ipv4Parts[2] << 8) + ipv4Parts[3];
211
+ address = address.substring(0, ipv4Delimiter + 1) + high.toString(16) + ":" + low.toString(16);
212
+ }
213
+ if (address === "::") return "0000:0000:0000:0000:0000:0000:0000:0000";
214
+ if (address.startsWith("::")) address = "0000" + address;
215
+ if (address.endsWith("::")) address = address + "0000";
216
+ address = address.replace("::", ":0000".repeat(8 - (address.match(/:/g) || []).length) + ":");
217
+ return address.split(":").map((part) => part.padStart(4, "0")).join(":");
218
+ }
219
+ const nonPublicIPv4Prefixes = [
220
+ ipv4Prefix("0.0.0.0/8", "RFC 6890"),
221
+ ipv4Prefix("10.0.0.0/8", "RFC 1918"),
222
+ ipv4Prefix("100.64.0.0/10", "RFC 6598"),
223
+ ipv4Prefix("127.0.0.0/8", "RFC 1122"),
224
+ ipv4Prefix("169.254.0.0/16", "RFC 3927"),
225
+ ipv4Prefix("172.16.0.0/12", "RFC 1918"),
226
+ ipv4Prefix("192.0.0.0/24", "RFC 6890"),
227
+ ipv4Prefix("192.0.2.0/24", "RFC 5737"),
228
+ ipv4Prefix("192.88.99.0/24", "RFC 7526"),
229
+ ipv4Prefix("192.168.0.0/16", "RFC 1918"),
230
+ ipv4Prefix("198.18.0.0/15", "RFC 2544"),
231
+ ipv4Prefix("198.51.100.0/24", "RFC 5737"),
232
+ ipv4Prefix("203.0.113.0/24", "RFC 5737"),
233
+ ipv4Prefix("224.0.0.0/4", "RFC 5771"),
234
+ ipv4Prefix("240.0.0.0/4", "RFC 1112")
235
+ ];
236
+ const nonPublicIPv6Prefixes = [
237
+ ipv6Prefix("::/16", "RFC 4291"),
238
+ ipv6Prefix("2001::/32", "RFC 4380"),
239
+ ipv6Prefix("2002::/16", "RFC 3056"),
240
+ ipv6Prefix("64:ff9b:1::/48", "RFC 8215"),
241
+ ipv6Prefix("fc00::/7", "RFC 4193"),
242
+ ipv6Prefix("fe80::/10", "RFC 4291"),
243
+ ipv6Prefix("ff00::/8", "RFC 4291")
244
+ ];
245
+ const ipv6WithIPv4Prefixes = [{
246
+ ...ipv6Prefix("64:ff9b::/96", "RFC 6052"),
247
+ extractIPv4: (words) => ipv4FromWords(words[6], words[7])
248
+ }];
249
+ function ipv4Prefix(cidr, rfc) {
250
+ const [address, prefixText] = cidr.split("/");
251
+ const prefix = parseInt(prefixText, 10);
252
+ const parts = parseIPv4Address(address);
253
+ if (parts == null || !Number.isInteger(prefix) || prefix < 0 || prefix > 32) throw new Error(`Invalid IPv4 prefix: ${cidr}`);
254
+ return {
255
+ cidr,
256
+ base: ipv4PartsToNumber(parts),
257
+ prefix,
258
+ rfc
259
+ };
260
+ }
261
+ function ipv6Prefix(cidr, rfc) {
262
+ const [address, prefixText] = cidr.split("/");
263
+ const prefix = parseInt(prefixText, 10);
264
+ const words = parseIPv6Address(address);
265
+ if (words == null || !Number.isInteger(prefix) || prefix < 0 || prefix > 128) throw new Error(`Invalid IPv6 prefix: ${cidr}`);
266
+ return {
267
+ cidr,
268
+ words,
269
+ prefix,
270
+ rfc
271
+ };
272
+ }
273
+ function parseIPv4Address(address) {
274
+ const parts = address.split(".").map((part) => {
275
+ if (!/^\d+$/.test(part)) return NaN;
276
+ return parseInt(part, 10);
277
+ });
278
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return null;
279
+ return parts;
280
+ }
281
+ function parseIPv6Address(address) {
282
+ const parts = expandIPv6Address(address).split(":");
283
+ if (parts.length !== 8) return null;
284
+ const words = parts.map((part) => {
285
+ if (!/^[0-9a-f]{1,4}$/i.test(part)) return NaN;
286
+ return parseInt(part, 16);
287
+ });
288
+ if (words.some((word) => !Number.isInteger(word) || word < 0 || word > 65535)) return null;
289
+ return words;
290
+ }
291
+ function ipv4PartsToNumber(parts) {
292
+ return parts[0] * 2 ** 24 + parts[1] * 2 ** 16 + parts[2] * 2 ** 8 + parts[3];
293
+ }
294
+ function ipv4FromWords(highWord, lowWord) {
295
+ return [
296
+ highWord >> 8,
297
+ highWord & 255,
298
+ lowWord >> 8,
299
+ lowWord & 255
300
+ ].join(".");
301
+ }
302
+ function matchesIPv4Prefix(address, prefixBase, prefixLength) {
303
+ const blockSize = 2 ** (32 - prefixLength);
304
+ return Math.floor(address / blockSize) === Math.floor(prefixBase / blockSize);
305
+ }
306
+ function matchesIPv6Prefix(address, prefixWords, prefixLength) {
307
+ let remaining = prefixLength;
308
+ for (let i = 0; i < 8 && remaining > 0; i++) if (remaining >= 16) {
309
+ if (address[i] !== prefixWords[i]) return false;
310
+ remaining -= 16;
311
+ } else {
312
+ const mask = 65535 << 16 - remaining & 65535;
313
+ if ((address[i] & mask) !== (prefixWords[i] & mask)) return false;
314
+ remaining = 0;
315
+ }
316
+ return true;
317
+ }
318
+ //#endregion
319
+ //#region src/pinners/bun.ts
320
+ const logger$1 = getLogger([
321
+ "fedify",
322
+ "runtime",
323
+ "fetch"
324
+ ]);
325
+ /**
326
+ * The first Bun version that honors `proxy: false` when proxy environment
327
+ * variables are set at startup. Earlier versions send pinned requests
328
+ * through the proxy, with the validated IP address as the target.
329
+ */
330
+ const PROXY_FALSE_MIN_VERSION = "1.4.3";
331
+ const PROXY_VARIABLES = [
332
+ "HTTP_PROXY",
333
+ "http_proxy",
334
+ "HTTPS_PROXY",
335
+ "https_proxy",
336
+ "ALL_PROXY",
337
+ "all_proxy"
338
+ ];
339
+ const FALLBACK_ERROR_CODES = new Set([
340
+ "ConnectionRefused",
341
+ "ECONNREFUSED",
342
+ "EHOSTUNREACH",
343
+ "ENETUNREACH",
344
+ "ETIMEDOUT"
345
+ ]);
346
+ /**
347
+ * Bun versions before 1.3.11 verify the server certificate against the `Host`
348
+ * header, including a non-default port, instead of `tls.serverName`, so
349
+ * pinned requests to HTTPS servers on non-default ports always fail the check
350
+ * there. A custom `checkServerIdentity` cannot stand in for it: these
351
+ * versions send the whole request before a failing custom check aborts it
352
+ * (and 1.3.10 even reuses the connection for the next request), so such
353
+ * requests are refused instead.
354
+ */
355
+ const HOST_HEADER_IDENTITY_RANGE = "<1.3.11";
356
+ /**
357
+ * Creates a pinner for Bun. Every request is sent to an IP literal URL with
358
+ * the original `Host` header, `tls.serverName` set to the original hostname
359
+ * (so that the certificate is still verified against it), and `proxy: false`.
360
+ *
361
+ * GET and HEAD requests fall back to the next address on transport errors
362
+ * raised before a response arrives. Other methods use only the first
363
+ * address, since a transport error does not guarantee that the request did
364
+ * not reach the server, and retrying it could deliver an activity twice.
365
+ * Together with the transport retries of `doubleKnock()`, a GET request is
366
+ * attempted at most twice per address. Note that Bun 1.4 also reports
367
+ * a connection reset after the request was sent as a `TypeError`, so GET and
368
+ * HEAD requests may be repeated against the next address in that case, which
369
+ * is acceptable for these idempotent methods.
370
+ *
371
+ * Bun versions before 1.3.11 verify certificates against the `Host` header,
372
+ * which includes a non-default port, and cannot safely check them against
373
+ * the original hostname in any other way, so requests to HTTPS servers on
374
+ * non-default ports fail there with a `TypeError` before connecting.
375
+ *
376
+ * Bun versions before 1.4.3 ignore `proxy: false` when proxy environment
377
+ * variables are set, so requests go through the proxy with the validated IP
378
+ * address as the target. In that case a warning is logged once.
379
+ * @param options The pinner options.
380
+ * @returns The pinner.
381
+ */
382
+ function createBunPinner({ verifyAddress }) {
383
+ let proxyWarningPending = ignoresProxyFalse() && hasProxyVariables();
384
+ return {
385
+ supports(url) {
386
+ return url.protocol === "http:" || url.protocol === "https:";
387
+ },
388
+ async fetch(grant, request, signal) {
389
+ const url = new URL(request.url);
390
+ const { hostname, addresses } = redeemPinGrant(grant, url);
391
+ if (proxyWarningPending) {
392
+ proxyWarningPending = false;
393
+ 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}.", {
394
+ version: getBun()?.version,
395
+ minVersion: PROXY_FALSE_MIN_VERSION,
396
+ url: "https://fedify.dev/manual/deploy#bun-behind-an-http-proxy"
397
+ });
398
+ }
399
+ const fallback = request.method === "GET" || request.method === "HEAD";
400
+ const candidates = fallback ? addresses : addresses.slice(0, 1);
401
+ const body = request.body == null ? null : await request.arrayBuffer();
402
+ let lastError = /* @__PURE__ */ new TypeError(`No address to connect to for ${url.host}.`);
403
+ for (const address of candidates) {
404
+ throwIfAborted(signal, request.signal);
405
+ verifyAddress(address);
406
+ const headers = new Headers(request.headers);
407
+ headers.set("Host", url.host);
408
+ const init = {
409
+ method: request.method,
410
+ headers,
411
+ body,
412
+ redirect: "manual",
413
+ signal: signal == null || signal === request.signal ? request.signal : anySignal(signal, request.signal),
414
+ proxy: false
415
+ };
416
+ if (url.protocol === "https:") init.tls = getTlsOptions(url, hostname);
417
+ try {
418
+ return await fetch(toAddressUrl(url, address), init);
419
+ } catch (error) {
420
+ throwIfAborted(signal, request.signal);
421
+ if (!fallback || !isFallbackError(error)) throw error;
422
+ lastError = error;
423
+ }
424
+ }
425
+ throw lastError;
426
+ },
427
+ release() {}
428
+ };
429
+ }
430
+ function getTlsOptions(url, hostname) {
431
+ const bun = getBun();
432
+ 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.`);
433
+ return isIP(hostname) === 0 ? { serverName: hostname } : {};
434
+ }
435
+ /**
436
+ * Combines two signals without `AbortSignal.any()`, which Bun 1.1.0 lacks.
437
+ */
438
+ function anySignal(a, b) {
439
+ if (a.aborted) return a;
440
+ if (b.aborted) return b;
441
+ const controller = new AbortController();
442
+ const abort = (event) => {
443
+ controller.abort(event.target.reason);
444
+ a.removeEventListener("abort", abort);
445
+ b.removeEventListener("abort", abort);
446
+ };
447
+ a.addEventListener("abort", abort);
448
+ b.addEventListener("abort", abort);
449
+ return controller.signal;
450
+ }
451
+ function toAddressUrl(url, address) {
452
+ const result = new URL(url);
453
+ result.hostname = address.family === 6 ? `[${address.address}]` : address.address;
454
+ return result;
455
+ }
456
+ function isFallbackError(error) {
457
+ if (error instanceof Error && error.name === "AbortError") return false;
458
+ if (error instanceof TypeError) return true;
459
+ const code = error?.code;
460
+ return typeof code === "string" && FALLBACK_ERROR_CODES.has(code);
461
+ }
462
+ function throwIfAborted(...signals) {
463
+ for (const signal of signals) signal?.throwIfAborted();
464
+ }
465
+ function getBun() {
466
+ return globalThis.Bun;
467
+ }
468
+ function ignoresProxyFalse() {
469
+ const bun = getBun();
470
+ if (bun == null) return false;
471
+ return !bun.semver.satisfies(bun.version, `>=${PROXY_FALSE_MIN_VERSION}`);
472
+ }
473
+ function hasProxyVariables() {
474
+ const env = globalThis.process?.env;
475
+ if (env == null) return false;
476
+ return PROXY_VARIABLES.some((name) => (env[name] ?? "") !== "");
477
+ }
478
+ //#endregion
479
+ //#region src/pinners/node.ts
480
+ /**
481
+ * Creates a pinner for Node.js. Every request is sent through the global
482
+ * `fetch()` with an undici `Agent` as the `dispatcher`. The agent's
483
+ * `connect.lookup` answers only with the addresses of live grants for
484
+ * the hostname, checking each of them again right before connecting, and
485
+ * fails when there are none, so a connection can never be made to an address
486
+ * that was not validated.
487
+ *
488
+ * The agent is shared by the requests of all grants, so keep-alive
489
+ * connections are reused. A pooled connection was made to an address of
490
+ * a grant that was valid when it was connected, so reusing it from another
491
+ * session of the same origin still reaches a validated address. Response
492
+ * bodies have to be consumed or cancelled for their connections to return to
493
+ * the pool, which sessions do when they are closed.
494
+ *
495
+ * Since the dispatcher is passed explicitly, neither proxy environment
496
+ * variables nor the global dispatcher (e.g., `NODE_USE_ENV_PROXY=1`) apply.
497
+ * @param options The pinner options.
498
+ * @returns The pinner.
499
+ */
500
+ function createNodePinner({ verifyAddress, undici }) {
501
+ const grants = /* @__PURE__ */ new Map();
502
+ function lookup(hostname, options, callback) {
503
+ let addresses;
504
+ try {
505
+ addresses = getGrantedAddresses(hostname, options.family);
506
+ } catch (error) {
507
+ callback(error, []);
508
+ return;
509
+ }
510
+ if (options.all) callback(null, addresses);
511
+ else callback(null, addresses[0].address, addresses[0].family);
512
+ }
513
+ function getGrantedAddresses(hostname, family) {
514
+ const addresses = /* @__PURE__ */ new Map();
515
+ for (const [grant, record] of grants.get(hostname) ?? []) {
516
+ try {
517
+ redeemPinGrant(grant, new URL(record.origin));
518
+ } catch {
519
+ continue;
520
+ }
521
+ for (const address of record.addresses) addresses.set(address.address, address);
522
+ }
523
+ const familyNumber = family === "IPv4" ? 4 : family === "IPv6" ? 6 : typeof family === "number" ? family : 0;
524
+ const result = [...addresses.values()].filter((address) => familyNumber === 0 || address.family === familyNumber);
525
+ if (result.length < 1) throw new UrlError(`No validated address to connect to: ${hostname}`);
526
+ for (const address of result) verifyAddress(address);
527
+ return result;
528
+ }
529
+ const agent = new undici.Agent({ connect: { lookup } });
530
+ return {
531
+ supports(url) {
532
+ return url.protocol === "http:" || url.protocol === "https:";
533
+ },
534
+ async fetch(grant, request, signal) {
535
+ const record = redeemPinGrant(grant, new URL(request.url));
536
+ if (isIP(record.hostname) !== 0) for (const address of record.addresses) verifyAddress(address);
537
+ let registered = grants.get(record.hostname);
538
+ if (registered == null) {
539
+ registered = /* @__PURE__ */ new Map();
540
+ grants.set(record.hostname, registered);
541
+ }
542
+ registered.set(grant, record);
543
+ return await fetch(request, {
544
+ redirect: "manual",
545
+ signal: signal == null || signal === request.signal ? request.signal : AbortSignal.any([signal, request.signal]),
546
+ dispatcher: agent
547
+ });
548
+ },
549
+ release(grant) {
550
+ for (const [hostname, registered] of grants) {
551
+ if (!registered.delete(grant)) continue;
552
+ if (registered.size < 1) grants.delete(hostname);
553
+ break;
554
+ }
555
+ }
556
+ };
557
+ }
558
+ //#endregion
559
+ //#region src/pinners/mod.ts
560
+ /**
561
+ * Detects the current runtime. Cloudflare Workers is checked first, since
562
+ * `process` can exist there with `nodejs_compat`, and Deno and Bun before
563
+ * Node.js, since both provide `process.versions.node`.
564
+ * @returns The current runtime.
565
+ */
566
+ function detectRuntime() {
567
+ const g = globalThis;
568
+ if (g.navigator?.userAgent === "Cloudflare-Workers") return "cfworkers";
569
+ if ("Deno" in globalThis) return "deno";
570
+ if ("Bun" in globalThis) return "bun";
571
+ if (g.process?.versions?.node != null) return "node";
572
+ return "other";
573
+ }
574
+ let runtimePinner;
575
+ /**
576
+ * Gets the production pinner of the current runtime, which rejects
577
+ * non-public addresses right before connecting. Deno and Cloudflare Workers
578
+ * have no pinner.
579
+ * @returns The pinner, or `null` if the runtime has none.
580
+ */
581
+ function getRuntimePinner() {
582
+ runtimePinner ??= createRuntimePinner(detectRuntime());
583
+ return runtimePinner;
584
+ }
585
+ async function createRuntimePinner(runtime) {
586
+ switch (runtime) {
587
+ case "bun": return createBunPinner({ verifyAddress: assertPublicAddress });
588
+ case "node": return createNodePinner({
589
+ verifyAddress: assertPublicAddress,
590
+ undici: await import("undici")
591
+ });
592
+ default: return null;
593
+ }
594
+ }
595
+ //#endregion
596
+ //#region src/public-fetch.ts
597
+ const logger = getLogger([
598
+ "fedify",
599
+ "runtime",
600
+ "fetch"
601
+ ]);
602
+ /**
603
+ * Creates {@link PublicFetch.openPublicFetch} and
604
+ * {@link PublicFetch.withPublicFetch} bound to the given pinner and lookup.
605
+ * This is exported only for tests; it is not exported from any entry point.
606
+ * @param dependencies The pinner and the default lookup function.
607
+ * @returns The functions.
608
+ */
609
+ function createPublicFetch(dependencies) {
610
+ async function openPublicFetch(url, options = {}) {
611
+ const { url: parsed, hostname, family } = parsePublicUrl(url);
612
+ if (parsed.username !== "" || parsed.password !== "") throw new UrlError("URLs with credentials are not allowed");
613
+ const lookup = options.lookup ?? dependencies.lookup;
614
+ let addresses;
615
+ if (family !== 0) addresses = [{
616
+ address: hostname,
617
+ family
618
+ }];
619
+ else if (lookup === lookupAllAddresses && !await canResolve()) return createSession(parsed, globalFetch);
620
+ else {
621
+ options.signal?.throwIfAborted();
622
+ addresses = await lookupPublicAddresses(hostname, lookup);
623
+ options.signal?.throwIfAborted();
624
+ }
625
+ const pinner = await dependencies.pinner();
626
+ if (pinner == null || !pinner.supports(parsed)) {
627
+ logUnpinned(parsed);
628
+ return createSession(parsed, globalFetch);
629
+ }
630
+ const grant = issuePinGrant(parsed, addresses);
631
+ return createSession(parsed, (input, init) => pinner.fetch(grant, new Request(input, init), init.signal ?? void 0), {
632
+ grant,
633
+ pinner
634
+ });
635
+ }
636
+ async function withPublicFetch(url, fn, options) {
637
+ const session = await openPublicFetch(url, options);
638
+ try {
639
+ const result = await fn(session.fetch);
640
+ if (result instanceof Response) throw new TypeError("withPublicFetch() callbacks must not return a Response, since its body is cancelled when the session is closed.");
641
+ return result;
642
+ } catch (error) {
643
+ logger.debug("Failed while fetching {url}; closing the session: {error}", {
644
+ url: session.url.href,
645
+ error
646
+ });
647
+ throw error;
648
+ } finally {
649
+ await session.close();
650
+ }
651
+ }
652
+ return {
653
+ openPublicFetch,
654
+ withPublicFetch
655
+ };
656
+ }
657
+ const runtimePublicFetch = createPublicFetch({
658
+ pinner: getRuntimePinner,
659
+ lookup: lookupAllAddresses
660
+ });
661
+ /**
662
+ * Validates the URL, resolves its hostname, checks that every resolved
663
+ * address is public, and opens a session that connects only to those
664
+ * addresses. Connections are pinned on Node.js and Bun. On other runtimes,
665
+ * the session uses the global `fetch()` after the check.
666
+ * @param url The URL to open a session for.
667
+ * @param options The options.
668
+ * @returns The session. It must be closed.
669
+ * @throws {UrlError} If the URL is not allowed, or its hostname cannot be
670
+ * resolved (with `reason: "dns"`).
671
+ */
672
+ const openPublicFetch = runtimePublicFetch.openPublicFetch;
673
+ /**
674
+ * Opens a session with {@link openPublicFetch}, runs the given function with
675
+ * its `fetch()`, and closes the session afterwards.
676
+ * @param url The URL to open a session for.
677
+ * @param fn The function to run. It must not return a `Response`, since
678
+ * the response bodies are cancelled when the session is closed.
679
+ * @param options The options.
680
+ * @returns The value returned by `fn`.
681
+ * @throws {UrlError} If the URL is not allowed.
682
+ * @throws {TypeError} If `fn` returns a `Response`.
683
+ */
684
+ const withPublicFetch = runtimePublicFetch.withPublicFetch;
685
+ /**
686
+ * Opens a session that neither validates nor pins addresses, for callers that
687
+ * allow private addresses. It has the same rules as {@link openPublicFetch}
688
+ * sessions otherwise: requests are limited to the URL's origin, redirects are
689
+ * never followed, and unconsumed response bodies are cancelled on close.
690
+ * It grants nothing beyond calling the global `fetch()` directly.
691
+ * @param url The URL to open a session for.
692
+ * @returns The session. It must be closed.
693
+ */
694
+ function openDirectFetch(url) {
695
+ return Promise.resolve(createSession(new URL(url), globalFetch));
696
+ }
697
+ /**
698
+ * Starts cancelling the body of a response without waiting for it to settle.
699
+ * The cancellation of a branch of a tee (e.g., a body cloned by a fetch mock)
700
+ * settles only after the other branch is cancelled too, per the Streams
701
+ * standard, so awaiting it could block forever. Failures are only logged.
702
+ */
703
+ function cancelResponseBody(response, url) {
704
+ response.body?.cancel().catch((error) => {
705
+ logger.debug("Failed to cancel a response body from {url}: {error}", {
706
+ url: url.href,
707
+ error
708
+ });
709
+ });
710
+ }
711
+ function globalFetch(input, init) {
712
+ return fetch(input, init);
713
+ }
714
+ function createSession(url, send, pin) {
715
+ const origin = url.origin;
716
+ const tracked = [];
717
+ let closed = false;
718
+ async function sessionFetch(input, init) {
719
+ if (closed) throw new TypeError("The fetch session is closed.");
720
+ const target = new URL(input instanceof Request ? input.url : input);
721
+ if (target.origin !== origin) throw new TypeError(`A fetch session for ${origin} cannot fetch ${target.origin}.`);
722
+ const response = await send(input, {
723
+ ...init,
724
+ redirect: "manual"
725
+ });
726
+ if (closed) {
727
+ cancelResponseBody(response, url);
728
+ throw new TypeError("The fetch session is closed.");
729
+ }
730
+ tracked.push(response);
731
+ return response;
732
+ }
733
+ async function close() {
734
+ if (closed) return;
735
+ closed = true;
736
+ for (const response of tracked) {
737
+ if (response.body == null || response.bodyUsed) continue;
738
+ if (response.body.locked) {
739
+ logger.debug("Cannot cancel a locked response body from {url}.", { url: url.href });
740
+ continue;
741
+ }
742
+ cancelResponseBody(response, url);
743
+ }
744
+ if (pin == null) return;
745
+ revokePinGrant(pin.grant);
746
+ await pin.pinner.release(pin.grant);
747
+ }
748
+ return {
749
+ get url() {
750
+ return new URL(url);
751
+ },
752
+ fetch: sessionFetch,
753
+ close
754
+ };
755
+ }
756
+ async function canResolve() {
757
+ if (!("Deno" in globalThis)) return true;
758
+ return (await Deno.permissions.query({ name: "net" })).state === "granted";
759
+ }
760
+ const loggedUnpinned = /* @__PURE__ */ new Set();
761
+ function logUnpinned(url) {
762
+ const runtime = detectRuntime();
763
+ const key = `${runtime} ${url.protocol}`;
764
+ if (loggedUnpinned.has(key)) return;
765
+ loggedUnpinned.add(key);
766
+ logger.debug("Outbound {protocol} connections are not pinned to validated addresses on {runtime}; the hostname is resolved again when connecting.", {
767
+ runtime,
768
+ protocol: url.protocol
769
+ });
770
+ }
771
+ //#endregion
772
+ export { expandIPv6Address as a, validatePublicUrl as c, UrlError as i, openPublicFetch as n, isValidPublicIPv4Address as o, withPublicFetch as r, isValidPublicIPv6Address as s, openDirectFetch as t };