@fedify/fedify 2.0.36-dev.2828 → 2.0.36-dev.2843

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 (72) hide show
  1. package/dist/{builder-NquOFkEx.mjs → builder-CcDcpJbi.mjs} +3 -3
  2. package/dist/{callback-ySj5p3Ml.d.mts → callback-Bmi_V7Ai.d.mts} +16 -0
  3. package/dist/{client-jE7oGvRh.d.ts → client-9DPcy_Yx.d.ts} +16 -0
  4. package/dist/{client-BIBzqEIp.d.cts → client-B3ruDgWg.d.cts} +16 -0
  5. package/dist/{client-DLAWT9ep.mjs → client-DMnQeMkz.mjs} +86 -11
  6. package/dist/compat/mod.d.cts +1 -1
  7. package/dist/compat/mod.d.ts +1 -1
  8. package/dist/compat/transformers.test.mjs +1 -1
  9. package/dist/{context-DGC1C_UU.d.cts → context-CO7Qh6cG.d.cts} +1 -1
  10. package/dist/{context-CgpkmUFq.d.ts → context-D-oakGjH.d.ts} +1 -1
  11. package/dist/{deno-uX5OxSMQ.mjs → deno-y8JmzzvA.mjs} +1 -1
  12. package/dist/{docloader-BVio_R-w.mjs → docloader-y8c0QD51.mjs} +2 -2
  13. package/dist/federation/attachment-responses.test.mjs +2 -2
  14. package/dist/federation/builder.test.mjs +1 -1
  15. package/dist/federation/delivery-attachments.test.mjs +3 -3
  16. package/dist/federation/handler.test.mjs +6 -6
  17. package/dist/federation/idempotency.test.mjs +2 -2
  18. package/dist/federation/inbox.test.mjs +1 -1
  19. package/dist/federation/middleware.test.mjs +23 -7
  20. package/dist/federation/mod.cjs +1 -1
  21. package/dist/federation/mod.d.cts +2 -2
  22. package/dist/federation/mod.d.ts +2 -2
  23. package/dist/federation/mod.js +1 -1
  24. package/dist/federation/send.test.mjs +283 -3
  25. package/dist/federation/temporal.test.mjs +1 -1
  26. package/dist/federation/webfinger.test.mjs +1 -1
  27. package/dist/{http-Bp6bXNxO.cjs → http-BaS2YI7N.cjs} +1 -1
  28. package/dist/{http-Cx49vN9O.mjs → http-Bc__CJad.mjs} +2 -2
  29. package/dist/{http-DaxiTQXs.js → http-DSXmvBHu.js} +1 -1
  30. package/dist/{inbox-Rw21yNrv.mjs → inbox-C_wa-LYT.mjs} +1 -1
  31. package/dist/{key-CxZXo3sZ.mjs → key-B_0zygjz.mjs} +1 -1
  32. package/dist/{kv-cache-BjsvCInD.cjs → kv-cache-CTDDgSAY.cjs} +1 -1
  33. package/dist/{kv-cache-BEYK4z_E.js → kv-cache-D5LTdGp1.js} +1 -1
  34. package/dist/{ld-DTaV6DUm.mjs → ld-Dn_1iRZn.mjs} +2 -2
  35. package/dist/{middleware-Cz87lzGU.mjs → middleware-C0kb-J_z.mjs} +1 -1
  36. package/dist/{middleware-ByAekFky.cjs → middleware-C9DzAb43.cjs} +1 -1
  37. package/dist/{middleware-BuQURchh.mjs → middleware-CiFuNfkj.mjs} +16 -12
  38. package/dist/{middleware-By3uBhIJ.cjs → middleware-DWeZgneL.cjs} +99 -24
  39. package/dist/{middleware-Bnn9AKMf.js → middleware-DzOFdjWu.js} +98 -23
  40. package/dist/{mod-BzKteaAe.d.cts → mod-DUC2Rnne.d.cts} +1 -1
  41. package/dist/{mod-BqnolIm8.d.ts → mod-Dl09kqul.d.ts} +1 -1
  42. package/dist/mod.cjs +5 -5
  43. package/dist/mod.d.cts +3 -3
  44. package/dist/mod.d.ts +3 -3
  45. package/dist/mod.js +5 -5
  46. package/dist/nodeinfo/client.test.mjs +432 -5
  47. package/dist/nodeinfo/handler.test.mjs +1 -1
  48. package/dist/nodeinfo/mod.cjs +1 -1
  49. package/dist/nodeinfo/mod.d.cts +1 -1
  50. package/dist/nodeinfo/mod.d.ts +1 -1
  51. package/dist/nodeinfo/mod.js +1 -1
  52. package/dist/{owner-CEFC5tVI.mjs → owner-ATab1_Ig.mjs} +2 -2
  53. package/dist/{proof-Bl3zk5c6.cjs → proof-Biei-37s.cjs} +1 -1
  54. package/dist/{proof-Ct8tSLww.js → proof-s1jWHtTh.js} +1 -1
  55. package/dist/{proof-DFrHHTit.mjs → proof-wb_nX2ts.mjs} +2 -2
  56. package/dist/{send-Dn11B6x2.mjs → send-CGSvhwBb.mjs} +92 -21
  57. package/dist/sig/http.test.mjs +2 -2
  58. package/dist/sig/key-types.test.d.mts +1 -1
  59. package/dist/sig/key.test.mjs +2 -2
  60. package/dist/sig/ld.test.mjs +2 -2
  61. package/dist/sig/mod.cjs +2 -2
  62. package/dist/sig/mod.js +2 -2
  63. package/dist/sig/owner.test.mjs +1 -1
  64. package/dist/sig/proof.test.mjs +2 -2
  65. package/dist/{temporal-DEWMgahT.mjs → temporal-kI2oPgzl.mjs} +1 -1
  66. package/dist/testing/mod.d.mts +1 -1
  67. package/dist/{types-DOvyymM4.cjs → types-B5wRhemi.cjs} +85 -10
  68. package/dist/{types-B1_pRFE_.js → types-CXy2lRVU.js} +86 -11
  69. package/dist/utils/docloader.test.mjs +2 -2
  70. package/dist/utils/mod.cjs +1 -1
  71. package/dist/utils/mod.js +1 -1
  72. package/package.json +5 -5
