@fedify/vocab-runtime 2.0.35-dev.2480 → 2.0.35

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 (108) 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 -253
  7. package/dist/mod.d.cts +5 -27
  8. package/dist/mod.d.ts +6 -27
  9. package/dist/mod.js +98 -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-s65I5CCa.mjs → body-ByUnLtuw.mjs} +1 -1
  15. package/dist/tests/{body-moFua5l6.cjs → body-Cul4-oB8.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/docloader.test.cjs +616 -1306
  19. package/dist/tests/docloader.test.mjs +562 -1271
  20. package/dist/tests/esm-4DuocLvD.cjs +1208 -0
  21. package/dist/tests/esm-CnLt0wAF.mjs +1225 -0
  22. package/dist/tests/internal/multicodec.test.cjs +1 -1
  23. package/dist/tests/internal/multicodec.test.mjs +1 -1
  24. package/dist/tests/key.test.cjs +2 -2
  25. package/dist/tests/key.test.mjs +2 -2
  26. package/dist/tests/langstr.test.cjs +1 -1
  27. package/dist/tests/langstr.test.mjs +1 -1
  28. package/dist/tests/langtag.test.cjs +1 -1
  29. package/dist/tests/langtag.test.mjs +1 -1
  30. package/dist/tests/link.test.cjs +1 -1
  31. package/dist/tests/link.test.mjs +1 -1
  32. package/dist/tests/multibase/multibase.test.cjs +1 -1
  33. package/dist/tests/multibase/multibase.test.mjs +1 -1
  34. package/dist/tests/node-BTPYk2h-.mjs +84 -0
  35. package/dist/tests/node-DWD76vPo.cjs +90 -0
  36. package/dist/tests/pin-grant-BAlKqSph.mjs +53 -0
  37. package/dist/tests/pin-grant-CU-o367k.cjs +70 -0
  38. package/dist/tests/pin-grant.test.cjs +88 -0
  39. package/dist/tests/pin-grant.test.d.cts +1 -0
  40. package/dist/tests/pin-grant.test.d.mts +1 -0
  41. package/dist/tests/pin-grant.test.mjs +88 -0
  42. package/dist/tests/pinners/bun.test.cjs +167 -0
  43. package/dist/tests/pinners/bun.test.d.cts +1 -0
  44. package/dist/tests/pinners/bun.test.d.mts +1 -0
  45. package/dist/tests/pinners/bun.test.mjs +167 -0
  46. package/dist/tests/pinners/node.test.cjs +269 -0
  47. package/dist/tests/pinners/node.test.d.cts +1 -0
  48. package/dist/tests/pinners/node.test.d.mts +1 -0
  49. package/dist/tests/pinners/node.test.mjs +268 -0
  50. package/dist/tests/pinners/pinners.test.cjs +197 -0
  51. package/dist/tests/pinners/pinners.test.d.cts +1 -0
  52. package/dist/tests/pinners/pinners.test.d.mts +1 -0
  53. package/dist/tests/pinners/pinners.test.mjs +197 -0
  54. package/dist/tests/pinners/testdata/node-child.cjs +135 -0
  55. package/dist/tests/pinners/testdata/node-child.d.cts +1 -0
  56. package/dist/tests/pinners/testdata/node-child.d.mts +1 -0
  57. package/dist/tests/pinners/testdata/node-child.mjs +134 -0
  58. package/dist/tests/pinners-BjE-YJLL.cjs +221 -0
  59. package/dist/tests/pinners-C0SoXz-S.mjs +203 -0
  60. package/dist/tests/public-fetch-BUSPlh1C.mjs +170 -0
  61. package/dist/tests/public-fetch-Ddjfxbwc.cjs +187 -0
  62. package/dist/tests/public-fetch.test.cjs +1074 -0
  63. package/dist/tests/public-fetch.test.d.cts +1 -0
  64. package/dist/tests/public-fetch.test.d.mts +1 -0
  65. package/dist/tests/public-fetch.test.mjs +1074 -0
  66. package/dist/tests/{request-BnwgFF6c.cjs → request-B7Iyskql.cjs} +1 -1
  67. package/dist/tests/{request-CZWDeBC-.mjs → request-pGToUa6Q.mjs} +1 -1
  68. package/dist/tests/request.test.cjs +1 -1
  69. package/dist/tests/request.test.mjs +1 -1
  70. package/dist/tests/support-EdBgVdNy.cjs +363 -0
  71. package/dist/tests/support-SnCB9BSR.mjs +272 -0
  72. package/dist/tests/{url-Qk1svKZU.cjs → url-DLuSj57U.cjs} +88 -12
  73. package/dist/tests/{url-DzlMS01z.mjs → url-DjsVF44Q.mjs} +65 -13
  74. package/dist/tests/url.test.cjs +4 -1
  75. package/dist/tests/url.test.mjs +4 -1
  76. package/package.json +13 -2
  77. package/src/docloader.test.ts +690 -31
  78. package/src/docloader.ts +174 -67
  79. package/src/internal.ts +13 -0
  80. package/src/pin-grant.test.ts +118 -0
  81. package/src/pin-grant.ts +99 -0
  82. package/src/pinners/bun.test.ts +278 -0
  83. package/src/pinners/bun.ts +223 -0
  84. package/src/pinners/mod.ts +59 -0
  85. package/src/pinners/node.test.ts +415 -0
  86. package/src/pinners/node.ts +144 -0
  87. package/src/pinners/pinners.test.ts +316 -0
  88. package/src/pinners/testdata/node-child.ts +147 -0
  89. package/src/pinners/testdata/proxy-child.ts +82 -0
  90. package/src/pinners/testdata/support.ts +343 -0
  91. package/src/pinners/testdata/tls-cert.pem +12 -0
  92. package/src/pinners/testdata/tls-child.ts +88 -0
  93. package/src/pinners/testdata/tls-key.pem +5 -0
  94. package/src/pinners/types.ts +48 -0
  95. package/src/public-fetch.test.ts +1286 -0
  96. package/src/public-fetch.ts +338 -0
  97. package/src/testdata/public-fetch-deno-worker.ts +74 -0
  98. package/src/url.test.ts +11 -0
  99. package/src/url.ts +113 -22
  100. package/tsdown.config.ts +12 -3
  101. /package/dist/tests/{langtag-Bm8oKhIO.cjs → langtag-B_fXk5oL.cjs} +0 -0
  102. /package/dist/tests/{langtag-QZZgy903.mjs → langtag-CwDxJ10m.mjs} +0 -0
  103. /package/dist/tests/{link-NUUWCdnK.mjs → link-CYszIegt.mjs} +0 -0
  104. /package/dist/tests/{link-FguCydMA.cjs → link-qDTmjPw_.cjs} +0 -0
  105. /package/dist/tests/{multibase-CnmModw0.cjs → multibase-BKJat02S.cjs} +0 -0
  106. /package/dist/tests/{multibase-DLBufb99.mjs → multibase-CNswrMoP.mjs} +0 -0
  107. /package/dist/tests/{multicodec-CxGVGa91.cjs → multicodec-B-_CSt1M.cjs} +0 -0
  108. /package/dist/tests/{multicodec-CyFp54fI.mjs → multicodec-CDEzQTyO.mjs} +0 -0
package/dist/mod.js CHANGED
@@ -1,9 +1,8 @@
1
1
 
2
+ import { a as expandIPv6Address, c as validatePublicUrl, i as UrlError, n as openPublicFetch, o as isValidPublicIPv4Address, s as isValidPublicIPv6Address, t as openDirectFetch } from "./public-fetch-Dfmc_Kfy.js";
2
3
  import { getLogger } from "@logtape/logtape";
3
4
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
4
5
  import process from "node:process";
5
- import dns from "node:dns/promises";
6
- import { isIP } from "node:net";
7
6
  import { Integer, Sequence } from "asn1js";
8
7
  import { decodeBase64, encodeBase64 } from "byte-encodings/base64";
9
8
  import { decodeBase64Url } from "byte-encodings/base64url";
@@ -4499,7 +4498,7 @@ const preloadedContexts = {
4499
4498
  //#endregion
4500
4499
  //#region deno.json
4501
4500
  var name = "@fedify/vocab-runtime";
4502
- var version = "2.0.35-dev.2480+2330a2e7";
4501
+ var version = "2.0.35";
4503
4502
  //#endregion
4504
4503
  //#region src/request.ts
4505
4504
  /**
@@ -4820,216 +4819,6 @@ var HttpHeaderLink = class HttpHeaderLink {
4820
4819
  }
4821
4820
  };
4822
4821
  //#endregion
4823
- //#region src/url.ts
4824
- var UrlError = class extends Error {
4825
- /**
4826
- * The failure category. Defaults to `"disallowed"`.
4827
- * `"dns"` includes lookup errors and results with no usable IP addresses.
4828
- * @since 2.0.29
4829
- */
4830
- reason;
4831
- constructor(message, options) {
4832
- super(message, options);
4833
- this.name = "UrlError";
4834
- this.reason = options?.reason ?? "disallowed";
4835
- }
4836
- };
4837
- /**
4838
- * Validates a URL to prevent SSRF attacks.
4839
- */
4840
- async function validatePublicUrl(url) {
4841
- const parsed = new URL(url);
4842
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new UrlError(`Unsupported protocol: ${parsed.protocol}`);
4843
- let hostname = parsed.hostname;
4844
- if (hostname.startsWith("[") && hostname.endsWith("]")) hostname = hostname.slice(1, -1);
4845
- if (hostname === "localhost") throw new UrlError("Localhost is not allowed");
4846
- const hostnameFamily = isIP(hostname);
4847
- if (hostnameFamily !== 0) {
4848
- validatePublicIpAddress(hostname, hostnameFamily);
4849
- return;
4850
- }
4851
- if ("Deno" in globalThis && !isIP(hostname)) {
4852
- if ((await Deno.permissions.query({ name: "net" })).state !== "granted") return;
4853
- }
4854
- if ("Bun" in globalThis) {
4855
- if (hostname === "example.com" || hostname.endsWith(".example.com")) return;
4856
- else if (hostname === "fedify-test.internal") throw new UrlError("Invalid or private address: fedify-test.internal");
4857
- }
4858
- let addresses;
4859
- try {
4860
- addresses = await dns.lookup(hostname, { all: true });
4861
- } catch (error) {
4862
- throw new UrlError("DNS lookup failed", {
4863
- cause: error,
4864
- reason: "dns"
4865
- });
4866
- }
4867
- validateLookupAddresses(addresses);
4868
- }
4869
- /**
4870
- * Validates the IP addresses returned by `node:dns.lookup()`.
4871
- *
4872
- * Cloudflare Workers' `node:dns` implementation currently maps every record
4873
- * in a DNS-over-HTTPS `Answer` array—including CNAME records—to a
4874
- * `LookupAddress`, even though Node.js specifies that the `address` field must
4875
- * contain an IPv4 or IPv6 literal. See:
4876
- * https://github.com/cloudflare/workerd/issues/6886
4877
- *
4878
- * Work around that bug by ignoring non-IP entries only when the lookup also
4879
- * returns at least one actual IP address. This remains fail-closed: a result
4880
- * containing no IP addresses is rejected, and every returned IP address is
4881
- * still validated and must be public. This workaround can be revisited once
4882
- * the Workerd issue is fixed in supported Cloudflare Workers runtimes.
4883
- *
4884
- * @internal
4885
- */
4886
- function validateLookupAddresses(addresses) {
4887
- let ipAddressCount = 0;
4888
- for (const { address } of addresses) {
4889
- const family = isIP(address);
4890
- if (family === 0) continue;
4891
- ipAddressCount++;
4892
- validatePublicIpAddress(address, family);
4893
- }
4894
- if (ipAddressCount === 0) throw new UrlError("DNS lookup did not return any IP address", { reason: "dns" });
4895
- }
4896
- function validatePublicIpAddress(address, family) {
4897
- if (family === 4 && isValidPublicIPv4Address(address) || family === 6 && isValidPublicIPv6Address(address)) return;
4898
- throw new UrlError(`Invalid or private address: ${address}`);
4899
- }
4900
- function isValidPublicIPv4Address(address) {
4901
- const parts = parseIPv4Address(address);
4902
- if (parts == null) return false;
4903
- const value = ipv4PartsToNumber(parts);
4904
- return !nonPublicIPv4Prefixes.some(({ base, prefix }) => matchesIPv4Prefix(value, base, prefix));
4905
- }
4906
- function isValidPublicIPv6Address(address) {
4907
- const words = parseIPv6Address(address);
4908
- if (words == null) return false;
4909
- if (nonPublicIPv6Prefixes.some(({ words: prefixWords, prefix }) => matchesIPv6Prefix(words, prefixWords, prefix))) return false;
4910
- for (const { extractIPv4, prefix, words: prefixWords } of ipv6WithIPv4Prefixes) {
4911
- if (!matchesIPv6Prefix(words, prefixWords, prefix)) continue;
4912
- const ipv4Address = extractIPv4(words);
4913
- if (ipv4Address != null && !isValidPublicIPv4Address(ipv4Address)) return false;
4914
- }
4915
- return true;
4916
- }
4917
- function expandIPv6Address(address) {
4918
- address = address.toLowerCase();
4919
- const ipv4Delimiter = address.lastIndexOf(":");
4920
- if (address.includes(".") && ipv4Delimiter >= 0) {
4921
- const ipv4Parts = parseIPv4Address(address.substring(ipv4Delimiter + 1));
4922
- if (ipv4Parts == null) return address;
4923
- const high = (ipv4Parts[0] << 8) + ipv4Parts[1];
4924
- const low = (ipv4Parts[2] << 8) + ipv4Parts[3];
4925
- address = address.substring(0, ipv4Delimiter + 1) + high.toString(16) + ":" + low.toString(16);
4926
- }
4927
- if (address === "::") return "0000:0000:0000:0000:0000:0000:0000:0000";
4928
- if (address.startsWith("::")) address = "0000" + address;
4929
- if (address.endsWith("::")) address = address + "0000";
4930
- address = address.replace("::", ":0000".repeat(8 - (address.match(/:/g) || []).length) + ":");
4931
- return address.split(":").map((part) => part.padStart(4, "0")).join(":");
4932
- }
4933
- const nonPublicIPv4Prefixes = [
4934
- ipv4Prefix("0.0.0.0/8", "RFC 6890"),
4935
- ipv4Prefix("10.0.0.0/8", "RFC 1918"),
4936
- ipv4Prefix("100.64.0.0/10", "RFC 6598"),
4937
- ipv4Prefix("127.0.0.0/8", "RFC 1122"),
4938
- ipv4Prefix("169.254.0.0/16", "RFC 3927"),
4939
- ipv4Prefix("172.16.0.0/12", "RFC 1918"),
4940
- ipv4Prefix("192.0.0.0/24", "RFC 6890"),
4941
- ipv4Prefix("192.0.2.0/24", "RFC 5737"),
4942
- ipv4Prefix("192.88.99.0/24", "RFC 7526"),
4943
- ipv4Prefix("192.168.0.0/16", "RFC 1918"),
4944
- ipv4Prefix("198.18.0.0/15", "RFC 2544"),
4945
- ipv4Prefix("198.51.100.0/24", "RFC 5737"),
4946
- ipv4Prefix("203.0.113.0/24", "RFC 5737"),
4947
- ipv4Prefix("224.0.0.0/4", "RFC 5771"),
4948
- ipv4Prefix("240.0.0.0/4", "RFC 1112")
4949
- ];
4950
- const nonPublicIPv6Prefixes = [
4951
- ipv6Prefix("::/16", "RFC 4291"),
4952
- ipv6Prefix("2001::/32", "RFC 4380"),
4953
- ipv6Prefix("2002::/16", "RFC 3056"),
4954
- ipv6Prefix("64:ff9b:1::/48", "RFC 8215"),
4955
- ipv6Prefix("fc00::/7", "RFC 4193"),
4956
- ipv6Prefix("fe80::/10", "RFC 4291"),
4957
- ipv6Prefix("ff00::/8", "RFC 4291")
4958
- ];
4959
- const ipv6WithIPv4Prefixes = [{
4960
- ...ipv6Prefix("64:ff9b::/96", "RFC 6052"),
4961
- extractIPv4: (words) => ipv4FromWords(words[6], words[7])
4962
- }];
4963
- function ipv4Prefix(cidr, rfc) {
4964
- const [address, prefixText] = cidr.split("/");
4965
- const prefix = parseInt(prefixText, 10);
4966
- const parts = parseIPv4Address(address);
4967
- if (parts == null || !Number.isInteger(prefix) || prefix < 0 || prefix > 32) throw new Error(`Invalid IPv4 prefix: ${cidr}`);
4968
- return {
4969
- cidr,
4970
- base: ipv4PartsToNumber(parts),
4971
- prefix,
4972
- rfc
4973
- };
4974
- }
4975
- function ipv6Prefix(cidr, rfc) {
4976
- const [address, prefixText] = cidr.split("/");
4977
- const prefix = parseInt(prefixText, 10);
4978
- const words = parseIPv6Address(address);
4979
- if (words == null || !Number.isInteger(prefix) || prefix < 0 || prefix > 128) throw new Error(`Invalid IPv6 prefix: ${cidr}`);
4980
- return {
4981
- cidr,
4982
- words,
4983
- prefix,
4984
- rfc
4985
- };
4986
- }
4987
- function parseIPv4Address(address) {
4988
- const parts = address.split(".").map((part) => {
4989
- if (!/^\d+$/.test(part)) return NaN;
4990
- return parseInt(part, 10);
4991
- });
4992
- if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return null;
4993
- return parts;
4994
- }
4995
- function parseIPv6Address(address) {
4996
- const parts = expandIPv6Address(address).split(":");
4997
- if (parts.length !== 8) return null;
4998
- const words = parts.map((part) => {
4999
- if (!/^[0-9a-f]{1,4}$/i.test(part)) return NaN;
5000
- return parseInt(part, 16);
5001
- });
5002
- if (words.some((word) => !Number.isInteger(word) || word < 0 || word > 65535)) return null;
5003
- return words;
5004
- }
5005
- function ipv4PartsToNumber(parts) {
5006
- return parts[0] * 2 ** 24 + parts[1] * 2 ** 16 + parts[2] * 2 ** 8 + parts[3];
5007
- }
5008
- function ipv4FromWords(highWord, lowWord) {
5009
- return [
5010
- highWord >> 8,
5011
- highWord & 255,
5012
- lowWord >> 8,
5013
- lowWord & 255
5014
- ].join(".");
5015
- }
5016
- function matchesIPv4Prefix(address, prefixBase, prefixLength) {
5017
- const blockSize = 2 ** (32 - prefixLength);
5018
- return Math.floor(address / blockSize) === Math.floor(prefixBase / blockSize);
5019
- }
5020
- function matchesIPv6Prefix(address, prefixWords, prefixLength) {
5021
- let remaining = prefixLength;
5022
- for (let i = 0; i < 8 && remaining > 0; i++) if (remaining >= 16) {
5023
- if (address[i] !== prefixWords[i]) return false;
5024
- remaining -= 16;
5025
- } else {
5026
- const mask = 65535 << 16 - remaining & 65535;
5027
- if ((address[i] & mask) !== (prefixWords[i] & mask)) return false;
5028
- remaining = 0;
5029
- }
5030
- return true;
5031
- }
5032
- //#endregion
5033
4822
  //#region src/docloader.ts
5034
4823
  const logger = getLogger([
5035
4824
  "fedify",
@@ -5041,13 +4830,47 @@ const DEFAULT_MAX_REDIRECTION = 20;
5041
4830
  * Gets a {@link RemoteDocument} from the given response.
5042
4831
  * @param url The URL of the document to load.
5043
4832
  * @param response The response to get the document from.
5044
- * @param fetch The function to fetch the document.
4833
+ * @param fetch The function to fetch the document. It is called with the URL
4834
+ * of an alternate document, if any, after the response body has
4835
+ * been either read or its cancellation has been started.
5045
4836
  * @returns The loaded remote document.
5046
4837
  * @throws {FetchError} If the response is not OK.
5047
4838
  * @internal
5048
4839
  */
5049
4840
  async function getRemoteDocument(url, response, fetch) {
5050
- const documentUrl = response.url === "" ? url : response.url;
4841
+ const result = await parseRemoteDocument(url, response);
4842
+ if ("alternate" in result) return await fetch(result.alternate);
4843
+ return result.document;
4844
+ }
4845
+ /**
4846
+ * Starts cancelling the body of a response without waiting for it to settle.
4847
+ * The cancellation of a branch of a tee (e.g., a body cloned by a fetch mock)
4848
+ * settles only after the other branch is cancelled too, per the Streams
4849
+ * standard, so awaiting it could block forever. Failures are only logged.
4850
+ * @param response The response whose body is cancelled.
4851
+ * @param url The URL of the response, for logging.
4852
+ */
4853
+ function cancelResponseBody(response, url) {
4854
+ response.body?.cancel().catch((error) => {
4855
+ logger.debug("Failed to cancel the response body from {url}: {error}", {
4856
+ url,
4857
+ error
4858
+ });
4859
+ });
4860
+ }
4861
+ /**
4862
+ * Gets a {@link RemoteDocument} from the given response, or the URL of an
4863
+ * alternate document to load instead. When an alternate document is found,
4864
+ * the response body has been either read or its cancellation has been started
4865
+ * (without waiting for it), so that the alternate document can be loaded after
4866
+ * the response's session is closed.
4867
+ * @param url The URL of the document to load.
4868
+ * @param response The response to get the document from.
4869
+ * @returns The loaded remote document, or the alternate document URL.
4870
+ * @throws {FetchError} If the response is not OK.
4871
+ */
4872
+ async function parseRemoteDocument(url, response) {
4873
+ const documentUrl = url;
5051
4874
  const docUrl = new URL(documentUrl);
5052
4875
  if (!response.ok) {
5053
4876
  logger.error("Failed to fetch document: {status} {url} {headers}", {
@@ -5084,7 +4907,8 @@ async function getRemoteDocument(url, response, fetch) {
5084
4907
  alternateUrl: altUri.href,
5085
4908
  url: documentUrl
5086
4909
  });
5087
- return await fetch(altUri.href);
4910
+ cancelResponseBody(response, documentUrl);
4911
+ return { alternate: altUri.href };
5088
4912
  }
5089
4913
  }
5090
4914
  }
@@ -5109,7 +4933,7 @@ async function getRemoteDocument(url, response, fetch) {
5109
4933
  alternateUrl: attribs.href,
5110
4934
  url: documentUrl
5111
4935
  });
5112
- return await fetch(new URL(attribs.href, docUrl).href);
4936
+ return { alternate: new URL(attribs.href, docUrl).href };
5113
4937
  }
5114
4938
  }
