@fedify/relay 2.3.7 → 2.3.8

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-D810htEY.js";
4
+ import { n as exportSpki, r as getDocumentLoader, t as isRelayFollowerData } from "./types-BmCR1mc4.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-D810htEY.js";
4
+ import { n as exportSpki, r as getDocumentLoader, t as isRelayFollowerData } from "./types-BmCR1mc4.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";
@@ -25783,7 +25783,147 @@ const preloadedContexts = {
25783
25783
  } }
25784
25784
  };
25785
25785
  var name = "@fedify/vocab-runtime";
25786
- var version = "2.3.7";
25786
+ var version = "2.3.8";
25787
+ /**
25788
+ * Error thrown when fetching a JSON-LD document failed.
25789
+ */
25790
+ var FetchError = class extends Error {
25791
+ /**
25792
+ * The URL that failed to fetch.
25793
+ */
25794
+ url;
25795
+ /**
25796
+ * The HTTP response that failed, if available.
25797
+ */
25798
+ response;
25799
+ /**
25800
+ * Constructs a new `FetchError`.
25801
+ *
25802
+ * @param url The URL that failed to fetch.
25803
+ * @param message Error message.
25804
+ * @param response The failed HTTP response, if available.
25805
+ */
25806
+ constructor(url, message, response) {
25807
+ super(message == null ? url.toString() : `${url}: ${message}`);
25808
+ this.name = "FetchError";
25809
+ this.url = typeof url === "string" ? new URL(url) : url;
25810
+ this.response = response;
25811
+ }
25812
+ };
25813
+ /**
25814
+ * Creates a request for the given URL.
25815
+ * @param url The URL to create the request for.
25816
+ * @param options The options for the request.
25817
+ * @returns The created request.
25818
+ * @internal
25819
+ */
25820
+ function createActivityPubRequest(url, options = {}) {
25821
+ return new Request(url, {
25822
+ headers: {
25823
+ Accept: "application/activity+json, application/ld+json",
25824
+ "User-Agent": typeof options.userAgent === "string" ? options.userAgent : getUserAgent(options.userAgent)
25825
+ },
25826
+ redirect: "manual"
25827
+ });
25828
+ }
25829
+ /**
25830
+ * Gets the user agent string for the given application and URL.
25831
+ * @param options The options for making the user agent string.
25832
+ * @returns The user agent string.
25833
+ * @since 1.3.0
25834
+ */
25835
+ function getUserAgent({ software, url } = {}) {
25836
+ const fedify = `Fedify/${version}`;
25837
+ 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;
25838
+ const userAgent = software == null ? [fedify] : [software, fedify];
25839
+ if (runtime != null) userAgent.push(runtime);
25840
+ if (url != null) userAgent.push(`+${url.toString()}`);
25841
+ return `${userAgent.shift()} (${userAgent.join("; ")})`;
25842
+ }
25843
+ /**
25844
+ * Logs the request.
25845
+ * @param request The request to log.
25846
+ * @internal
25847
+ */
25848
+ function logRequest(logger, request) {
25849
+ logger.debug("Fetching document: {method} {url} {headers}", {
25850
+ method: request.method,
25851
+ url: request.url,
25852
+ headers: Object.fromEntries(request.headers.entries())
25853
+ });
25854
+ }
25855
+ /** Decoded JSON body limit: 16 MiB. @internal */
25856
+ const MAX_BODY_SIZE = 16 * 1024 * 1024;
25857
+ /** A body exceeded the byte limit. @internal */
25858
+ var BodyTooLargeError = class extends FetchError {
25859
+ /** Creates an error for a body exceeding the given limit. */
25860
+ constructor(url, maxBytes) {
25861
+ super(url, `Body exceeds the limit of ${maxBytes} bytes`);
25862
+ this.name = "BodyTooLargeError";
25863
+ }
25864
+ };
25865
+ /** Validates a finite, positive byte limit. @internal */
25866
+ function validateBodySizeLimit(maxBytes) {
25867
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError("The body size limit must be a positive safe integer.");
25868
+ }
25869
+ /**
25870
+ * Reads UTF-8 text while limiting bytes received from the body stream.
25871
+ * Fetch responses are already decompressed, so the stream count is authoritative.
25872
+ * @param message The response or request to read.
25873
+ * @param maxBytes The maximum number of decoded bytes to read.
25874
+ * @param url The URL to include in errors and logs.
25875
+ * @returns The decoded body text.
25876
+ * @throws {BodyTooLargeError} If the body exceeds the limit.
25877
+ * @internal
25878
+ */
25879
+ async function readBoundedText(message, maxBytes, url) {
25880
+ validateBodySizeLimit(maxBytes);
25881
+ const reader = message.body?.getReader();
25882
+ const tooLarge = () => {
25883
+ getLogger([
25884
+ "fedify",
25885
+ "runtime",
25886
+ "body"
25887
+ ]).warn("Body from {url} exceeds the limit of {maxBytes} bytes.", {
25888
+ url: url.toString(),
25889
+ maxBytes
25890
+ });
25891
+ throw new BodyTooLargeError(url, maxBytes);
25892
+ };
25893
+ try {
25894
+ const length = message.headers.get("Content-Length");
25895
+ const encoding = message.headers.get("Content-Encoding");
25896
+ if ((encoding == null || encoding.toLowerCase() === "identity") && length != null && /^\d+$/.test(length) && Number(length) > maxBytes) tooLarge();
25897
+ if (reader == null) return "";
25898
+ let size = 0;
25899
+ const textReader = new ReadableStream({ async pull(controller) {
25900
+ const { done, value } = await reader.read();
25901
+ if (done) {
25902
+ controller.close();
25903
+ return;
25904
+ }
25905
+ size += value.byteLength;
25906
+ if (size > maxBytes) tooLarge();
25907
+ controller.enqueue(value);
25908
+ } }, { highWaterMark: 0 }).pipeThrough(new TextDecoderStream()).getReader();
25909
+ try {
25910
+ const chunks = [];
25911
+ while (true) {
25912
+ const { done, value } = await textReader.read();
25913
+ if (done) break;
25914
+ chunks.push(value);
25915
+ }
25916
+ return chunks.join("");
25917
+ } finally {
25918
+ textReader.releaseLock();
25919
+ }
25920
+ } catch (error) {
25921
+ if (reader != null) reader.cancel(error).catch(() => {});
25922
+ throw error;
25923
+ } finally {
25924
+ reader?.releaseLock();
25925
+ }
25926
+ }
25787
25927
  const parametersNeedLowerCase = ["rel", "type"];