@@ -1,8 +1,8 @@
1
1
  import "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { n as version, t as name } from "./deno-uX5OxSMQ.mjs";
5
- import { r as doubleKnockScoped } from "./http-Cx49vN9O.mjs";
4
+ import { n as version, t as name } from "./deno-y8JmzzvA.mjs";
5
+ import { r as doubleKnockScoped } from "./http-Bc__CJad.mjs";
6
6
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
7
7
  import { FetchError, UrlError } from "@fedify/vocab-runtime";
8
8
  import { openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
@@ -40,7 +40,8 @@ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
40
40
  * @param parameters The parameters for sending the activity.
41
41
  * See also {@link SendActivityParameters}.
42
42
  * @param deps The dependencies, for tests.
43
- * @throws {Error} If the activity fails to send.
43
+ * @throws {FetchError} If the delivery times out before receiving a response.
44
+ * @throws {SendActivityError} If the inbox returns an unsuccessful response.
44
45
  */
45
46
  function sendActivity(options, deps = {}) {
46
47
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
@@ -67,7 +68,25 @@ function sendActivity(options, deps = {}) {
67
68
  });
68
69
  }
69
70
  const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
70
- async function readLimitedResponseBody(response, maxBytes) {
71
+ const SEND_ACTIVITY_TIMEOUT_MS = 3e4;
72
+ function raceWithAbort(promise, signal) {
73
+ if (signal.aborted) return Promise.reject(signal.reason);
74
+ return new Promise((resolve, reject) => {
75
+ const onAbort = () => {
76
+ signal.removeEventListener("abort", onAbort);
77
+ reject(signal.reason);
78
+ };
79
+ signal.addEventListener("abort", onAbort, { once: true });
80
+ promise.then((value) => {
81
+ signal.removeEventListener("abort", onAbort);
82
+ resolve(value);
83
+ }, (error) => {
84
+ signal.removeEventListener("abort", onAbort);
85
+ reject(error);
86
+ });
87
+ });
88
+ }
89
+ async function readLimitedResponseBody(response, maxBytes, signal) {
71
90
  if (response.body == null) return "";
72
91
  const reader = response.body.getReader();
73
92
  const decoder = new TextDecoder();
@@ -76,7 +95,8 @@ async function readLimitedResponseBody(response, maxBytes) {
76
95
  let truncated = false;
77
96
  try {
78
97
  while (true) {
79
- const { done, value } = await reader.read();
98
+ signal.throwIfAborted();
99
+ const { done, value } = await raceWithAbort(reader.read(), signal);
80
100
  if (done) break;
81
101
  if (totalBytes + value.length > maxBytes) {
82
102
  const remaining = maxBytes - totalBytes;
@@ -88,8 +108,10 @@ async function readLimitedResponseBody(response, maxBytes) {
88
108
  totalBytes += value.length;
89
109
  }
90
110
  } finally {
91
- if (truncated) reader.cancel().catch(() => {});
92
- reader.releaseLock();
111
+ if (truncated || signal.aborted) reader.cancel().catch(() => {});
112
+ try {
113
+ reader.releaseLock();
114
+ } catch (_) {}
93
115
  }
94
116
  let result = chunks.join("");
95
117
  if (truncated) result += "… (truncated)";
@@ -101,12 +123,24 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
101
123
  "federation",
102
124
  "outbox"
103
125
  ]);
104
- const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? openDirectFetch : (url) => openPublicFetch(url));
126
+ const timeoutMs = deps.timeoutMs ?? SEND_ACTIVITY_TIMEOUT_MS;
127
+ const controller = new AbortController();
128
+ const { signal } = controller;
129
+ const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? openDirectFetch : (url) => openPublicFetch(url, { signal }));
105
130
  let opened = false;
106
131
  async function openHop(url) {
107
132
  let session;
108
133
  try {
109
- session = await openUnvalidatedHop(url);
134
+ signal.throwIfAborted();
135
+ const opening = openUnvalidatedHop(url);
136
+ opening.then((lateSession) => {
137
+ if (signal.aborted) closeAfterError(lateSession, logger);
138
+ }, () => {});
139
+ session = await raceWithAbort(opening, signal);
140
+ if (signal.aborted) {
141
+ closeAfterError(session, logger);
142
+ signal.throwIfAborted();
143
+ }
110
144
  } catch (error) {
111
145
  if (error instanceof UrlError && error.reason === "dns") {
112
146
  logger.error("DNS resolution failed for URL: {url}", {
@@ -132,7 +166,8 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
132
166
  method: "POST",
133
167
  headers,
134
168
  body: JSON.stringify(activity),
135
- redirect: "manual"
169
+ redirect: "manual",
170
+ signal
136
171
  });
137
172
  let rsaKey = null;
138
173
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -147,18 +182,48 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
147
182
  }))
148
183
  });