5115
4939
  document = JSON.parse(html);
@@ -5119,11 +4943,11 @@ async function getRemoteDocument(url, response, fetch) {
5119
4943
  url: documentUrl,
5120
4944
  headers: Object.fromEntries(response.headers.entries())
5121
4945
  });
5122
- return {
4946
+ return { document: {
5123
4947
  contextUrl,
5124
4948
  document,
5125
4949
  documentUrl
5126
- };
4950
+ } };
5127
4951
  }
5128
4952
  /**
5129
4953
  * Creates a JSON-LD document loader that utilizes the browser's `fetch` API.
@@ -5149,8 +4973,53 @@ async function getRemoteDocument(url, response, fetch) {
5149
4973
  * @returns The document loader.
5150
4974
  * @since 1.3.0
5151
4975
  */
5152
- function getDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAgent } = {}) {
4976
+ function getDocumentLoader(options = {}) {
4977
+ return createDocumentLoader(options);
4978
+ }
4979
+ /**
4980
+ * The implementation of {@link getDocumentLoader}, with injectable
4981
+ * dependencies. This is not exported from any entry point.
4982
+ * @param options Options for the document loader.
4983
+ * @param deps The dependencies.
4984
+ * @returns The document loader.
4985
+ */
4986
+ function createDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAgent } = {}, deps = {}) {
5153
4987
  const tracer = trace.getTracerProvider().getTracer(name, version);
4988
+ async function openHop(url, signal) {
4989
+ try {
4990
+ if (deps.openHop != null) return await deps.openHop(url);
4991
+ return allowPrivateAddress ? await openDirectFetch(url) : await openPublicFetch(url, { signal });
4992
+ } catch (error) {
4993
+ if (error instanceof UrlError) if (error.reason === "dns") logger.debug("DNS lookup failed for {url}", {
4994
+ url,
4995
+ error
4996
+ });
4997
+ else logger.error("Disallowed private URL: {url}", {
4998
+ url,
4999
+ error
5000
+ });
5001
+ throw error;
5002
+ }
5003
+ }
5004
+ async function fetchHop(session, url, span, options) {
5005
+ try {
5006
+ const request = createActivityPubRequest(url, { userAgent });
5007
+ logRequest(logger, request);
5008
+ const response = await session.fetch(request, {
5009
+ redirect: "manual",
5010
+ signal: options?.signal
5011
+ });
5012
+ span.setAttribute("http.response.status_code", response.status);
5013
+ if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
5014
+ const location = response.headers.get("Location");
5015
+ cancelResponseBody(response, url);
5016
+ return { location };
5017
+ }
5018
+ return await parseRemoteDocument(url, response);
5019
+ } finally {
5020
+ await session.close();
5021
+ }
5022
+ }
5154
5023
  async function load(url, options, redirected = 0, visited = /* @__PURE__ */ new Set()) {
5155
5024
  options?.signal?.throwIfAborted();
5156
5025
  const parsedUrl = new URL(url);
@@ -5165,33 +5034,15 @@ function getDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAge
5165
5034
  documentUrl: currentUrl
5166
5035
  };
