@fedify/fedify 2.2.20 → 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 (102) hide show
  1. package/dist/attachment-arrays-CalAATqD.mjs +16 -0
  2. package/dist/{builder-BolQ56ab.mjs → builder-4ImvtjG4.mjs} +3 -3
  3. package/dist/callback-0KrwzutD.d.mts +2607 -0
  4. package/dist/{client-jE7oGvRh.d.ts → client-9DPcy_Yx.d.ts} +16 -0
  5. package/dist/{client-BIBzqEIp.d.cts → client-B3ruDgWg.d.cts} +16 -0
  6. package/dist/{client-DhxaVgOv.mjs → client-XYMC0Mmk.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/public-audience.test.mjs +1 -1
  13. package/dist/compat/transformers.test.mjs +1 -1
  14. package/dist/{context-CFQGaq5x.d.cts → context-CjWuov0g.d.cts} +31 -14
  15. package/dist/{context-DdbLVV_k.d.ts → context-DZqI2LJD.d.ts} +31 -14
  16. package/dist/{deno-BUj4roJc.mjs → deno-AWk3S2Ug.mjs} +1 -1
  17. package/dist/{docloader-CbtF_0cD.mjs → docloader-Bogpjg4d.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/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 +1184 -8
  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 +283 -3
  35. package/dist/federation/temporal.test.mjs +25 -1
  36. package/dist/federation/webfinger.test.mjs +1 -1
  37. package/dist/{http-CQMVisM0.mjs → http-B3wCvgu8.mjs} +6 -4
  38. package/dist/{http-D8I7LBfx.cjs → http-BNaPJVnF.cjs} +6 -4
  39. package/dist/{http-C5g_VrA_.js → http-BpdLaGy8.js} +6 -4
  40. package/dist/{http-9IFUxdkp.d.cts → http-C8qLHs_Z.d.cts} +3 -3
  41. package/dist/{http-SbfezERn.d.ts → http-D8WmcRAF.d.ts} +3 -3
  42. package/dist/{inbox-CD8IDILN.mjs → inbox-DLy6WBXU.mjs} +1 -1
  43. package/dist/{key-C3o3DGap.mjs → key-Bhc8cQC7.mjs} +3 -2
  44. package/dist/{kv-cache-DC9LcfoC.cjs → kv-cache-Bj3CY9Jo.cjs} +1 -1
  45. package/dist/{kv-cache-CSKXXleR.js → kv-cache-CvjLUQTf.js} +1 -1
  46. package/dist/{ld-ijSr-0AB.mjs → ld-DTeykI0e.mjs} +153 -21
  47. package/dist/ld-signature-Dgz_b89j.mjs +23 -0
  48. package/dist/{middleware-DNueR0GD.cjs → middleware-BSQP4d9p.cjs} +475 -107
  49. package/dist/{middleware-DmcY2TWS.cjs → middleware-CWOzxb3o.cjs} +1 -1
  50. package/dist/{middleware-yqqfI7oJ.mjs → middleware-DkMsC5mQ.mjs} +1 -1
  51. package/dist/{middleware-sjhz30sm.js → middleware-Dx1iwFk8.js} +474 -107
  52. package/dist/{middleware-CYAaUTi5.mjs → middleware-dlGvSrXl.mjs} +386 -96
  53. package/dist/{mod-BYWp77-z.d.cts → mod-BmxqcEnU.d.ts} +30 -13
  54. package/dist/{mod-CVSKw-5H.d.cts → mod-DWEx2D4q.d.cts} +1 -1
  55. package/dist/{mod-BuRRdsfD.d.ts → mod-DnPmz3-S.d.ts} +1 -1
  56. package/dist/{mod-CM5_J_cx.d.ts → mod-INjDw-m0.d.cts} +30 -13
  57. package/dist/{mod-BRnwh2oy.d.ts → mod-REfljt0T.d.ts} +3 -3
  58. package/dist/{mod-Co7LEK9X.d.cts → mod-UvIGUHqW.d.cts} +3 -3
  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 +432 -4
  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/{outgoing-jsonld-amccRMrV.mjs → outgoing-jsonld-DHf_DYXp.mjs} +38 -8
  71. package/dist/{owner-B8kXzD0q.mjs → owner-BsA7qMHB.mjs} +2 -2
  72. package/dist/{proof-CBQOjOgA.mjs → proof-C63Hqt9N.mjs} +40 -15
  73. package/dist/{proof-qiuGJCD7.cjs → proof-Dbz6ApNP.cjs} +1190 -1007
  74. package/dist/{proof-DKX6nASL.js → proof-QV_o5ZqS.js} +1174 -1003
  75. package/dist/{send-DRpisX_f.mjs → send-CAdpwbFX.mjs} +92 -21
  76. package/dist/sig/http.test.mjs +2 -2
  77. package/dist/sig/key-types.test.d.mts +218 -0
  78. package/dist/sig/key-types.test.mjs +8 -0
  79. package/dist/sig/key.test.mjs +2 -2
  80. package/dist/sig/ld.test.mjs +573 -8
  81. package/dist/sig/mod.cjs +2 -2
  82. package/dist/sig/mod.d.cts +3 -3
  83. package/dist/sig/mod.d.ts +3 -3
  84. package/dist/sig/mod.js +2 -2
  85. package/dist/sig/owner.test.mjs +1 -1
  86. package/dist/sig/proof.test.mjs +96 -4
  87. package/dist/{temporal-BQGEINad.mjs → temporal-B3JGkVgk.mjs} +3 -5
  88. package/dist/testing/mod.d.mts +2 -2422
  89. package/dist/{types-DOvyymM4.cjs → types-BWx7zw3Y.cjs} +85 -10
  90. package/dist/{types-B1_pRFE_.js → types-Dx_w2JSM.js} +86 -11
  91. package/dist/utils/docloader.test.mjs +2 -2
  92. package/dist/utils/mod.cjs +1 -1
  93. package/dist/utils/mod.d.cts +1 -1
  94. package/dist/utils/mod.d.ts +1 -1
  95. package/dist/utils/mod.js +1 -1
  96. package/package.json +5 -5
  97. /package/dist/{activity-listener-ell7W1s9.mjs → activity-listener-tztVvlNb.mjs} +0 -0
  98. /package/dist/{collection-D-HqUuA2.mjs → collection-CA3V5zyK.mjs} +0 -0
  99. /package/dist/{negotiation-SQvQgUqe.mjs → negotiation-VnHNB0Q5.mjs} +0 -0
  100. /package/dist/{public-audience-DpJqzPuh.mjs → public-audience-4g3_Ze4y.mjs} +0 -0
  101. /package/dist/{retry-v_sGLH1d.mjs → retry-CXg_MBI-.mjs} +0 -0
  102. /package/dist/{types-J53Kw7so.mjs → types-BFowWFTT.mjs} +0 -0
@@ -2,22 +2,24 @@ 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 doubleKnockScoped, v as name, y as version } from "./http-C5g_VrA_.js";
6
- import { a as MAX_BODY_SIZE, i as BodyTooLargeError, n as getNodeInfo, o as readBoundedText, t as nodeInfoToJson } from "./types-B1_pRFE_.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-DKX6nASL.js";
8
- import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-CSKXXleR.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 } 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
- import { openDirectFetch, openPublicFetch } from "@fedify/vocab-runtime/internal";
21
23
  import { domainToASCII } from "node:url";
