@fedify/fedify 2.2.19 → 2.2.21

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 (109) hide show
  1. package/dist/attachment-arrays-CalAATqD.mjs +16 -0
  2. package/dist/{builder-UmydCxtK.mjs → builder-4ImvtjG4.mjs} +3 -3
  3. package/dist/callback-0KrwzutD.d.mts +2607 -0
  4. package/dist/{client-CSddvgWN.d.ts → client-9DPcy_Yx.d.ts} +16 -1
  5. package/dist/{client-CAM_bQXx.d.cts → client-B3ruDgWg.d.cts} +16 -1
  6. package/dist/{client-9F_u23dc.mjs → client-XYMC0Mmk.mjs} +189 -65
  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/public-audience.test.mjs +1 -1
  13. package/dist/compat/transformers.test.mjs +1 -1
  14. package/dist/{context-tJbL_Hkw.d.cts → context-CjWuov0g.d.cts} +57 -14
  15. package/dist/{context-OkwEpc3-.d.ts → context-DZqI2LJD.d.ts} +57 -14
  16. package/dist/{deno-CD-8UlUi.mjs → deno-AWk3S2Ug.mjs} +1 -1
  17. package/dist/docloader-Bogpjg4d.mjs +125 -0
  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/collection.test.mjs +1 -1
  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.test.mjs +208 -16
  25. package/dist/federation/idempotency.test.mjs +2 -2
  26. package/dist/federation/inbox.test.mjs +2 -2
  27. package/dist/federation/middleware.test.mjs +1567 -30
  28. package/dist/federation/mod.cjs +1 -1
  29. package/dist/federation/mod.d.cts +2 -2
  30. package/dist/federation/mod.d.ts +2 -2
  31. package/dist/federation/mod.js +1 -1
  32. package/dist/federation/negotiation.test.mjs +1 -1
  33. package/dist/federation/retry.test.mjs +1 -1
  34. package/dist/federation/send.test.mjs +723 -68
  35. package/dist/federation/temporal.test.mjs +25 -1
  36. package/dist/federation/webfinger.test.mjs +1 -1
  37. package/dist/{http-BBBUbwKh.mjs → http-B3wCvgu8.mjs} +199 -99
  38. package/dist/{http-DrUG4fPS.cjs → http-BNaPJVnF.cjs} +178 -107
  39. package/dist/{http-DJK2udgX.js → http-BpdLaGy8.js} +177 -106
  40. package/dist/{http-Dl00HXr4.d.ts → http-C8qLHs_Z.d.cts} +3 -4
  41. package/dist/{http-DqZhyEso.d.cts → http-D8WmcRAF.d.ts} +3 -4
  42. package/dist/{inbox-Dca_0fwc.mjs → inbox-DLy6WBXU.mjs} +1 -1
  43. package/dist/{key-DolXUaLH.mjs → key-Bhc8cQC7.mjs} +3 -2
  44. package/dist/{kv-cache-Bk3V1Tiu.cjs → kv-cache-Bj3CY9Jo.cjs} +59 -17
  45. package/dist/{kv-cache-DDm80t1K.js → kv-cache-CvjLUQTf.js} +60 -18
  46. package/dist/{ld-rTdIfZ63.mjs → ld-DTeykI0e.mjs} +153 -21
  47. package/dist/ld-signature-Dgz_b89j.mjs +23 -0
  48. package/dist/{middleware-BWOwEGpy.cjs → middleware-BSQP4d9p.cjs} +642 -149
  49. package/dist/{middleware-B4-Rzdi3.cjs → middleware-CWOzxb3o.cjs} +1 -1
  50. package/dist/{middleware-DYK_res8.mjs → middleware-DkMsC5mQ.mjs} +1 -1
  51. package/dist/{middleware-BimXKBcP.js → middleware-Dx1iwFk8.js} +641 -149
  52. package/dist/{middleware-CpXoRHs3.mjs → middleware-dlGvSrXl.mjs} +452 -122
  53. package/dist/{mod-D2JyWtW3.d.cts → mod-BmxqcEnU.d.ts} +30 -13
  54. package/dist/{mod-a6kmB8xD.d.cts → mod-DWEx2D4q.d.cts} +1 -1
  55. package/dist/{mod-DQGjRJUG.d.ts → mod-DnPmz3-S.d.ts} +1 -1
  56. package/dist/{mod-ej_rLx8h.d.ts → mod-INjDw-m0.d.cts} +30 -13
  57. package/dist/{mod-B6LmugJ4.d.ts → mod-REfljt0T.d.ts} +4 -10
  58. package/dist/{mod-V2vDnYNu.d.cts → mod-UvIGUHqW.d.cts} +4 -10
  59. package/dist/mod.cjs +5 -5
  60. package/dist/mod.d.cts +8 -8
  61. package/dist/mod.d.ts +8 -8
  62. package/dist/mod.js +5 -5
  63. package/dist/nodeinfo/client.test.mjs +764 -18
  64. package/dist/nodeinfo/handler.test.mjs +1 -1
  65. package/dist/nodeinfo/mod.cjs +1 -1
  66. package/dist/nodeinfo/mod.d.cts +1 -1
  67. package/dist/nodeinfo/mod.d.ts +1 -1
  68. package/dist/nodeinfo/mod.js +1 -1
  69. package/dist/nodeinfo/types.test.mjs +1 -1
  70. package/dist/otel/exporter.test.mjs +292 -30
  71. package/dist/otel/mod.cjs +36 -30
  72. package/dist/otel/mod.d.cts +13 -0
  73. package/dist/otel/mod.d.ts +13 -0
  74. package/dist/otel/mod.js +36 -30
  75. package/dist/{outgoing-jsonld-amccRMrV.mjs → outgoing-jsonld-DHf_DYXp.mjs} +38 -8
  76. package/dist/{owner-CVfzyM5V.mjs → owner-BsA7qMHB.mjs} +2 -2
  77. package/dist/{proof-gOGM-sJS.mjs → proof-C63Hqt9N.mjs} +40 -15
  78. package/dist/{proof-DhaTTn-P.cjs → proof-Dbz6ApNP.cjs} +1190 -1007
  79. package/dist/{proof-CaQ4KG6y.js → proof-QV_o5ZqS.js} +1174 -1003
  80. package/dist/send-CAdpwbFX.mjs +416 -0
  81. package/dist/sig/http.test.mjs +528 -2
  82. package/dist/sig/key-types.test.d.mts +218 -0
  83. package/dist/sig/key-types.test.mjs +8 -0
  84. package/dist/sig/key.test.mjs +2 -2
  85. package/dist/sig/ld.test.mjs +573 -8
  86. package/dist/sig/mod.cjs +2 -2
  87. package/dist/sig/mod.d.cts +3 -3
  88. package/dist/sig/mod.d.ts +3 -3
  89. package/dist/sig/mod.js +2 -2
  90. package/dist/sig/owner.test.mjs +1 -1
  91. package/dist/sig/proof.test.mjs +96 -4
  92. package/dist/{temporal-CA4Y9hBJ.mjs → temporal-B3JGkVgk.mjs} +3 -5
  93. package/dist/testing/mod.d.mts +1 -2396
  94. package/dist/{types-DRPjmHVV.cjs → types-BWx7zw3Y.cjs} +187 -63
  95. package/dist/{types-miAYfiGO.js → types-Dx_w2JSM.js} +188 -64
  96. package/dist/utils/docloader.test.mjs +318 -34
  97. package/dist/utils/mod.cjs +1 -1
  98. package/dist/utils/mod.d.cts +1 -1
  99. package/dist/utils/mod.d.ts +1 -1
  100. package/dist/utils/mod.js +1 -1
  101. package/package.json +6 -6
  102. package/dist/docloader-D1ghurDJ.mjs +0 -83
  103. package/dist/send-D35Va72B.mjs +0 -260
  104. /package/dist/{activity-listener-ell7W1s9.mjs → activity-listener-tztVvlNb.mjs} +0 -0
  105. /package/dist/{collection-D-HqUuA2.mjs → collection-CA3V5zyK.mjs} +0 -0
  106. /package/dist/{negotiation-SQvQgUqe.mjs → negotiation-VnHNB0Q5.mjs} +0 -0
  107. /package/dist/{public-audience-DpJqzPuh.mjs → public-audience-4g3_Ze4y.mjs} +0 -0
  108. /package/dist/{retry-v_sGLH1d.mjs → retry-CXg_MBI-.mjs} +0 -0
  109. /package/dist/{types-J53Kw7so.mjs → types-BFowWFTT.mjs} +0 -0
