@fedify/relay 2.1.23 → 2.1.25

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,7 +1,7 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as exportSpki, r as getDocumentLoader, t as isRelayFollowerData } from "./types-B1sgbiQi.js";
4
+ import { n as exportSpki, r as getDocumentLoader, t as isRelayFollowerData } from "./types-tCNkKDi5.js";
5
5
  import { MemoryKvStore, signRequest } from "@fedify/fedify";
6
6
  import { createRelay } from "@fedify/relay";
7
7
  import { Accept, Announce, Create, Delete, Follow, Move, Note, Person, Undo, Update } from "@fedify/vocab";
@@ -1,7 +1,7 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as exportSpki, r as getDocumentLoader, t as isRelayFollowerData } from "./types-B1sgbiQi.js";
4
+ import { n as exportSpki, r as getDocumentLoader, t as isRelayFollowerData } from "./types-tCNkKDi5.js";
5
5
  import { MemoryKvStore, signRequest } from "@fedify/fedify";
6
6
  import { createRelay } from "@fedify/relay";
7
7
  import { Create, Delete, Follow, Move, Note, Person, Undo, Update } from "@fedify/vocab";
@@ -4,7 +4,7 @@ globalThis.addEventListener = () => {};
4
4
  import { createRequire } from "node:module";
5
5
  import { getLogger } from "@logtape/logtape";
6
6
  import process$1 from "node:process";
7
- import { lookup } from "node:dns/promises";
7
+ import dns from "node:dns/promises";
8
8
  import { isIP } from "node:net";
9
9
  //#region \0rolldown/runtime.js
10
10
  var __create = Object.create;
@@ -21815,6 +21815,28 @@ var fep_5711_default = { "@context": {
21815
21815
  "@type": "@id"
21816
21816
  }
21817
21817
  } };