22
24
  //#region src/federation/activity-listener.ts
23
25
  var ActivityListenerSet = class {
@@ -781,6 +783,17 @@ async function buildCollectionSynchronizationHeader(collectionId, actorIds) {
781
783
  return `collectionId="${collectionId}", url="${url}", digest="${encodeHex(await digest(actorIds))}"`;
782
784
  }
783
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
784
797
  //#region src/federation/inbox.ts
785
798
  /**
786
799
  * Checks whether an activity's ID and all of its actor IDs have the same
@@ -1122,9 +1135,6 @@ function acceptsJsonLd(request) {
1122
1135
  function isPlainObject(value) {
1123
1136
  return typeof value === "object" && value != null && !Array.isArray(value);
1124
1137
  }
1125
- function normalizeDateTimeLiteral(value) {
1126
- return value.substring(19).match(/[Z+-]/) ? value : value + "Z";
1127
- }
1128
1138
  function isMalformedDateTimeLiteral(value) {
1129
1139
  if (typeof value !== "string") return false;
1130
1140
  try {
@@ -1166,7 +1176,7 @@ function hasMalformedExpandedQuestionClosedLiteral(value) {
1166
1176
  if (typeof literal === "boolean") return false;
1167
1177
  if (typeof literal !== "string") return false;
1168
1178
  if (value["@type"] !== XSD_DATE_TIME_IRI) return false;
1169
- 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;
1170
1180
  return isMalformedDateTimeLiteral(literal);
1171
1181
  }
1172
1182
  function hasMalformedExpandedDurationLiteral(value) {
@@ -1261,7 +1271,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1261
1271
  if (!await authorizePredicate(context, identifier)) return await onUnauthorized(request);
1262
1272
  }
1263
1273
  if (actor instanceof Tombstone) {
1264
- const jsonLd = await actor.toJsonLd(context);
1274
+ const jsonLd = await serializeForResponse(actor, context);
1265
1275
  return new Response(JSON.stringify(jsonLd), {
1266
1276
  status: 410,
1267
1277
  headers: {
@@ -1270,7 +1280,7 @@ async function handleActor(request, { identifier, context, actorDispatcher, auth
1270
1280
  }
1271
1281
  });
1272
1282
  }
1273
- const jsonLd = await actor.toJsonLd(context);
1283
+ const jsonLd = await serializeForResponse(actor, context);
1274
1284
  return new Response(JSON.stringify(jsonLd), { headers: {
1275
1285
  "Content-Type": "application/activity+json",
1276
1286
  Vary: "Accept"
@@ -1290,7 +1300,7 @@ async function handleObject(request, { values, context, objectDispatcher, author
1290
1300
  if (authorizePredicate != null) {
1291
1301
  if (!await authorizePredicate(context, values)) return await onUnauthorized(request);
1292
1302
  }
1293
- const jsonLd = await object.toJsonLd(context);
1303
+ const jsonLd = await serializeForResponse(object, context);
1294
1304
  return new Response(JSON.stringify(jsonLd), { headers: {
1295
1305
  "Content-Type": "application/activity+json",
1296
1306
  Vary: "Accept"
@@ -1421,7 +1431,7 @@ async function handleCollection(request, { name: name$1, identifier, uriGetter,
1421
1431
  if (collectionCallbacks.authorizePredicate != null) {
1422
1432
  if (!await collectionCallbacks.authorizePredicate(context, identifier)) return await onUnauthorized(request);
1423
1433
  }
1424
- const jsonLd = await collection.toJsonLd(context);
1434
+ const jsonLd = await serializeForResponse(collection, context);
1425
1435
  return new Response(JSON.stringify(jsonLd), { headers: {
1426
1436
  "Content-Type": "application/activity+json",
1427
1437
  Vary: "Accept"
@@ -1770,7 +1780,11 @@ async function handleInboxInternal(request, parameters, span) {
1770
1780
  }
1771
1781
  const keyCache = new KvKeyCache(kv, kvPrefixes.publicKey, ctx);
1772
1782
  const jsonWithoutSig = detachSignature(json);
1773
- 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
+ }
1774
1788
  const canAttemptAlternateAuthAfterLdSignatureFailure = skipSignatureVerification || hasHttpSignatureHeaders(request) || hasObjectIntegrityProof(jsonWithoutSig);
1775
1789
  let deferredLdSignatureError = void 0;
1776
1790
  const respondInvalidActivity = async (error) => {
@@ -2249,7 +2263,7 @@ var CustomCollectionHandler = class {
2249
2263
  * @returns A promise that resolves to the JSON-LD representation.
2250
2264
  */
2251
2265
  async toJsonLd() {
2252
- return (await this.collection).toJsonLd(this.context);
2266
+ return serializeForResponse(await this.collection, this.context);
2253
2267
  }
2254
2268
  /**
2255
2269
  * Fetches the collection with optional cursor for pagination.
@@ -2552,7 +2566,7 @@ var UnauthorizedError = class extends HandlerError {
2552
2566
  * @since 0.3.0
2553
2567
  */
2554
2568
  async function respondWithObject(object, options) {
2555
- const jsonLd = await object.toJsonLd(options);
2569
+ const jsonLd = await serializeForResponse(object, options);
2556
2570
  return new Response(JSON.stringify(jsonLd), { headers: { "Content-Type": "application/activity+json" } });
2557
2571
  }
2558
2572
  /**
@@ -2640,6 +2654,106 @@ const MIN_COMPONENTS = [
2640
2654
  "@target-uri",
2641
2655
  "@authority"
2642
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
+ }
2643
2757
  //#endregion
2644
2758
  //#region src/nodeinfo/handler.ts
2645
2759
  /**
@@ -2739,7 +2853,8 @@ function extractInboxes({ recipients, preferSharedInbox, excludeBaseUris }) {
2739
2853
  * @param parameters The parameters for sending the activity.
2740
2854
  * See also {@link SendActivityParameters}.
2741
2855
  * @param deps The dependencies, for tests.
2742
- * @throws {Error} If the activity fails to send.
2856
+ * @throws {FetchError} If the delivery times out before receiving a response.
2857
+ * @throws {SendActivityError} If the inbox returns an unsuccessful response.
2743
2858
  */
2744
2859
  function sendActivity(options, deps = {}) {
2745
2860
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
@@ -2766,7 +2881,25 @@ function sendActivity(options, deps = {}) {
2766
2881
  });
2767
2882
  }
