@fedify/fedify 2.4.6-dev.2837 → 2.4.6

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 (126) hide show
  1. package/dist/attachment-arrays-5yDbmjEb.mjs +16 -0
  2. package/dist/{builder-DYeeuJIZ.mjs → builder-CadJYxhX.mjs} +2 -2
  3. package/dist/callback-DPDs_dxC.d.mts +5280 -0
  4. package/dist/{client-3InDZbba.d.cts → client-DLHsPY7X.d.cts} +16 -0
  5. package/dist/{client-3InDZbba.d.ts → client-DLHsPY7X.d.ts} +16 -0
  6. package/dist/{client-5SIFzW3q.mjs → client-DU3owZBD.mjs} +86 -11
  7. package/dist/compat/attachment-arrays.test.d.mts +2 -0
  8. package/dist/compat/attachment-arrays.test.mjs +255 -0
  9. package/dist/compat/mod.d.cts +1 -1
  10. package/dist/compat/mod.d.ts +1 -1
  11. package/dist/compat/outgoing-jsonld.test.mjs +1 -1
  12. package/dist/compat/transformers.test.mjs +1 -1
  13. package/dist/{compound-proof-CxRUa-wY.mjs → compound-proof-CbWKyg2H.mjs} +2 -2
  14. package/dist/{context-D0gFIgev.d.cts → context-DUwicVx-.d.cts} +31 -14
  15. package/dist/{context-CVOOd9pD.d.ts → context-iGMHITvS.d.ts} +31 -14
  16. package/dist/{deno-CRpGtqm6.mjs → deno-BKSRi6w3.mjs} +1 -1
  17. package/dist/{docloader-CZtA3Qjh.mjs → docloader-BcDiJfFl.mjs} +2 -2
  18. package/dist/federation/attachment-responses.test.d.mts +2 -0
  19. package/dist/federation/attachment-responses.test.mjs +182 -0
  20. package/dist/federation/builder.test.mjs +1 -1
  21. package/dist/federation/compound-fanout.test.mjs +4 -4
  22. package/dist/federation/delivery-attachments.test.d.mts +2 -0
  23. package/dist/federation/delivery-attachments.test.mjs +288 -0
  24. package/dist/federation/handler-compound-proof.test.mjs +3 -3
  25. package/dist/federation/handler.test.mjs +206 -14
  26. package/dist/federation/hashlink-media.test.mjs +2 -2
  27. package/dist/federation/idempotency.test.mjs +2 -2
  28. package/dist/federation/inbox-report.test.mjs +5 -5
  29. package/dist/federation/inbox.test.mjs +1 -1
  30. package/dist/federation/metrics.test.mjs +1 -1
  31. package/dist/federation/middleware.test.mjs +1188 -13
  32. package/dist/federation/mod.cjs +1 -1
  33. package/dist/federation/mod.d.cts +3 -3
  34. package/dist/federation/mod.d.ts +3 -3
  35. package/dist/federation/mod.js +1 -1
  36. package/dist/federation/outgoing-proof.test.mjs +4 -4
  37. package/dist/federation/portable-actor.test.mjs +3 -3
  38. package/dist/federation/portable-chain.test.mjs +3 -3
  39. package/dist/federation/portable-collection.test.mjs +4 -4
  40. package/dist/federation/portable-delivery.test.mjs +2 -2
  41. package/dist/federation/portable-gateway-keys.test.mjs +5 -5
  42. package/dist/federation/portable-inbox.test.mjs +4 -4
  43. package/dist/federation/portable-parse-uri.test.mjs +1 -1
  44. package/dist/federation/portable-route-activity.test.mjs +2 -2
  45. package/dist/federation/portable.test.mjs +3 -3
  46. package/dist/federation/send.test.mjs +293 -3
  47. package/dist/federation/tasks/enqueue.test.mjs +1 -1
  48. package/dist/federation/tasks/tasks.test.mjs +2 -2
  49. package/dist/federation/temporal.test.mjs +25 -1
  50. package/dist/federation/webfinger.test.mjs +1 -1
  51. package/dist/{federation-DkIcc4TV.cjs → federation-CM4nzbhO.cjs} +500 -144
  52. package/dist/{http-G2ORncQt.mjs → http-B6sfb5xN.mjs} +8 -6
  53. package/dist/{http-DnJvGLuL.js → http-BwgldAIk.js} +2798 -2629
  54. package/dist/{http-DWIArxRV.cjs → http-Tj9eQ_rd.cjs} +2634 -2453
  55. package/dist/{inbox-WfHbmNbc.mjs → inbox-B7NVkb8j.mjs} +2 -2
  56. package/dist/{key-VEL1QqHF.d.cts → key-CIdQA7Pc.d.cts} +5 -5
  57. package/dist/{key-CyCcut3h.d.ts → key-CjtBFzaE.d.ts} +5 -5
  58. package/dist/{kv-cache-CSJwIUzA.js → kv-cache-C-5yfTw-.js} +1 -1
  59. package/dist/{kv-cache-C9jAD4VW.mjs → kv-cache-CvWuigft.mjs} +1 -1
  60. package/dist/{kv-cache-C7b-sBZL.cjs → kv-cache-Vbq0yM7W.cjs} +1 -1
  61. package/dist/{ld-CKWvh95H.mjs → ld-BGnZDnia.mjs} +155 -22
  62. package/dist/ld-signature-D1tFSFK8.mjs +23 -0
  63. package/dist/{metrics-Og1y_3kX.mjs → metrics-DHUP4F1-.mjs} +1 -1
  64. package/dist/{middleware-BLnbBpsz.mjs → middleware-CUb31OGG.mjs} +1 -1
  65. package/dist/{middleware-ClfuKN0B.js → middleware-DX8wADUa.js} +451 -97
  66. package/dist/{middleware-CcNRQv7R.mjs → middleware-mRXKHq68.mjs} +355 -86
  67. package/dist/{mod-B1Qt5cQQ.d.ts → mod-B6s6hA4y.d.ts} +3 -3
  68. package/dist/{mod-ss0wBUH1.d.cts → mod-CJf5GcVD.d.cts} +3 -3
  69. package/dist/{mod-makPMVMg.d.cts → mod-CSlxqNto.d.cts} +1 -1
  70. package/dist/{mod-CpyjFA9s.d.ts → mod-D2DiA8u5.d.cts} +29 -7
  71. package/dist/{mod-BTxJG7ZH.d.cts → mod-DKRf1FLm.d.ts} +29 -7
  72. package/dist/{mod-B5COx5Wd.d.ts → mod-Dqu6Dl1k.d.ts} +1 -1
  73. package/dist/mod.cjs +5 -5
  74. package/dist/mod.d.cts +8 -8
  75. package/dist/mod.d.ts +8 -8
  76. package/dist/mod.js +5 -5
  77. package/dist/nodeinfo/client.test.mjs +432 -4
  78. package/dist/nodeinfo/handler.test.mjs +1 -1
  79. package/dist/nodeinfo/mod.cjs +1 -1
  80. package/dist/nodeinfo/mod.d.cts +1 -1
  81. package/dist/nodeinfo/mod.d.ts +1 -1
  82. package/dist/nodeinfo/mod.js +1 -1
  83. package/dist/{outgoing-jsonld-4IJqPYos.mjs → outgoing-jsonld-Dsca6G_Y.mjs} +35 -4
  84. package/dist/{owner-DxVC0b0R.mjs → owner-DEiBiiqR.mjs} +3 -3
  85. package/dist/{portable-collection-8BzIIWJb.cjs → portable-collection--h11WDIi.cjs} +1 -1
  86. package/dist/{portable-collection-pWL8BrQk.mjs → portable-collection-D0-tInp2.mjs} +2 -2
  87. package/dist/{portable-collection-Bz3Zn527.js → portable-collection-M6d5I5JQ.js} +1 -1
  88. package/dist/{portable-key-BGmzMBYm.mjs → portable-key-CyVJpWWJ.mjs} +1 -1
  89. package/dist/{proof-Cgvg3rEH.mjs → proof-C4pwAF2k.mjs} +29 -9
  90. package/dist/{send-DheMZ6fh.mjs → send-ivzJCtb-.mjs} +100 -22
  91. package/dist/sig/compound-proof-discovery.test.mjs +1 -1
  92. package/dist/sig/compound-proof-producer.test.mjs +1 -1
  93. package/dist/sig/compound-proof-verification.test.mjs +2 -2
  94. package/dist/sig/compound-proof.test.mjs +3 -3
  95. package/dist/sig/http.test.mjs +2 -2
  96. package/dist/sig/key-types.test.d.mts +162 -0
  97. package/dist/sig/key-types.test.mjs +8 -0
  98. package/dist/sig/key.test.mjs +1 -1
  99. package/dist/sig/ld.test.mjs +572 -7
  100. package/dist/sig/mitra-receive-interop.test.mjs +4 -4
  101. package/dist/sig/mitra-send-interop.test.mjs +3 -3
  102. package/dist/sig/mod.cjs +2 -2
  103. package/dist/sig/mod.d.cts +3 -3
  104. package/dist/sig/mod.d.ts +3 -3
  105. package/dist/sig/mod.js +2 -2
  106. package/dist/sig/owner.test.mjs +1 -1
  107. package/dist/sig/portable-collection.test.mjs +1 -1
  108. package/dist/sig/portable-interop.test.mjs +3 -3
  109. package/dist/sig/portable-key.test.mjs +5 -5
  110. package/dist/sig/proof.test.mjs +100 -6
  111. package/dist/sig/tootik-request-interop.test.mjs +4 -4
  112. package/dist/sig/tootik-send-interop.test.mjs +3 -3
  113. package/dist/sig/verification.test.mjs +3 -3
  114. package/dist/{temporal-B7odHbLs.mjs → temporal-B6OlxwK_.mjs} +3 -5
  115. package/dist/testing/kv.test.mjs +1 -1
  116. package/dist/testing/mod.d.mts +3 -5045
  117. package/dist/{types-DUjZb4i6.js → types-BbCbtwZp.js} +86 -11
  118. package/dist/{types-hKCCjii0.cjs → types-C8gac_AD.cjs} +85 -10
  119. package/dist/utils/docloader.test.mjs +2 -2
  120. package/dist/utils/kv-cache.test.mjs +1 -1
  121. package/dist/utils/mod.cjs +1 -1
  122. package/dist/utils/mod.d.cts +1 -1
  123. package/dist/utils/mod.d.ts +1 -1
  124. package/dist/utils/mod.js +1 -1
  125. package/dist/utils/portable-verifier.test.mjs +3 -3
  126. package/package.json +6 -6