@@ -2,20 +2,23 @@ import { Temporal } from "@js-temporal/polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
3
  import { t as __exportAll } from "./chunk-CRNNMoPX.js";
4
4
  import { r as getDefaultActivityTransformers } from "./transformers-BGMIq1cs.js";
5
- import { a as verifyRequestDetailed, d as importJwk, f as validateCryptoKey, i as verifyRequest, m as formatAcceptSignature, n as parseRfc9421SignatureInput, o as exportJwk, t as doubleKnock, v as name, y as version } from "./http-DJK2udgX.js";
6
- import { a as MAX_BODY_SIZE, i as BodyTooLargeError, n as getNodeInfo, o as readBoundedText, t as nodeInfoToJson } from "./types-miAYfiGO.js";
7
- import { _ as hasSignatureLike, b as signJsonLd, c as getKeyOwner, f as compactJsonLd, g as hasSignature, h as getNormalizationContextLoader, i as verifyObject, l as InvalidContextReferenceError, m as detachSignature, n as hasProofLike, o as normalizeOutgoingActivityJsonLd, r as signObject, s as doesActorOwnKey, u as assertSafeJsonLd, v as isClearlyMalformedContextReference, w as wrapContextLoaderForJsonLd, x as verifyCompactJsonLd, y as isInvalidUrlTypeError } from "./proof-CaQ4KG6y.js";
8
- import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-DDm80t1K.js";
5
+ import { a as verifyRequestDetailed, d as importJwk, f as validateCryptoKey, i as verifyRequest, m as formatAcceptSignature, n as parseRfc9421SignatureInput, o as exportJwk, t as doubleKnockScoped, v as name, y as version } from "./http-BpdLaGy8.js";
6
+ import { E as normalizeOutgoingActivityJsonLd, T as normalizeAttachmentArrays$1, _ as hasVerifiableSignature, b as signJsonLd, c as InvalidContextReferenceError, d as compactJsonLd, g as hasSignatureLike, h as getNormalizationContextLoader, i as verifyObject, l as assertSafeJsonLd, m as detachSignature, n as hasProofLike, o as doesActorOwnKey, p as describeSignatureShape, r as signObject, s as getKeyOwner, v as isClearlyMalformedContextReference, w as wrapContextLoaderForJsonLd, x as verifyCompactJsonLd, y as isInvalidUrlTypeError } from "./proof-QV_o5ZqS.js";
7
+ import { a as MAX_BODY_SIZE, i as BodyTooLargeError, n as getNodeInfo, o as readBoundedText, t as nodeInfoToJson } from "./types-Dx_w2JSM.js";
8
+ import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-CvjLUQTf.js";
9
9
  import { getLogger, withContext } from "@logtape/logtape";