2768
2883
  const MAX_ERROR_RESPONSE_BODY_BYTES = 1024;
2769
- 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) {
2770
2903
  if (response.body == null) return "";
2771
2904
  const reader = response.body.getReader();
2772
2905
  const decoder = new TextDecoder();
@@ -2775,7 +2908,8 @@ async function readLimitedResponseBody(response, maxBytes) {
2775
2908
  let truncated = false;
2776
2909
  try {
2777
2910
  while (true) {
2778
- const { done, value } = await reader.read();
2911
+ signal.throwIfAborted();
2912
+ const { done, value } = await raceWithAbort(reader.read(), signal);
2779
2913
  if (done) break;
2780
2914
  if (totalBytes + value.length > maxBytes) {
2781
2915
  const remaining = maxBytes - totalBytes;
@@ -2787,8 +2921,10 @@ async function readLimitedResponseBody(response, maxBytes) {
2787
2921
  totalBytes += value.length;
2788
2922
  }
2789
2923
  } finally {
2790
- if (truncated) reader.cancel().catch(() => {});
2791
- reader.releaseLock();
2924
+ if (truncated || signal.aborted) reader.cancel().catch(() => {});
2925
+ try {
2926
+ reader.releaseLock();
2927
+ } catch (_) {}
2792
2928
  }
2793
2929
  let result = chunks.join("");
2794
2930
  if (truncated) result += "… (truncated)";
@@ -2800,12 +2936,24 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2800
2936
  "federation",
2801
2937
  "outbox"
2802
2938
  ]);
2803
- const openUnvalidatedHop = deps.openHop ?? (allowPrivateAddress ? openDirectFetch : (url) => openPublicFetch(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 }));
2804
2943
  let opened = false;
2805
2944
  async function openHop(url) {
2806
2945
  let session;
2807
2946
  try {
2808
- session = await openUnvalidatedHop(url);
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
+ }
2809
2957
  } catch (error) {
2810
2958
  if (error instanceof UrlError && error.reason === "dns") {
2811
2959
  logger.error("DNS resolution failed for URL: {url}", {
@@ -2831,7 +2979,8 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2831
2979
  method: "POST",
2832
2980
  headers,
2833
2981
  body: JSON.stringify(activity),
2834
- redirect: "manual"
2982
+ redirect: "manual",
2983
+ signal
2835
2984
  });
2836
2985
  let rsaKey = null;
2837
2986
  for (const key of keys) if (key.privateKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
@@ -2846,18 +2995,48 @@ async function sendActivityInternal({ activity, activityId, keys, inbox, allowPr
2846
2995
  }))
2847
2996
  });
2848
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);
2849
3019
  try {
2850
- outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox)) : await doubleKnockScoped(request, rsaKey, {
3020
+ outcome = rsaKey == null ? await fetchWithValidatedRedirects(request, openHop, (response) => consumeSendActivityResponse(response, inbox, signal), signal) : await doubleKnockScoped(request, rsaKey, {
2851
3021
  tracerProvider,
2852
- specDeterminer
2853
- }, openHop, (response) => consumeSendActivityResponse(response, inbox));
3022
+ specDeterminer: boundedSpecDeterminer,
3023
+ signal
3024
+ }, openHop, (response) => consumeSendActivityResponse(response, inbox, signal));
2854
3025
  } catch (error) {
2855
- if (opened) 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}", {
2856
3033
  activityId,