@@ -3,15 +3,16 @@ import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
4
  import { i as getPortableDid, l as isPortableId } from "./portable-key-id-Ca30-hOa.mjs";
5
5
  import { a as verificationObservation, i as triedKey, n as observeCheck, t as observeAttempt } from "./verification-Dpfcw8ml.mjs";
6
- import { n as version, t as name } from "./deno-CRpGtqm6.mjs";
7
- import { n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch } from "./metrics-Og1y_3kX.mjs";
8
- import { D as getDefaultPortableObjectVerifier, T as validateCryptoKey, c as getNormalizationContextLoader, v as bypassKeyCacheReads, x as fetchKey } from "./ld-CKWvh95H.mjs";
6
+ import { n as version, t as name } from "./deno-BKSRi6w3.mjs";
7
+ import { n as getDurationMs, r as getFederationMetrics, s as measureSignatureKeyFetch } from "./metrics-DHUP4F1-.mjs";
8
+ import { C as fetchKey, D as validateCryptoKey, b as bypassKeyCacheReads, k as getDefaultPortableObjectVerifier, l as getNormalizationContextLoader } from "./ld-BGnZDnia.mjs";
9
9
  import { n as preloadedOnlyDocumentLoader } from "./public-audience--klBIOk1.mjs";
10
- import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-4IJqPYos.mjs";
10
+ import { r as normalizeOutgoingActivityJsonLd } from "./outgoing-jsonld-Dsca6G_Y.mjs";
11
11
  import { getLogger } from "@logtape/logtape";