21818
+ var fep_7aa9_default = { "@context": {
21819
+ "FeaturedCollection": "https://w3id.org/fep/7aa9#FeaturedCollection",
21820
+ "FeaturedItem": "https://w3id.org/fep/7aa9#FeaturedItem",
21821
+ "FeatureRequest": "https://w3id.org/fep/7aa9#FeatureRequest",
21822
+ "FeatureAuthorization": "https://w3id.org/fep/7aa9#FeatureAuthorization",
21823
+ "topic": {
21824
+ "@id": "https://w3id.org/fep/7aa9#topic",
21825
+ "@type": "@id"
21826
+ },
21827
+ "featuredObject": {
21828
+ "@id": "https://w3id.org/fep/7aa9#featuredObject",
21829
+ "@type": "@id"
21830
+ },
21831
+ "canFeature": {
21832
+ "@id": "https://w3id.org/fep/7aa9#canFeature",
21833
+ "@type": "@id"
21834
+ },
21835
+ "featureAuthorization": {
21836
+ "@id": "https://w3id.org/fep/7aa9#featureAuthorization",
21837
+ "@type": "@id"
21838
+ }
21839
+ } };
21818
21840
  var fep_ef61_default = { "@context": {
21819
21841
  "gateways": {
21820
21842
  "@id": "https://w3id.org/fep/ef61/gateways",
@@ -25707,12 +25729,153 @@ const preloadedContexts = {
25707
25729
  "https://w3id.org/fep/5711": fep_5711_default,
25708
25730
  "https://www.w3.org/ns/cid/v1": cid_v1_default,
25709
25731
  "https://w3id.org/fep/ef61": fep_ef61_default,
25732
+ "https://w3id.org/fep/7aa9": fep_7aa9_default,
25710
25733
  "https://join-lemmy.org/context.json": join_lemmy_default,
25711
25734
  "http://joinmastodon.org/ns": joinmastodon_default,
25712
25735
  "https://purl.archive.org/miscellany": miscellany_default
25713
25736
  };
25714
25737
  var name = "@fedify/vocab-runtime";
25715
- var version = "2.1.23";
25738
+ var version = "2.1.25";
25739
+ /**
25740
+ * Error thrown when fetching a JSON-LD document failed.
25741
+ */
25742
+ var FetchError = class extends Error {
25743
+ /**
25744
+ * The URL that failed to fetch.
25745
+ */
25746
+ url;
25747
+ /**
25748
+ * The HTTP response that failed, if available.
25749
+ */
25750
+ response;
25751
+ /**
25752
+ * Constructs a new `FetchError`.
25753
+ *
25754
+ * @param url The URL that failed to fetch.
25755
+ * @param message Error message.
25756
+ * @param response The failed HTTP response, if available.
25757
+ */
25758
+ constructor(url, message, response) {
25759
+ super(message == null ? url.toString() : `${url}: ${message}`);
25760
+ this.name = "FetchError";
25761
+ this.url = typeof url === "string" ? new URL(url) : url;
25762
+ this.response = response;
25763
+ }
25764
+ };
25765
+ /**
25766
+ * Creates a request for the given URL.
25767
+ * @param url The URL to create the request for.
25768
+ * @param options The options for the request.
25769
+ * @returns The created request.
25770
+ * @internal
25771
+ */
25772
+ function createActivityPubRequest(url, options = {}) {
25773
+ return new Request(url, {
25774
+ headers: {
25775
+ Accept: "application/activity+json, application/ld+json",
25776
+ "User-Agent": typeof options.userAgent === "string" ? options.userAgent : getUserAgent(options.userAgent)
25777
+ },
25778
+ redirect: "manual"
25779
+ });
25780
+ }
25781
+ /**
25782
+ * Gets the user agent string for the given application and URL.
25783
+ * @param options The options for making the user agent string.
25784
+ * @returns The user agent string.
25785
+ * @since 1.3.0
25786
+ */
25787
+ function getUserAgent({ software, url } = {}) {
25788
+ const fedify = `Fedify/${version}`;
25789
+ const runtime = globalThis.Deno?.version?.deno != null ? `Deno/${Deno.version.deno}` : globalThis.process?.versions?.bun != null ? `Bun/${process$1.versions.bun}` : "navigator" in globalThis && navigator.userAgent === "Cloudflare-Workers" ? navigator.userAgent : globalThis.process?.versions?.node != null ? `Node.js/${process$1.versions.node}` : null;
25790
+ const userAgent = software == null ? [fedify] : [software, fedify];
25791
+ if (runtime != null) userAgent.push(runtime);
25792
+ if (url != null) userAgent.push(`+${url.toString()}`);
25793
+ return `${userAgent.shift()} (${userAgent.join("; ")})`;
25794
+ }
25795
+ /**
25796
+ * Logs the request.
25797
+ * @param request The request to log.
25798
+ * @internal
25799
+ */
25800
+ function logRequest(logger, request) {
25801
+ logger.debug("Fetching document: {method} {url} {headers}", {
25802
+ method: request.method,
25803
+ url: request.url,
25804
+ headers: Object.fromEntries(request.headers.entries())
25805
+ });
25806
+ }
25807
+ /** Decoded JSON body limit: 16 MiB. @internal */
25808
+ const MAX_BODY_SIZE = 16 * 1024 * 1024;
25809
+ /** A body exceeded the byte limit. @internal */
25810
+ var BodyTooLargeError = class extends FetchError {
25811
+ /** Creates an error for a body exceeding the given limit. */
25812
+ constructor(url, maxBytes) {
25813
+ super(url, `Body exceeds the limit of ${maxBytes} bytes`);
25814
+ this.name = "BodyTooLargeError";
25815
+ }
25816
+ };
25817
+ /** Validates a finite, positive byte limit. @internal */
25818
+ function validateBodySizeLimit(maxBytes) {
25819
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError("The body size limit must be a positive safe integer.");
25820
+ }
25821
+ /**
25822
+ * Reads UTF-8 text while limiting bytes received from the body stream.
25823
+ * Fetch responses are already decompressed, so the stream count is authoritative.
25824
+ * @param message The response or request to read.
25825
+ * @param maxBytes The maximum number of decoded bytes to read.
25826
+ * @param url The URL to include in errors and logs.
25827
+ * @returns The decoded body text.
25828
+ * @throws {BodyTooLargeError} If the body exceeds the limit.
25829
+ * @internal
25830
+ */
25831
+ async function readBoundedText(message, maxBytes, url) {
25832
+ validateBodySizeLimit(maxBytes);
25833
+ const reader = message.body?.getReader();
25834
+ const tooLarge = () => {
25835
+ getLogger([
25836
+ "fedify",
25837
+ "runtime",
25838
+ "body"
25839
+ ]).warn("Body from {url} exceeds the limit of {maxBytes} bytes.", {
25840
+ url: url.toString(),
25841
+ maxBytes
25842
+ });
25843
+ throw new BodyTooLargeError(url, maxBytes);
25844
+ };
25845
+ try {
25846
+ const length = message.headers.get("Content-Length");
25847
+ const encoding = message.headers.get("Content-Encoding");
25848
+ if ((encoding == null || encoding.toLowerCase() === "identity") && length != null && /^\d+$/.test(length) && Number(length) > maxBytes) tooLarge();
25849
+ if (reader == null) return "";
25850
+ let size = 0;
25851
+ const textReader = new ReadableStream({ async pull(controller) {
25852
+ const { done, value } = await reader.read();
25853
+ if (done) {
25854
+ controller.close();
25855
+ return;
25856
+ }
25857
+ size += value.byteLength;
25858
+ if (size > maxBytes) tooLarge();
25859
+ controller.enqueue(value);
25860
+ } }, { highWaterMark: 0 }).pipeThrough(new TextDecoderStream()).getReader();
25861
+ try {
25862
+ const chunks = [];
25863
+ while (true) {
25864
+ const { done, value } = await textReader.read();
25865
+ if (done) break;
25866
+ chunks.push(value);
25867
+ }
25868
+ return chunks.join("");
25869
+ } finally {
25870
+ textReader.releaseLock();
25871
+ }
25872
+ } catch (error) {
25873
+ if (reader != null) reader.cancel(error).catch(() => {});
25874
+ throw error;
25875
+ } finally {
25876
+ reader?.releaseLock();
25877
+ }
25878
+ }
25716
25879
  const parametersNeedLowerCase = ["rel", "type"];
25717
25880
  const regexpLinkWhitespace = /[\n\r\s\t]/;
25718
25881
  function validateURI(uri) {
@@ -25892,78 +26055,17 @@ var HttpHeaderLink = class HttpHeaderLink {
25892
26055
  return new this(...inputs).toString();
25893
26056
  }
25894
26057
  };
25895
- /**
25896
- * Error thrown when fetching a JSON-LD document failed.
25897
- */
25898
- var FetchError = class extends Error {
25899
- /**
25900
- * The URL that failed to fetch.
25901
- */
25902
- url;
25903
- /**
25904
- * The HTTP response that failed, if available.
25905
- */
25906
- response;
26058
+ var UrlError = class extends Error {
25907
26059
  /**
25908
- * Constructs a new `FetchError`.
25909
- *
25910
- * @param url The URL that failed to fetch.
25911
- * @param message Error message.
25912
- * @param response The failed HTTP response, if available.
26060
+ * The failure category. Defaults to `"disallowed"`.
26061
+ * `"dns"` includes lookup errors and results with no usable IP addresses.
26062
+ * @since 2.0.29
25913
26063
  */
25914
- constructor(url, message, response) {
25915
- super(message == null ? url.toString() : `${url}: ${message}`);
25916
- this.name = "FetchError";
25917
- this.url = typeof url === "string" ? new URL(url) : url;
25918
- this.response = response;
25919
- }
25920
- };
25921
- /**
25922
- * Creates a request for the given URL.
25923
- * @param url The URL to create the request for.
25924
- * @param options The options for the request.
25925
- * @returns The created request.
25926
- * @internal
25927
- */
25928
- function createActivityPubRequest(url, options = {}) {
25929
- return new Request(url, {
25930
- headers: {
25931
- Accept: "application/activity+json, application/ld+json",
25932
- "User-Agent": typeof options.userAgent === "string" ? options.userAgent : getUserAgent(options.userAgent)
25933
- },
25934
- redirect: "manual"
25935
- });
25936
- }
25937
- /**
25938
- * Gets the user agent string for the given application and URL.
25939
- * @param options The options for making the user agent string.
25940
- * @returns The user agent string.
25941
- * @since 1.3.0
25942
- */
25943
- function getUserAgent({ software, url } = {}) {
25944
- const fedify = `Fedify/${version}`;
25945
- const runtime = globalThis.Deno?.version?.deno != null ? `Deno/${Deno.version.deno}` : globalThis.process?.versions?.bun != null ? `Bun/${process$1.versions.bun}` : "navigator" in globalThis && navigator.userAgent === "Cloudflare-Workers" ? navigator.userAgent : globalThis.process?.versions?.node != null ? `Node.js/${process$1.versions.node}` : null;
25946
- const userAgent = software == null ? [fedify] : [software, fedify];
25947
- if (runtime != null) userAgent.push(runtime);
25948
- if (url != null) userAgent.push(`+${url.toString()}`);
25949
- return `${userAgent.shift()} (${userAgent.join("; ")})`;
25950
- }
25951
- /**
25952
- * Logs the request.
25953
- * @param request The request to log.
25954
- * @internal
25955
- */
25956
- function logRequest(logger, request) {
25957
- logger.debug("Fetching document: {method} {url} {headers}", {
25958
- method: request.method,
25959
- url: request.url,
25960
- headers: Object.fromEntries(request.headers.entries())
25961
- });
25962
- }
25963
- var UrlError = class extends Error {
26064
+ reason;
25964
26065
  constructor(message, options) {
25965
26066
  super(message, options);
25966
26067
  this.name = "UrlError";
26068
+ this.reason = options?.reason ?? "disallowed";
25967
26069
  }
25968
26070
  };
25969
26071
  /**
@@ -25989,9 +26091,12 @@ async function validatePublicUrl(url) {
25989
26091
  }
25990
26092
  let addresses;
25991
26093
  try {
25992
- addresses = await lookup(hostname, { all: true });
26094
+ addresses = await dns.lookup(hostname, { all: true });
25993
26095
  } catch (error) {
25994
- throw new UrlError("DNS lookup failed", { cause: error });
26096
+ throw new UrlError("DNS lookup failed", {
26097
+ cause: error,
26098
+ reason: "dns"
26099
+ });
25995
26100
  }
25996
26101
  validateLookupAddresses(addresses);
25997
26102
  }
@@ -26020,7 +26125,7 @@ function validateLookupAddresses(addresses) {
26020
26125
  ipAddressCount++;
26021
26126
  validatePublicIpAddress(address, family);
26022
26127
  }
26023
- if (ipAddressCount === 0) throw new UrlError("DNS lookup did not return any IP address");
26128
+ if (ipAddressCount === 0) throw new UrlError("DNS lookup did not return any IP address", { reason: "dns" });
26024
26129
  }
26025
26130
  function validatePublicIpAddress(address, family) {
26026
26131
  if (family === 4 && isValidPublicIPv4Address(address) || family === 6 && isValidPublicIPv6Address(address)) return;
@@ -26218,38 +26323,29 @@ async function getRemoteDocument(url, response, fetch) {
26218
26323
  }
26219
26324
  let document;
26220
26325
  if (!jsonLd && (contentType === "text/html" || contentType?.startsWith("text/html;") || contentType === "application/xhtml+xml" || contentType?.startsWith("application/xhtml+xml;"))) {
26221
- const MAX_HTML_SIZE = 1024 * 1024;
26222
- const html = await response.text();
26223
- if (html.length > MAX_HTML_SIZE) {
26224
- logger.warn("HTML response too large, skipping alternate link discovery: {url}", {
26225
- url: documentUrl,
26226
- size: html.length
26227
- });
26228
- document = JSON.parse(html);
26229
- } else {
26230
- const tagPattern = /<(a|link)\s+([^>]*?)\s*\/?>/gi;
26231
- const attrPattern = /([a-z][a-z:_-]*)=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi;
26232
- let tagMatch;
26233
- while ((tagMatch = tagPattern.exec(html)) !== null) {
26234
- const tagContent = tagMatch[2];
26235
- let attrMatch;
26236
- const attribs = {};
26237
- attrPattern.lastIndex = 0;
26238
- while ((attrMatch = attrPattern.exec(tagContent)) !== null) {
26239
- const key = attrMatch[1].toLowerCase();
26240
- attribs[key] = attrMatch[2] ?? attrMatch[3] ?? attrMatch[4] ?? "";
26241
- }
26242
- if (attribs.rel === "alternate" && "type" in attribs && (attribs.type === "application/activity+json" || attribs.type === "application/ld+json" || attribs.type.startsWith("application/ld+json;")) && "href" in attribs && new URL(attribs.href, docUrl).href !== docUrl.href) {
26243
- logger.debug("Found alternate document: {alternateUrl} from {url}", {
26244
- alternateUrl: attribs.href,
26245
- url: documentUrl
26246
- });
26247
- return await fetch(new URL(attribs.href, docUrl).href);
26248
- }
26326
+ const html = await readBoundedText(response, 1024 * 1024, documentUrl);
26327
+ const tagPattern = /<(a|link)\s+([^>]*?)\s*\/?>/gi;
26328
+ const attrPattern = /([a-z][a-z:_-]*)=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi;
26329
+ let tagMatch;
26330
+ while ((tagMatch = tagPattern.exec(html)) !== null) {
26331
+ const tagContent = tagMatch[2];
26332
+ let attrMatch;
26333
+ const attribs = {};
26334
+ attrPattern.lastIndex = 0;
26335
+ while ((attrMatch = attrPattern.exec(tagContent)) !== null) {
26336
+ const key = attrMatch[1].toLowerCase();
26337
+ attribs[key] = attrMatch[2] ?? attrMatch[3] ?? attrMatch[4] ?? "";
26338
+ }
26339
+ if (attribs.rel === "alternate" && "type" in attribs && (attribs.type === "application/activity+json" || attribs.type === "application/ld+json" || attribs.type.startsWith("application/ld+json;")) && "href" in attribs && new URL(attribs.href, docUrl).href !== docUrl.href) {
26340
+ logger.debug("Found alternate document: {alternateUrl} from {url}", {
26341
+ alternateUrl: attribs.href,
26342
+ url: documentUrl
26343
+ });
26344
+ return await fetch(new URL(attribs.href, docUrl).href);
26249
26345
  }
26250
- document = JSON.parse(html);
26251
26346
  }
26252
- } else document = await response.json();
26347
+ document = JSON.parse(html);
26348
+ } else document = JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, documentUrl));
26253
26349
  logger.debug("Fetched document: {status} {url} {headers}", {
26254
26350
  status: response.status,
26255
26351
  url: documentUrl,
@@ -26263,6 +26359,8 @@ async function getRemoteDocument(url, response, fetch) {
26263
26359
  }
26264
26360
  /**
26265
26361
  * Creates a JSON-LD document loader that utilizes the browser's `fetch` API.
26362
+ * At most 20 HTTP redirects and alternate document links are followed in total
26363
+ * per call. Revisiting a URL within that chain throws a {@link FetchError}.
26266
26364
  *
26267
26365
  * The created loader preloads the below frequently used contexts by default
26268
26366
  * (unless `options.skipPreloadedContexts` is set to `true`):
@@ -26274,6 +26372,7 @@ async function getRemoteDocument(url, response, fetch) {
26274
26372
  * - <https://www.w3.org/ns/cid/v1>
26275
26373
  * - <https://w3id.org/security/multikey/v1>
26276
26374
  * - <https://w3id.org/fep/ef61>
26375
+ * - <https://w3id.org/fep/7aa9>
26277
26376
  * - <https://purl.archive.org/socialweb/webfinger>
26278
26377
  * - <http://schema.org/>
26279
26378
  * @param options Options for the document loader.
@@ -26296,7 +26395,11 @@ function getDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAge
26296
26395
  if (!allowPrivateAddress) try {
26297
26396
  await validatePublicUrl(currentUrl);
26298
26397
  } catch (error) {
26299
- if (error instanceof UrlError) logger.error("Disallowed private URL: {url}", {
26398
+ if (error instanceof UrlError) if (error.reason === "dns") logger.debug("DNS lookup failed for {url}", {
26399
+ url: currentUrl,
26400
+ error
26401
+ });
26402
+ else logger.error("Disallowed private URL: {url}", {
26300
26403
  url: currentUrl,
26301
26404
  error
26302
26405
  });
@@ -26334,7 +26437,12 @@ function getDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAge
26334
26437
  }
26335
26438
  return await load(redirectUrl, options, redirected + 1, visited);
26336
26439
  }
26337
- const result = await getRemoteDocument(currentUrl, response, load);
26440
+ const result = await getRemoteDocument(currentUrl, response, async (alternateUrl) => {
26441
+ options?.signal?.throwIfAborted();
26442
+ if (redirected >= DEFAULT_MAX_REDIRECTION) throw new FetchError(currentUrl, `Too many redirections (${redirected + 1})`);
26443
+ if (visited.has(alternateUrl)) throw new FetchError(currentUrl, `Redirect loop detected: ${alternateUrl}`);
26444
+ return await load(alternateUrl, options, redirected + 1, visited);
26445
+ });
26338
26446
  span.setAttribute("docloader.document_url", result.documentUrl);
26339
26447
  if (result.contextUrl != null) span.setAttribute("docloader.context_url", result.contextUrl);
26340
26448
  return result;
@@ -26350,7 +26458,7 @@ function getDocumentLoader({ allowPrivateAddress, skipPreloadedContexts, userAge
26350
26458
  }
26351
26459
  });
26352
26460
  }
26353
- return load;
26461
+ return (url, options) => load(url, options);
26354
26462
  }
26355
26463
  function validateCryptoKey(key, type) {
26356
26464
  if (type != null && key.type !== type) throw new TypeError(`The key is not a ${type} key.`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/relay",
3
- "version": "2.1.23",
3
+ "version": "2.1.25",
4
4
  "description": "ActivityPub relay support for Fedify",
5
5
  "keywords": [
6
6
  "Fedify",
@@ -50,14 +50,14 @@
50
50
  "dependencies": {
51
51
  "@js-temporal/polyfill": "^0.5.1",
52
52
  "@logtape/logtape": "^2.0.5",
53
- "@fedify/fedify": "^2.1.23",
54
- "@fedify/vocab": "2.1.23"
53
+ "@fedify/fedify": "^2.1.25",
54
+ "@fedify/vocab": "2.1.25"
55
55
  },
56
56
  "devDependencies": {
57
57
  "tsdown": "^0.21.6",
58
58
  "typescript": "^6.0.0",
59
59
  "urlpattern-polyfill": "^10.1.0",
60
- "@fedify/vocab-runtime": "^2.1.23"
60
+ "@fedify/vocab-runtime": "^2.1.25"
61
61
  },
62
62
  "scripts": {
63
63
  "build:self": "tsdown",