2857
3034
  inbox: inbox.href,
2858
- error
3035
+ error: failureError
2859
3036
  });
2860
- throw error;
3037
+ throw failureError;
3038
+ } finally {
3039
+ clearTimeout(timer);
2861
3040
  }
2862
3041
  if (!outcome.ok) {
2863
3042
  const { status, statusText, error } = outcome;
@@ -2899,17 +3078,18 @@ function cancelResponseBody(response, url) {
2899
3078
  * session is open: the body of a successful response is cancelled, and at
2900
3079
  * most 1 KiB of an error response body is read.
2901
3080
  */
2902
- async function consumeSendActivityResponse(response, inbox) {
3081
+ async function consumeSendActivityResponse(response, inbox, signal) {
2903
3082
  if (response.ok) {
2904
3083
  cancelResponseBody(response, response.url || inbox.href);
2905
3084
  return { ok: true };
2906
3085
  }
2907
3086
  let error;
2908
3087
  try {
2909
- error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES);
3088
+ error = await readLimitedResponseBody(response, MAX_ERROR_RESPONSE_BODY_BYTES, signal);
2910
3089
  } catch (_) {
2911
3090
  error = "";
2912
3091
  }
3092
+ if (signal.aborted) error = "(timed out reading response body)";
2913
3093
  return {
2914
3094
  ok: false,
2915
3095
  status: response.status,
@@ -2928,7 +3108,7 @@ async function consumeSendActivityResponse(response, inbox) {
2928
3108
  * @param consume The function to consume the final response.
2929
3109
  * @returns The value returned by `consume`.
2930
3110
  */
2931
- async function fetchWithValidatedRedirects(request, openHop, consume) {
3111
+ async function fetchWithValidatedRedirects(request, openHop, consume, signal) {
2932
3112
  const logger = getLogger([
2933
3113
  "fedify",
2934
3114
  "federation",
@@ -2936,10 +3116,14 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
2936
3116
  ]);
2937
3117
  let body = await request.clone().text();
2938
3118
  for (let redirects = 0;; redirects++) {
3119
+ signal?.throwIfAborted();
2939
3120
  const session = await openHop(request.url);
2940
3121
  let response;
2941
3122
  try {
2942
- response = await session.fetch(request, { redirect: "manual" });
3123
+ response = await session.fetch(request, {
3124
+ redirect: "manual",
3125
+ signal
3126
+ });
2943
3127
  } catch (error) {
2944
3128
  await closeAfterError(session, logger);
2945
3129
  throw error;
@@ -2989,7 +3173,8 @@ async function fetchWithValidatedRedirects(request, openHop, consume) {
2989
3173
  method,
2990
3174
  headers,
2991
3175
  body,
2992
- redirect: "manual"
3176
+ redirect: "manual",
3177
+ signal: signal ?? request.signal
2993
3178
  });
2994
3179
  }
2995
3180
  }
@@ -3354,8 +3539,25 @@ var FederationImpl = class extends FederationBuilderImpl {
3354
3539
  _getTracer() {
3355
3540
  return this.tracerProvider.getTracer(name, version);
3356
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
+ }
3357
3559
  async _startQueueInternal(ctxData, signal, queue) {
3358
- if (this.inboxQueue == null && this.outboxQueue == null) return;
3560
+ if (this.inboxQueue == null && this.outboxQueue == null && this.fanoutQueue == null) return;
3359
3561
  const logger = getLogger([
3360
3562
  "fedify",
3361
3563
  "federation",
@@ -3365,20 +3567,38 @@ var FederationImpl = class extends FederationBuilderImpl {
3365
3567
  if (this.inboxQueue != null && (queue == null || queue === "inbox") && !this.inboxQueueStarted) {
3366
3568
  logger.debug("Starting an inbox task worker.");
3367
3569
  this.inboxQueueStarted = true;
3368
- promises.push(this.inboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3570
+ promises.push(this.#listenQueue(this.inboxQueue, ctxData, signal));
3369
3571
  }
3370
3572
  if (this.outboxQueue != null && this.outboxQueue !== this.inboxQueue && (queue == null || queue === "outbox") && !this.outboxQueueStarted) {
3371
3573
  logger.debug("Starting an outbox task worker.");
3372
3574
  this.outboxQueueStarted = true;
3373
- promises.push(this.outboxQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3575
+ promises.push(this.#listenQueue(this.outboxQueue, ctxData, signal));
3374
3576
  }
3375
3577
  if (this.fanoutQueue != null && this.fanoutQueue !== this.inboxQueue && this.fanoutQueue !== this.outboxQueue && (queue == null || queue === "fanout") && !this.fanoutQueueStarted) {
3376
3578
  logger.debug("Starting a fanout task worker.");
3377
3579
  this.fanoutQueueStarted = true;
3378
- promises.push(this.fanoutQueue.listen((msg) => this.processQueuedTask(ctxData, msg), { signal }));
3580
+ promises.push(this.#listenQueue(this.fanoutQueue, ctxData, signal));
3379
3581
  }
3380
3582
  await Promise.all(promises);
3381
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
+ }
3382
3602
  processQueuedTask(contextData, message) {
3383
3603
  const tracer = this._getTracer();
3384
3604
  const extractedContext = propagation.extract(context.active(), message.traceContext);
@@ -3488,7 +3708,8 @@ var FederationImpl = class extends FederationBuilderImpl {
3488
3708
  collectionSync: message.collectionSync,
3489
3709
  orderingKey: message.orderingKey,
3490
3710
  normalizeExistingProofs: message.normalizeExistingProofs,
3491
- context
3711
+ context,
3712
+ activityJsonLd: hasTopLevelProof(message.activity) ? message.activity : void 0
3492
3713
  });
3493
3714
  }
3494
3715
  async #listenOutboxMessage(_, message, span) {
@@ -3691,7 +3912,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3691
3912
  let parseInput = void 0;
3692
3913
  let parseContextLoader = context.contextLoader;
3693
3914
  try {
3694
- const hasSignatureField = hasSignature(message.activity);
3915
+ const hasSignatureField = hasVerifiableSignature(message.activity);
3695
3916
  const shouldParseFromNormalizedSignedPayload = message.ldSignatureVerified === true || message.normalizedActivity != null || message.ldSignatureVerified == null && hasSignatureField;
3696
3917
  const parseContext = hasSignatureField ? {
3697
3918
  ...context,
@@ -3887,21 +4108,31 @@ var FederationImpl = class extends FederationBuilderImpl {
3887
4108
  hasProof = true;
3888
4109
  break;
3889
4110
  }
3890
- if (!hasProof) {
3891
- for (const { keyId, privateKey } of keys) if (privateKey.algorithm.name === "Ed25519") {
3892
- activity = await signObject(activity, privateKey, keyId, {
3893
- contextLoader,
3894
- tracerProvider: this.tracerProvider
3895
- });
3896
- hasProof = true;
3897
- 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
+ }
3898
4128
  }
4129
+ jsonLd = options.activityJsonLd != null ? detachSignature(options.activityJsonLd) : await activity.toJsonLd({
4130
+ format: "compact",
4131
+ contextLoader
4132
+ });
3899
4133
  }
3900
- let jsonLd = await activity.toJsonLd({
3901
- format: "compact",
3902
- contextLoader
3903
- });
3904
- 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;
3905
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.", {
3906
4137
  activityId,
3907
4138
  keys: keys.map((pair) => ({
@@ -3938,19 +4169,27 @@ var FederationImpl = class extends FederationBuilderImpl {
3938
4169
  activity: jsonLd
3939
4170
  });
3940
4171
  const promises = [];
3941
- for (const inbox in inboxes) promises.push(sendActivity({
3942
- allowPrivateAddress: this.allowPrivateAddress,
3943
- keys,
3944
- activity: jsonLd,
3945
- activityId: activity.id?.href,
3946
- activityType: getTypeId(activity).href,
3947
- inbox: new URL(inbox),
3948
- sharedInbox: inboxes[inbox].sharedInbox,
3949
- headers: collectionSync == null ? void 0 : new Headers({ "Collection-Synchronization": await buildCollectionSynchronizationHeader(collectionSync, inboxes[inbox].actorIds) }),
3950
- specDeterminer: new KvSpecDeterminer(this.kv, this.kvPrefixes.httpMessageSignaturesSpec, this.firstKnock),
3951
- tracerProvider: this.tracerProvider
3952
- }));
3953
- 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
+ }
3954
4193
  return;
3955
4194
  }
3956
4195
  logger.debug("Enqueuing activity {activityId} to send later.", {
@@ -3965,7 +4204,7 @@ var FederationImpl = class extends FederationBuilderImpl {
3965
4204
  privateKey: privateKeyJwk
3966
4205
  });
3967
4206
  }
3968
- if (!this.manuallyStartQueue) this._startQueueInternal(ctx.data);
4207
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(ctx.data);
3969
4208
  const carrier = {};
3970
4209
  propagation.inject(context.active(), carrier);
3971
4210
  const messages = [];
@@ -4198,7 +4437,7 @@ var FederationImpl = class extends FederationBuilderImpl {
4198
4437
  const identity = await this.sharedInboxKeyDispatcher(context);
4199
4438
  if (identity != null) context = this.#createContext(request, contextData, { documentLoader: "identifier" in identity || "username" in identity ? await context.getDocumentLoader(identity) : context.getDocumentLoader(identity) });
4200
4439
  }
4201
- if (!this.manuallyStartQueue) this._startQueueInternal(contextData);
4440
+ if (!this.manuallyStartQueue) this._startQueueAutomatically(contextData);
4202
4441
  const inboxContextFactory = context.toInboxContext.bind(context);
4203
4442
  inboxContextFactory[rawInboxContextFactorySymbol] = context.toInboxContext.bind(context);
4204
4443
  return await handleInbox(request, {
@@ -4531,6 +4770,8 @@ var ContextImpl = class ContextImpl {
4531
4770
  for (const keyPair of keyPairs) {
4532
4771
  const newPair = {
4533
4772
  ...keyPair,
4773
+ privateKey: asCryptoKey(keyPair.privateKey),
4774
+ publicKey: asCryptoKey(keyPair.publicKey),
4534
4775
  cryptographicKey: new CryptographicKey({
4535
4776
  id: keyPair.keyId,
4536
4777
  owner,
@@ -4607,10 +4848,16 @@ var ContextImpl = class ContextImpl {
4607
4848
  } else identifierPromise = Promise.resolve(identity.identifier);
4608
4849
  return identifierPromise.then((identifier) => {
4609
4850
  if (identifier == null) return this.documentLoader;
4610
- 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
+ }));
4611
4855
  });
4612
4856
  }
4613
- return this.federation.authenticatedDocumentLoaderFactory(identity);
4857
+ return this.federation.authenticatedDocumentLoaderFactory({
4858
+ keyId: identity.keyId,
4859
+ privateKey: asCryptoKey(identity.privateKey)
4860
+ });
4614
4861
  }
4615
4862
  lookupObject(identifier, options = {}) {
4616
4863
  return lookupObject(identifier, {
@@ -4633,10 +4880,14 @@ var ContextImpl = class ContextImpl {
4633
4880
  return options.parse === "none" ? getNodeInfo(url, {
4634
4881
  parse: "none",
4635
4882
  direct: options.direct,
4883
+ timeout: options.timeout,
4884
+ signal: options.signal,
4636
4885
  userAgent: options?.userAgent ?? this.federation.userAgent
4637
4886
  }) : getNodeInfo(url, {
4638
4887
  parse: options.parse,
4639
4888
  direct: options.direct,
4889
+ timeout: options.timeout,
4890
+ signal: options.signal,
4640
4891
  userAgent: options?.userAgent ?? this.federation.userAgent
4641
4892
  });
4642
4893
  }
@@ -4648,7 +4899,17 @@ var ContextImpl = class ContextImpl {
4648
4899
  allowPrivateAddress: this.federation.allowPrivateAddress
4649
4900
  });
4650
4901
  }
4651
- 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
+ }
4652
4913
  return this.tracerProvider.getTracer(name, version).startActiveSpan(this.federation.outboxQueue == null || options.immediate ? "activitypub.outbox" : "activitypub.fanout", {
4653
4914
  kind: this.federation.outboxQueue == null || options.immediate ? SpanKind.CLIENT : SpanKind.PRODUCER,
4654
4915
  attributes: {
@@ -4661,7 +4922,7 @@ var ContextImpl = class ContextImpl {
4661
4922
  }, async (span) => {
4662
4923
  try {
4663
4924
  if (activity.id != null) span.setAttribute("activitypub.activity.id", activity.id.href);
4664
- await this.sendActivityInternal(sender, recipients, activity, options, span);
4925
+ await this.sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd);
4665
4926
  } catch (e) {
4666
4927
  span.setStatus({
4667
4928
  code: SpanStatusCode.ERROR,
@@ -4673,7 +4934,7 @@ var ContextImpl = class ContextImpl {
4673
4934
  }
4674
4935
  });
4675
4936
  }
4676
- async sendActivityInternal(sender, recipients, activity, options, span) {
4937
+ async sendActivityInternal(sender, recipients, activity, options, span, activityJsonLd) {
4677
4938
  const logger = getLogger([
4678
4939
  "fedify",
4679
4940
  "federation",
@@ -4720,15 +4981,23 @@ var ContextImpl = class ContextImpl {
4720
4981
  if (!(error instanceof RouterError)) throw error;
4721
4982
  }
4722
4983
  } else expandedRecipients = [recipients];
4723
- const opts = {
4724
- context: this,
4725
- orderingKey: options.orderingKey,
4726
- collectionSync,
4727
- immediate: options.immediate,
4728
- normalizeExistingProofs: options.normalizeExistingProofs
4729
- };
4730
4984
  span.setAttribute("activitypub.inboxes", expandedRecipients.length);
4731
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
+ }
4732
5001
  span?.setAttribute("activitypub.activity.id", activity?.id?.href ?? "");
4733
5002
  if (activity.actorId == null) {
4734
5003
  logger.error("Activity {activityId} to send does not have an actor.", {
@@ -4740,15 +5009,42 @@ var ContextImpl = class ContextImpl {
4740
5009
  let proofCreated = false;
4741
5010
  if (actorKeyPairs != null) {
4742
5011
  const contextLoader = this.contextLoader;
4743
- for (const kp of actorKeyPairs) {
4744
- if (kp.privateKey.algorithm.name !== "Ed25519" || kp.multikey.id == null) continue;
4745
- activity = await signObject(activity, kp.privateKey, kp.multikey.id, {
4746
- contextLoader,
4747
- tracerProvider: this.tracerProvider
4748
- });
4749
- 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;
4750
5038
  }
4751
5039
  }
5040
+ const opts = {
5041
+ context: this,
5042
+ orderingKey: options.orderingKey,
5043
+ collectionSync,
5044
+ immediate: options.immediate,
5045
+ activityJsonLd,
5046
+ normalizeExistingProofs: options.normalizeExistingProofs
5047
+ };
4752
5048
  const inboxes = extractInboxes({
4753
5049
  recipients: expandedRecipients,
4754
5050
  preferSharedInbox: options.preferSharedInbox,
@@ -4788,7 +5084,7 @@ var ContextImpl = class ContextImpl {
4788
5084
  actorIds: [...actorIds],
4789
5085
  sharedInbox
4790
5086
  }])),
4791
- activity: await activity.toJsonLd({
5087
+ activity: activityJsonLd != null ? detachSignature(activityJsonLd) : await activity.toJsonLd({
4792
5088
  format: "compact",
4793
5089
  contextLoader: this.contextLoader
4794
5090
  }),
@@ -4799,7 +5095,7 @@ var ContextImpl = class ContextImpl {
4799
5095
  normalizeExistingProofs: proofCreated || options.normalizeExistingProofs,
4800
5096
  traceContext: carrier
4801
5097
  };
4802
- if (!this.federation.manuallyStartQueue) this.federation._startQueueInternal(this.data);
5098
+ if (!this.federation.manuallyStartQueue) this.federation._startQueueAutomatically(this.data);
4803
5099
  await this.federation.fanoutQueue.enqueue(message, { orderingKey: options.orderingKey });
4804
5100
  return true;
4805
5101
  }
@@ -5126,7 +5422,7 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
5126
5422
  if (forwarder.length < 1) throw new Error("The forwarder's key pairs are empty.");
5127
5423
  keys = forwarder;
5128
5424
  } else keys = [forwarder];
5129
- if (!hasSignatureLike(ctx.activity)) {
5425
+ if (!hasVerifiableSignature(ctx.activity) && !hasSignatureLike(ctx.activity)) {
5130
5426
  if (!hasProofLike(ctx.activity)) {
5131
5427
  if (options?.skipIfUnsigned) return false;
5132
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.", {
@@ -5164,25 +5460,33 @@ async function forwardActivityInternal(ctx, loggerCategory, forwarder, recipient
5164
5460
  if (options?.immediate) logger.debug("Forwarding activity immediately without queue since immediate option is set.");
5165
5461
  else logger.debug("Forwarding activity immediately without queue since queue is not set.");
5166
5462
  const promises = [];
5167
- for (const inbox in inboxes) promises.push(sendActivity({
5168
- allowPrivateAddress: ctx.federation.allowPrivateAddress,
5169
- keys,
5170
- activity: ctx.activity,
5171
- activityId: ctx.activityId,
5172
- activityType: ctx.activityType,
5173
- inbox: new URL(inbox),
5174
- sharedInbox: inboxes[inbox].sharedInbox,
5175
- tracerProvider: ctx.tracerProvider,
5176
- specDeterminer: new KvSpecDeterminer(ctx.federation.kv, ctx.federation.kvPrefixes.httpMessageSignaturesSpec, ctx.federation.firstKnock)
5177
- }));
5178
- 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
+ }
5179
5483
  return true;
5180
5484
  }
5181
5485
  logger.debug("Enqueuing activity {activityId} to forward later.", {
5182
5486
  activityId: ctx.activityId,
5183
5487
  activity: ctx.activity
5184
5488
  });
5185
- if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueInternal(ctx.data);
5489
+ if (!ctx.federation.manuallyStartQueue) ctx.federation._startQueueAutomatically(ctx.data);
5186
5490
  const keyJwkPairs = [];
5187
5491
  for (const { keyId, privateKey } of keys) {
5188
5492
  const privateKeyJwk = await exportJwk(privateKey);
@@ -5354,6 +5658,69 @@ var KvSpecDeterminer = class {
5354
5658
  function notFound(_request) {
5355
5659
  return new Response("Not Found", { status: 404 });
5356
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
+ }
5357
5724
  function notAcceptable(_request) {
5358
5725
  return new Response("Not Acceptable", {
5359
5726
  status: 406,