12
12
  import { Activity, DataIntegrityProof, Multikey, getTypeId } from "@fedify/vocab";
13
13
  import { SpanStatusCode, trace } from "@opentelemetry/api";
14
14
  import { encodeMultibase, formatIri, fromCompatibleEf61Id, getDocumentLoader, getFe34Origin, parseGatewayUrl, parseIri } from "@fedify/vocab-runtime";
15
+ import { asCryptoKey } from "@fedify/vocab-runtime/internal";
15
16
  import { encodeHex } from "byte-encodings/hex";
16
17
  import { getPortableActorGateways } from "@fedify/vocab-runtime/internal/jsonld-cache";
17
18
  import { isPlainJsonTree, retainSignedRepresentation } from "@fedify/vocab-runtime/internal/signed-representation";
@@ -140,7 +141,7 @@ async function createProofInternal(object, privateKey, keyId, { contextLoader, c
140
141
  const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
141
142
  digest.set(new Uint8Array(proofDigest), 0);
142
143
  digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
143
- const sig = new Uint8Array(await crypto.subtle.sign("Ed25519", privateKey, digest));
144
+ const sig = new Uint8Array(await crypto.subtle.sign("Ed25519", asCryptoKey(privateKey), digest));
144
145
  const proof = new DataIntegrityProof({
145
146
  cryptosuite: "eddsa-jcs-2022",
146
147
  verificationMethod: keyId,
@@ -150,7 +151,8 @@ async function createProofInternal(object, privateKey, keyId, { contextLoader, c
150
151
  });
151
152
  return {
152
153
  proof,
153
- securedDocument: capture ? await captureSecuredDocument(proof, compactMsg, msgCanon, proofCanon, new TextDecoder().decode(encodeMultibase("base58btc", sig)), contextLoader) : null
154
+ securedDocument: capture ? await captureSecuredDocument(proof, compactMsg, msgCanon, proofCanon, new TextDecoder().decode(encodeMultibase("base58btc", sig)), contextLoader) : null,
155
+ jsonLd: compactMsg
154
156
  };
155
157
  }
156
158
  /**
@@ -167,6 +169,15 @@ async function createProof(object, privateKey, keyId, options = {}) {
167
169
  const { proof } = await createProofInternal(object, privateKey, keyId, options);
168
170
  return proof;
169
171
  }
172
+ function getJsonLdContextKey(value) {
173
+ const context = typeof value === "object" && value != null && !Array.isArray(value) ? value["@context"] ?? null : null;
174
+ return JSON.stringify(sortJsonKeys(context));
175
+ }
176
+ function sortJsonKeys(value) {
177
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
178
+ if (typeof value !== "object" || value == null) return value;
179
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
180
+ }
170
181
  /**
171
182
  * Signs the given object with the private key and returns the signed object.
172
183
  * @param object The object to create a proof for.
@@ -181,16 +192,25 @@ async function signObject(object, privateKey, keyId, options = {}) {
181
192
  return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(object).href } }, async (span) => {
182
193
  try {
183
194
  if (object.id != null) span.setAttribute("activitypub.object.id", object.id.href);
195
+ const { proof, jsonLd, securedDocument } = await createProofInternal(object, privateKey, keyId, options, true);
184
196
  const existingProofs = [];
185
- for await (const proof of object.getProofs(options)) existingProofs.push(proof);
186
- const { proof, securedDocument } = await createProofInternal(object, privateKey, keyId, options, existingProofs.length < 1);
197
+ let hasProofs = object.proofIds.length > 0;
198
+ if (!hasProofs) for await (const _ of object.getProofs(options)) {
199
+ hasProofs = true;
200
+ break;
201
+ }
202
+ if (hasProofs) {
203
+ let sameContext = true;
204
+ if (options.context == null) sameContext = getJsonLdContextKey(await object.toJsonLd({ contextLoader: options.contextLoader })) === getJsonLdContextKey(jsonLd);
205
+ if (sameContext) for await (const existingProof of object.getProofs(options)) existingProofs.push(existingProof);
206
+ }
187
207
  if (span.isRecording()) {
188
208
  if (proof.cryptosuite != null) span.setAttribute("object_integrity_proofs.cryptosuite", proof.cryptosuite);
189
209
  if (proof.verificationMethodId != null) span.setAttribute("object_integrity_proofs.key_id", proof.verificationMethodId.href);
190
210
  if (proof.proofValue != null) span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
191
211
  }
192
212
  const signed = object.clone({ proofs: [...existingProofs, proof] }, { verifyPortableObject: getDefaultPortableObjectVerifier(object) });
193
- if (securedDocument != null) retainSignedRepresentation(signed, securedDocument);
213
+ if (securedDocument != null && existingProofs.length < 1) retainSignedRepresentation(signed, securedDocument);
194
214
  else if (existingProofs.length > 0) logger.debug("The object {objectId} already had {proofCount} proof(s), so its signed representation is not retained for embedding; the map-local compound-proof profile accepts exactly one direct proof per map.", {
195
215
  objectId: object.id?.href,
196
216
  proofCount: existingProofs.length
@@ -2,9 +2,9 @@ import "temporal-polyfill";
2
2
  import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
4
  import { d as isPortableUri } from "./portable-key-id-Ca30-hOa.mjs";
5
- import { n as version, t as name } from "./deno-CRpGtqm6.mjs";
6
- import { n as getDurationMs, r as getFederationMetrics } from "./metrics-Og1y_3kX.mjs";
7
- import { r as doubleKnockScoped } from "./http-G2ORncQt.mjs";
5
+ import { n as version, t as name } from "./deno-BKSRi6w3.mjs";
6
+ import { n as getDurationMs, r as getFederationMetrics } from "./metrics-DHUP4F1-.mjs";
7
+ import { r as doubleKnockScoped } from "./http-B6sfb5xN.mjs";
8
8
  import { getLogger } from "@logtape/logtape";
9
9
  import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
10
10
  import { FetchError, UrlError, canonicalizePortableUri, getFe34Origin, isGatewayUrl, toCompatibleEf61Id } from "@fedify/vocab-runtime";
@@ -190,7 +190,8 @@ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
190
190
  * @param parameters The parameters for sending the activity.
191
191
  * See also {@link SendActivityParameters}.
192
192
  * @param deps The dependencies, for tests.
193
- * @throws {Error} If the activity fails to send.
193
+ * @throws {FetchError} If the delivery times out before receiving a response.
194
+ * @throws {SendActivityError} If the inbox returns an unsuccessful response.
194
195
  */
195
196
  function sendActivity(options, deps = {}) {
196
197
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
@@ -249,6 +250,24 @@ async function sendActivityThroughGateways(parameters, inboxes) {
249
250
  throw lastError;
250
251
  }
251
252
  const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
253
+ const SEND_ACTIVITY_TIMEOUT_MS = 3e4;
254
+ function raceWithAbort(promise, signal) {
255
+ if (signal.aborted) return Promise.reject(signal.reason);
256
+ return new Promise((resolve, reject) => {
257
+ const onAbort = () => {
258
+ signal.removeEventListener("abort", onAbort);
259
+ reject(signal.reason);
260
+ };
261
+ signal.addEventListener("abort", onAbort, { once: true });
262
+ promise.then((value) => {
263
+ signal.removeEventListener("abort", onAbort);
264
+ resolve(value);
265
+ }, (error) => {
266
+ signal.removeEventListener("abort", onAbort);
267
+ reject(error);
268
+ });
269
+ });
270
+ }
252
271
  function getActivityActorId(activity) {
253
272
  if (!isRecord(activity)) return void 0;
254
273
  return getIdValue(activity.actor);
@@ -268,7 +287,7 @@ function getIdValue(value) {
268
287
  function isRecord(value) {
269
288
  return typeof value === "object" && value != null;
270
289
  }
271
- async function readLimitedResponseBody(response, maxBytes) {
290
+ async function readLimitedResponseBody(response, maxBytes, signal) {
272
291
  if (response.body == null) return "";
273
292
  const reader = response.body.getReader();
274
293
  const decoder = new TextDecoder();
@@ -277,7 +296,8 @@ async function readLimitedResponseBody(response, maxBytes) {
277
296
  let truncated = false;
278
297
  try {
279
298
  while (true) {
280
- const { done, value } = await reader.read();
299
+ signal.throwIfAborted();
300
+ const { done, value } = await raceWithAbort(reader.read(), signal);
281
301
  if (done) break;
282
302
  if (totalBytes + value.length > maxBytes) {
283
303
  const remaining = maxBytes - totalBytes;
@@ -289,8 +309,10 @@ async function readLimitedResponseBody(response, maxBytes) {
289
309
  totalBytes += value.length;
290
310
  }
291
311
  } finally {
292
- if (truncated) reader.cancel().catch(() => {});
293
- reader.releaseLock();
312
+ if (truncated || signal.aborted) reader.cancel().catch(() => {});
313
+ try {
314
+ reader.releaseLock();
315
+ } catch (_) {}
294
316
  }
295
317
  let result = chunks.join("");
296
318
  if (truncated) result += "… (truncated)";
@@ -305,11 +327,30 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
305
327
  const federationMetrics = getFederationMetrics(meterProvider);
306
328
  const started = performance.now();
307
329
  let deliverySuccess = false;
308
- const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? openDirectFetch : (url) => openPublicFetch(url));
330
+ const timeoutMs = deps.timeoutMs ?? SEND_ACTIVITY_TIMEOUT_MS;
331
+ const controller = new AbortController();
332
+ const { signal } = controller;
333
+ const timer = setTimeout(() => controller.abort(new DOMException("The delivery timed out.", "TimeoutError")), timeoutMs);
334
+ function timeoutFailure(error) {
335
+ if (!signal.aborted || error instanceof SendActivityError) return error;
336
+ const failure = new FetchError(inbox.href, `Timed out after ${timeoutMs} ms`);
337
+ failure.cause = signal.reason;
338
+ return failure;
339
+ }
340
+ const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? openDirectFetch : (url) => openPublicFetch(url, { signal }));
309
341
  async function openHop(url) {
310
342
  let session;
311
343
  try {
312
- session = await openUnvalidatedHop(url);
344
+ signal.throwIfAborted();
345
+ const opening = openUnvalidatedHop(url);
346
+ opening.then((lateSession) => {
347
+ if (signal.aborted) closeAfterError(lateSession, logger);
348
+ }, () => {});
349
+ session = await raceWithAbort(opening, signal);
350
+ if (signal.aborted) {
351
+ closeAfterError(session, logger);
352
+ signal.throwIfAborted();
353
+ }
313
354
  } catch (error) {
314
355
  if (error instanceof UrlError && error.reason === "dns") {
315
356
  logger.error("DNS resolution failed for URL: {url}", {
@@ -332,8 +373,15 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
332
373
  try {
333
374
  initialSession = await openHop(inbox.href);
334
375
  } catch (error) {
335
- if (error instanceof FetchError) federationMetrics.recordDelivery(inbox, getDurationMs(started), false, activityType);
336
- throw error;
376
+ const failure = timeoutFailure(error);
377
+ if (failure instanceof FetchError) federationMetrics.recordDelivery(inbox, getDurationMs(started), false, activityType);
378
+ if (signal.aborted) logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
379
+ activityId,
380
+ inbox: inbox.href,
381
+ error: failure
382
+ });
383
+ clearTimeout(timer);
384
+ throw failure;
337
385
  }
338
386
  let initialPending = true;
339
387
  const openDeliveryHop = (url) => {
@@ -350,7 +398,8 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
350
398
  method: "POST",
351
399
  headers,
352
400
  body: JSON.stringify(activity),
353
- redirect: "manual"
401
+ redirect: "manual",
402
+ signal
354
403
  });
355
404
  let rsaKey = null;
356
405
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -369,13 +418,35 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
369
418
  }))
370
419
  });
371
420
  let outcome;
421
+ const boundedSpecDeterminer = specDeterminer == null ? void 0 : {
422
+ determineSpec(origin) {
423
+ signal.throwIfAborted();
424
+ return raceWithAbort(Promise.resolve(specDeterminer.determineSpec(origin)), signal);
425
+ },
426
+ rememberSpec(origin, spec) {
427
+ if (signal.aborted) return;
428
+ try {
429
+ Promise.resolve(specDeterminer.rememberSpec(origin, spec)).catch((error) => logger.debug("Failed to remember the signature spec for {origin}: {error}", {
430
+ origin,
431
+ error
432
+ }));
433
+ } catch (error) {
434
+ logger.debug("Failed to remember the signature spec for {origin}: {error}", {
435
+ origin,
436
+ error
437
+ });
438
+ }
439
+ }
440
+ };
372
441
  try {
373
- outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox)) : await doubleKnockScoped(request, rsaKey, {
442
+ outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox, signal), signal) : await doubleKnockScoped(request, rsaKey, {
374
443
  tracerProvider,
375
- specDeterminer
376
- }, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox));
444
+ specDeterminer: boundedSpecDeterminer,
445
+ signal
446
+ }, openDeliveryHop, (response) => consumeSendActivityResponse(response, inbox, signal));
377
447
  } catch (error) {
378
- const failure = error instanceof FetchError || error instanceof UrlError ? error : createFetchError(inbox.href, error);
448
+ const boundedError = timeoutFailure(error);
449
+ const failure = boundedError instanceof FetchError || boundedError instanceof UrlError ? boundedError : createFetchError(inbox.href, boundedError);
379
450
  logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
380
451
  activityId,
381
452
  inbox: inbox.href,
@@ -409,6 +480,7 @@ async function sendActivityInternal({ activity, activityId, activityType, keys,
409
480
  federationMetrics.recordDelivery(inbox, getDurationMs(started), deliverySuccess, activityType);
410
481
  }
411
482
  } finally {
483
+ clearTimeout(timer);
412
484
  if (initialPending) await initialSession.close();
413
485
  }
414
486
  }
@@ -440,17 +512,18 @@ function cancelResponseBody(response, url) {
440
512
  * session is open: the body of a successful response is cancelled, and at
441
513
  * most 1 KiB of an error response body is read.
442
514
  */
443
- async function consumeSendActivityResponse(response, inbox) {
515
+ async function consumeSendActivityResponse(response, inbox, signal) {
444
516
  if (response.ok) {
445
517
  cancelResponseBody(response, response.url || inbox.href);
446
518
  return { ok: true };
447
519
  }
448
520
  let error;
449
521
  try {
450
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
522
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES, signal);
451
523
  } catch (_) {
452
524
  error = "";
453
525
  }
526
+ if (signal.aborted) error = "(timed out reading response body)";
454
527
  return {
455
528
  ok: false,
456
529
  status: response.status,
@@ -470,7 +543,7 @@ async function consumeSendActivityResponse(response, inbox) {
470
543
  * @param consume The function to consume the final response.
471
544
  * @returns The value returned by `consume`.
472
545
  */
473
- async function fetchWithValidatedRedirects(request, openHop, consume) {
546
+ async function fetchWithValidatedRedirects(request, openHop, consume, signal) {
474
547
  const logger = getLogger([
475
548
  "fedify",
476
549
  "federation",
@@ -478,10 +551,14 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
478
551
  ]);
479
552
  let body = await request.clone().text();
480
553
  for (let redirects = 0;; redirects++) {
554
+ signal?.throwIfAborted();
481
555
  const session = await openHop(request.url);
482
556
  let response;
483
557
  try {
484
- response = await session.fetch(request, { redirect: "manual" });
558
+ response = await session.fetch(request, {
559
+ redirect: "manual",
560
+ signal
561
+ });
485
562
  } catch (error) {
486
563
  await closeAfterError(session, logger);
487
564
  throw error;
@@ -531,7 +608,8 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
531
608
  method,
532
609
  headers,
533
610
  body,
534
- redirect: "manual"
611
+ redirect: "manual",
612
+ signal: signal ?? request.signal
535
613
  });
536
614
  }
537
615
  }
@@ -3,7 +3,7 @@ import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
4
  import { t as assertEquals } from "../assert_equals-Z6IcEbWU.mjs";
5
5
  import "../std__assert-DvMDRPes.mjs";
6
- import { a as inspectCompoundPortableObjectApplicability, n as discoverCompoundProofDocuments } from "../compound-proof-CxRUa-wY.mjs";
6
+ import { a as inspectCompoundPortableObjectApplicability, n as discoverCompoundProofDocuments } from "../compound-proof-CbWKyg2H.mjs";
7
7
  import { t as map_local_create_note_default } from "../map-local-create-note-B0SeXJms.mjs";
8
8
  import { test } from "@fedify/fixture";
9
9
  //#region src/sig/compound-proof-discovery.test.ts
@@ -3,7 +3,7 @@ import "urlpattern-polyfill";
3
3
  globalThis.addEventListener = () => {};
4
4
  import { t as assertEquals } from "../assert_equals-Z6IcEbWU.mjs";
5
5
  import "../std__assert-DvMDRPes.mjs";
6
- import { a as inspectCompoundPortableObjectApplicability, i as findUnsupportedCompoundProofShape, t as containsCompoundPortableObject } from "../compound-proof-CxRUa-wY.mjs";
6
+ import { a as inspectCompoundPortableObjectApplicability, i as findUnsupportedCompoundProofShape, t as containsCompoundPortableObject } from "../compound-proof-CbWKyg2H.mjs";
7
7
  import { test } from "@fedify/fixture";
8
8
  //#region src/sig/compound-proof-producer.test.ts
9
9
  const portableId = "ap+ef61://did:key:z6MkAlice/objects/1";
@@ -4,9 +4,9 @@ globalThis.addEventListener = () => {};
4
4
  import { t as assertEquals } from "../assert_equals-Z6IcEbWU.mjs";
5
5
  import "../std__assert-DvMDRPes.mjs";
6
6
  import { t as assert } from "../assert-D1Eafmd_.mjs";
7
- import { l as verifyPortableObjectProofPolicy, o as verifyMapLocalProof } from "../proof-Cgvg3rEH.mjs";
7
+ import { l as verifyPortableObjectProofPolicy, o as verifyMapLocalProof } from "../proof-C4pwAF2k.mjs";
8
8
  import { n as ed25519PrivateKey, r as ed25519PublicKey, s as rsaPublicKey2 } from "../keys-DIJNHW-Y.mjs";
9
- import { a as inspectCompoundPortableObjectApplicability, o as verifyCompoundPortableObjectProofs, s as verifyCompoundProofDocuments, t as containsCompoundPortableObject } from "../compound-proof-CxRUa-wY.mjs";
9
+ import { a as inspectCompoundPortableObjectApplicability, o as verifyCompoundPortableObjectProofs, s as verifyCompoundProofDocuments, t as containsCompoundPortableObject } from "../compound-proof-CbWKyg2H.mjs";
10
10
  import { t as map_local_create_note_default } from "../map-local-create-note-B0SeXJms.mjs";
11
11
  import { t as map_local_context_conflict_default } from "../map-local-context-conflict-DOYEEJ3u.mjs";
12
12
  import { CryptographicKey, Multikey, Person } from "@fedify/vocab";
@@ -5,10 +5,10 @@ import { t as assertEquals } from "../assert_equals-Z6IcEbWU.mjs";
5
5
  import "../std__assert-DvMDRPes.mjs";
6
6
  import { t as assert } from "../assert-D1Eafmd_.mjs";
7
7
  import { n as preloadedOnlyDocumentLoader } from "../public-audience--klBIOk1.mjs";
8
- import { r as normalizeOutgoingActivityJsonLd } from "../outgoing-jsonld-4IJqPYos.mjs";
9
- import { a as signObject, d as verifyProof } from "../proof-Cgvg3rEH.mjs";
8
+ import { r as normalizeOutgoingActivityJsonLd } from "../outgoing-jsonld-Dsca6G_Y.mjs";
9
+ import { a as signObject, d as verifyProof } from "../proof-C4pwAF2k.mjs";
10
10
  import { n as ed25519PrivateKey, r as ed25519PublicKey } from "../keys-DIJNHW-Y.mjs";
11
- import { s as verifyCompoundProofDocuments } from "../compound-proof-CxRUa-wY.mjs";
11
+ import { s as verifyCompoundProofDocuments } from "../compound-proof-CbWKyg2H.mjs";
12
12
  import { t as map_local_create_note_default } from "../map-local-create-note-B0SeXJms.mjs";
13
13
  import { t as map_local_context_conflict_default } from "../map-local-context-conflict-DOYEEJ3u.mjs";
14
14
  import { Create, DataIntegrityProof, Note, Question } from "@fedify/vocab";
@@ -12,8 +12,8 @@ import { t as assertThrows } from "../assert_throws-BYITOvPO.mjs";
12
12
  import "../std__assert-DvMDRPes.mjs";
13
13
  import { t as assertRejects } from "../assert_rejects-CTptdYck.mjs";
14
14
  import { t as assert } from "../assert-D1Eafmd_.mjs";
15
- import { y as exportJwk } from "../ld-CKWvh95H.mjs";
16
- import { a as formatRfc9421SignatureParameters, c as parseRfc9421SignatureInput, d as timingSafeEqual, i as formatRfc9421Signature, l as selectRequestSignature, m as verifyRequestDetailed, n as doubleKnock, o as listRequestSignatures, p as verifyRequest, r as doubleKnockScoped, s as parseRfc9421Signature, t as createRfc9421SignatureBase, u as signRequest } from "../http-G2ORncQt.mjs";
15
+ import { x as exportJwk } from "../ld-BGnZDnia.mjs";
16
+ import { a as formatRfc9421SignatureParameters, c as parseRfc9421SignatureInput, d as timingSafeEqual, i as formatRfc9421Signature, l as selectRequestSignature, m as verifyRequestDetailed, n as doubleKnock, o as listRequestSignatures, p as verifyRequest, r as doubleKnockScoped, s as parseRfc9421Signature, t as createRfc9421SignatureBase, u as signRequest } from "../http-B6sfb5xN.mjs";
17
17
  import { a as rsaPrivateKey3, i as rsaPrivateKey2, l as rsaPublicKey5, n as ed25519PrivateKey, o as rsaPublicKey1, r as ed25519PublicKey, s as rsaPublicKey2 } from "../keys-DIJNHW-Y.mjs";
18
18
  import { t as KvKeyCache } from "../keycache-N2opu4-3.mjs";
19
19
  import { configure, reset } from "@logtape/logtape";
@@ -0,0 +1,162 @@
1
+ import { Temporal } from "temporal-polyfill";
2
+ import { URLPattern } from "urlpattern-polyfill";
3
+ import { C as exportJwk, S as signObject, b as signRequest, d as SenderKeyPair, l as InboxListenerSetters, n as Context, o as ActorCallbackSetters, r as InboxContext, t as ActorKeyPairsDispatcher, x as createProof, y as HttpMessageSignaturesSpecDeterminer } from "../callback-DPDs_dxC.mjs";
4
+ import { Activity, CryptographicKey, Multikey, Recipient } from "@fedify/vocab";
5
+ import { MeterProvider, TracerProvider } from "@opentelemetry/api";
6
+ import { AuthenticatedDocumentLoaderFactory, CryptoKeyLike, CryptoKeyPairLike, DocumentLoader, DocumentLoaderFactoryOptions, exportMultibaseKey, exportSpki } from "@fedify/vocab-runtime";
7
+
8
+ //#region src/utils/docloader.d.ts
9
+ /**
10
+ * Options for {@link getAuthenticatedDocumentLoader}.
11
+ * @see {@link getAuthenticatedDocumentLoader}
12
+ * @since 1.3.0
13
+ */
14
+ interface GetAuthenticatedDocumentLoaderOptions extends DocumentLoaderFactoryOptions {
15
+ /**
16
+ * An optional spec determiner for HTTP Message Signatures.
17
+ * It determines the spec to use for signing requests.
18
+ * It is used for double-knocking
19
+ * (see <https://swicg.github.io/activitypub-http-signature/#how-to-upgrade-supported-versions>).
20
+ * @since 1.6.0
21
+ */
22
+ specDeterminer?: HttpMessageSignaturesSpecDeterminer;
23
+ /**
24
+ * The OpenTelemetry tracer provider. If omitted, the global tracer provider
25
+ * is used.
26
+ * @since 1.6.0
27
+ */
28
+ tracerProvider?: TracerProvider;
29
+ }
30
+ /**
31
+ * Gets an authenticated {@link DocumentLoader} for the given identity.
32
+ * Note that an authenticated document loader intentionally does not cache
33
+ * the fetched documents.
34
+ * At most 20 HTTP redirects and alternate document links are followed in total
35
+ * per call. Revisiting a URL within that chain throws a {@link FetchError}.
36
+ * Each call, including its double-knocking retries, times out after
37
+ * 10 seconds by default; see {@link DocumentLoaderFactoryOptions.timeout}.
38
+ * @param identity The identity to get the document loader for.
39
+ * The actor's key pair.
40
+ * @param options The options for the document loader.
41
+ * @returns The authenticated document loader.
42
+ * @throws {TypeError} If the key is invalid or unsupported.
43
+ * @throws {RangeError} If the `timeout` option is invalid.
44
+ * @since 0.4.0
45
+ */
46
+ declare function getAuthenticatedDocumentLoader(identity: {
47
+ keyId: URL;
48
+ privateKey: CryptoKeyLike;
49
+ }, options?: GetAuthenticatedDocumentLoaderOptions): DocumentLoader;
50
+ //#endregion
51
+ //#region src/sig/ld.d.ts
52
+ /**
53
+ * A signature of a JSON-LD document.
54
+ * @since 1.0.0
55
+ */
56
+ interface Signature {
57
+ "@context"?: "https://w3id.org/identity/v1" | "https://w3id.org/security/v1";
58
+ type: "RsaSignature2017";
59
+ id?: string;
60
+ creator: string;
61
+ created: string;
62
+ signatureValue: string;
63
+ }
64
+ /**
65
+ * Options for creating Linked Data Signatures.
66
+ * @since 1.0.0
67
+ */
68
+ interface CreateSignatureOptions {
69
+ /**
70
+ * The context loader for loading remote JSON-LD contexts.
71
+ */
72
+ contextLoader?: DocumentLoader;
73
+ /**
74
+ * The time when the signature was created. If not specified, the current
75
+ * time will be used.
76
+ */
77
+ created?: Temporal.Instant;
78
+ }
79
+ /**
80
+ * Creates a LD signature for the given JSON-LD document.
81
+ *
82
+ * If the document's context does not define the `signature` property, the
83
+ * signature is computed over the document with a minimal inline definition
84
+ * added. Use {@link attachSignature} to attach the signature to that exact
85
+ * document. Documents that already carry a `proof`, or whose context includes
86
+ * an unrecognized remote context, are hashed unchanged.
87
+ * @param jsonLd The JSON-LD document to sign.
88
+ * @param privateKey The private key to sign the document.
89
+ * @param keyId The ID of the public key that corresponds to the private key.
90
+ * @param options Additional options for creating the signature.
91
+ * See also {@link CreateSignatureOptions}.
92
+ * @return The created signature.
93
+ * @throws {TypeError} If the private key is invalid or unsupported.
94
+ * @since 1.0.0
95
+ */
96
+ declare function createSignature(jsonLd: unknown, privateKey: CryptoKeyLike, keyId: URL, {
97
+ contextLoader,
98
+ created
99
+ }?: CreateSignatureOptions): Promise<Signature>;
100
+ /**
101
+ * Options for signing JSON-LD documents.
102
+ * @since 1.0.0
103
+ */
104
+ interface SignJsonLdOptions extends CreateSignatureOptions {
105
+ /**
106
+ * The OpenTelemetry tracer provider for tracing the signing process.
107
+ * If omitted, the global tracer provider is used.
108
+ * @since 1.3.0
109
+ */
110
+ tracerProvider?: TracerProvider;
111
+ }
112
+ /**
113
+ * Signs the given JSON-LD document with the private key and returns the signed
114
+ * JSON-LD document.
115
+ * @param jsonLd The JSON-LD document to sign.
116
+ * @param privateKey The private key to sign the document.
117
+ * @param keyId The key ID to use in the signature. It will be used by the
118
+ * verifier to fetch the corresponding public key.
119
+ * @param options Additional options for signing the document.
120
+ * See also {@link SignJsonLdOptions}.
121
+ * @returns The signed JSON-LD document.
122
+ * @throws {TypeError} If the private key is invalid or unsupported.
123
+ * @since 1.0.0
124
+ */
125
+ declare function signJsonLd(jsonLd: unknown, privateKey: CryptoKeyLike, keyId: URL, options: SignJsonLdOptions): Promise<{
126
+ signature: Signature;
127
+ }>;
128
+ //#endregion
129
+ //#region src/sig/key-types.test.d.ts
130
+ /**
131
+ * Asserts at compile time that `T` is assignable to `U`.
132
+ */
133
+ type AssertAssignable<T extends U, U> = T;
134
+ /**
135
+ * The key usages Node.js adds on top of the DOM and Web Worker ones since
136
+ * Node.js 24.7, when ML-KEM support was added to its Web Crypto API.
137
+ */
138
+ type NodeKeyUsage = KeyUsage | "encapsulateBits" | "decapsulateBits" | "encapsulateKey" | "decapsulateKey";
139
+ /**
140
+ * Mirrors `import("node:crypto").webcrypto.CryptoKey`, whose `usages` array
141
+ * has a wider element type than the ambient `CryptoKey`.
142
+ */
143
+ interface NodeCryptoKey extends Omit<CryptoKey, "usages"> {
144
+ readonly usages: NodeKeyUsage[];
145
+ }
146
+ /**
147
+ * Mirrors `import("node:crypto").webcrypto.CryptoKeyPair`.
148
+ */
149
+ interface NodeCryptoKeyPair {
150
+ readonly privateKey: NodeCryptoKey;
151
+ readonly publicKey: NodeCryptoKey;
152
+ }
153
+ /**
154
+ * These are compile-time assertions. A regression in any of the public
155
+ * signatures fails `deno check` even though nothing here runs.
156
+ */
157
+ type NodeKeyTypeChecks = [AssertAssignable<NodeCryptoKey, CryptoKeyLike>, AssertAssignable<NodeCryptoKeyPair, CryptoKeyPairLike>, AssertAssignable<(context: Context<void>, identifier: string) => NodeCryptoKeyPair[] | Promise<NodeCryptoKeyPair[]>, ActorKeyPairsDispatcher<void, CryptoKeyPairLike>>, AssertAssignable<ActorKeyPairsDispatcher<void, CryptoKeyPairLike>, Parameters<ActorCallbackSetters<void>["setKeyPairsDispatcher"]>[0]>, AssertAssignable<SenderKeyPair["privateKey"], CryptoKey>, AssertAssignable<NodeCryptoKey, SenderKeyPair<CryptoKeyLike>["privateKey"]>, AssertAssignable<(context: Context<void>) => SenderKeyPair<CryptoKeyLike>, Parameters<InboxListenerSetters<void>["setSharedKeyDispatcher"]>[0]>, AssertAssignable<Parameters<AuthenticatedDocumentLoaderFactory>[0]["privateKey"], CryptoKey>, AssertAssignable<NodeCryptoKey, Parameters<typeof getAuthenticatedDocumentLoader>[0]["privateKey"]>, AssertAssignable<NodeCryptoKey, Parameters<typeof signRequest>[1]>, AssertAssignable<NodeCryptoKey, Parameters<typeof createProof>[1]>, AssertAssignable<NodeCryptoKey, Parameters<typeof signObject>[1]>, AssertAssignable<NodeCryptoKey, Parameters<typeof createSignature>[1]>, AssertAssignable<NodeCryptoKey, Parameters<typeof signJsonLd>[1]>, AssertAssignable<NodeCryptoKey, Parameters<typeof exportJwk>[0]>, AssertAssignable<NodeCryptoKey, Parameters<typeof exportSpki>[0]>, AssertAssignable<NodeCryptoKey, Parameters<typeof exportMultibaseKey>[0]>, AssertAssignable<NodeCryptoKey, NonNullable<ConstructorParameters<typeof CryptographicKey>[0]["publicKey"]>>, AssertAssignable<NodeCryptoKey, NonNullable<ConstructorParameters<typeof Multikey>[0]["publicKey"]>>, AssertAssignable<NodeCryptoKey, NonNullable<NonNullable<Parameters<CryptographicKey["clone"]>[0]>["publicKey"]>>, AssertAssignable<NodeCryptoKey, NonNullable<NonNullable<Parameters<Multikey["clone"]>[0]>["publicKey"]>>, AssertAssignable<Context<void>["getDocumentLoader"], (identity: {
158
+ keyId: URL;
159
+ privateKey: NodeCryptoKey;
160
+ }) => unknown>, AssertAssignable<Context<void>["sendActivity"], (sender: SenderKeyPair<NodeCryptoKey>, recipients: Recipient, activity: Activity) => Promise<void>>, AssertAssignable<InboxContext<void>["forwardActivity"], (forwarder: SenderKeyPair<NodeCryptoKey>, recipients: Recipient) => Promise<void>>];
161
+ //#endregion
162
+ export { NodeKeyTypeChecks };
@@ -0,0 +1,8 @@
1
+ import "temporal-polyfill";
2
+ import "urlpattern-polyfill";
3
+ globalThis.addEventListener = () => {};
4
+ import { test } from "@fedify/fixture";
5
+ //#region src/sig/key-types.test.ts
6
+ test("Node.js Web Crypto keys are accepted by the public key types", () => {});
7
+ //#endregion
8
+ export {};
@@ -8,7 +8,7 @@ import "../std__assert-DvMDRPes.mjs";
8
8
  import { t as assertRejects } from "../assert_rejects-CTptdYck.mjs";
9
9
  import { t as assertStrictEquals } from "../assert_strict_equals-CYvBmkpC.mjs";
10
10
  import { t as assert } from "../assert-D1Eafmd_.mjs";
11
- import { C as generateCryptoKeyPair, S as fetchKeyDetailed, T as validateCryptoKey, _ as wrapContextLoaderForJsonLd, w as importJwk, x as fetchKey, y as exportJwk } from "../ld-CKWvh95H.mjs";
11
+ import { C as fetchKey, D as validateCryptoKey, E as importJwk, T as generateCryptoKeyPair, w as fetchKeyDetailed, x as exportJwk, y as wrapContextLoaderForJsonLd } from "../ld-BGnZDnia.mjs";
12
12
  import { c as rsaPublicKey3, i as rsaPrivateKey2, o as rsaPublicKey1, r as ed25519PublicKey, s as rsaPublicKey2, t as ed25519Multikey } from "../keys-DIJNHW-Y.mjs";
13
13
  import { CryptographicKey, Multikey, Person } from "@fedify/vocab";
14
14
  import { FetchError, UrlError, exportDidKey, getDocumentLoader } from "@fedify/vocab-runtime";