25788
25928
  const regexpLinkWhitespace = /[\n\r\s\t]/;
25789
25929
  function validateURI(uri) {
@@ -25963,74 +26103,6 @@ var HttpHeaderLink = class HttpHeaderLink {
25963
26103
  return new this(...inputs).toString();
25964
26104
  }
25965
26105
  };
25966
- /**
25967
- * Error thrown when fetching a JSON-LD document failed.
25968
- */
25969
- var FetchError = class extends Error {
25970
- /**
25971
- * The URL that failed to fetch.
25972
- */
25973
- url;
25974
- /**
25975
- * The HTTP response that failed, if available.
25976
- */
25977
- response;
25978
- /**
25979
- * Constructs a new `FetchError`.
25980
- *
25981
- * @param url The URL that failed to fetch.
25982
- * @param message Error message.
25983
- * @param response The failed HTTP response, if available.
25984
- */
25985
- constructor(url, message, response) {
25986
- super(message == null ? url.toString() : `${url}: ${message}`);
25987
- this.name = "FetchError";
25988
- this.url = typeof url === "string" ? new URL(url) : url;
25989
- this.response = response;
25990
- }
25991
- };
25992
- /**
25993
- * Creates a request for the given URL.
25994
- * @param url The URL to create the request for.
25995
- * @param options The options for the request.
25996
- * @returns The created request.
25997
- * @internal
25998
- */
25999
- function createActivityPubRequest(url, options = {}) {
26000
- return new Request(url, {
26001
- headers: {
26002
- Accept: "application/activity+json, application/ld+json",
26003
- "User-Agent": typeof options.userAgent === "string" ? options.userAgent : getUserAgent(options.userAgent)
26004
- },
26005
- redirect: "manual"
26006
- });
26007
- }
26008
- /**
26009
- * Gets the user agent string for the given application and URL.
26010
- * @param options The options for making the user agent string.
26011
- * @returns The user agent string.
26012
- * @since 1.3.0
26013
- */
26014
- function getUserAgent({ software, url } = {}) {
26015
- const fedify = `Fedify/${version}`;
26016
- 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;
26017
- const userAgent = software == null ? [fedify] : [software, fedify];
26018
- if (runtime != null) userAgent.push(runtime);
26019
- if (url != null) userAgent.push(`+${url.toString()}`);
26020
- return `${userAgent.shift()} (${userAgent.join("; ")})`;
26021
- }
26022
- /**
26023
- * Logs the request.
26024
- * @param request The request to log.
26025
- * @internal
26026
- */
26027
- function logRequest(logger, request) {
26028
- logger.debug("Fetching document: {method} {url} {headers}", {
26029
- method: request.method,
26030
- url: request.url,
26031
- headers: Object.fromEntries(request.headers.entries())
26032
- });
26033
- }
26034
26106
  var UrlError = class extends Error {
26035
26107
  constructor(message, options) {
26036
26108
  super(message, options);
@@ -26289,38 +26361,29 @@ async function getRemoteDocument(url, response, fetch) {
26289
26361
  }
26290
26362
  let document;
26291
26363
  if (!jsonLd && (contentType === "text/html" || contentType?.startsWith("text/html;") || contentType === "application/xhtml+xml" || contentType?.startsWith("application/xhtml+xml;"))) {
26292
- const MAX_HTML_SIZE = 1024 * 1024;
26293
- const html = await response.text();
26294
- if (html.length > MAX_HTML_SIZE) {
26295
- logger.warn("HTML response too large, skipping alternate link discovery: {url}", {
26296
- url: documentUrl,
26297
- size: html.length
26298
- });
26299
- document = JSON.parse(html);
26300
- } else {
26301
- const tagPattern = /<(a|link)\s+([^>]*?)\s*\/?>/gi;
26302
- const attrPattern = /([a-z][a-z:_-]*)=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi;
26303
- let tagMatch;
26304
- while ((tagMatch = tagPattern.exec(html)) !== null) {
26305
- const tagContent = tagMatch[2];
26306
- let attrMatch;
26307
- const attribs = {};
26308
- attrPattern.lastIndex = 0;
26309
- while ((attrMatch = attrPattern.exec(tagContent)) !== null) {
26310
- const key = attrMatch[1].toLowerCase();
26311
- attribs[key] = attrMatch[2] ?? attrMatch[3] ?? attrMatch[4] ?? "";
26312
- }
26313
- 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) {
26314
- logger.debug("Found alternate document: {alternateUrl} from {url}", {
26315
- alternateUrl: attribs.href,
26316
- url: documentUrl
26317
- });
26318
- return await fetch(new URL(attribs.href, docUrl).href);
26319
- }
26364
+ const html = await readBoundedText(response, 1024 * 1024, documentUrl);
26365
+ const tagPattern = /<(a|link)\s+([^>]*?)\s*\/?>/gi;
26366
+ const attrPattern = /([a-z][a-z:_-]*)=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi;
26367
+ let tagMatch;
26368
+ while ((tagMatch = tagPattern.exec(html)) !== null) {
26369
+ const tagContent = tagMatch[2];
26370
+ let attrMatch;
26371
+ const attribs = {};
26372
+ attrPattern.lastIndex = 0;
26373
+ while ((attrMatch = attrPattern.exec(tagContent)) !== null) {
26374
+ const key = attrMatch[1].toLowerCase();
26375
+ attribs[key] = attrMatch[2] ?? attrMatch[3] ?? attrMatch[4] ?? "";
26376
+ }
26377
+ 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) {
26378
+ logger.debug("Found alternate document: {alternateUrl} from {url}", {
26379
+ alternateUrl: attribs.href,
26380
+ url: documentUrl
26381
+ });
26382
+ return await fetch(new URL(attribs.href, docUrl).href);
26320
26383
  }
26321
- document = JSON.parse(html);
26322
26384
  }
26323
- } else document = await response.json();
26385
+ document = JSON.parse(html);
26386
+ } else document = JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, documentUrl));
26324
26387
  logger.debug("Fetched document: {status} {url} {headers}", {
26325
26388
  status: response.status,
26326
26389
  url: documentUrl,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/relay",
3
- "version": "2.3.7",
3
+ "version": "2.3.8",
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.2.0",
53
- "@fedify/fedify": "^2.3.7",
54
- "@fedify/vocab": "2.3.7"
53
+ "@fedify/fedify": "^2.3.8",
54
+ "@fedify/vocab": "2.3.8"
55
55
  },
56
56
  "devDependencies": {
57
57
  "tsdown": "^0.22.0",
58
58
  "typescript": "^6.0.0",
59
59
  "urlpattern-polyfill": "^10.1.0",
60
- "@fedify/vocab-runtime": "^2.3.7"
60
+ "@fedify/vocab-runtime": "^2.3.8"
61
61
  },
62
62
  "scripts": {
63
63
  "build:self": "tsdown",