149
184
  let outcome;
185
+ const boundedSpecDeterminer = specDeterminer == null ? void 0 : {
186
+ determineSpec(origin) {
187
+ signal.throwIfAborted();
188
+ return raceWithAbort(Promise.resolve(specDeterminer.determineSpec(origin)), signal);
189
+ },
190
+ rememberSpec(origin, spec) {
191
+ if (signal.aborted) return;
192
+ try {
193
+ Promise.resolve(specDeterminer.rememberSpec(origin, spec)).catch((error) => logger.debug("Failed to remember the signature spec for {origin}: {error}", {
194
+ origin,
195
+ error
196
+ }));
197
+ } catch (error) {
198
+ logger.debug("Failed to remember the signature spec for {origin}: {error}", {
199
+ origin,
200
+ error
201
+ });
202
+ }
203
+ }
204
+ };
205
+ const timer = setTimeout(() => controller.abort(new DOMException("The delivery timed out.", "TimeoutError")), timeoutMs);
150
206
  try {
151
- outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox)) : await doubleKnockScoped(request, rsaKey, {
207
+ outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox, signal), signal) : await doubleKnockScoped(request, rsaKey, {
152
208
  tracerProvider,
153
- specDeterminer
154
- }, openHop, (response) => consumeSendActivityResponse(response, inbox));
209
+ specDeterminer: boundedSpecDeterminer,
210
+ signal
211
+ }, openHop, (response) => consumeSendActivityResponse(response, inbox, signal));
155
212
  } catch (error) {
156
- if (opened) logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
213
+ let failureError = error;
214
+ if (signal.aborted && !(error instanceof SendActivityError)) {
215
+ const failure = new FetchError(inbox.href, `Timed out after ${timeoutMs} ms`);
216
+ failure.cause = signal.reason;
217
+ failureError = failure;
218
+ }
219
+ if (opened || signal.aborted) logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
157
220
  activityId,
158
221
  inbox: inbox.href,
159
- error
222
+ error: failureError
160
223
  });
161
- throw error;
224
+ throw failureError;
225
+ } finally {
226
+ clearTimeout(timer);
162
227
  }