10
- import { Activity, Collection, CollectionPage, CryptographicKey, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, Tombstone, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
10
+ import { Activity, Collection, CollectionPage, CryptographicKey, DataIntegrityProof, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, Tombstone, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
11
11
  import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
12
12
  import { cloneDeep, uniq } from "es-toolkit";
13
13
  import { Router } from "uri-template-router";
14
14
  import { parseTemplate } from "url-template";
15
15
  import { encodeHex } from "byte-encodings/hex";
16
- import { FetchError, UrlError, getDocumentLoader, validatePublicUrl } from "@fedify/vocab-runtime";
17
- import { ATTR_HTTP_REQUEST_HEADER, ATTR_HTTP_REQUEST_METHOD, ATTR_HTTP_RESPONSE_HEADER, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_URL_FULL } from "@opentelemetry/semantic-conventions";
16
+ import { FetchError, UrlError, encodeMultibase, getDocumentLoader } from "@fedify/vocab-runtime";
18
17
  import jsonld from "@fedify/vocab-runtime/jsonld";
18
+ import { asCryptoKey, openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
19
+ import { ATTR_HTTP_REQUEST_HEADER, ATTR_HTTP_REQUEST_METHOD, ATTR_HTTP_RESPONSE_HEADER, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_URL_FULL } from "@opentelemetry/semantic-conventions";
20
+ import serialize from "json-canon";
21
+ import { normalizeDateTimeLiteral } from "@fedify/vocab-runtime/temporal";
19
22
  import { lookupWebFinger } from "@fedify/webfinger";
20
23
  import { domainToASCII } from "node:url";
21
24
  //#region src/federation/activity-listener.ts
@@ -780,6 +783,17 @@ async function buildCollectionSynchronizationHeader(collectionId, actorIds) {
780
783
  return `collectionId="${collectionId}", url="${url}", digest="${encodeHex(await digest(actorIds))}"`;
781
784
  }
782
785
  //#endregion
786
+ //#region src/compat/attachment-arrays.ts
787
+ /**
788
+ * Applies the shared attachment workaround to served documents without
789
+ * rewriting any document that contains a semantic proof or LD signature.
790
+ * RDF equivalence alone cannot preserve JCS signatures.
791
+ * @internal
792
+ */
793
+ function normalizeAttachmentArrays(document, contextLoader) {
794
+ return normalizeAttachmentArrays$1(document, contextLoader, true);
795
+ }
796
+ //#endregion
783
797
  //#region src/federation/inbox.ts
784
798
  /**
785
799
  * Checks whether an activity's ID and all of its actor IDs have the same
@@ -1121,9 +1135,6 @@ function acceptsJsonLd(request) {
1121
1135
  function isPlainObject(value) {
1122
1136
  return typeof value === "object" && value != null && !Array.isArray(value);
1123
1137
  }
1124
- function normalizeDateTimeLiteral(value) {
1125
- return value.substring(19).match(/[Z+-]/) ? value : value + "Z";
1126
- }
1127
1138
  function isMalformedDateTimeLiteral(value) {
1128
1139
  if (typeof value !== "string") return false;
1129
1140
  try {
@@ -1165,7 +1176,7 @@ function hasMalformedExpandedQuestionClosedLiteral(value) {
1165
1176
  if (typeof literal === "boolean") return false;
1166
1177
  if (typeof literal !== "string") return false;
1167
1178
  if (value["@type"] !== XSD_DATE_TIME_IRI) return false;
1168
- if (new Date(literal).toString() === "Invalid Date") return false;
1179
+ if (new Date(literal).toString() === "Invalid Date" && new Date(normalizeDateTimeLiteral(literal)).toString() === "Invalid Date") return false;
1169
1180
  return isMalformedDateTimeLiteral(literal);
1170
1181
  }
1171
1182
  function hasMalformedExpandedDurationLiteral(value) {
@@ -1260,7 +1271,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1260
1271
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
1261
1272
  }
1262
1273
  if (actor instanceof Tombstone) {
1263
- const jsonLd = await actor.toJsonLd(context);
1274
+ const jsonLd = await serializeForResponse(actor, context);
1264
1275
  return new Response(JSON.stringify(jsonLd), {
1265
1276
  status: 410,
1266
1277
  headers: {
@@ -1269,7 +1280,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1269
1280
  }
1270
1281
  });
1271
1282
  }
1272
- const jsonLd = await actor.toJsonLd(context);
1283
+ const jsonLd = await serializeForResponse(actor, context);
1273
1284
  return new Response(JSON.stringify(jsonLd), { headers: {
1274
1285
  "Content-Type": "application/activity+json",
1275
1286
  Vary: "Accept"
@@ -1289,7 +1300,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
1289
1300
  if (authorizePredicate != null) {
1290
1301
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
1291
1302
  }
1292
- const jsonLd = await object.toJsonLd(context);
1303
+ const jsonLd = await serializeForResponse(object, context);
1293
1304
  return new Response(JSON.stringify(jsonLd), { headers: {
1294
1305
  "Content-Type": "application/activity+json",
1295
1306
  Vary: "Accept"
@@ -1420,7 +1431,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1420
1431
  if (collectionCallbacks.authorizePredicate != null) {
1421
1432
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return await onUnauthorized(request);
1422
1433
  }
1423
- const jsonLd = await collection.toJsonLd(context);
1434
+ const jsonLd = await serializeForResponse(collection, context);
1424
1435
  return new Response(JSON.stringify(jsonLd), { headers: {
1425
1436
  "Content-Type": "application/activity+json",
1426
1437
  Vary: "Accept"
@@ -1769,7 +1780,11 @@ async function handleInboxInternal(request, parameters, span) {
1769
1780
  }
1770
1781
  const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
1771
1782
  const jsonWithoutSig = detachSignature(json);
1772
- const hasLdSignature = hasSignature(json);
1783
+ const hasLdSignature = hasVerifiableSignature(json);
1784
+ if (!hasLdSignature) {
1785
+ const shape = describeSignatureShape(json);
1786
+ if (shape != null) logger.debug("Linked Data Signature has an unsupported shape: {signatureKind}; properties: {signatureProperties}.", shape);
1787
+ }
1773
1788
  const canAttemptAlternateAuthAfterLdSignatureFailure = skipSignatureVerification || hasHttpSignatureHeaders(request) || hasObjectIntegrityProof(jsonWithoutSig);
1774
1789
  let deferredLdSignatureError = void 0;
1775
1790
  const respondInvalidActivity = async (error) => {
@@ -2248,7 +2263,7 @@ var CustomCollectionHandler = class {
2248
2263
  * @returns A promise that resolves to the JSON-LD representation.
2249
2264
  */
2250
2265
  async toJsonLd() {
2251
- return (await this.collection).toJsonLd(this.context);
2266
+ return serializeForResponse(await this.collection, this.context);
2252
2267
  }
2253
2268
  /**
2254
2269
  * Fetches the collection with optional cursor for pagination.
@@ -2551,7 +2566,7 @@ var UnauthorizedError = class extends HandlerError {
2551
2566
  * @since 0.3.0
2552
2567
  */
2553
2568
  async function respondWithObject(object, options) {
2554
- const jsonLd = await object.toJsonLd(options);
2569
+ const jsonLd = await serializeForResponse(object, options);
2555
2570
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
2556
2571
  }
2557
2572
  /**
@@ -2639,6 +2654,106 @@ const MIN_COMPONENTS = [
2639
2654
  "@target-uri",
2640
2655
  "@authority"
2641
2656
  ];
2657
+ /** Applies compatibility changes only after ordinary vocabulary serialization. */
2658
+ async function serializeForResponse(object, options) {
2659
+ return await normalizeAttachmentArrays(await object.toJsonLd(options), options?.contextLoader);
2660
+ }
2661
+ //#endregion
2662
+ //#region src/sig/proof-creation.ts
2663
+ /** Signs the exact serialized message supplied by an internal producer. */
2664
+ async function createProofForJsonLd(jsonLd, privateKey, keyId, created) {
2665
+ validateCryptoKey(privateKey, "private");
2666
+ if (privateKey.algorithm.name !== "Ed25519") throw new TypeError("Unsupported algorithm: " + privateKey.algorithm.name);
2667
+ const encoder = new TextEncoder();
2668
+ const msgDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(jsonLd)));
2669
+ created ??= Temporal.Now.instant();
2670
+ const proofConfig = {
2671
+ "@context": jsonLd["@context"],
2672
+ type: "DataIntegrityProof",
2673
+ cryptosuite: "eddsa-jcs-2022",
2674
+ verificationMethod: keyId.href,
2675
+ proofPurpose: "assertionMethod",
2676
+ created: created.toString()
2677
+ };
2678
+ const proofDigest = await crypto.subtle.digest("SHA-256", encoder.encode(serialize(proofConfig)));
2679
+ const digest = new Uint8Array(proofDigest.byteLength + msgDigest.byteLength);
2680
+ digest.set(new Uint8Array(proofDigest), 0);
2681
+ digest.set(new Uint8Array(msgDigest), proofDigest.byteLength);
2682
+ const sig = await crypto.subtle.sign("Ed25519", asCryptoKey(privateKey), digest);
2683
+ return new DataIntegrityProof({
2684
+ cryptosuite: "eddsa-jcs-2022",
2685
+ verificationMethod: keyId,
2686
+ proofPurpose: "assertionMethod",
2687
+ created,
2688
+ proofValue: new Uint8Array(sig)
2689
+ });
2690
+ }
2691
+ //#endregion
2692
+ //#region src/compat/delivery-jsonld.ts
2693
+ /**
2694
+ * Returns changed wire JSON only; unchanged documents keep the existing
2695
+ * delivery signing path. This uses ordinary vocabulary serialization, without
2696
+ * retaining or repairing independently signed child representations.
2697
+ */
2698
+ async function prepareActivityJsonLd(activity, contextLoader) {
2699
+ if (activity.proofIds.length > 0) return void 0;
2700
+ for await (const _ of activity.getProofs({ contextLoader })) return void 0;
2701
+ const source = await activity.clone().toJsonLd({
2702
+ format: "compact",
2703
+ contextLoader
2704
+ });
2705
+ const prepared = await normalizeOutgoingActivityJsonLd(source, contextLoader, true);
2706
+ return prepared !== source && typeof prepared === "object" && prepared != null && !Array.isArray(prepared) ? prepared : void 0;
2707
+ }
2708
+ /** Signs a changed, proof-free delivery map without serializing it again. */
2709
+ async function signActivityJsonLd(activity, unsigned, keys, options) {
2710
+ const proofs = [];
2711
+ const serializedProofs = [];
2712
+ const tracer = (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version);
2713
+ for (const { privateKey, keyId } of keys) {
2714
+ const proof = await tracer.startActiveSpan("object_integrity_proofs.sign", { attributes: { "activitypub.object.type": getTypeId(activity).href } }, async (span) => {
2715
+ try {
2716
+ if (activity.id != null) span.setAttribute("activitypub.object.id", activity.id.href);
2717
+ const proof = await createProofForJsonLd(unsigned, privateKey, keyId);
2718
+ if (span.isRecording()) {
2719
+ span.setAttribute("object_integrity_proofs.cryptosuite", "eddsa-jcs-2022");
2720
+ span.setAttribute("object_integrity_proofs.key_id", keyId.href);
2721
+ span.setAttribute("object_integrity_proofs.signature", encodeHex(proof.proofValue));
2722
+ }
2723
+ return proof;
2724
+ } catch (error) {
2725
+ span.setStatus({
2726
+ code: SpanStatusCode.ERROR,
2727
+ message: String(error)
2728
+ });
2729
+ throw error;
2730
+ } finally {
2731
+ span.end();
2732
+ }
2733
+ });
2734
+ proofs.push(proof);
2735
+ serializedProofs.push({
2736
+ "@context": unsigned["@context"],
2737
+ type: "DataIntegrityProof",
2738
+ cryptosuite: proof.cryptosuite,
2739
+ verificationMethod: keyId.href,
2740
+ proofPurpose: "assertionMethod",
2741
+ created: proof.created.toString(),
2742
+ proofValue: new TextDecoder().decode(encodeMultibase("base58btc", proof.proofValue))
2743
+ });
2744
+ }
2745
+ if (proofs.length === 0) return {
2746
+ activity,
2747
+ jsonLd: unsigned
2748
+ };
2749
+ return {
2750
+ activity: activity.clone({ proofs }),
2751
+ jsonLd: {
2752
+ ...unsigned,
2753
+ proof: serializedProofs.length === 1 ? serializedProofs[0] : serializedProofs
2754
+ }
2755
+ };
2756
+ }
2642
2757
  //#endregion
2643
2758
  //#region src/nodeinfo/handler.ts
2644
2759
  /**
@@ -2737,9 +2852,11 @@ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
2737
2852
  *
2738
2853
  * @param parameters The parameters for sending the activity.
2739
2854
  * See also {@link SendActivityParameters}.
2740
- * @throws {Error} If the activity fails to send.
2855
+ * @param deps The dependencies, for tests.
2856
+ * @throws {FetchError} If the delivery times out before receiving a response.
2857
+ * @throws {SendActivityError} If the inbox returns an unsuccessful response.
2741
2858
  */
2742
- function sendActivity(options) {
2859
+ function sendActivity(options, deps = {}) {
2743
2860
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
2744
2861
  return tracerProvider.getTracer(name, version).startActiveSpan("activitypub.send_activity", {
2745
2862
  kind: SpanKind.CLIENT,
@@ -2751,7 +2868,7 @@ function sendActivity(options) {
2751
2868
  await sendActivityInternal({
2752
2869
  ...options,
2753
2870
  tracerProvider
2754
- }, span);
2871
+ }, span, deps);
2755
2872
  } catch (e) {
2756
2873
  span.setStatus({
2757
2874
  code: SpanStatusCode.ERROR,
@@ -2764,7 +2881,25 @@ function sendActivity(options) {
2764
2881
  });
2765
2882
  }
2766
2883
  const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
2767
- async function readLimitedResponseBody(response, maxBytes) {
2884
+ const SEND_ACTIVITY_TIMEOUT_MS = 3e4;
2885
+ function raceWithAbort(promise, signal) {
2886
+ if (signal.aborted) return Promise.reject(signal.reason);
2887
+ return new Promise((resolve, reject) => {
2888
+ const onAbort = () => {
2889
+ signal.removeEventListener("abort", onAbort);
2890
+ reject(signal.reason);
2891
+ };
2892
+ signal.addEventListener("abort", onAbort, { once: true });
2893
+ promise.then((value) => {
2894
+ signal.removeEventListener("abort", onAbort);
2895
+ resolve(value);
2896
+ }, (error) => {
2897
+ signal.removeEventListener("abort", onAbort);
2898
+ reject(error);
2899
+ });
2900
+ });
2901
+ }
2902
+ async function readLimitedResponseBody(response, maxBytes, signal) {
2768
2903
  if (response.body == null) return "";
2769
2904
  const reader = response.body.getReader();
2770
2905
  const decoder = new TextDecoder();
@@ -2773,7 +2908,8 @@ async function readLimitedResponseBody(response, maxBytes) {
2773
2908
  let truncated = false;
2774
2909
  try {
2775
2910
  while (true) {
2776
- const { done, value } = await reader.read();
2911
+ signal.throwIfAborted();
2912
+ const { done, value } = await raceWithAbort(reader.read(), signal);
2777
2913
  if (done) break;
2778
2914
  if (totalBytes + value.length > maxBytes) {
2779
2915
  const remaining = maxBytes - totalBytes;
@@ -2785,21 +2921,39 @@ async function readLimitedResponseBody(response, maxBytes) {
2785
2921
  totalBytes += value.length;
2786
2922
  }
2787
2923
  } finally {
2788
- reader.releaseLock();
2924
+ if (truncated || signal.aborted) reader.cancel().catch(() => {});
2925
+ try {
2926
+ reader.releaseLock();
2927
+ } catch (_) {}
2789
2928
  }
2790
2929
  let result = chunks.join("");
2791
2930
  if (truncated) result += "… (truncated)";
2792
2931
  return result;
2793
2932
  }
2794
- async function sendActivityInternal({ activity, activityId, keys, inbox, allowPrivateAddress, headers, specDeterminer, tracerProvider }, span) {
2933
+ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPrivateAddress, headers, specDeterminer, tracerProvider }, span, deps) {
2795
2934
  const logger = getLogger([
2796
2935
  "fedify",
2797
2936
  "federation",
2798
2937
  "outbox"
2799
2938
  ]);
2800
- async function validateUrl(url) {
2801
- if (!allowPrivateAddress) try {
2802
- await validatePublicUrl(url);
2939
+ const timeoutMs = deps.timeoutMs ?? SEND_ACTIVITY_TIMEOUT_MS;
2940
+ const controller = new AbortController();
2941
+ const { signal } = controller;
2942
+ const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? openDirectFetch : (url) => openPublicFetch(url, { signal }));
2943
+ let opened = false;
2944
+ async function openHop(url) {
2945
+ let session;
2946
+ try {
2947
+ signal.throwIfAborted();
2948
+ const opening = openUnvalidatedHop(url);
2949
+ opening.then((lateSession) => {
2950
+ if (signal.aborted) closeAfterError(lateSession, logger);
2951
+ }, () => {});
2952
+ session = await raceWithAbort(opening, signal);
2953
+ if (signal.aborted) {
2954
+ closeAfterError(session, logger);
2955
+ signal.throwIfAborted();
2956
+ }
2803
2957
  } catch (error) {
2804
2958
  if (error instanceof UrlError && error.reason === "dns") {
2805
2959
  logger.error("DNS resolution failed for URL: {url}", {
@@ -2816,15 +2970,17 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2816
2970
  });
2817
2971
  throw error;
2818
2972
  }
2973
+ opened = true;
2974
+ return session;
2819
2975
  }
2820
- await validateUrl(inbox.href);
2821
2976
  headers = new Headers(headers);
2822
2977
  headers.set("Content-Type", "application/activity+json");
2823
2978
  const request = new Request(inbox, {
2824
2979
  method: "POST",
2825
2980
  headers,
2826
2981
  body: JSON.stringify(activity),
2827
- redirect: "manual"
2982
+ redirect: "manual",
2983
+ signal
2828
2984
  });
2829
2985
  let rsaKey = null;
2830
2986
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -2838,36 +2994,60 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2838
2994
  privateKey: pair.privateKey
2839
2995
  }))
2840
2996
  });
2841
- let response;
2997
+ let outcome;
2998
+ const boundedSpecDeterminer = specDeterminer == null ? void 0 : {
2999
+ determineSpec(origin) {
3000
+ signal.throwIfAborted();
3001
+ return raceWithAbort(Promise.resolve(specDeterminer.determineSpec(origin)), signal);
3002
+ },
3003
+ rememberSpec(origin, spec) {
3004
+ if (signal.aborted) return;
3005
+ try {
3006
+ Promise.resolve(specDeterminer.rememberSpec(origin, spec)).catch((error) => logger.debug("Failed to remember the signature spec for {origin}: {error}", {
3007
+ origin,
3008
+ error
3009
+ }));
3010
+ } catch (error) {
3011
+ logger.debug("Failed to remember the signature spec for {origin}: {error}", {
3012
+ origin,
3013
+ error
3014
+ });
3015
+ }
3016
+ }
3017
+ };
3018
+ const timer = setTimeout(() => controller.abort(new DOMException("The delivery timed out.", "TimeoutError")), timeoutMs);
2842
3019
  try {
2843
- response = rsaKey == null ? await fetchWithValidatedRedirects(request, validateUrl) : await doubleKnock(request, rsaKey, {
3020
+ outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox, signal), signal) : await doubleKnockScoped(request, rsaKey, {
2844
3021
  tracerProvider,
2845
- specDeterminer,
2846
- validateRedirect: validateUrl
2847
- });
3022
+ specDeterminer: boundedSpecDeterminer,
3023
+ signal
3024
+ }, openHop, (response) => consumeSendActivityResponse(response, inbox, signal));
2848
3025
  } catch (error) {
2849
- logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
3026
+ let failureError = error;
3027
+ if (signal.aborted && !(error instanceof SendActivityError)) {
3028
+ const failure = new FetchError(inbox.href, `Timed out after ${timeoutMs} ms`);
3029
+ failure.cause = signal.reason;
3030
+ failureError = failure;
3031
+ }
3032
+ if (opened || signal.aborted) logger.error("Failed to send activity {activityId} to {inbox}:\n{error}", {
2850
3033
  activityId,
2851
3034
  inbox: inbox.href,
2852
- error
3035
+ error: failureError
2853
3036
  });
2854
- throw error;
3037
+ throw failureError;
3038
+ } finally {
3039
+ clearTimeout(timer);
2855
3040
  }
2856
- if (!response.ok) {
2857
- let error;
2858
- try {
2859
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
2860
- } catch (_) {
2861
- error = "";
2862
- }
3041
+ if (!outcome.ok) {
3042
+ const { status, statusText, error } = outcome;
2863
3043
  logger.error("Failed to send activity {activityId} to {inbox} ({status} {statusText}):\n{error}", {
2864
3044
  activityId,
2865
3045
  inbox: inbox.href,
2866
- status: response.status,
2867
- statusText: response.statusText,
3046
+ status,
3047
+ statusText,
2868
3048
  error
2869
3049
  });
2870
- throw new SendActivityError(inbox, response.status, `Failed to send activity ${activityId} to ${inbox.href} (${response.status} ${response.statusText}):\n${error}`, error);
3050
+ throw new SendActivityError(inbox, status, `Failed to send activity ${activityId} to ${inbox.href} (${status} ${statusText}):\n${error}`, error);
2871
3051
  }
2872
3052
  span.addEvent("activitypub.activity.sent", {
2873
3053
  "activitypub.activity.json": JSON.stringify(activity),
@@ -2875,10 +3055,79 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2875
3055
  "activitypub.activity.id": activityId ?? ""
2876
3056
  });
2877
3057
  }
2878
- async function fetchWithValidatedRedirects(request, validateUrl) {
3058
+ /**
3059
+ * Starts cancelling the body of a response without waiting for it to settle.
3060
+ * The cancellation of a branch of a tee (e.g., a body cloned by a fetch mock)
3061
+ * settles only after the other branch is cancelled too, per the Streams
3062
+ * standard, so awaiting it could block forever. Failures are only logged.
3063
+ */
3064
+ function cancelResponseBody(response, url) {
3065
+ response.body?.cancel().catch((error) => {
3066
+ getLogger([
3067
+ "fedify",
3068
+ "federation",
3069
+ "outbox"
3070
+ ]).debug("Failed to cancel the response body from {url}: {error}", {
3071
+ url,
3072
+ error
3073
+ });
3074
+ });
3075
+ }
3076
+ /**
3077
+ * Reads what is needed from the final response of a delivery while its
3078
+ * session is open: the body of a successful response is cancelled, and at
3079
+ * most 1 KiB of an error response body is read.
3080
+ */
3081
+ async function consumeSendActivityResponse(response, inbox, signal) {
3082
+ if (response.ok) {
3083
+ cancelResponseBody(response, response.url || inbox.href);
3084
+ return { ok: true };
3085
+ }
3086
+ let error;
3087
+ try {
3088
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES, signal);
3089
+ } catch (_) {
3090
+ error = "";
3091
+ }
3092
+ if (signal.aborted) error = "(timed out reading response body)";
3093
+ return {
3094
+ ok: false,
3095
+ status: response.status,
3096
+ statusText: response.statusText,
3097
+ error
3098
+ };
3099
+ }
3100
+ /**
3101
+ * Sends a request without signing it, following redirects manually like the
3102
+ * Fetch standard does. Every hop is opened with `openHop()`, which validates
3103
+ * the destination, after the previous hop is closed. The final response is
3104
+ * passed to `consume()`, and its session is closed after that.
3105
+ * This is exported only for tests; it is not exported from any entry point.
3106
+ * @param request The request to send.
3107
+ * @param openHop The function to open a session for each hop.
3108
+ * @param consume The function to consume the final response.
3109
+ * @returns The value returned by `consume`.
3110
+ */
3111
+ async function fetchWithValidatedRedirects(request, openHop, consume, signal) {
3112
+ const logger = getLogger([
3113
+ "fedify",
3114
+ "federation",
3115
+ "outbox"
3116
+ ]);
2879
3117
  let body = await request.clone().text();
2880
3118
  for (let redirects = 0;; redirects++) {
2881
- const response = await fetch(request, { redirect: "manual" });
3119
+ signal?.throwIfAborted();
3120
+ const session = await openHop(request.url);
3121
+ let response;
3122
+ try {
3123
+ response = await session.fetch(request, {
3124
+ redirect: "manual",
3125
+ signal
3126
+ });
3127
+ } catch (error) {
3128
+ await closeAfterError(session, logger);
3129
+ throw error;
3130
+ }
2882
3131
  const location = response.headers.get("Location");
2883
3132
  if (![
2884
3133
  301,
@@ -2886,11 +3135,21 @@ async function fetchWithValidatedRedirects(request, validateUrl) {
2886
3135
  303,
2887
3136
  307,
2888
3137
  308
2889
- ].includes(response.status) || location == null) return response;
2890
- await response.body?.cancel();
3138
+ ].includes(response.status) || location == null) try {
3139
+ return await consume(response);
3140
+ } catch (error) {
3141
+ logger.debug("Failed to consume the response from {url}; closing the session: {error}", {
3142
+ url: request.url,
3143
+ error
3144
+ });
3145
+ throw error;
3146
+ } finally {
3147
+ await session.close();
3148
+ }
3149
+ cancelResponseBody(response, request.url);
3150
+ await session.close();
2891
3151
  if (redirects >= 20) throw new TypeError("Too many redirects");
2892
3152
  const url = new URL(location, request.url);
2893
- await validateUrl(url.href);
2894
3153
  const headers = new Headers(request.headers);
2895
3154
  if (url.origin !== new URL(request.url).origin) {
2896
3155
  headers.delete("Authorization");
@@ -2914,7 +3173,18 @@ async function fetchWithValidatedRedirects(request, validateUrl) {
2914
3173
  method,
2915
3174
  headers,
2916
3175
  body,
2917
- redirect: "manual"
3176
+ redirect: "manual",
3177
+ signal: signal ?? request.signal
3178
+ });
3179
+ }
3180
+ }
3181
+ async function closeAfterError(session, logger) {
3182
+ try {
3183
+ await session.close();
3184
+ } catch (error) {
3185
+ logger.debug("Failed to close the session for {url}: {error}", {
3186
+ url: session.url.href,
3187
+ error
2918
3188
  });
2919
3189
  }
2920
3190
  }
@@ -3269,8 +3539,25 @@ var FederationImpl = class extends FederationBuilderImpl {
3269
3539
  _getTracer() {
3270
3540
  return this.tracerProvider.getTracer(name, version);
3271
3541
  }
3542
+ /**
3543
+ * Starts listening on a queue, converting a synchronous throw into
3544
+ * a rejected promise.
3545
+ *
3546
+ * `MessageQueue.listen()` is documented to never reject, but some
3547
+ * implementations (e.g., `WorkersMessageQueue`) throw synchronously. Without
3548
+ * this normalization, one such throw aborts {@link _startQueueInternal} while
3549
+ * it is still collecting listener promises, so listeners started earlier are
3550
+ * never awaited and later queues are never started.
3551
+ */
3552
+ #listenQueue(queue, ctxData, signal) {
3553
+ try {
3554
+ return queue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal });
3555
+ } catch (error) {
3556
+ return Promise.reject(error);
3557
+ }
3558
+ }
3272
3559
  async _startQueueInternal(ctxData, signal, queue) {
3273
- if (this.inboxQueue == null && this.outboxQueue == null) return;
3560
+ if (this.inboxQueue == null && this.outboxQueue == null && this.fanoutQueue == null) return;
3274
3561
  const logger = getLogger([
3275
3562
  "fedify",
3276
3563
  "federation",
@@ -3280,20 +3567,38 @@ var FederationImpl = class extends FederationBuilderImpl {
3280
3567
  if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
3281
3568
  logger.debug("Starting an inbox task worker.");
3282
3569
  this.inboxQueueStarted = true;
3283
- promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3570
+ promises.push(this.#listenQueue(this.inboxQueue, ctxData, signal));
3284
3571
  }
3285
3572
  if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
3286
3573
  logger.debug("Starting an outbox task worker.");
3287
3574
  this.outboxQueueStarted = true;
3288
- promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3575
+ promises.push(this.#listenQueue(this.outboxQueue, ctxData, signal));
3289
3576
  }
3290
3577
  if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
3291
3578
  logger.debug("Starting a fanout task worker.");
3292
3579
  this.fanoutQueueStarted = true;
3293
- promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3580
+ promises.push(this.#listenQueue(this.fanoutQueue, ctxData, signal));
3294
3581
  }
3295
3582
  await Promise.all(promises);
3296
3583
  }
3584
+ /**
3585
+ * Starts the queue workers automatically, reporting a failure instead of
3586
+ * leaving the returned promise unobserved.
3587
+ *
3588
+ * Automatic startup is best-effort: call sites cannot await it, so a failing
3589
+ * listener (e.g., `WorkersMessageQueue`, whose `listen()` throws) must not
3590
+ * become an unhandled rejection. {@link startQueue} keeps rejecting for
3591
+ * callers that start workers deliberately.
3592
+ */
3593
+ _startQueueAutomatically(ctxData) {
3594
+ this._startQueueInternal(ctxData).catch((error) => {
3595
+ getLogger([
3596
+ "fedify",
3597
+ "federation",
3598
+ "queue"
3599
+ ]).warn("Failed to start queue workers automatically: {error}", { error });
3600
+ });
3601
+ }
3297
3602
  processQueuedTask(contextData, message) {
3298
3603
  const tracer = this._getTracer();
3299
3604
  const extractedContext = propagation.extract(context.active(), message.traceContext);
@@ -3403,7 +3708,8 @@ var FederationImpl = class extends FederationBuilderImpl {
3403
3708
  collectionSync: message.collectionSync,
3404
3709
  orderingKey: message.orderingKey,
3405
3710
  normalizeExistingProofs: message.normalizeExistingProofs,
3406
- context
3711
+ context,
3712
+ activityJsonLd: hasTopLevelProof(message.activity) ? message.activity : void 0
3407
3713
  });
3408
3714
  }
3409
3715
  async #listenOutboxMessage(_, message, span) {
@@ -3606,7 +3912,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3606
3912
  let parseInput = void 0;
3607
3913
  let parseContextLoader = context.contextLoader;
3608
3914
  try {
3609
- const hasSignatureField = hasSignature(message.activity);
3915
+ const hasSignatureField = hasVerifiableSignature(message.activity);
3610
3916
  const shouldParseFromNormalizedSignedPayload = message.ldSignatureVerified === true || message.normalizedActivity != null || message.ldSignatureVerified == null && hasSignatureField;
3611
3917
  const parseContext = hasSignatureField ? {
3612
3918
  ...context,
@@ -3802,21 +4108,31 @@ var FederationImpl = class extends FederationBuilderImpl {
3802
4108
  hasProof = true;
3803
4109
  break;
3804
4110
  }
3805
- if (!hasProof) {
3806
- for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3807
- activity = await signObject(activity, privateKey, keyId, {
3808
- contextLoader,
3809
- tracerProvider: this.tracerProvider
3810
- });
3811
- hasProof = true;
3812
- proofCreated = true;
4111
+ const prepared = !hasProof && options.activityJsonLd == null ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
4112
+ let jsonLd;
4113
+ if (prepared != null) {
4114
+ const signingKeys = keys.filter(({ privateKey }) => privateKey.algorithm.name === "Ed25519");
4115
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
4116
+ activity = signed.activity;
4117
+ jsonLd = signed.jsonLd;
4118
+ proofCreated = signingKeys.length > 0;
4119
+ } else {
4120
+ if (!hasProof) {
4121
+ for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
4122
+ activity = await signObject(activity, privateKey, keyId, {
4123
+ contextLoader,
4124
+ tracerProvider: this.tracerProvider
4125
+ });
4126
+ proofCreated = true;
4127
+ }
3813
4128
  }
4129
+ jsonLd = options.activityJsonLd != null ? detachSignature(options.activityJsonLd) : await activity.toJsonLd({
4130
+ format: "compact",
4131
+ contextLoader
4132
+ });
3814
4133
  }
3815
- let jsonLd = await activity.toJsonLd({
3816
- format: "compact",
3817
- contextLoader
3818
- });
3819
- if (proofCreated || !hasProof || options.normalizeExistingProofs) jsonLd = await normalizeOutgoingActivityJsonLd(jsonLd, contextLoader);
4134
+ if (prepared == null && (proofCreated || !hasProof || options.normalizeExistingProofs)) jsonLd = await normalizeOutgoingActivityJsonLd(jsonLd, contextLoader);
4135
+ hasProof ||= proofCreated;
3820
4136
  if (rsaKey == null) logger.warn("No supported key found to create a Linked Data signature for the activity {activityId}. The activity will be sent without a Linked Data signature. In order to create a Linked Data signature, at least one RSASSA-PKCS1-v1_5 key must be provided.", {
3821
4137
  activityId,
3822
4138
  keys: keys.map((pair) => ({
@@ -3853,19 +4169,27 @@ var FederationImpl = class extends FederationBuilderImpl {
3853
4169
  activity: jsonLd
3854
4170
  });
3855
4171
  const promises = [];
3856
- for (const inbox in inboxes) promises.push(sendActivity({
3857
- allowPrivateAddress: this.allowPrivateAddress,
3858
- keys,
3859
- activity: jsonLd,
3860
- activityId: activity.id?.href,
3861
- activityType: getTypeId(activity).href,
3862
- inbox: new URL(inbox),
3863
- sharedInbox: inboxes[inbox].sharedInbox,
3864
- headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
3865
- specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
3866
- tracerProvider: this.tracerProvider
3867
- }));
3868
- await Promise.all(promises);
4172
+ try {
4173
+ for (const inbox in inboxes) {
4174
+ const promise = sendActivity({
4175
+ allowPrivateAddress: this.allowPrivateAddress,
4176
+ keys,
4177
+ activity: jsonLd,
4178
+ activityId: activity.id?.href,
4179
+ activityType: getTypeId(activity).href,
4180
+ inbox: new URL(inbox),
4181
+ sharedInbox: inboxes[inbox].sharedInbox,
4182
+ headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
4183
+ specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
4184
+ tracerProvider: this.tracerProvider
4185
+ });
4186
+ promise.catch(() => {});
4187
+ promises.push(promise);
4188
+ }
4189
+ await Promise.all(promises);
4190
+ } finally {
4191
+ await Promise.allSettled(promises);
4192
+ }
3869
4193
  return;
3870
4194
  }
3871
4195
  logger.debug("Enqueuing activity {activityId} to send later.", {
@@ -3880,7 +4204,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3880
4204
  privateKey: privateKeyJwk
3881
4205
  });
3882
4206
  }
3883
- if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
4207
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(ctx.data);
3884
4208
  const carrier = {};
3885
4209
  propagation.inject(context.active(), carrier);
3886
4210
  const messages = [];
@@ -4113,7 +4437,7 @@ var FederationImpl = class extends FederationBuilderImpl {
4113
4437
  const identity = await this.sharedInboxKeyDispatcher(context);
4114
4438
  if (identity != null) context = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity ? await context.getDocumentLoader(identity) : context.getDocumentLoader(identity) });
4115
4439
  }
4116
- if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
4440
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(contextData);
4117
4441
  const inboxContextFactory = context.toInboxContext.bind(context);
4118
4442
  inboxContextFactory[rawInboxContextFactorySymbol] = context.toInboxContext.bind(context);
4119
4443
  return await handleInbox(request, {
@@ -4446,6 +4770,8 @@ var ContextImpl = class ContextImpl {
4446
4770
  for (const keyPair of keyPairs) {
4447
4771
  const newPair = {
4448
4772
  ...keyPair,
4773
+ privateKey: asCryptoKey(keyPair.privateKey),
4774
+ publicKey: asCryptoKey(keyPair.publicKey),
4449
4775
  cryptographicKey: new CryptographicKey({
4450
4776
  id: keyPair.keyId,
4451
4777
  owner,
@@ -4522,10 +4848,16 @@ var ContextImpl = class ContextImpl {
4522
4848
  } else identifierPromise = Promise.resolve(identity.identifier);
4523
4849
  return identifierPromise.then((identifier) => {
4524
4850
  if (identifier == null) return this.documentLoader;
4525
- return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory(pair));
4851
+ return this.getRsaKeyPairFromIdentifier(identifier).then((pair) => pair == null ? this.documentLoader : this.federation.authenticatedDocumentLoaderFactory({
4852
+ keyId: pair.keyId,
4853
+ privateKey: asCryptoKey(pair.privateKey)
4854
+ }));
4526
4855
  });
4527
4856
  }
4528
- return this.federation.authenticatedDocumentLoaderFactory(identity);
4857
+ return this.federation.authenticatedDocumentLoaderFactory({
4858
+ keyId: identity.keyId,
4859
+ privateKey: asCryptoKey(identity.privateKey)
4860
+ });
4529
4861
  }
4530
4862
  lookupObject(identifier, options = {}) {
4531
4863
  return lookupObject(identifier, {
@@ -4548,10 +4880,14 @@ var ContextImpl = class ContextImpl {
4548
4880
  return options.parse === "none" ? getNodeInfo(url, {
4549
4881
  parse: "none",
4550
4882
  direct: options.direct,
4883
+ timeout: options.timeout,
4884
+ signal: options.signal,
4551
4885
  userAgent: options?.userAgent ?? this.federation.userAgent
4552
4886
  }) : getNodeInfo(url, {
4553
4887
  parse: options.parse,
4554
4888
  direct: options.direct,
4889
+ timeout: options.timeout,
4890
+ signal: options.signal,
4555
4891
  userAgent: options?.userAgent ?? this.federation.userAgent
4556
4892
  });
4557
4893
  }
@@ -4563,7 +4899,17 @@ var ContextImpl = class ContextImpl {
4563
4899
  allowPrivateAddress: this.federation.allowPrivateAddress
4564
4900
  });
4565
4901
  }
4566
- sendActivity(sender, recipients, activity, options = {}) {
4902
+ async sendActivity(sender, recipients, activity, options = {}) {
4903
+ let activityJsonLd = void 0;
4904
+ let hasProof = activity.proofIds.length > 0;
4905
+ if (!hasProof) for await (const _ of activity.getProofs({ contextLoader: this.contextLoader })) {
4906
+ hasProof = true;
4907
+ break;
4908
+ }
4909
+ if (hasProof) {
4910
+ activityJsonLd = await activity.toJsonLd({ contextLoader: this.contextLoader });
4911
+ if (!hasTopLevelProof(activityJsonLd)) activityJsonLd = void 0;
4912
+ }
4567
4913
  return this.tracerProvider.getTracer(name, version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
4568
4914
  kind: this.federation.outboxQueue == null || options.immediate ? SpanKind.CLIENT : SpanKind.PRODUCER,
4569
4915
  attributes: {
@@ -4576,7 +4922,7 @@ var ContextImpl = class ContextImpl {
4576
4922
  }, async (span) => {
4577
4923
  try {
4578
4924
  if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
4579
- await this.sendActivityInternal(sender, recipients, activity, options, span);
4925
+ await this.sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd);
4580
4926
  } catch (e) {
4581
4927
  span.setStatus({
4582
4928
  code: SpanStatusCode.ERROR,
@@ -4588,7 +4934,7 @@ var ContextImpl = class ContextImpl {
4588
4934
  }
4589
4935
  });
4590
4936
  }
4591
- async sendActivityInternal(sender, recipients, activity, options, span) {
4937
+ async sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd) {
4592
4938
  const logger = getLogger([
4593
4939
  "fedify",
4594
4940
  "federation",
@@ -4635,15 +4981,23 @@ var ContextImpl = class ContextImpl {
4635
4981
  if (!(error instanceof RouterError)) throw error;
4636
4982
  }
4637
4983
  } else expandedRecipients = [recipients];
4638
- const opts = {
4639
- context: this,
4640
- orderingKey: options.orderingKey,
4641
- collectionSync,
4642
- immediate: options.immediate,
4643
- normalizeExistingProofs: options.normalizeExistingProofs
4644
- };
4645
4984
  span.setAttribute("activitypub.inboxes", expandedRecipients.length);
4646
4985
  for (const activityTransformer of this.federation.activityTransformers) activity = activityTransformer(activity, this);
4986
+ let contextMatches = false;
4987
+ if (activityJsonLd != null) {
4988
+ const capturedJsonLd = activityJsonLd;
4989
+ const transformedJsonLd = await activity.toJsonLd({
4990
+ format: "compact",
4991
+ contextLoader: this.contextLoader
4992
+ });
4993
+ const contentChanged = getContentFields(transformedJsonLd) !== getContentFields(capturedJsonLd);
4994
+ contextMatches = getContextFields(transformedJsonLd) === getContextFields(capturedJsonLd);
4995
+ const proofsChanged = getProofFields(transformedJsonLd) !== getProofFields(capturedJsonLd);
4996
+ if (contentChanged || !contextMatches && proofsChanged) {
4997
+ activity = activity.clone({ proofs: await getUncapturedProofs(activity, capturedJsonLd, this.contextLoader) });
4998
+ activityJsonLd = void 0;
4999
+ } else if (proofsChanged) activityJsonLd = void 0;
5000
+ }
4647
5001
  span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
4648
5002
  if (activity.actorId == null) {
4649
5003
  logger.error("Activity {activityId} to send does not have an actor.", {
@@ -4655,15 +5009,42 @@ var ContextImpl = class ContextImpl {
4655
5009
  let proofCreated = false;
4656
5010
  if (actorKeyPairs != null) {
4657
5011
  const contextLoader = this.contextLoader;
4658
- for (const kp of actorKeyPairs) {
4659
- if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4660
- activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
4661
- contextLoader,
4662
- tracerProvider: this.tracerProvider
4663
- });
4664
- proofCreated = true;
5012
+ const willSign = actorKeyPairs.some((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null);
5013
+ if (willSign) {
5014
+ if (activityJsonLd != null && !contextMatches) activity = activity.clone({ proofs: [] });
5015
+ }
5016
+ const prepared = willSign ? await prepareActivityJsonLd(activity, contextLoader) : void 0;
5017
+ if (prepared != null) {
5018
+ const signingKeys = actorKeyPairs.flatMap((kp) => kp.privateKey.algorithm.name === "Ed25519" && kp.multikey.id != null ? [{
5019
+ privateKey: kp.privateKey,
5020
+ keyId: kp.multikey.id
5021
+ }] : []);
5022
+ const signed = await signActivityJsonLd(activity, prepared, signingKeys, { tracerProvider: this.tracerProvider });
5023
+ activity = signed.activity;
5024
+ activityJsonLd = signed.jsonLd;
5025
+ proofCreated = signingKeys.length > 0;
5026
+ } else {
5027
+ let proofAdded = false;
5028
+ for (const kp of actorKeyPairs) {
5029
+ if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
5030
+ activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
5031
+ contextLoader,
5032
+ tracerProvider: this.tracerProvider
5033
+ });
5034
+ proofAdded = true;
5035
+ }
5036
+ if (proofAdded) activityJsonLd = void 0;
5037
+ proofCreated = proofAdded;
4665
5038
  }
4666
5039
  }
5040
+ const opts = {
5041
+ context: this,
5042
+ orderingKey: options.orderingKey,
5043
+ collectionSync,
5044
+ immediate: options.immediate,
5045
+ activityJsonLd,
5046
+ normalizeExistingProofs: options.normalizeExistingProofs
5047
+ };
4667
5048
  const inboxes = extractInboxes({
4668
5049
  recipients: expandedRecipients,
4669
5050
  preferSharedInbox: options.preferSharedInbox,
@@ -4703,7 +5084,7 @@ var ContextImpl = class ContextImpl {
4703
5084
  actorIds: [...actorIds],
4704
5085
  sharedInbox
4705
5086
  }])),
4706
- activity: await activity.toJsonLd({
5087
+ activity: activityJsonLd != null ? detachSignature(activityJsonLd) : await activity.toJsonLd({
4707
5088
  format: "compact",
4708
5089
  contextLoader: this.contextLoader
4709
5090
  }),
@@ -4714,7 +5095,7 @@ var ContextImpl = class ContextImpl {
4714
5095
  normalizeExistingProofs: proofCreated || options.normalizeExistingProofs,
4715
5096
  traceContext: carrier
4716
5097
  };
4717
- if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
5098
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueAutomatically(this.data);
4718
5099
  await this.federation.fanoutQueue.enqueue(message, { orderingKey: options.orderingKey });
4719
5100
  return true;
4720
5101
  }
@@ -4914,43 +5295,83 @@ var RequestContextImpl = class RequestContextImpl extends ContextImpl {
4914
5295
  }
4915
5296
  }), values);
4916
5297
  }
4917
- #signedKey = void 0;
5298
+ #signedKey = null;
5299
+ #signedKeyOwner = null;
5300
+ #signatureChecks = /* @__PURE__ */ new WeakMap();
5301
+ #getSignatureCheck(documentLoader, contextLoader) {
5302
+ let checks = this.#signatureChecks.get(documentLoader);
5303
+ if (checks == null) {
5304
+ checks = /* @__PURE__ */ new WeakMap();
5305
+ this.#signatureChecks.set(documentLoader, checks);
5306
+ }
5307
+ let check = checks.get(contextLoader);
5308
+ if (check == null) {
5309
+ check = {};
5310
+ checks.set(contextLoader, check);
5311
+ }
5312
+ return check;
5313
+ }
4918
5314
  async getSignedKey(options = {}) {
4919
5315
  if (this.#signedKey != null) return this.#signedKey;
4920
- return this.#signedKey = await verifyRequest(this.request, {
5316
+ const documentLoader = options.documentLoader ?? this.documentLoader;
5317
+ const contextLoader = options.contextLoader ?? this.contextLoader;
5318
+ const check = this.#getSignatureCheck(documentLoader, contextLoader);
5319
+ if (check.key != null) return check.key;
5320
+ const promise = verifyRequest(this.request, {
4921
5321
  ...this,
4922
- contextLoader: options.contextLoader ?? this.contextLoader,
4923
- documentLoader: options.documentLoader ?? this.documentLoader,
5322
+ contextLoader,
5323
+ documentLoader,
4924
5324
  timeWindow: this.federation.signatureTimeWindow,
4925
5325
  tracerProvider: options.tracerProvider ?? this.tracerProvider
5326
+ }).then((key) => {
5327
+ if (key != null) this.#signedKey ??= key;
5328
+ return key;
5329
+ }).catch((error) => {
5330
+ if (check.key === promise) check.key = void 0;
5331
+ throw error;
4926
5332
  });
5333
+ check.key = promise;
5334
+ return await promise;
4927
5335
  }
4928
- #signedKeyOwner = void 0;
4929
5336
  async getSignedKeyOwner(options = {}) {
4930
5337
  if (this.#signedKeyOwner != null) return this.#signedKeyOwner;
4931
- const key = await this.getSignedKey(options);
4932
- if (key == null) return this.#signedKeyOwner = null;
4933
- try {
4934
- return this.#signedKeyOwner = await getKeyOwner(key, {
4935
- contextLoader: options.contextLoader ?? this.contextLoader,
4936
- documentLoader: options.documentLoader ?? this.documentLoader,
4937
- tracerProvider: options.tracerProvider ?? this.tracerProvider
4938
- });
4939
- } catch (error) {
4940
- if (error instanceof FetchError) {
4941
- getLogger([
4942
- "fedify",
4943
- "federation",
4944
- "actor"
4945
- ]).warn("Failed to fetch the key owner {keyOwner} of {keyId} while verifying the request signature; treating the request as unauthenticated: {error}", {
4946
- keyId: key.id?.href,
4947
- keyOwner: error.url.href,
4948
- error
4949
- });
4950
- return this.#signedKeyOwner = null;
5338
+ const normalizedOptions = {
5339
+ documentLoader: options.documentLoader ?? this.documentLoader,
5340
+ contextLoader: options.contextLoader ?? this.contextLoader,
5341
+ tracerProvider: options.tracerProvider ?? this.tracerProvider
5342
+ };
5343
+ const check = this.#getSignatureCheck(normalizedOptions.documentLoader, normalizedOptions.contextLoader);
5344
+ if (check.owner != null) return check.owner;
5345
+ const promise = this.getSignedKey(normalizedOptions).then(async (key) => {
5346
+ if (key == null) {
5347
+ if (check.owner === promise) check.owner = void 0;
5348
+ return null;
5349
+ }
5350
+ try {
5351
+ const owner = await getKeyOwner(key, normalizedOptions);
5352
+ if (owner != null) this.#signedKeyOwner ??= owner;
5353
+ return owner;
5354
+ } catch (error) {
5355
+ if (error instanceof FetchError) {
5356
+ getLogger([
5357
+ "fedify",
5358
+ "federation",
5359
+ "actor"
5360
+ ]).warn("Failed to fetch the key owner {keyOwner} of {keyId} while verifying the request signature; treating the request as unauthenticated: {error}", {
5361
+ keyId: key.id?.href,
5362
+ keyOwner: error.url.href,
5363
+ error
5364
+ });
5365
+ return null;
5366
+ }
5367
+ throw error;
4951
5368
  }
5369
+ }).catch((error) => {
5370
+ if (check.owner === promise) check.owner = void 0;
4952
5371
  throw error;
4953
- }
5372
+ });
5373
+ check.owner = promise;
5374
+ return await promise;
4954
5375
  }
4955
5376
  };
4956
5377
  function forwardActivity(ctx, loggerCategory, forwarder, recipients, options) {
@@ -5001,7 +5422,7 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
5001
5422
  if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
5002
5423
  keys = forwarder;
5003
5424
  } else keys = [forwarder];
5004
- if (!hasSignatureLike(ctx.activity)) {
5425
+ if (!hasVerifiableSignature(ctx.activity) && !hasSignatureLike(ctx.activity)) {
5005
5426
  if (!hasProofLike(ctx.activity)) {
5006
5427
  if (options?.skipIfUnsigned) return false;
5007
5428
  logger.warn("The activity {activityId} is not signed; even if it is forwarded to other servers as is, it may not be accepted by them due to the lack of a signature/proof.", {
@@ -5039,25 +5460,33 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
5039
5460
  if (options?.immediate) logger.debug("Forwarding activity immediately without queue since immediate option is set.");
5040
5461
  else logger.debug("Forwarding activity immediately without queue since queue is not set.");
5041
5462
  const promises = [];
5042
- for (const inbox in inboxes) promises.push(sendActivity({
5043
- allowPrivateAddress: ctx.federation.allowPrivateAddress,
5044
- keys,
5045
- activity: ctx.activity,
5046
- activityId: ctx.activityId,
5047
- activityType: ctx.activityType,
5048
- inbox: new URL(inbox),
5049
- sharedInbox: inboxes[inbox].sharedInbox,
5050
- tracerProvider: ctx.tracerProvider,
5051
- specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
5052
- }));
5053
- await Promise.all(promises);
5463
+ try {
5464
+ for (const inbox in inboxes) {
5465
+ const promise = sendActivity({
5466
+ allowPrivateAddress: ctx.federation.allowPrivateAddress,
5467
+ keys,
5468
+ activity: ctx.activity,
5469
+ activityId: ctx.activityId,
5470
+ activityType: ctx.activityType,
5471
+ inbox: new URL(inbox),
5472
+ sharedInbox: inboxes[inbox].sharedInbox,
5473
+ tracerProvider: ctx.tracerProvider,
5474
+ specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
5475
+ });
5476
+ promise.catch(() => {});
5477
+ promises.push(promise);
5478
+ }
5479
+ await Promise.all(promises);
5480
+ } finally {
5481
+ await Promise.allSettled(promises);
5482
+ }
5054
5483
  return true;
5055
5484
  }
5056
5485
  logger.debug("Enqueuing activity {activityId} to forward later.", {
5057
5486
  activityId: ctx.activityId,
5058
5487
  activity: ctx.activity
5059
5488
  });
5060
- if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueInternal(ctx.data);
5489
+ if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueAutomatically(ctx.data);
5061
5490
  const keyJwkPairs = [];
5062
5491
  for (const { keyId, privateKey } of keys) {
5063
5492
  const privateKeyJwk = await exportJwk(privateKey);
@@ -5229,6 +5658,69 @@ var KvSpecDeterminer = class {
5229
5658
  function notFound(_request) {
5230
5659
  return new Response("Not Found", { status: 404 });
5231
5660
  }
5661
+ function hasTopLevelProof(value) {
5662
+ return typeof value === "object" && value != null && !Array.isArray(value) && globalThis.Object.prototype.hasOwnProperty.call(value, "proof");
5663
+ }
5664
+ function getContentFields(value) {
5665
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
5666
+ const record = { ...value };
5667
+ delete record["@context"];
5668
+ delete record.proof;
5669
+ delete record.signature;
5670
+ return JSON.stringify(sortJsonKeys(record));
5671
+ }
5672
+ function getContextFields(value) {
5673
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return JSON.stringify(sortJsonKeys(value));
5674
+ const context = value["@context"];
5675
+ return JSON.stringify(sortJsonKeys(context ?? null));
5676
+ }
5677
+ function getProofEntries(value) {
5678
+ if (typeof value !== "object" || value == null || Array.isArray(value)) return [];
5679
+ const proof = value.proof;
5680
+ if (proof == null) return [];
5681
+ return Array.isArray(proof) ? proof : [proof];
5682
+ }
5683
+ function normalizeProofEntry(proof) {
5684
+ const stripped = stripContexts(proof);
5685
+ if (typeof stripped !== "object" || stripped == null || Array.isArray(stripped)) return stripped;
5686
+ const record = { ...stripped };
5687
+ if (typeof record.created === "string") try {
5688
+ record.created = Temporal.Instant.from(record.created).toString();
5689
+ } catch {}
5690
+ return record;
5691
+ }
5692
+ function getProofEntryFields(proof) {
5693
+ return JSON.stringify(sortJsonKeys(normalizeProofEntry(proof)));
5694
+ }
5695
+ function getProofFields(value) {
5696
+ return JSON.stringify(getProofEntries(value).map(getProofEntryFields).sort());
5697
+ }
5698
+ async function getUncapturedProofs(activity, capturedJsonLd, contextLoader) {
5699
+ const capturedProofs = new Set(getProofEntries(capturedJsonLd).map(getProofEntryFields));
5700
+ const retainedProofs = [];
5701
+ for await (const proof of activity.getProofs({ contextLoader })) {
5702
+ const proofJsonLd = await proof.toJsonLd({
5703
+ format: "compact",
5704
+ contextLoader
5705
+ });
5706
+ if (!capturedProofs.has(getProofEntryFields(proofJsonLd))) retainedProofs.push(proof);
5707
+ }
5708
+ return retainedProofs;
5709
+ }
5710
+ function stripContexts(value) {
5711
+ if (Array.isArray(value)) return value.map(stripContexts);
5712
+ if (typeof value !== "object" || value == null) return value;
5713
+ const record = { ...value };
5714
+ delete record["@context"];
5715
+ delete record.signature;
5716
+ for (const key of globalThis.Object.keys(record)) record[key] = stripContexts(record[key]);
5717
+ return record;
5718
+ }
5719
+ function sortJsonKeys(value) {
5720
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
5721
+ if (typeof value !== "object" || value == null) return value;
5722
+ return globalThis.Object.fromEntries(globalThis.Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
5723
+ }
5232
5724
  function notAcceptable(_request) {
5233
5725
  return new Response("Not Acceptable", {
5234
5726
  status: 406,