5167
5036
  }
5168
- if (!allowPrivateAddress) try {
5169
- await validatePublicUrl(currentUrl);
5170
- } catch (error) {
5171
- if (error instanceof UrlError) if (error.reason === "dns") logger.debug("DNS lookup failed for {url}", {
5172
- url: currentUrl,
5173
- error
5174
- });
5175
- else logger.error("Disallowed private URL: {url}", {
5176
- url: currentUrl,
5177
- error
5178
- });
5179
- throw error;
5180
- }
5037
+ const session = await openHop(currentUrl, options?.signal);
5181
5038
  visited.add(currentUrl);
5182
5039
  return await tracer.startActiveSpan("activitypub.fetch_document", {
5183
5040
  kind: SpanKind.CLIENT,
5184
5041
  attributes: { "url.full": currentUrl }
5185
5042
  }, async (span) => {
5186
5043
  try {
5187
- const request = createActivityPubRequest(currentUrl, { userAgent });
5188
- logRequest(logger, request);
5189
- const response = await fetch(request, {
5190
- redirect: "manual",
5191
- signal: options?.signal
5192
- });
5193
- span.setAttribute("http.response.status_code", response.status);
5194
- if (response.status >= 300 && response.status < 400 && response.headers.has("Location")) {
5044
+ const outcome = await fetchHop(session, currentUrl, span, options);
5045
+ if ("location" in outcome) {
5195
5046
  if (redirected >= DEFAULT_MAX_REDIRECTION) {
5196
5047
  logger.error("Too many redirections ({redirections}) while fetching document.", {
5197
5048
  redirections: redirected + 1,
@@ -5199,7 +5050,7 @@ function getDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAge
5199
5050
  });
5200
5051
  throw new FetchError(currentUrl, `Too many redirections (${redirected + 1})`);
5201
5052
  }
5202
- const redirectUrl = new URL(response.headers.get("Location"), response.url === "" ? currentUrl : response.url).href;
5053
+ const redirectUrl = new URL(outcome.location, currentUrl).href;
5203
5054
  span.setAttribute("http.redirect.url", redirectUrl);
5204
5055
  if (visited.has(redirectUrl)) {
5205
5056
  logger.error("Detected a redirect loop while fetching document: {url} -> {redirectUrl}", {
@@ -5210,12 +5061,14 @@ function getDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAge
5210
5061
  }
5211
5062
  return await load(redirectUrl, options, redirected + 1, visited);
5212
5063
  }
5213
- const result = await getRemoteDocument(currentUrl, response, async (alternateUrl) => {
5064
+ let result;
5065
+ if ("alternate" in outcome) {
5066
+ const alternateUrl = outcome.alternate;
5214
5067
  options?.signal?.throwIfAborted();
5215
5068
  if (redirected >= DEFAULT_MAX_REDIRECTION) throw new FetchError(currentUrl, `Too many redirections (${redirected + 1})`);
5216
5069
  if (visited.has(alternateUrl)) throw new FetchError(currentUrl, `Redirect loop detected: ${alternateUrl}`);
5217
- return await load(alternateUrl, options, redirected + 1, visited);
5218
- });
5070
+ result = await load(alternateUrl, options, redirected + 1, visited);
5071
+ } else result = outcome.document;
5219
5072
  span.setAttribute("docloader.document_url", result.documentUrl);
5220
5073
  if (result.contextUrl != null) span.setAttribute("docloader.context_url", result.contextUrl);
5221
5074
  return result;
@@ -0,0 +1,143 @@
1
+ /// <reference lib="esnext.temporal" />
2
+ //#region src/url.d.ts
3
+ /**
4
+ * An address returned by a DNS lookup. It has the same shape as
5
+ * `ResolvedAddress` of `node:dns`, without depending on its type declarations.
6
+ * @internal
7
+ */
8
+ interface ResolvedAddress {
9
+ /** An IPv4 or IPv6 address. */
10
+ readonly address: string;
11
+ /** The IP family of the address: `4` or `6`. */
12
+ readonly family: number;
13
+ }
14
+ declare class UrlError extends Error {
15
+ /**
16
+ * The failure category. Defaults to `"disallowed"`.
17
+ * `"dns"` includes lookup errors and results with no usable IP addresses.
18
+ * @since 2.0.29
19
+ */
20
+ readonly reason: "dns" | "disallowed";
21
+ constructor(message: string, options?: {
22
+ cause?: unknown;
23
+ reason?: "dns" | "disallowed";
24
+ });
25
+ }
26
+ /**
27
+ * Validates a URL to prevent SSRF attacks.
28
+ *
29
+ * This function only checks the addresses that the hostname currently
30
+ * resolves to; it does not pin the connection to those addresses. A request
31
+ * made after this check resolves the hostname again, so this function alone
32
+ * does not prevent DNS rebinding.
33
+ */
34
+ declare function validatePublicUrl(url: string): Promise<void>;
35
+ declare function isValidPublicIPv4Address(address: string): boolean;
36
+ declare function isValidPublicIPv6Address(address: string): boolean;
37
+ declare function expandIPv6Address(address: string): string;
38
+ //#endregion
39
+ //#region src/public-fetch.d.ts
40
+ /**
41
+ * Options for {@link openPublicFetch} and {@link withPublicFetch}.
42
+ */
43
+ interface PublicFetchOptions {
44
+ /**
45
+ * An `AbortSignal` for cancelling the DNS lookup.
46
+ */
47
+ readonly signal?: AbortSignal;
48
+ /**
49
+ * A function that resolves all addresses of a hostname, used instead of
50
+ * `node:dns.lookup()`. The addresses it returns are validated in the same
51
+ * way as the default lookup's.
52
+ */
53
+ readonly lookup?: (hostname: string) => Promise<readonly ResolvedAddress[]>;
54
+ }
55
+ /**
56
+ * A session for fetching resources from a single origin. Its `fetch()`
57
+ * connects only to the addresses validated when the session was opened, on
58
+ * runtimes that support it.
59
+ */
60
+ interface PublicFetchSession {
61
+ /**
62
+ * A copy of the URL the session was opened for.
63
+ */
64
+ readonly url: URL;
65
+ /**
66
+ * Fetches a resource from the session's origin. Redirects are never
67
+ * followed; the redirect mode is always `"manual"`.
68
+ * @throws {TypeError} If the input's origin differs from the session's, or
69
+ * if the session is closed.
70
+ */
71
+ fetch(input: Request | URL | string, init?: RequestInit): Promise<Response>;
72
+ /**
73
+ * Closes the session. The cancellation of response bodies that have been
74
+ * neither consumed nor cancelled is started (without waiting for it), and
75
+ * the session can no longer fetch. Calling this more than once has no
76
+ * effect.
77
+ */
78
+ close(): Promise<void>;
79
+ }
80
+ /**
81
+ * The functions created by {@link createPublicFetch}.
82
+ */
83
+ interface PublicFetch {
84
+ /**
85
+ * Validates the URL, resolves its hostname, checks that every resolved
86
+ * address is public, and opens a session that connects only to those
87
+ * addresses.
88
+ * @param url The URL to open a session for.
89
+ * @param options The options.
90
+ * @returns The session. It must be closed.
91
+ * @throws {UrlError} If the URL is not allowed, or its hostname cannot be
92
+ * resolved (with `reason: "dns"`).
93
+ */
94
+ openPublicFetch(url: URL | string, options?: PublicFetchOptions): Promise<PublicFetchSession>;
95
+ /**
96
+ * Opens a session with {@link PublicFetch.openPublicFetch}, runs the given
97
+ * function with its `fetch()`, and closes the session afterwards.
98
+ * @param url The URL to open a session for.
99
+ * @param fn The function to run. It must not return a `Response`, since
100
+ * the response bodies are cancelled when the session is closed.
101
+ * @param options The options.
102
+ * @returns The value returned by `fn`.
103
+ * @throws {UrlError} If the URL is not allowed.
104
+ * @throws {TypeError} If `fn` returns a `Response`.
105
+ */
106
+ withPublicFetch<T>(url: URL | string, fn: (fetch: PublicFetchSession["fetch"]) => Promise<T>, options?: PublicFetchOptions): Promise<T>;
107
+ }
108
+ /**
109
+ * Validates the URL, resolves its hostname, checks that every resolved
110
+ * address is public, and opens a session that connects only to those
111
+ * addresses. Connections are pinned on Node.js and Bun. On other runtimes,
112
+ * the session uses the global `fetch()` after the check.
113
+ * @param url The URL to open a session for.
114
+ * @param options The options.
115
+ * @returns The session. It must be closed.
116
+ * @throws {UrlError} If the URL is not allowed, or its hostname cannot be
117
+ * resolved (with `reason: "dns"`).
118
+ */
119
+ declare const openPublicFetch: PublicFetch["openPublicFetch"];
120
+ /**
121
+ * Opens a session with {@link openPublicFetch}, runs the given function with
122
+ * its `fetch()`, and closes the session afterwards.
123
+ * @param url The URL to open a session for.
124
+ * @param fn The function to run. It must not return a `Response`, since
125
+ * the response bodies are cancelled when the session is closed.
126
+ * @param options The options.
127
+ * @returns The value returned by `fn`.
128
+ * @throws {UrlError} If the URL is not allowed.
129
+ * @throws {TypeError} If `fn` returns a `Response`.
130
+ */
131
+ declare const withPublicFetch: PublicFetch["withPublicFetch"];
132
+ /**
133
+ * Opens a session that neither validates nor pins addresses, for callers that
134
+ * allow private addresses. It has the same rules as {@link openPublicFetch}
135
+ * sessions otherwise: requests are limited to the URL's origin, redirects are
136
+ * never followed, and unconsumed response bodies are cancelled on close.
137
+ * It grants nothing beyond calling the global `fetch()` directly.
138
+ * @param url The URL to open a session for.
139
+ * @returns The session. It must be closed.
140
+ */
141
+ declare function openDirectFetch(url: URL | string): Promise<PublicFetchSession>;
142
+ //#endregion
143
+ export { withPublicFetch as a, isValidPublicIPv4Address as c, openPublicFetch as i, isValidPublicIPv6Address as l, PublicFetchSession as n, UrlError as o, openDirectFetch as r, expandIPv6Address as s, PublicFetchOptions as t, validatePublicUrl as u };