163
228
  if (!outcome.ok) {
164
229
  const { status, statusText, error } = outcome;
@@ -200,17 +265,18 @@ function cancelResponseBody(response, url) {
200
265
  * session is open: the body of a successful response is cancelled, and at
201
266
  * most 1 KiB of an error response body is read.
202
267
  */
203
- async function consumeSendActivityResponse(response, inbox) {
268
+ async function consumeSendActivityResponse(response, inbox, signal) {
204
269
  if (response.ok) {
205
270
  cancelResponseBody(response, response.url || inbox.href);
206
271
  return { ok: true };
207
272
  }
208
273
  let error;
209
274
  try {
210
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
275
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES, signal);
211
276
  } catch (_) {
212
277
  error = "";
213
278
  }
279
+ if (signal.aborted) error = "(timed out reading response body)";
214
280
  return {
215
281
  ok: false,
216
282
  status: response.status,
@@ -229,7 +295,7 @@ async function consumeSendActivityResponse(response, inbox) {
229
295
  * @param consume The function to consume the final response.
230
296
  * @returns The value returned by `consume`.
231
297
  */
232
- async function fetchWithValidatedRedirects(request, openHop, consume) {
298
+ async function fetchWithValidatedRedirects(request, openHop, consume, signal) {
233
299
  const logger = getLogger([
234
300
  "fedify",
235
301
  "federation",
@@ -237,10 +303,14 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
237
303
  ]);
238
304
  let body = await request.clone().text();
239
305
  for (let redirects = 0;; redirects++) {
306
+ signal?.throwIfAborted();
240
307
  const session = await openHop(request.url);
241
308
  let response;
242
309
  try {
243
- response = await session.fetch(request, { redirect: "manual" });
310
+ response = await session.fetch(request, {
311
+ redirect: "manual",
312
+ signal
313
+ });
244
314
  } catch (error) {
245
315
  await closeAfterError(session, logger);
246
316
  throw error;
@@ -290,7 +360,8 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
290
360
  method,
291
361
  headers,
292
362
  body,
293
- redirect: "manual"
363
+ redirect: "manual",
364
+ signal: signal ?? request.signal
294
365
  });
295
366
  }
296
367
  }
@@ -7,8 +7,8 @@ import { i as assertExists, t as assertStringIncludes } from "../std__assert-Dfl
7
7
  import { r as assertFalse, t as assertThrows } from "../assert_throws-D4DNWrux.mjs";
8
8
  import { t as assert } from "../assert-BhQd8QHP.mjs";
9
9
  import { t as assertRejects } from "../assert_rejects-WyYSTDDX.mjs";
10
- import { t as exportJwk } from "../key-CxZXo3sZ.mjs";
11
- import { a as formatRfc9421SignatureParameters, c as signRequest, i as formatRfc9421Signature, l as timingSafeEqual, n as doubleKnock, o as parseRfc9421Signature, r as doubleKnockScoped, s as parseRfc9421SignatureInput, t as createRfc9421SignatureBase, u as verifyRequest } from "../http-Cx49vN9O.mjs";
10
+ import { t as exportJwk } from "../key-B_0zygjz.mjs";
11
+ import { a as formatRfc9421SignatureParameters, c as signRequest, i as formatRfc9421Signature, l as timingSafeEqual, n as doubleKnock, o as parseRfc9421Signature, r as doubleKnockScoped, s as parseRfc9421SignatureInput, t as createRfc9421SignatureBase, u as verifyRequest } from "../http-Bc__CJad.mjs";
12
12
  import { i as rsaPrivateKey2, l as rsaPublicKey5, o as rsaPublicKey1, s as rsaPublicKey2 } from "../keys-CCxRJhWa.mjs";
13
13
  import { mockDocumentLoader, test } from "@fedify/fixture";
14
14
  import { FetchError, exportSpki } from "@fedify/vocab-runtime";
@@ -1,6 +1,6 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
- import { a as ActorCallbackSetters, c as SenderKeyPair, d as exportJwk, l as HttpMessageSignaturesSpecDeterminer, n as Context, r as InboxContext, s as InboxListenerSetters, t as ActorKeyPairsDispatcher, u as signRequest } from "../callback-ySj5p3Ml.mjs";
3
+ import { a as ActorCallbackSetters, c as SenderKeyPair, d as exportJwk, l as HttpMessageSignaturesSpecDeterminer, n as Context, r as InboxContext, s as InboxListenerSetters, t as ActorKeyPairsDispatcher, u as signRequest } from "../callback-Bmi_V7Ai.mjs";
4
4
  import { Activity, CryptographicKey, DataIntegrityProof, Multikey, Object as Object$1, Recipient } from "@fedify/vocab";
5
5
  import { TracerProvider } from "@opentelemetry/api";
6
6
  import { AuthenticatedDocumentLoaderFactory, CryptoKeyLike, CryptoKeyPairLike, DocumentLoader, DocumentLoaderFactoryOptions, exportMultibaseKey, exportSpki } from "@fedify/vocab-runtime";
@@ -6,9 +6,9 @@ import { n as assertStrictEquals } from "../std__assert-DflMZha5.mjs";
6
6
  import { r as assertFalse, t as assertThrows } from "../assert_throws-D4DNWrux.mjs";
7
7
  import { t as assert } from "../assert-BhQd8QHP.mjs";
8
8
  import { t as assertRejects } from "../assert_rejects-WyYSTDDX.mjs";
9
- import { a as importJwk, i as generateCryptoKeyPair, o as validateCryptoKey, r as fetchKey, t as exportJwk } from "../key-CxZXo3sZ.mjs";
9
+ import { a as importJwk, i as generateCryptoKeyPair, o as validateCryptoKey, r as fetchKey, t as exportJwk } from "../key-B_0zygjz.mjs";
10
10
  import { c as rsaPublicKey3, i as rsaPrivateKey2, o as rsaPublicKey1, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-CCxRJhWa.mjs";
11
- import { v as wrapContextLoaderForJsonLd } from "../ld-DTaV6DUm.mjs";
11
+ import { v as wrapContextLoaderForJsonLd } from "../ld-Dn_1iRZn.mjs";
12
12
  import { mockDocumentLoader, test } from "@fedify/fixture";
13
13
  import { CryptographicKey, Multikey, Person } from "@fedify/vocab";
14
14
  import { FetchError, UrlError, getDocumentLoader } from "@fedify/vocab-runtime";
@@ -5,9 +5,9 @@ import { t as assertEquals } from "../assert_equals-Ew3jOFa3.mjs";
5
5
  import { r as assertFalse, t as assertThrows } from "../assert_throws-D4DNWrux.mjs";
6
6
  import { n as assertInstanceOf, t as assert } from "../assert-BhQd8QHP.mjs";
7
7
  import { t as assertRejects } from "../assert_rejects-WyYSTDDX.mjs";
8
- import { i as generateCryptoKeyPair } from "../key-CxZXo3sZ.mjs";
8
+ import { i as generateCryptoKeyPair } from "../key-B_0zygjz.mjs";
9
9
  import { a as rsaPrivateKey3, c as rsaPublicKey3, i as rsaPrivateKey2, n as ed25519PrivateKey, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-CCxRJhWa.mjs";
10
- import { _ as verifySignature, a as compactJsonLd, c as detachSignature, d as hasVerifiableSignature, g as verifyJsonLd, i as attachSignature, m as signJsonLd, n as UnsafeJsonLdError, o as createSignature, p as isInvalidUrlTypeError, s as describeSignatureShape, u as hasSignature } from "../ld-DTaV6DUm.mjs";
10
+ import { _ as verifySignature, a as compactJsonLd, c as detachSignature, d as hasVerifiableSignature, g as verifyJsonLd, i as attachSignature, m as signJsonLd, n as UnsafeJsonLdError, o as createSignature, p as isInvalidUrlTypeError, s as describeSignatureShape, u as hasSignature } from "../ld-Dn_1iRZn.mjs";
11
11
  import { t as ldSignatureWithoutCreated } from "../ld-signature-_KYhPsqt.mjs";
12
12
  import { mockDocumentLoader, test } from "@fedify/fixture";
13
13
  import { Create, CryptographicKey, Note } from "@fedify/vocab";
package/dist/sig/mod.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  const { Temporal } = require("@js-temporal/polyfill");
2
2
  const { URLPattern } = require("urlpattern-polyfill");
3
3
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
4
- const require_http = require("../http-Bp6bXNxO.cjs");
5
- const require_proof = require("../proof-Bl3zk5c6.cjs");
4
+ const require_http = require("../http-BaS2YI7N.cjs");
5
+ const require_proof = require("../proof-Biei-37s.cjs");
6
6
  exports.attachSignature = require_proof.attachSignature;
7
7
  exports.createProof = require_proof.createProof;
8
8
  exports.createSignature = require_proof.createSignature;
package/dist/sig/mod.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
- import { c as importJwk, i as exportJwk, n as signRequest, o as fetchKey, r as verifyRequest, s as generateCryptoKeyPair } from "../http-DaxiTQXs.js";
4
- import { a as doesActorOwnKey, b as verifyJsonLd, d as createSignature, i as verifyProof, l as attachSignature, n as signObject, o as getKeyOwner, p as detachSignature, r as verifyObject, t as createProof, v as signJsonLd, x as verifySignature } from "../proof-Ct8tSLww.js";
3
+ import { c as importJwk, i as exportJwk, n as signRequest, o as fetchKey, r as verifyRequest, s as generateCryptoKeyPair } from "../http-DSXmvBHu.js";
4
+ import { a as doesActorOwnKey, b as verifyJsonLd, d as createSignature, i as verifyProof, l as attachSignature, n as signObject, o as getKeyOwner, p as detachSignature, r as verifyObject, t as createProof, v as signJsonLd, x as verifySignature } from "../proof-s1jWHtTh.js";
5
5
  export { attachSignature, createProof, createSignature, detachSignature, doesActorOwnKey, exportJwk, fetchKey, generateCryptoKeyPair, getKeyOwner, importJwk, signJsonLd, signObject, signRequest, verifyJsonLd, verifyObject, verifyProof, verifyRequest, verifySignature };
@@ -6,7 +6,7 @@ import "../std__assert-DflMZha5.mjs";
6
6
  import { r as assertFalse } from "../assert_throws-D4DNWrux.mjs";
7
7
  import { t as assert } from "../assert-BhQd8QHP.mjs";
8
8
  import { o as rsaPublicKey1, s as rsaPublicKey2 } from "../keys-CCxRJhWa.mjs";
9
- import { n as getKeyOwner, t as doesActorOwnKey } from "../owner-CEFC5tVI.mjs";
9
+ import { n as getKeyOwner, t as doesActorOwnKey } from "../owner-ATab1_Ig.mjs";
10
10
  import { createTestTracerProvider, mockDocumentLoader, test } from "@fedify/fixture";
11
11
  import { Create, CryptographicKey, lookupObject } from "@fedify/vocab";
12
12
  //#region src/sig/owner.test.ts
@@ -6,8 +6,8 @@ import "../std__assert-DflMZha5.mjs";
6
6
  import { n as assertInstanceOf } from "../assert-BhQd8QHP.mjs";
7
7
  import { t as assertRejects } from "../assert_rejects-WyYSTDDX.mjs";
8
8
  import { i as rsaPrivateKey2, n as ed25519PrivateKey, r as ed25519PublicKey, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-CCxRJhWa.mjs";
9
- import { _ as verifySignature, c as detachSignature, m as signJsonLd } from "../ld-DTaV6DUm.mjs";
10
- import { i as verifyProof, n as signObject, r as verifyObject, t as createProof } from "../proof-DFrHHTit.mjs";
9
+ import { _ as verifySignature, c as detachSignature, m as signJsonLd } from "../ld-Dn_1iRZn.mjs";
10
+ import { i as verifyProof, n as signObject, r as verifyObject, t as createProof } from "../proof-wb_nX2ts.mjs";
11
11
  import { mockDocumentLoader, test } from "@fedify/fixture";
12
12
  import { Create, DataIntegrityProof, Multikey, Note, OrderedCollectionPage, Place } from "@fedify/vocab";
13
13
  import { decodeMultibase, importMultibaseKey } from "@fedify/vocab-runtime";
@@ -1,7 +1,7 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
- import { l as getNormalizationContextLoader } from "./ld-DTaV6DUm.mjs";
4
+ import { l as getNormalizationContextLoader } from "./ld-Dn_1iRZn.mjs";
5
5
  import jsonld from "@fedify/vocab-runtime/jsonld";
6
6
  import { normalizeDateTimeLiteral } from "@fedify/vocab-runtime/temporal";
7
7
  //#region src/federation/temporal.ts
@@ -1,6 +1,6 @@
1
1
  import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
- import { i as RequestContext, o as Federation, r as InboxContext } from "../callback-ySj5p3Ml.mjs";
3
+ import { i as RequestContext, o as Federation, r as InboxContext } from "../callback-Bmi_V7Ai.mjs";
4
4
  import { testDefinitions } from "@fedify/fixture";
5
5
 
6
6
  //#region src/testing/context.d.ts
@@ -25,13 +25,18 @@ function validateBodySizeLimit(maxBytes) {
25
25
  * @param message The response or request to read.
26
26
  * @param maxBytes The maximum number of decoded bytes to read.
27
27
  * @param url The URL to include in errors and logs.
28
+ * @param signal An optional signal for cancelling the body read.
28
29
  * @returns The decoded body text.
29
30
  * @throws {BodyTooLargeError} If the body exceeds the limit.
30
31
  * @internal
31
32
  */
32
- async function readBoundedText(message, maxBytes, url) {
33
+ async function readBoundedText(message, maxBytes, url, signal) {
33
34
  validateBodySizeLimit(maxBytes);
34
35
  const reader = message.body?.getReader();
36
+ const onAbort = () => {
37
+ if (reader != null) reader.cancel(signal?.reason).catch(() => {});
38
+ };
39
+ signal?.addEventListener("abort", onAbort, { once: true });
35
40
  const tooLarge = () => {
36
41
  (0, _logtape_logtape.getLogger)([
37
42
  "fedify",
@@ -44,6 +49,7 @@ async function readBoundedText(message, maxBytes, url) {
44
49
  throw new BodyTooLargeError(url, maxBytes);
45
50
  };
46
51
  try {
52
+ signal?.throwIfAborted();
47
53
  const length = message.headers.get("Content-Length");
48
54
  const encoding = message.headers.get("Content-Encoding");
49
55
  if ((encoding == null || encoding.toLowerCase() === "identity") && length != null && /^\d+$/.test(length) && Number(length) > maxBytes) tooLarge();
@@ -51,6 +57,7 @@ async function readBoundedText(message, maxBytes, url) {
51
57
  let size = 0;
52
58
  const textReader = new ReadableStream({ async pull(controller) {
53
59
  const { done, value } = await reader.read();
60
+ signal?.throwIfAborted();
54
61
  if (done) {
55
62
  controller.close();
56
63
  return;
@@ -63,6 +70,7 @@ async function readBoundedText(message, maxBytes, url) {
63
70
  const chunks = [];
64
71
  while (true) {
65
72
  const { done, value } = await textReader.read();
73
+ signal?.throwIfAborted();
66
74
  if (done) break;
67
75
  chunks.push(value);
68
76
  }
@@ -74,6 +82,7 @@ async function readBoundedText(message, maxBytes, url) {
74
82
  if (reader != null) reader.cancel(error).catch(() => {});
75
83
  throw error;
76
84
  } finally {
85
+ signal?.removeEventListener("abort", onAbort);
77
86
  reader?.releaseLock();
78
87
  }
79
88
  }
@@ -85,6 +94,8 @@ const logger = (0, _logtape_logtape.getLogger)([
85
94
  "client"
86
95
  ]);
87
96
  const DEFAULT_MAX_REDIRECTION = 5;
97
+ const DEFAULT_TIMEOUT = 1e4;
98
+ const MAX_TIMEOUT = 2147483647;
88
99
  /**
89
100
  * Fetches a URL while guarding against SSRF. Every request—including each
90
101
  * redirect hop—is made in its own session opened with `openPublicFetch()`,
@@ -101,20 +112,27 @@ const DEFAULT_MAX_REDIRECTION = 5;
101
112
  * @param headers The request headers.
102
113
  * @param consume The function to consume the final response with.
103
114
  * @param deps The dependencies.
115
+ * @param signal The signal for the whole NodeInfo lookup.
104
116
  * @returns The value returned by `consume`, or `null` if the URL is
105
117
  * disallowed, its hostname cannot be resolved, or there are too many
106
118
  * redirects.
107
119
  * @internal
108
120
  */
109
- async function fetchPublicUrl(url, headers, consume, deps = {}) {
110
- const openHop = deps.openHop ?? ((hopUrl) => (0, _fedify_vocab_runtime_internal.openPublicFetch)(hopUrl));
121
+ async function fetchPublicUrl(url, headers, consume, deps = {}, signal) {
122
+ const openHop = deps.openHop ?? ((hopUrl, signal) => (0, _fedify_vocab_runtime_internal.openPublicFetch)(hopUrl, (0, _fedify_vocab_runtime_internal.detectRuntime)() === "node" ? {
123
+ signal,
124
+ lookup: (hostname) => (0, _fedify_vocab_runtime_internal.lookupAllAddressesBounded)(hostname, signal)
125
+ } : { signal }));
111
126
  let current = url instanceof URL ? url : new URL(url);
112
127
  let redirected = 0;
128
+ const visited = new Set([redirectKey(current)]);
113
129
  while (true) {
130
+ signal?.throwIfAborted();
114
131
  let session;
115
132
  try {
116
- session = await openHop(current.href);
133
+ session = await openHop(current.href, signal);
117
134
  } catch (e) {
135
+ signal?.throwIfAborted();
118
136
  if (e instanceof _fedify_vocab_runtime.UrlError) {
119
137
  if (e.reason === "dns") logger.error("DNS lookup failed for {url}: {error}", {
120
138
  url: current.href,
@@ -130,10 +148,16 @@ async function fetchPublicUrl(url, headers, consume, deps = {}) {
130
148
  }
131
149
  let location;
132
150
  try {
151
+ signal?.throwIfAborted();
133
152
  const response = await session.fetch(current, {
134
153
  headers,
135
- redirect: "manual"
154
+ redirect: "manual",
155
+ signal
136
156
  });
157
+ if (signal?.aborted) {
158
+ cancelBody(response, current);
159
+ signal.throwIfAborted();
160
+ }
137
161
  if (response.status < 300 || response.status >= 400 || !response.headers.has("Location")) return await consume(response);
138
162
  location = response.headers.get("Location");
139
163
  cancelBody(response, current);
@@ -156,9 +180,20 @@ async function fetchPublicUrl(url, headers, consume, deps = {}) {
156
180
  });
157
181
  return null;
158
182
  }
183
+ const key = redirectKey(next);
184
+ if (visited.has(key)) {
185
+ logger.error("Redirect cycle while fetching NodeInfo: {url}.", { url: next.href });
186
+ return null;
187
+ }
188
+ visited.add(key);
159
189
  current = next;
160
190
  }
161
191
  }
192
+ function redirectKey(url) {
193
+ const withoutFragment = new URL(url);
194
+ withoutFragment.hash = "";
195
+ return withoutFragment.href;
196
+ }
162
197
  /**
163
198
  * Starts cancelling a response body that is not read, without waiting for it
164
199
  * to settle. The cancellation of a branch of a tee (e.g., a body cloned by
@@ -189,6 +224,46 @@ async function getNodeInfo(url, options = {}) {
189
224
  * @internal
190
225
  */
191
226
  async function getNodeInfoInternal(url, options = {}, deps = {}) {
227
+ const timeout = resolveTimeout(options.timeout);
228
+ if (timeout == null && options.signal == null) return await getNodeInfoWithSignal(url, options, deps);
229
+ const controller = new AbortController();
230
+ const timeoutReason = timeout == null ? void 0 : new DOMException(`The NodeInfo lookup timed out after ${timeout} ms.`, "TimeoutError");
231
+ const timer = timeout == null ? void 0 : setTimeout(() => controller.abort(timeoutReason), timeout);
232
+ const onCallerAbort = () => controller.abort(options.signal?.reason);
233
+ options.signal?.addEventListener("abort", onCallerAbort, { once: true });
234
+ if (options.signal?.aborted) onCallerAbort();
235
+ let onAbort;
236
+ const aborted = new Promise((_, reject) => {
237
+ onAbort = () => reject(controller.signal.reason);
238
+ controller.signal.addEventListener("abort", onAbort, { once: true });
239
+ });
240
+ const loading = getNodeInfoWithSignal(url, options, deps, controller.signal);
241
+ loading.catch(() => {});
242
+ try {
243
+ return await Promise.race([loading, aborted]);
244
+ } catch (error) {
245
+ if (!controller.signal.aborted) throw error;
246
+ if (controller.signal.reason === timeoutReason) logger.error("Timed out after {timeout} ms while fetching NodeInfo: {url}", {
247
+ timeout,
248
+ url: url.toString()
249
+ });
250
+ else logger.debug("Cancelled NodeInfo lookup for {url}.", { url: url.toString() });
251
+ return;
252
+ } finally {
253
+ clearTimeout(timer);
254
+ options.signal?.removeEventListener("abort", onCallerAbort);
255
+ if (onAbort != null) controller.signal.removeEventListener("abort", onAbort);
256
+ }
257
+ }
258
+ function resolveTimeout(timeout) {
259
+ if (timeout === void 0) return DEFAULT_TIMEOUT;
260
+ if (timeout === null) return null;
261
+ if (!Number.isFinite(timeout) || timeout <= 0) throw new RangeError(`The NodeInfo timeout must be a positive finite number of milliseconds, but got ${String(timeout)}.`);
262
+ const ms = Math.ceil(timeout);
263
+ if (ms > MAX_TIMEOUT) throw new RangeError(`The NodeInfo timeout must not be greater than ${MAX_TIMEOUT} milliseconds, but got ${timeout}.`);
264
+ return ms;
265
+ }
266
+ async function getNodeInfoWithSignal(url, options, deps, signal) {
192
267
  try {
193
268
  const headers = {
194
269
  Accept: "application/json",
@@ -207,8 +282,8 @@ async function getNodeInfoInternal(url, options = {}, deps = {}) {
207
282
  cancelBody(response, wellKnownUrl);
208
283
  return;
209
284
  }
210
- return { rd: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, wellKnownUrl)) };
211
- }, deps);
285
+ return { rd: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, wellKnownUrl, signal)) };
286
+ }, deps, signal);
212
287
  if (wellKnown == null) return void 0;
213
288
  const wellKnownRd = wellKnown.rd;
214
289
  const link = wellKnownRd?.links?.find((link) => link != null && "rel" in link && (link.rel === "http://nodeinfo.diaspora.software/ns/schema/2.0" || link.rel === "http://nodeinfo.diaspora.software/ns/schema/2.1") && "href" in link && link.href != null);
@@ -231,14 +306,14 @@ async function getNodeInfoInternal(url, options = {}, deps = {}) {
231
306
  cancelBody(response, nodeInfoUrl);
232
307
  return;
233
308
  }
234
- return { data: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, nodeInfoUrl)) };
235
- }, deps);
309
+ return { data: JSON.parse(await readBoundedText(response, MAX_BODY_SIZE, nodeInfoUrl, signal)) };
310
+ }, deps, signal);
236
311
  if (document == null) return void 0;
237
312
  const { data } = document;
238
313
  if (options.parse === "none") return data;
239
314
  return parseNodeInfo(data, { tryBestEffort: options.parse === "best-effort" }) ?? void 0;
240
315
  } catch (error) {
241
- logger.error("Failed to fetch NodeInfo document from {url}: {error}", {
316
+ logger[signal?.aborted ? "debug" : "error"]("Failed to fetch NodeInfo document from {url}: {error}", {
242
317
  url: url.toString(),
243
318
  error
244
319
  });